body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>Let me start by saying that until very recently procedural was the paradigm of choice for about 100% of my programming activity, and I was a complete stranger to C++ and OOP concepts. Since a few weeks ago, I have been studying C++ and today I decided to take some random procedural code and translate it to object oriented design as an exercise. The code in question was an implementation of the classical game Tetris for Windows console.</p>
<pre><code>#include <iostream>
using namespace std;
#include <Windows.h>
#include <thread>
#include <vector>
#define XPADDING 34
#define YPADDING 5
// Screen buffer class
//==============================================================
class Screen
{
public:
Screen(int, int);
const int screenWidth;
const int screenHeight;
wchar_t *screen;
HANDLE hConsole;
DWORD dwBytesWritten;
};
Screen::Screen(int screenWidth, int screenHeight)
: screenWidth(screenWidth), screenHeight(screenHeight)
{
screen = new wchar_t[screenWidth * screenHeight];
for (int i = 0; i < screenWidth * screenHeight; i++) screen[i] = L' ';
hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(hConsole);
dwBytesWritten = 0;
}
// Tetromino Class
//==============================================================
class Tetromino
{
public:
Tetromino(wstring, int, int, int);
int y;
int x;
int rotation;
wstring layout;
int rotate(int, int);
};
Tetromino::Tetromino(wstring layout, int startingX, int startingY, int startingRotation)
: layout(layout), y(startingY), x(startingX), rotation(startingRotation)
{}
int Tetromino::rotate(int x, int y)
{
/*
* Rotates piece layout
* string based on given angle
* 'rotation'
*/
switch (rotation % 4) {
case 0: return y * 4 + x; // 0 degress
case 1: return 12 + y - (x * 4); // 90 degress
case 2: return 15 - (y * 4) - x; // 180 degress
case 3: return 3 - y + (x * 4); // 270 degress
}
return 0;
}
// Playing Field Class
//==============================================================
class PlayingField
{
public:
PlayingField(int, int);
const int fieldWidth;
const int fieldHeight;
unsigned char *pField;
bool doesPieceFit(Tetromino*, int, int, int);
};
PlayingField::PlayingField(int fieldWidth, int fieldHeight)
: fieldWidth(fieldWidth), fieldHeight(fieldHeight), pField(nullptr)
{
// Creating play field buffer
pField = new unsigned char[fieldHeight * fieldWidth];
for (int x = 0; x < fieldWidth; x++)
for (int y = 0; y < fieldHeight; y++)
// 0 characters are spaces and 9 are borders
pField[y * fieldWidth + x] = (x == 0 || x == fieldWidth - 1 || y == fieldHeight - 1) ? 9 : 0;
}
bool PlayingField::doesPieceFit(Tetromino *tetromino, int rotation, int x, int y)
{
for (int px = 0; px < 4; px++)
for (int py = 0; py < 4; py++) {
int pi = tetromino->rotate(px, py);
int fi = (y + py) * fieldWidth + (x + px);
if (x + px >= 0 && x + px < fieldWidth)
if (y + py >= 0 && y + py < fieldHeight)
// if cell value != 0, it's occupied
if (tetromino->layout[pi] == L'X' && pField[fi] != 0)
return false;
}
return true;
}
// Game class
//==============================================================
class Tetris
{
public:
Tetris(Screen*, PlayingField*, int);
bool gameOver;
int score;
void draw();
void checkLines();
void computeNextState();
void lockPieceOnField();
void processInput();
void synchronizeMovement();
private:
int lines;
int speed;
int nextPiece;
int pieceCount;
int currentPiece;
int speedCounter;
bool key[4];
bool forceDown;
bool rotateHold;
Screen *screenBuffer;
Tetromino *tetromino[7];
PlayingField *playingField;
vector<int> fullLines;
};
Tetris::Tetris(Screen *screenBuffer, PlayingField *playingField, int speed)
: speed(speed), screenBuffer(screenBuffer), playingField(playingField)
{
// Set game initial state
score = 0;
lines = 0;
pieceCount = 0;
speedCounter = 0;
gameOver = false;
forceDown = false;
nextPiece = rand() % 7;
currentPiece = rand() % 7;
// Generate pieces
int startingPieceX = playingField->fieldWidth / 2;
tetromino[0] = new Tetromino(L"..X...X...X...X.", startingPieceX, 0, 0);
tetromino[1] = new Tetromino(L"..X..XX...X.....", startingPieceX, 0, 0);
tetromino[2] = new Tetromino(L".....XX..XX.....", startingPieceX, 0, 0);
tetromino[3] = new Tetromino(L"..X..XX..X......", startingPieceX, 0, 0);
tetromino[4] = new Tetromino(L".X...XX...X.....", startingPieceX, 0, 0);
tetromino[5] = new Tetromino(L".X...X...XX.....", startingPieceX, 0, 0);
tetromino[6] = new Tetromino(L"..X...X..XX.....", startingPieceX, 0, 0);
rotateHold = true;
}
void Tetris::synchronizeMovement()
{
// Timing game ticks
this_thread::sleep_for(50ms);
speedCounter++;
forceDown = (speed == speedCounter);
}
void Tetris::processInput()
{
// x27 = right arrow key
// x25 = left arrow key
// x28 = down arrow key
for (int k = 0; k < 4; k++)
key[k] = (0x8000 & GetAsyncKeyState((unsigned char) ("\x27\x25\x28Z"[k]))) != 0;
// Handling input
Tetromino *currentTetromino = tetromino[currentPiece];
currentTetromino->x += (key[0] && playingField->doesPieceFit(currentTetromino, currentTetromino->rotation, currentTetromino->x + 1, currentTetromino->y)) ? 1 : 0;
currentTetromino->x -= (key[1] && playingField->doesPieceFit(currentTetromino, currentTetromino->rotation, currentTetromino->x - 1, currentTetromino->y)) ? 1 : 0;
currentTetromino->y += (key[2] && playingField->doesPieceFit(currentTetromino, currentTetromino->rotation, currentTetromino->x, currentTetromino->y + 1)) ? 1 : 0;
if (key[3]) {
currentTetromino->rotation += (rotateHold && playingField->doesPieceFit(currentTetromino, currentTetromino->rotation + 1, currentTetromino->x, currentTetromino->y)) ? 1 : 0;
rotateHold = false;
} else {
rotateHold = true;
}
}
void Tetris::computeNextState()
{
if (forceDown) {
Tetromino *currentTetromino = tetromino[currentPiece];
if (playingField->doesPieceFit(currentTetromino, currentTetromino->rotation, currentTetromino->x, currentTetromino->y + 1)) {
currentTetromino->y++;
} else {
lockPieceOnField();
// Set up new piece
currentPiece = nextPiece;
nextPiece = rand() % 7;
tetromino[currentPiece]->rotation = 0;
tetromino[currentPiece]->y = 0;
tetromino[currentPiece]->x = playingField->fieldWidth / 2;
// Increse game speed every 10 tics
pieceCount++;
if (pieceCount % 10 == 0)
if (speed >= 10) speed--;
checkLines();
score += 25;
if (!fullLines.empty()) score += (1 << fullLines.size()) * 100;
// Game over if it doesn't fit
gameOver = !playingField->doesPieceFit(tetromino[currentPiece], tetromino[currentPiece]->rotation, tetromino[currentPiece]->x, tetromino[currentPiece]->y);
}
speedCounter = 0;
}
}
void Tetris::lockPieceOnField()
{
Tetromino *currentTetromino = tetromino[currentPiece];
for (int px = 0; px < 4; px++)
for (int py = 0; py < 4; py++)
if (currentTetromino->layout[currentTetromino->rotate(px, py)] == L'X')
// nCurrentPiece + 1 because 0 means empty spots in the playing field
playingField->pField[(currentTetromino->y + py) * playingField->fieldWidth + (currentTetromino->x + px)] = currentPiece + 1;
}
void Tetris::checkLines()
{
Tetromino *currentTetromino = tetromino[currentPiece];
for (int py = 0; py < 4; py++) {
if (currentTetromino->y + py < playingField->fieldHeight - 1) {
bool bLine = true;
for (int px = 1; px < playingField->fieldWidth; px++)
// if any cell is empty, line isn't complete
bLine &= (playingField->pField[(currentTetromino->y + py) * playingField->fieldWidth + px]) != 0;
if (bLine) {
// draw '=' symbols
for (int px = 1; px < playingField->fieldWidth - 1; px++)
playingField->pField[(currentTetromino->y + py) * playingField->fieldWidth + px] = 8;
fullLines.push_back(currentTetromino->y + py);
lines++;
}
}
}
}
void Tetris::draw()
{
// Draw playing field
for (int x = 0; x < playingField->fieldWidth; x++)
for (int y = 0; y < playingField->fieldHeight; y++)
//mapping playing field (' ', 1,..., 9) to Screen characters (' ', A,...,#)
screenBuffer->screen[(y + YPADDING) * screenBuffer->screenWidth + (x + XPADDING)] = L" ABCDEFG=#"[playingField->pField[y * playingField->fieldWidth + x]];
// Draw pieces
for (int px = 0; px < 4; px++)
for (int py = 0; py < 4; py++) {
if (tetromino[currentPiece]->layout[tetromino[currentPiece]->rotate(px, py)] == L'X')
// Drawing current piece ( n + ASCII code of character 'A') 0 -> A, 1 - > B, ...
screenBuffer->screen[(tetromino[currentPiece]->y + py + YPADDING) * screenBuffer->screenWidth + (tetromino[currentPiece]->x + px + XPADDING)] = currentPiece + 65;
if (tetromino[nextPiece]->layout[tetromino[nextPiece]->rotate(px, py)] == L'X')
// Drawing next piece ( n + ASCII code of character 'A') 0 -> A, 1 - > B, ...
screenBuffer->screen[(YPADDING + 3 + py) * screenBuffer->screenWidth + (XPADDING / 2 + px + 3)] = nextPiece + 65;
else
screenBuffer->screen[(YPADDING + 3 + py) * screenBuffer->screenWidth + (XPADDING / 2 + px + 3)] = ' ';
}
swprintf_s(&screenBuffer->screen[YPADDING * screenBuffer->screenWidth + XPADDING / 4], 16, L"SCORE: %8d", score);
swprintf_s(&screenBuffer->screen[(YPADDING + 1) * screenBuffer->screenWidth + XPADDING / 4], 16, L"LINES: %8d", lines);
swprintf_s(&screenBuffer->screen[(YPADDING + 4) * screenBuffer->screenWidth + XPADDING / 4], 13, L"NEXT PIECE: ");
if (!fullLines.empty()) {
WriteConsoleOutputCharacter(screenBuffer->hConsole, screenBuffer->screen, screenBuffer->screenWidth * screenBuffer->screenHeight, {0,0}, &screenBuffer->dwBytesWritten);
this_thread::sleep_for(400ms);
for (auto &v : fullLines)
for (int px = 1; px < playingField->fieldWidth - 1; px++) {
for (int py = v; py > 0; py--)
// clear line, moving lines above one unit down
playingField->pField[py * playingField->fieldWidth + px] = playingField->pField[(py - 1) * playingField->fieldWidth + px];
playingField->pField[px] = 0;
}
fullLines.clear();
}
// Display Frame
WriteConsoleOutputCharacter(screenBuffer->hConsole, screenBuffer->screen, screenBuffer->screenWidth * screenBuffer->screenHeight, {0,0}, &screenBuffer->dwBytesWritten);
}
int main(void){
Screen *screenBuffer = new Screen(80, 30);
PlayingField *playingField = new PlayingField(12, 18);
Tetris *tetrisGame = new Tetris(screenBuffer, playingField, 20);
// Main game loop
while (!tetrisGame->gameOver) {
// Timing
tetrisGame->synchronizeMovement();
// Input
tetrisGame->processInput();
// Logic
tetrisGame->computeNextState();
//Render Output
tetrisGame->draw();
}
CloseHandle(screenBuffer->hConsole);
cout << "Game Over! Score:" << tetrisGame->score << endl;
system("pause");
return 0;
}
</code></pre>
<p><strong>Some doubts I had while coding:</strong></p>
<ul>
<li><p>Overall code logistics. What would be the best (advised) way of interrelating my class objects? Should I pass references around as member variables (the way I did with my <code>Tetris</code> class, it has pointers to <code>screenBuffer</code> and <code>playingField</code> objects) and make most of the game functionality internal to my objects or make them as independent of one another as possible, bringing all together in my program's <code>main</code> function by accessing each object when needed (essentially pulling some of the programs functionality out of my objects)?</p></li>
<li><p>I'm using the <code>this</code> keyword a lot. It sure clutters the code a little bit. I'll go ahead and not use it at all. I wonder if this is ok.</p></li>
<li><p>Most of these classes don't have anything private. Should I use structures instead?</p></li>
<li><p>I should probably split this code into multiple files, one for each class definition.</p></li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T18:07:33.380",
"Id": "427527",
"Score": "0",
"body": "Hm, that's unexpected. It builds perfectly for me on my Windows 10/Visual Studio environment, not a single warning. I have pushed my whole solution to https://github.com/northernSage/ConsoleTetris so you can just clone it to your machine and try building it again with the same project properties I'm using, try building it on release mode though (I'm assuming you are on windows platform since this project has platform dependent code). Thanks for taking the time to look into it..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T18:21:56.190",
"Id": "427529",
"Score": "0",
"body": "Okay I spent a few seconds figuring it out. [I blame `_UNICODE`](https://softwareengineering.stackexchange.com/a/194768/297895). Of course this makes your application implementation defined."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T17:59:59.573",
"Id": "427699",
"Score": "2",
"body": "That already makes one thing I hadn't thought about that came up on this thread, I'm glad you mentioned it. It seems the trouble maker is my wchar_t *screen console buffer pointer, I wonder what is the advised way of getting around this problem..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:18:12.083",
"Id": "427806",
"Score": "2",
"body": "There is one huge overarching problem in the code, and that is your excessive use of `new`. You should not need any `new` in the code. Simple values like `Screen screenBuffer(80, 30);` and `std::vector` for some other places would improve this code a lot in terms of fixing the memory leaks, making the syntax nicer and the program faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:52:18.853",
"Id": "427957",
"Score": "0",
"body": "@Chipster Your points would make a great answer so please consider answering instead of commenting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:52:33.603",
"Id": "427958",
"Score": "0",
"body": "@nwp Same point as with Chipster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T02:29:38.727",
"Id": "428068",
"Score": "0",
"body": "@nwp Excelent point, I have just finished the changes [Console Tetris](https://github.com/northernSage/ConsoleTetris/blob/master/ConsoleTetris/old/ConsoleTetris.cpp). I'm now using a `std::vector` to store the tetromino pieces and the only two places left with `new` keyword are `wchar_t *screen` and `unsigned char *pField` pointers since in both occasions I need to allocate memory chunks of sizes `screenWidth * screenHeight` and `fieldHeight * fieldWidth` respectively at runtime and I don't know a better way of doing that in C++ (yet)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T03:33:54.063",
"Id": "428071",
"Score": "0",
"body": "Just realised I linked the wrong version above (silly me), here is the updated code with all the previous suggestions applied: [Console Tetris](https://github.com/northernSage/ConsoleTetris/blob/master/ConsoleTetris/ConsoleTetrisOO.cpp)"
}
] | [
{
"body": "<blockquote>\n <p>Overall code logistics. What would be the best (advised) way of interrelating my class objects? Should I pass references around as member variables (the way I did with my Tetris class, it has pointers to <code>screenBuffer</code> and <code>playingField</code> objects) and make most of the game functionality internal to my objects or make them as independent of one another as possible, bringing all together in my program's main function by accessing each object when needed (essentially pulling some of the programs functionality out of my objects)?</p>\n</blockquote>\n\n<p>I don't feel like an authoritative source enough to answer this one specifically, but if you want my opinion, I'm going to say make them separate. That way, because the objects don't overlap, you have more control at the upper level to do with them what you want. If you want to change how these objects interact, you can change the upper level without messing with the internal representation. If you need a new way for them to interact, you can just make a new method, and then you can keep the old way too, if you want, much easier.</p>\n\n<blockquote>\n <p>I'm using the this keyword a lot. It sure clutters the code a little bit. I'll go ahead and not use it at all. I wonder if this is ok.</p>\n</blockquote>\n\n<p>Yeah, that should be okay. The <code>this</code> keyword is generally to avoid confusion for data member names. So if you had, for example:</p>\n\n<pre><code>class foo {\n private:\n int x;\n public:\n void bar() {\n int x = 0;\n x = 5; // the function version of x\n this->x = 5; // the data member \"x\"\n }\n};\n</code></pre>\n\n<p>If you don't have any data members the same name as other variables in your function, you should be good. <code>this</code> is unnecessary in that case.</p>\n\n<blockquote>\n <p>Most of these classes don't have anything private. Should I use structures instead?</p>\n</blockquote>\n\n<p>Private data members don't usually have anything to do with structures, so I'm not sure I understand the question correctly. However, I will say that structures are not a replacement for private data members. I think you misunderstand how the OOP model works.</p>\n\n<p>Generally, private data members are reserved for data that no one else needs to see or access. Only the class will access these members via its own methods. If for some reason you need to access or manipulate these members, you need to make a public interface for them, that is, make special methods tasked with adjusting those private data members.</p>\n\n<p>If I'm understanding you right by \"<em>Should I use structures instead?</em>\", meaning should you copy your data members to a special structure to pass around, the answer is no. Just pass the object itself around, and let other functions use the public interface you defined for it instead.</p>\n\n<blockquote>\n <p>I should probably split this code into multiple files, one for each class definition.</p>\n</blockquote>\n\n<p>This isn't necessary, per say, but yes, it would probably be good to do eventually. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T03:27:49.857",
"Id": "428070",
"Score": "0",
"body": "What I mean by the third question is: Since the difference between a class and a struct in C++ are that structs have default public members and bases and classes have default private members and bases, if I don't have anything private in my class, wouldn't it be more natural to use a struct which is public by default? But now that I read it again, I used quite a shady choice of words for that 3rd question, sorry about that. The aspects you pointed make a lot of sense, specially the idea of not overlapping, it would also make my code easier to understand now that I think about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T20:15:31.003",
"Id": "428299",
"Score": "2",
"body": "Oh. I got you now. I don't know if I can answer that. I prefer classes still. in case I want to change it later, but I would imagine that's just a style choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-02T21:39:00.223",
"Id": "428456",
"Score": "0",
"body": "Final product [Console Tetris](https://github.com/northernSage/ConsoleTetris). After pulling all code responsible for interrelating objects out of my classes, I was left with four simple classes with no overlap and seven or so helper methods responsible for bringing the objects together into the main execution flow of the program. I bundled all these helper methods into a single utility class (this class has internal references for each relevant object), so to make them available under the same namespace, it seemed to be the most organised thing to do (feel free to correct me here)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-02T22:29:01.323",
"Id": "428463",
"Score": "0",
"body": "First of all, really cool. You did some really good cleaning up and organization. Second of all, if you're looking for more feed back after taking suggestions, [you can ask another question with the revised code](https://codereview.stackexchange.com/help/someone-answers) if you like. It will make things easier so no one ends up reviewing two different revisions at once. There will be less confusion that way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T01:58:30.967",
"Id": "428483",
"Score": "0",
"body": "Fair enough, here is the [follow up question](https://codereview.stackexchange.com/questions/221567/classic-tetris-implementation-for-windows-console-follow-up)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T14:24:13.720",
"Id": "428548",
"Score": "3",
"body": "@NorthernSage https://stackoverflow.com/a/54596/5416291"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T22:00:40.957",
"Id": "221370",
"ParentId": "221091",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "221370",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T03:24:37.167",
"Id": "221091",
"Score": "8",
"Tags": [
"c++",
"object-oriented",
"game",
"tetris"
],
"Title": "Classic Tetris implementation for Windows console"
} | 221091 |
<p>I have taken the code from a tutorial of Microsoft webpage.
Of course, the example is for illustration only but I wanted to organize it and make it clear in order to understand it a little more.</p>
<p>Here the link: <a href="https://docs.microsoft.com/en-us/windows/desktop/winsock/complete-server-code" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/windows/desktop/winsock/complete-server-code</a></p>
<p>It almost the same but structured diffently. It already works but I think it can be better. Any help or tip will be apreciated</p>
<pre><code>#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment (lib, "Ws2_32.lib")
#define DEFAULT_PORT "27016"
#define DEFAULT_BUFLEN 512
int receiveBuffer(SOCKET *ClientSocket)
{
char recvbuf[DEFAULT_BUFLEN];
int bytesReceived, iSendResult;
int recvbuflen = DEFAULT_BUFLEN;
// Receive until the peer shuts down the connection
do {
bytesReceived = recv(*ClientSocket, recvbuf, recvbuflen, 0);
if (bytesReceived > 0) {
printf("Bytes received: %d\n", bytesReceived);
// Echo the buffer back to the sender
iSendResult = send(*ClientSocket, recvbuf, bytesReceived, 0);
if (iSendResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
return 1;
}
printf("Bytes sent: %d\n", iSendResult);
} else if (bytesReceived == 0)
printf("Connection closing...\n");
else {
printf("recv failed: %d\n", WSAGetLastError());
return 1;
}
} while (bytesReceived > 0);
// shutdown the connection since we're done
bytesReceived = shutdown(*ClientSocket, SD_SEND);
if (bytesReceived == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
return 1;
}
return 0;
}
SOCKET acceptSocket(SOCKET *ListenSocket)
{
// Accept a client socket
SOCKET ClientSocket = accept(*ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WSAGetLastError());
//closesocket(ListenSocket);
//WSACleanup();
return INVALID_SOCKET;
}
return ClientSocket;
}
int listenSocket(SOCKET *ListenSocket, int backlog)
{
if ( listen( *ListenSocket, backlog ) == SOCKET_ERROR ) {
printf( "Listen failed with error: %ld\n", WSAGetLastError() );
//closesocket(ListenSocket);
return SOCKET_ERROR;
}
return 0;
}
SOCKET createSocket(struct addrinfo *result)
{
SOCKET ListenSocket = INVALID_SOCKET;
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
//freeaddrinfo(result);
return INVALID_SOCKET;
}
return ListenSocket;
}
int bindSocket(SOCKET *ListenSocket, struct addrinfo *result)
{
int iResult = bind( *ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
return SOCKET_ERROR;
}
return 0;
}
int initializeWinSock()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0) {
/* Tell the user that we could not find a usable */
/* Winsock DLL. */
printf("WSAStartup failed with error: %d\n", err);
return 1;
}
}
int prepareSocket(SOCKET *ListenSocket, SOCKET *ClientSocket, struct addrinfo *result)
{
initializeWinSock();
struct addrinfo hints;
int iResult;
int err;
ZeroMemory(&hints, sizeof (hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the local address and port to be used by the server
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
freeaddrinfo(result);
printf("getaddrinfo failed: %d\n", iResult);
return 1;
}
*ListenSocket = createSocket(result);
//SOCKET ClientSocket = INVALID_SOCKET;
err = bindSocket(ListenSocket, result);
freeaddrinfo(result);
if(err != 0) {
return 1;
}
err = listenSocket(ListenSocket, SOMAXCONN);
if(err != 0) {
return 1;
}
*ClientSocket = acceptSocket(ListenSocket);
if(*ClientSocket == INVALID_SOCKET) {
return 1;
}
err = receiveBuffer(ClientSocket);
if(err != 0) {
return 1;
}
}
int main(int argc, char const *argv[])
{
struct addrinfo *result = NULL;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
int err = prepareSocket(&ListenSocket, &ClientSocket, result);
WSACleanup();
closesocket(ListenSocket);
closesocket(ClientSocket);
if(err != 0) {
printf("There is an error, we're trying to solve it, goodbye\n");
return 1;
}
return 0;
}
<span class="math-container">````</span>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T05:14:54.903",
"Id": "221092",
"Score": "2",
"Tags": [
"c",
"socket",
"windows",
"server"
],
"Title": "Simple Socket Server in C for Windows"
} | 221092 |
<p>As the title states, this is my 4th revision of this class.
<a href="https://codereview.stackexchange.com/questions/220775/simple-ring-circular-buffer-c-class-v3">Here is the previous post if needed.</a></p>
<p>I'm hoping someone experienced with things such as <code>noexcept</code>, <code>[[nodiscard]]</code>, etc can go over the uses in the class below any make sure I'm on the right track?</p>
<p>Further more, I've attempted to implement the <a href="https://stackoverflow.com/a/3279550/4831051">copy and swap</a> and would like to know if my implementation looks accurate?</p>
<p>I've changed <code>data</code> private member variable to <code>std::array</code> from the previous "c-style" array, was that a reasonable thing to do?</p>
<p>I've noticed that <code>std::aligned_storage</code> is in <code><type_traits></code> which also appears to supply an <code>std::move</code> and <code>std::forward</code> but <a href="https://en.cppreference.com/w/cpp/utility/forward" rel="nofollow noreferrer">this</a> mentions forward is in <code><utility></code>, that site also shows <code>std::move</code> in <code><utility></code> or <code><algorithm></code> how do I know if I'm including the correct files?</p>
<p>I'm also looking for any feedback on overlooked bugs/problems with my implementation, as well as any other feature suggestions. (I'm attempting to use this class as a standard for my future work so I'm trying to pack as much knowledge into it as possible.)</p>
<pre><code>#pragma once // not looking for feedback on include guard.
#include <new> // std::launder
#include <array> // std::array
#include <cstddef> // std::size_t
#include <cassert> // assert
#include <type_traits> // std::aligned_storage_t, std::forward, std::move
#include "../LangMacros.h" // NO_DISCARD
namespace datastructures {
template<class T, std::size_t N>
class RingBuffer {
std::array<std::aligned_storage_t<sizeof(T), alignof(T)>, N> data;
std::size_t head;
std::size_t tail;
bool isFull;
NO_DISCARD T* ptr_to(std::size_t pos) noexcept {
return std::launder(reinterpret_cast<T*>(&data[pos]));
}
NO_DISCARD const T* ptr_to(std::size_t pos) const noexcept {
return std::launder(reinterpret_cast<const T*>(&data[pos]));
}
public:
// default
constexpr RingBuffer() noexcept :
data{},
head{0},
tail{0},
isFull{false} {
};
// copy
RingBuffer(const RingBuffer& other) :
data{},
head{other.head},
tail{other.tail},
isFull{other.isFull}
{
// can this function be noexcept?
if (!is_empty())
// ignore bug with this for loop iteration
for (std::size_t i = tail; i < head; i = (i + 1) % N)
new (&data[i]) T(*other.ptr_to(i)); // `other.data[i]` give cosnt _Ty which causes error, why?
}
// move
/* replaced with "swap-move" below instead
RingBuffer(RingBuffer&& other) :
data{},
head{other.head},
tail{other.tail},
isFull{other.isFull}
{
// note: not exception safe
if (!is_empty())
for (std::size_t i = tail; i < head; i = (i + 1) % N)
new (&data[i]) T(std::move(other.data[i]));
}
*/
// swap-move
RingBuffer(RingBuffer&& other) :
RingBuffer() // initialize via default constructor, C++11 only
{
swap(*this, other);
}
~RingBuffer() noexcept {
clear();
}
// using https://stackoverflow.com/a/3279550/4831051 as a reference, can this be constexpr / noexcept?
friend void swap(RingBuffer& first, RingBuffer& second) /*nothrow*/ {
using std::swap;
swap(first.data, second.data); //TODO is this safe?!
swap(first.head, second.head);
swap(first.tail, second.tail);
swap(first.isFull, second.isFull);
}
RingBuffer& operator=(RingBuffer other) {
swap(*this, other);
return *this;
}
void clear() noexcept {
while (!is_empty()) pop();
}
template<typename ...Args>
void emplace_push(Args&&... args) noexcept {
assert(!isFull && "error: buffer is full!");
new (&data[head]) T(std::forward<Args>(args)...);
head = (head + 1) % N;
isFull = head == tail;
}
void push(T item) noexcept {
emplace_push(std::move(item));
}
void pop() noexcept {
assert(!is_empty() && "error: buffer is empty!");
ptr_to(tail)->~T();
tail = (tail + 1) % N;
isFull = false;
}
NO_DISCARD constexpr T& peek() noexcept {
assert(!is_empty() && "error: buffer is empty!");
return *ptr_to(tail);
}
NO_DISCARD constexpr const T& peek() const noexcept {
assert(!is_empty() && "error: buffer is empty!");
return *ptr_to(tail);
}
NO_DISCARD constexpr bool is_empty() const noexcept {
return !isFull && tail == head;
}
NO_DISCARD constexpr std::size_t get_capacity() const noexcept {
return N;
}
NO_DISCARD constexpr std::size_t get_size() const noexcept {
if (isFull)
return N;
if (head >= tail)
return head - tail;
return N + head - tail;
}
};
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T09:47:26.477",
"Id": "427434",
"Score": "2",
"body": "There are two distinct function templates called `move`. The one you are looking for is declared in `<utility>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T00:17:54.230",
"Id": "427559",
"Score": "0",
"body": "@L.F.Thanks for that clarification."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T06:46:11.020",
"Id": "221094",
"Score": "4",
"Tags": [
"c++",
"c++17",
"circular-list"
],
"Title": "Simple ring/circular buffer c++ class V4"
} | 221094 |
<p>This is a <a href="https://leetcode.com/problems/word-search-ii/" rel="nofollow noreferrer">Leetcode problem</a> - </p>
<blockquote>
<p><em>Given a 2D board and a list of words from the dictionary, find all
words in the board.</em></p>
<p><em>Each word must be constructed from letters of a sequentially adjacent
cell, where "adjacent" cells are those horizontally or vertically
neighboring. The same letter cell may not be used more than once in a
word.</em></p>
<p><strong><em>Note:</em></strong></p>
<ul>
<li><em>All inputs are consist of lowercase letters <code>a-z</code>.</em> </li>
<li><em>The values of
<code>words</code> are distinct.</em></li>
</ul>
</blockquote>
<p>Here is my solution to this challenge - </p>
<blockquote>
<pre><code>class Solution:
def __init__(self, board, words):
self.board = board
self.words = words
def find_words(self, board, words):
root = {}
for word in words:
node = root
for c in word:
node = node.setdefault(c, {})
node[None] = True
board = {i + 1j * j: c
for i, row in enumerate(board)
for j, c in enumerate(row)}
found = []
def search(node, z, word):
if node.pop(None, None):
found.append(word)
c = board.get(z)
if c in node:
board[z] = None
for k in range(4):
search(node[c], z + 1j ** k, word + c)
board[z] = c
for z in board:
search(root, z, '')
return found
</code></pre>
</blockquote>
<p>Program explanation - I first build a tree of words with root <code>root</code> and also represent the board a different way, namely as a one-dimensional dictionary where the keys are complex numbers representing the row/column indexes. That makes further work with it easier. Looping over all board positions is just <code>for z in board</code>, the four neighbors of a board position <code>z</code> are just <code>z + 1j ** k</code> (for <code>k</code> in <code>0</code> to <code>3</code>), and I don't need to check borders because <code>board.get</code> just returns <code>None</code> if I request an invalid position.</p>
<p>After this preparation, I just take the tree and recursively dive with it into each board position. Similar to how you'd search a single word, but with the tree instead.</p>
<p>Here is an example input/output - </p>
<blockquote>
<pre><code>output = Solution([
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
], ["oath","pea","eat","rain"])
print(output.find_words([
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
], ["oath","pea","eat","rain"]))
>>> ['oath', 'eat']
</code></pre>
</blockquote>
<p>So, I would like to know whether I could make this program shorter and more efficient.</p>
<p>Any help would be highly appreciated.</p>
| [] | [
{
"body": "<p><strong>Awkward API</strong></p>\n\n<p>It seems strange to initialise a <code>Solution</code> object with various info that we provide again in the call of the method <code>find_words</code>.</p>\n\n<p>Actually, looking for places where <code>self</code> is used makes it pretty obvious: the instance is never used.</p>\n\n<p>It is a good occasion to watch the <a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow noreferrer\">Stop Writing Classes talk from Jack Diederich</a>.</p>\n\n<p><em>To be continued ?</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T09:48:51.500",
"Id": "221102",
"ParentId": "221099",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221102",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T08:23:02.270",
"Id": "221099",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge",
"tree"
],
"Title": "Python program for Word Search II"
} | 221099 |
<p>This is a <a href="https://leetcode.com/problems/remove-invalid-parentheses/" rel="nofollow noreferrer">Leetcode problem</a> - </p>
<blockquote>
<p><em>Remove the minimum number of invalid parentheses in order to make the
input string valid. Return all possible results.</em></p>
<p><strong><em>Note -</em></strong> </p>
<p><em>The input string may contain letters other than the parentheses <code>(</code>
and <code>)</code>.</em></p>
</blockquote>
<p>Here is my solution to this challenge - </p>
<blockquote>
<pre><code>def remove_invalid_parentheses(s):
removed = 0
results = {s}
count = {"(": 0, ")": 0}
for i, c in enumerate(s):
if c == ")" and count["("] == count[")"]:
new_results = set()
while results:
result = results.pop()
for j in range(i - removed + 1):
if result[j] == ")":
new_results.add(result[:j] + result[j + 1:])
results = new_results
removed += 1
else:
if c in count:
count[c] += 1
count = {"(": 0, ")": 0}
i = len(s)
ll = len(s) - removed
for ii in range(ll - 1, -1, -1):
i-=1
c = s[i]
if c == "(" and count["("] == count[")"]:
new_results = set()
while results:
result = results.pop()
for j in range(ii, ll):
if result[j] == "(":
new_results.add(result[:j] + result[j + 1:])
results = new_results
ll -= 1
else:
if c in count:
count[c] += 1
return list(results)
</code></pre>
</blockquote>
<p>Explanation - </p>
<ul>
<li>Scan from left to right, make sure <code>count["("] >= count[")"]</code>.</li>
<li>Then scan from right to left, make sure <code>count["("] <= count[")"]</code>.</li>
</ul>
<p>Here are some inputs/outputs - </p>
<blockquote>
<pre><code>print(remove_invalid_parentheses("()())()"))
>>> ["()()()", "(())()"]
print(remove_invalid_parentheses("(a)())()"))
>>> ["(a)()()", "(a())()"]
print(remove_invalid_parentheses(")("))
>>> [""]
</code></pre>
</blockquote>
<p>Here are the times taken for each output - </p>
<pre><code>%timeit remove_invalid_parentheses("()())()")
6.54 µs ± 176 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit remove_invalid_parentheses("(a)())()")
8.43 µs ± 1.29 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit remove_invalid_parentheses(")(")
3.69 µs ± 67.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code></pre>
<p>So, I would like to know whether I could make this program shorter and more efficient.</p>
<p>Any help would be highly appreciated.</p>
| [] | [
{
"body": "<p><strong>Test, consistent behavior & data structure</strong></p>\n\n<p>Trying to add tests for the code based on the example of input/output provided led to the following result: the behavior is not consistent : in particular the order of the elements in the returned list is not always the same.</p>\n\n<p>The root cause for this is that we are using sets in the logic only to convert to list at the end.</p>\n\n<p>A solution would be to return <code>sorted(results)</code> at the end. An alternative would be to just return a set instead of trying to convert to list.</p>\n\n<p>Then, we get the following automated tests:</p>\n\n<pre><code>print(remove_invalid_parentheses(\"()())()\") == {\"(())()\", \"()()()\"})\nprint(remove_invalid_parentheses(\"(a)())()\") == {\"(a())()\", \"(a)()()\"})\nprint(remove_invalid_parentheses(\")(\") == {\"\"})\n</code></pre>\n\n<p>It would make sense to try to rewrite it as unit-tests using a proper unit-test framework but I will stop here as this is enough for me to keep working.</p>\n\n<p><strong>More explicit loop</strong></p>\n\n<p>I tend to find loops based on <code>for ii in range(ll - 1, -1, -1)</code> very error-prone/hard to understand because of the number of tweaks on both sides of the range. I'd suggest a much more explicit alternative: <code>for ii in reversed(range(ll)):</code>.</p>\n\n<p><strong>Similar indices</strong></p>\n\n<p>As <code>ii</code> will go over <code>]ll, 0]</code> which is <code>]len(s) - removed, 0]</code>, i will go over <code>]len(s), removed]</code>.</p>\n\n<p>The difference between the indices is always <code>removed</code>, we have <code>ii + removed == i</code>: we can get rid of the <code>i</code> variable. We can take this chance to rename <code>ii</code> into <code>i</code>.</p>\n\n<p>At this stage, we have:</p>\n\n<pre><code>def remove_invalid_parentheses(s):\n removed = 0\n results = {s}\n count = {\"(\": 0, \")\": 0}\n for i, c in enumerate(s):\n if c == \")\" and count[\"(\"] == count[\")\"]:\n new_results = set()\n while results:\n result = results.pop()\n for j in range(i - removed + 1):\n if result[j] == \")\":\n new_results.add(result[:j] + result[j + 1:])\n results = new_results\n removed += 1\n elif c in count:\n count[c] += 1\n count = {\"(\": 0, \")\": 0}\n ll = len(s) - removed\n for i in reversed(range(ll)):\n c = s[i + removed]\n if c == \"(\" and count[\"(\"] == count[\")\"]:\n new_results = set()\n while results:\n result = results.pop()\n for j in range(i, ll):\n if result[j] == \"(\":\n new_results.add(result[:j] + result[j + 1:])\n results = new_results\n ll -= 1\n elif c in count:\n count[c] += 1\n return results\n\n\nprint(remove_invalid_parentheses(\"()())()\") == {\"(())()\", \"()()()\"})\nprint(remove_invalid_parentheses(\"()())))()\") == {\"(())()\", \"()()()\"})\nprint(remove_invalid_parentheses(\"(a)())()\") == {\"(a())()\", \"(a)()()\"})\nprint(remove_invalid_parentheses(\")(\") == {\"\"})\n</code></pre>\n\n<p>(I took this chance to add a new test case)</p>\n\n<p><strong>More explicit loop again</strong></p>\n\n<p>We want to iterate in reversed order over the beginning of the <code>s</code> string. Here again, we can try to make things more explicit and remove some computation as we go:</p>\n\n<pre><code> for i, c in enumerate(reversed(s[removed:])):\n if c == \"(\" and count[\"(\"] == count[\")\"]:\n new_results = set()\n while results:\n result = results.pop()\n for j in range(len(s) - i - removed - 1, ll):\n if result[j] == \"(\":\n new_results.add(result[:j] + result[j + 1:])\n results = new_results\n ll -= 1\n elif c in count:\n count[c] += 1\n</code></pre>\n\n<p>In order to test this more throughly, I took this chance to add the following test case:</p>\n\n<pre><code>print(remove_invalid_parentheses(\"((((((((()(\") == {\"()\"})\n</code></pre>\n\n<p><strong>More beautiful loops</strong></p>\n\n<p>Instead of using a combination of <code>while</code> and <code>pop</code> to iterate over the elements of a set, you can just use <code>for</code>:</p>\n\n<pre><code> for result in results:\n</code></pre>\n\n<p><em>Work in progress: I have to go. I may continue in the future.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T09:24:38.760",
"Id": "221244",
"ParentId": "221103",
"Score": "1"
}
},
{
"body": "<pre><code>> s = '()())()'\n> \n> \n> def set_par(s):\n> d = {}\n> updated_s = ''\n> counter_1 = 0\n> counter_2 = 0\n> for i in list(s):\n> if i == '(':\n> counter_1 += 1\n> if counter_1 - counter_2 == 1:\n> updated_s = updated_s + i\n> else:\n> counter_1 = counter_1 - 1\n> elif i == ')':\n> counter_2 += 1\n> if counter_1 == counter_2:\n> updated_s = updated_s + i\n> elif counter_2 > counter_1:`enter code here`\n> counter_2 = counter_2 - 1\n> \n> print updated_s\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T01:49:24.967",
"Id": "503541",
"Score": "2",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T01:01:26.673",
"Id": "255236",
"ParentId": "221103",
"Score": "-2"
}
}
] | {
"AcceptedAnswerId": "221244",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T09:52:08.277",
"Id": "221103",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge",
"balanced-delimiters"
],
"Title": "Python program to remove invalid parentheses"
} | 221103 |
<p>I wrote this 2048 game using Python 3 and pygame a few weeks ago. Since I'm getting into CS this summer, I would like to get some review on how I can improve my code in generel. Any tips and improvements are welcome, and highly appreciated.</p>
<p>The code is found below:</p>
<pre class="lang-py prettyprint-override"><code>import pygame
import random
class Main:
def __init__(self):
# SETUP pygame environment
pygame.init()
self.screen = pygame.display.set_mode((500,500))
pygame.display.set_caption('2048')
self.clock = pygame.time.Clock()
# Create the Board
self.board = Board()
#self.board.add_tile()
self.run()
def paint(self):
# Paint the background
self.screen.fill((240,240,206))
# Paint the board object to screen
self.board.paint(self.screen)
pygame.display.update()
# Handling pygame.QUIT event, and
# KEYDOWNS. Keydowns is parsed to board.move function
def eventhandler(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.board.move("LEFT")
if event.key == pygame.K_RIGHT:
self.board.move("RIGTH")
if event.key == pygame.K_UP:
self.board.move("UP")
if event.key == pygame.K_DOWN:
self.board.move("DOWN")
# Update function.
def update(self):
self.board.update_tiles()
# Main loop. 60 FPS
def run(self):
self.running = True
while self.running:
self.clock.tick(60)
self.eventhandler()
self.update()
self.paint()
class Tile:
def __init__(self,x,y,stage):
# SETUP tiles x,y and stage. Stage is the number it represents, 2,4,8 etc.
self.x = x
self.y = y
self.stage = stage
self.colorlist = [(245,240,255),(237,224,200),(242,177,121),(245,149,99),(246,124,95),(246,94,59),(237,207,113),(237,204,97),(237,200,80),(237,197,63),(238,205,94)]
# Move the tile to new x,y coordinates. Returns False if it moves into a wall.
def move_tile(self,x=0,y=0):
self.x += x
self.y += y
if self.x<0 or self.x > 3 or self.y < 0 or self.y > 3:
self.x -= x
self.y -=y
return False
return True
# Merge two tiles.
def merge(self,Tile):
if Tile.stage == self.stage:
self.increasestage()
return True
else:
return False
def increasestage(self):
self.stage += 1
# Draw the tile to Board.
def draw(self,screen,x,y,font):
pygame.draw.rect(screen,self.colorlist[self.stage-1],(x,y,87,87))
# draw the numbers on tiles:
if self.stage <= 2:
color = (120,110,101)
else:
color = (250,248,239)
text = font.render(str(2**self.stage),2,color)
screen.blit(text,(x+(87/2 - text.get_width()/2), y + (87/2 -text.get_height()/2)))
class Board:
def __init__(self):
## self.tiles keep track of the tiles GUI positions.
self.tiles = [[0,0,0,0] for i in range(4)]
self.board = pygame.Rect(50,50,400,400)
self.color = (186,173,160)
# tilearray stores the tiles as a list. When self.update_tiles is called
# the tiles in tile_array gets updated in self.tiles (the tiles GUI position)
self.tilearray = []
self.add_tile()
self.add_tile()
self.font = pygame.font.SysFont('comicsans',61)
#Draw the board background to screen.
def paint(self,screen):
pygame.draw.rect(screen,self.color,self.board)
self.drawtiles(screen)
# Draw tiles to screen. If no tile, draw empty square.
def drawtiles(self,screen):
for i,array in enumerate(self.tiles):
for j,tile in enumerate(array):
if tile == 0:
pygame.draw.rect(screen,(204,193,180),(60+i*87+10*i,60+j*87+10*j,87,87))
else:
tile.draw(screen,60+i*87+10*i,60+j*87+10*j,self.font)
# Returns an arraylist with positions in self.tiles which are empty
def get_empty_spaces(self):
empty = []
for i,array in enumerate(self.tiles):
for j,tile in enumerate(array):
if tile==0:
empty.append([i,j])
return empty
# Add a new tile to the game. Coordinates chosen at random.
def add_tile(self):
empty = self.get_empty_spaces()
chosen = random.choice(empty)
if random.randrange(1,100) <10:
stage = 2
else:
stage = 1
t = Tile(chosen[0],chosen[1],stage)
self.tilearray.append(t)
# Move all tiles on the board.
def move(self,key):
stepstaken = 0
if key=="LEFT":
for i, array in enumerate(self.tiles):
for j, _ in enumerate(array):
tile = self.tiles[j][i]
if tile!=0:
stepstaken += self.move_single_tile(tile,-1,0)
self.update_tiles()
if key =="RIGTH":
for i,array in enumerate(self.tiles):
for j,_ in enumerate(array):
tile = self.tiles[3-j][3-i]
if tile!= 0:
stepstaken += self.move_single_tile(tile,1,0)
self.update_tiles()
if key == "UP":
for i,array in enumerate(self.tiles):
for j,_ in enumerate(array):
tile = self.tiles[i][j]
if tile!=0:
stepstaken += self.move_single_tile(tile,0,-1)
self.update_tiles()
if key == "DOWN":
for i, array in enumerate(self.tiles):
for j,_ in enumerate(array):
tile = self.tiles[3-i][3-j]
if tile!=0:
stepstaken += self.move_single_tile(tile,0,1)
self.update_tiles()
if stepstaken>0:
self.add_tile()
# Tiles are stored in self.tilearray. When updating, the tiles from self.tilearray is
# stored in the 2d array.
def move_single_tile(self,tile,vx=0,vy=0):
steps = 0
for i in range(0,3):
if self.position_is_inside_grid(tile.x+vx,tile.y+vy) and self.tile_is_empty(tile.x+vx,tile.y+vy):
tile.move_tile(vx,vy)
steps+=1
else:
if self.position_is_inside_grid(tile.x+vx,tile.y+vy) and self.tiles[tile.x+vx][tile.y+vy].merge(tile):
self.tilearray.remove(tile)
steps += 1
return steps
def position_is_inside_grid(self,x,y):
if x>-1 and x<4 and y>-1 and y<4:
return True
else:
return False
def tile_is_empty(self,x,y):
if self.tiles[x][y] == 0:
return True
else:
return False
def update_tiles(self):
self.tiles = [[0,0,0,0] for i in range(4)]
for tile in self.tilearray:
self.tiles[tile.x][tile.y] = tile
m = Main()
# TO DO
# Refactor move() to loop functions
#
#
#
</code></pre>
| [] | [
{
"body": "<p>The code looks good, but the</p>\n\n<pre><code>if key==\"LEFT\":\n for i, array in enumerate(self.tiles):\n for j, _ in enumerate(array):\n tile = self.tiles[j][i]\n if tile!=0:\n stepstaken += self.move_single_tile(tile,-1,0)\n self.update_tiles()\n\n if key ==\"RIGTH\":\n for i,array in enumerate(self.tiles):\n for j,_ in enumerate(array):\n tile = self.tiles[3-j][3-i]\n if tile!= 0:\n stepstaken += self.move_single_tile(tile,1,0)\n self.update_tiles()\n</code></pre>\n\n<p>has some redundant loops. You can move the if statement so the array looping os only written once.</p>\n\n<pre><code>for i, array in enumerate(self.tiles):\nfor j, _ in enumerate(array):\n if key==\"LEFT\":\n tile = self.tiles[j][i]\n if tile!=0:\n stepstaken += self.move_single_tile(tile,-1,0)\n self.update_tiles()\n if key ==\"RIGTH\":\n tile = self.tiles[3-j][3-i]\n if tile!= 0:\n stepstaken += self.move_single_tile(tile,1,0)\n self.update_tiles()\n</code></pre>\n\n<p>I also recommend to use <a href=\"https://www.geeksforgeeks.org/enum-in-python/\" rel=\"nofollow noreferrer\">Enums</a> for the directions.</p>\n\n<p>When you replace the</p>\n\n<pre><code>m = Main()\n</code></pre>\n\n<p>with</p>\n\n<pre><code>if __name__ == \"__main__\":\n m = Main();\n</code></pre>\n\n<p>This allows you to import this file for example to use the Board class for another project. Otherwise the whole game would run on import.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:01:18.087",
"Id": "221262",
"ParentId": "221107",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T11:13:29.583",
"Id": "221107",
"Score": "2",
"Tags": [
"python",
"game",
"pygame",
"2048"
],
"Title": "2048 game in Python 3"
} | 221107 |
<p>I've tried to solve this challenge about 4 hours during the contest, but all my attempts exceeded the time limit. I tried to solve it with min-heap, but can't pass all the tests. How it can be solved within given time and space requirements?</p>
<blockquote>
<p><strong>Problem statement</strong></p>
<p>Programmer Alexey likes to work at night and does not like to come to
work late. In order to precisely wake up in the morning, Alexey every
evening starts <span class="math-container">\$N\$</span> alarm clocks on his phone. Each alarm clock is
arranged in such a way that it rings every <span class="math-container">\$X\$</span> minutes from the time
at which it was turned on.</p>
<p>For example, if the alarm clock was started at the moment of time
<span class="math-container">\$t_i\$</span>, then it will ring at the moments of time <span class="math-container">\$t_i, t_i + X, t_i + 2 * X\$</span> and so on. Moreover, if some two alarms begin to ring at one time, only one of them is displayed.</p>
<p>It is known that before waking up, Alexey listens every morning to
exactly <span class="math-container">\$K\$</span> alarm clocks, and then wakes up. Determine the point in
time when Alex wakes up.</p>
<p><strong>Input format</strong></p>
<p>Input format The first line contains three integers. <span class="math-container">\$N, X\$</span> and <span class="math-container">\$K\$</span> <span class="math-container">\$(1 ≤ N ≤10^5, 1≤X, K≤10^9)\$</span> - the number of alarms, the frequency of
calls and the number of alarms that need to be turned off in order for
Alex to wake up. The second line contains N integers - the points in
time at which the alarm clocks were entered.</p>
<p><strong>Requirements</strong></p>
<pre><code>Time limit: 2 seconds
Memory limit: 256Mb
</code></pre>
<p><strong>Examples</strong></p>
<p>Example 1</p>
<p>Input</p>
<pre><code>6 5 10
1 2 3 4 5 6
</code></pre>
<p>Output <code>10</code></p>
<p>Example 2</p>
<p>Input</p>
<pre><code>5 7 12
5 22 17 13 8
</code></pre>
<p>Output <code>27</code></p>
<p>Notes</p>
<p>In the second example, there are 5 alarm clocks with a frequency of 7
calls. For example, the first alarm clock will ring at times 5, 12,
19, 26, 33, etc. If you look at all the alarms at the same time, they
will ring at the following times: 5, 8, 12, 13, 15, 17, 19, 20, 22
(2nd and 5th alarm clocks at the same time), 24, 26, 27, 29,…. On the
12th call Alexey must wake up, What corresponds to the point in time
27.</p>
</blockquote>
<p><strong>My solution</strong></p>
<p>Classified as "time limit exceeded"</p>
<pre><code>import heapq
def main():
n, x, k = map(int, input().split(" "))
times = list(map(int, input().split(" ")))
heapq.heapify(times)
answers = []
while k:
v = heapq.heappop(times)
heapq.heappush(times, v + x)
if len(answers) == 0 or answers[len(answers)-1] != v:
answers.append(v)
k -= 1
print(answers[k-1])
if __name__ == "__main__":
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T18:12:33.447",
"Id": "427704",
"Score": "1",
"body": "Did you write this for Python 2 or 3?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T18:30:48.743",
"Id": "427709",
"Score": "1",
"body": "I used Python 3.7"
}
] | [
{
"body": "<p>The minheap approach seems correct. The problem is in the <code>answers</code>. It may grow quite large (up to <span class=\"math-container\">\\$10^9\\$</span>). All the reallocations due to its growth are very costly.</p>\n\n<p>However you don't need it at all. You only care about the time of the most recent alarm. Just one value:</p>\n\n<pre><code> while k:\n v = heapq.heappop(times)\n heapq.heappush(times, v + x)\n\n if last_alarm != v:\n last_alarm = v\n k -= 1\n</code></pre>\n\n<p>That said, an idiomatic way to access the last element of the list is <code>answers[-1]</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T14:32:58.153",
"Id": "427493",
"Score": "2",
"body": "Exactly! But, I suppose iterating over `k` is not a right approach too: `for i in range(10 ** 9): pass` takes more than 2s."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T14:08:43.640",
"Id": "221117",
"ParentId": "221113",
"Score": "10"
}
},
{
"body": "<p>Not all counting problems require enumerating the items being counted. If you were asked to count how many sheep there are in total if there are <span class=\"math-container\">\\$n\\$</span> trucks with <span class=\"math-container\">\\$k\\$</span> sheep each, you could write something like:</p>\n\n<pre><code>total_sheep = 0\nfor truck in range(n):\n for sheep in range(k):\n total_sheep += 1\n</code></pre>\n\n<p>Or you could cut to the chase and compute it as:</p>\n\n<pre><code>total_sheep = n * k\n</code></pre>\n\n<p>The problem you are trying to solve is more subtle, but can be attacked in a similar fashion. <a href=\"https://en.wikipedia.org/wiki/Modular_arithmetic\" rel=\"noreferrer\">Modular arithmetic</a> will be your friend in doing this. Rather than looking at the setting times as single numbers, convert them to tuples of <code>(quotient, remainder)</code> after dividing by <span class=\"math-container\">\\$X\\$</span>. This would e.g. convert the list of times for the second example into:</p>\n\n<pre><code> 5 --> (0, 5)\n22 --> (3, 1)\n17 --> (2, 3)\n13 --> (1, 6)\n 8 --> (1, 1)\n</code></pre>\n\n<p>We can use this information to prune the list of alarms: if any two alarms have the same remainder, they will ring at the same time, so we only need to keep the smaller one. This would convert the above list, after also sorting it, into:</p>\n\n<pre><code> 5 --> (0, 5)\n 8 --> (1, 1)\n13 --> (1, 6)\n17 --> (2, 3)\n</code></pre>\n\n<p>Those two numbers tell us in which of the <span class=\"math-container\">\\$X\\$</span> minute periods the alarm sounds for the first time, and at what offset into that period does it first go off. So we can process it sequentially and know that:</p>\n\n<ul>\n<li>at the end of the first (0) period, 1 alarm has sounded for the first time, a total of 1 alarm will sound in every subsequent period, and the total number of alarms sounded is also 1.</li>\n<li>at the end of the second (1) period, 2 alarms have sounded for the first time, 3 alarms will sound in every subsequent period, and the total number of alarms sounded is 4.</li>\n<li>at the end of the third (2) period, 1 new alarm has sounded, 4 alarms will sound every period, and a total of 8 alarms will have sounded.</li>\n</ul>\n\n<p>Since there are no more alarms to process, we have 8 alarms so far, 4 more sounding each period, and want to reach a total of 12, some simple math tells us that this will happen during the fourth (3) period, and that it will be the last of the alarms that will reach it.</p>\n\n<p>To make the math more clear, lets imagine that we wanted to reach a total of 14 alarms instead. Since 8 have already sounded, we have 14 - 8 = 6 more to go. Since 4 alarms will sound in each period, and the quotient and remainder of 6 divided by 4 are 1 and 2, we know that we will reach our target after 1 full more period, plus 2 of the four alarms in the next period. This translates to 4 full periods, plus the time for the second alarm in that period to sound. The time of 4 full periods is 7 * 4 = 28. We need to add the offset of the second alarm <strong>when sorting them by offset, not by start time</strong>, so we need to add 3, not 1, and the end result would be 31.</p>\n\n<p>This general outline omits many gruesome details, like what to do if we reach the target number of alarms before we finish processing the list. And the math described above is hard to get right in all corner cases, as there are many chances for off-by-one errors. I'm not going to spoil the fun for you by coding it up: give a try, and I'll be happy to review your next version.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T00:05:20.370",
"Id": "427557",
"Score": "7",
"body": "Yes, math is the way. I believe the condition \"K < 10^9\" was intended as a subtle hint that iteration is not a viable approach. A billion alarms to wake up: that's my hero :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T08:59:59.013",
"Id": "427591",
"Score": "0",
"body": "This looks like a nice exercise for learning to handle data structures in python."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T15:27:18.893",
"Id": "221129",
"ParentId": "221113",
"Score": "13"
}
}
] | {
"AcceptedAnswerId": "221129",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T12:52:39.923",
"Id": "221113",
"Score": "17",
"Tags": [
"python",
"algorithm",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Yandex programming contest: Alarms"
} | 221113 |
<p>During implementation and testing of different small hobby projects I often reach the point where I need (at least I like it more) some random data beyond the usual foo-bar strings or lists. <em>Random</em> here does not mean really mathematical random data but just something that looks random to humans.</p>
<p>Therefore I came up with the following:</p>
<pre><code>;;;; random.lisp
;;; Time-stamp: <2019-05-27 14:53:38 m.buchmann>
;;;
;;; A short sketch of some random data generating functions.
;;;
(ql:quickload "alexandria")
;; * Choosing a random element from a given list.
(defun random-draw (list &aux (len (length list)) (pos (random len)))
"Returns a random element from LIST."
(nth pos list))
;;; * Generating a random element
(defun random-element (type &key (radix 10) (case :up))
"Returns a random element of type :digit (depending on :radix) or
:character (case given by :case :up, :down or :both). Limited to
7bit ASCII characters from A to z."
(let ((char-range (ecase case
(:up (alexandria:iota 26 :start 65))
(:down (alexandria:iota 26 :start 97))
(:both (append (alexandria:iota 26 :start 65)
(alexandria:iota 26 :start 97))))))
(ecase type
(:digit (random radix))
(:character (code-char (random-draw char-range))))))
(defun random-list (len &key (type :digit) (radix 10) (case :up))
"Returns a list of length LEN filled with random elements of TYPE :digit or :character."
(loop :for i from 0 below len
:collect (random-element type :radix radix :case case)))
(defun random-string (len &key (case :up) &aux (result (make-array len :element-type 'character)))
"Returns a random string of length LEN and :case (:up, :down or :both)."
(loop :for i :from 0 :below len
:do (setf (aref result i) (random-element :character :case case)))
result)
</code></pre>
<p>I did not pack it in a proper package etc. yet because my use case is pretty simple and usually temporary. I was wondering if other people have implemented similar things or if the need I felt was just so individual that no one else really cares about it. I did not find other libraries for this. </p>
<p>I think it could be easily extended to supply random-arrays, hash-tables and so on. Also the character encoding could be improved to deliver more than 7bit ASCII and this in a portable way. </p>
<p>Any comments on the usability, style etc. are gratefully acknowledged.</p>
| [] | [
{
"body": "<p>Note that <a href=\"https://gitlab.common-lisp.net/alexandria/alexandria\" rel=\"nofollow noreferrer\"><em>Alexandria</em></a> defines <code>random-elt</code> (and <code>whichever</code>).</p>\n\n<p>My only complain is that <code>random-element</code> does too much, both digits and characters.\nThis would be the kind of use cases where I would rely on generic functions:</p>\n\n<pre><code>(defgeneric generate (type &key &allow-other-keys))\n\n(defmethod generate ((type (eql :number/offset)) &key offset length)\n (+ offset (random length)))\n\n(defmethod generate ((type (eql :number/around)) &key (origin 0) (length 1.0))\n (generate :number/offset\n :offset (- origin (/ length 2))\n :length length))\n\n(defmethod generate ((type (eql :ascii)) &key case)\n (multiple-value-bind (offset length)\n (ecase case\n (:down (values 97 26))\n (:up (values 65 26))\n (:both (values 65 52)))\n (code-char\n (generate :number/offset :offset offset :length length))))\n\n(defmethod generate ((type (eql :digit)) &key radix)\n (random radix))\n\n(defmethod generate ((type (eql :choose-from)) &key sequence)\n (random-elt sequence))\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>(list (generate :ascii :case :up)\n (generate :digit :radix 8)\n (generate :number/around :origin 0 :length 10)\n (generate :choose-from :sequence #(5 6 8)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T11:56:30.147",
"Id": "427598",
"Score": "1",
"body": "Using generic functions is the right way here, of course. Thanks for reminding me ;-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T15:25:59.893",
"Id": "221128",
"ParentId": "221114",
"Score": "1"
}
},
{
"body": "<p>Within python there is the faker package creating \"human\" data. It's often used for testing and can easily be extended to your personal needs:</p>\n\n<p><a href=\"https://github.com/joke2k/faker\" rel=\"nofollow noreferrer\">Link to github</a></p>\n\n<p>It also has a command line interface. Here is the example from the official <a href=\"https://faker.readthedocs.io/en/master/\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<pre><code>$ faker address\n968 Bahringer Garden Apt. 722\nKristinaland, NJ 09890\n\n$ faker -l de_DE address\nSamira-Niemeier-Allee 56\n94812 Biedenkopf\n\n$ faker profile ssn,birthdate\n{'ssn': u'628-10-1085', 'birthdate': '2008-03-29'}\n\n$ faker -r=3 -s=\";\" name\nWillam Kertzmann;\nJosiah Maggio;\nGayla Schmitt;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T16:13:02.283",
"Id": "221135",
"ParentId": "221114",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221128",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T13:11:59.030",
"Id": "221114",
"Score": "2",
"Tags": [
"strings",
"random",
"common-lisp"
],
"Title": "Generating a list (or a string) with random elements"
} | 221114 |
<p>I'm trying to optimize my solution to <a href="https://codingcompetitions.withgoogle.com/kickstart/round/0000000000050ff2/0000000000150aac" rel="nofollow noreferrer">Wiggle Walk</a> for Kickstart's round 1C. </p>
<blockquote>
<p><strong>Problem</strong></p>
<p>Banny has just bought a new programmable robot. Eager to test his
coding skills, he has placed the robot in a grid of squares with R
rows (numbered 1 to R from north to south) and C columns (numbered 1
to C from west to east). The square in row r and column c is denoted
(r, c).</p>
<p>Initially the robot starts in the square (SR, SC). Banny will give the
robot N instructions. Each instruction is one of N, S, E or W,
instructing the robot to move one square north, south, east or west
respectively.</p>
<p>If the robot moves into a square that it has been in before, the robot
will continue moving in the same direction until it reaches a square
that it has not been in before. Banny will never give the robot an
instruction that will cause it to move out of the grid.</p>
<p>Can you help Banny determine which square the robot will finish in,
after following the N instructions? </p>
<p><strong>Input</strong></p>
<p>The first line of the input gives the number of test cases, T. T test
cases follow. Each test case starts with a line containing the five
integers N, R, C, SR and SC, the number of instructions, the number of
rows, the number of columns, the robot's starting row and starting
column, respectively.</p>
<p>Then, another line follows containing a single string of N characters;
the i-th of these characters is the i-th instruction Banny gives the
robot (one of N, S, E or W, as described above). </p>
<p><strong>Output</strong></p>
<p>For each test case, output one line containing Case #x: r c, where x
is the test case number (starting from 1), r is the row the robot
finishes in and c is the column the robot finishes in. </p>
<p><strong>Limits</strong></p>
<p>Memory limit: 1GB. 1 ≤ T ≤ 100. 1 ≤ R ≤ 5 × 104. 1 ≤ C ≤ 5 × 104. 1 ≤
SR ≤ R. 1 ≤ SC ≤ C. The instructions will not cause the robot to move
out of the grid. Test set 1 (Visible)</p>
<p>Time limit: 20 seconds. 1 ≤ N ≤ 100. Test set 2 (Hidden)</p>
<p>Time limit: 60 seconds. 1 ≤ N ≤ 5 × 104.</p>
</blockquote>
<p>Here's my current solution:</p>
<pre><code>def main():
T = int(input()) # the number of test cases
for case in range(1, T+1):
N, R, C, r, c = map(int, input().split())
instructions = input() # string of N, S, E or W
seen = {(r, c)}
for i in instructions:
if i == 'N':
r -= 1
while (r, c) in seen:
r -= 1
elif i == 'S':
r += 1
while (r, c) in seen:
r += 1
elif i == 'E':
c += 1
while (r, c) in seen:
c += 1
else: # 'W'
c -= 1
while (r, c) in seen:
c -= 1
seen.add((r, c))
print('Case #{}: {} {}'.format(case, r, c))
main()
</code></pre>
<p>How can I represent visited areas in the grid so that getting the destination cell for each instruction would be faster?</p>
| [] | [
{
"body": "<p>A simple dictionary will do once you get the idea ;)</p>\n\n<pre><code>def get_neighbor(r, c, i, neighbors):\n if (r, c, i) in neighbors:\n return neighbors[(r, c, i)]\n\n if i == 'N':\n return (r - 1, c)\n elif i == 'S':\n return (r + 1, c)\n elif i == 'E':\n return (r, c + 1)\n else: # 'W'\n return (r, c - 1)\n\n\ndef link_neighbors(r, c, neighbors):\n north = get_neighbor(r, c, 'N', neighbors)\n south = get_neighbor(r, c, 'S', neighbors)\n east = get_neighbor(r, c, 'E', neighbors)\n west = get_neighbor(r, c, 'W', neighbors)\n\n neighbors[(*north, 'S')] = south\n neighbors[(*south, 'N')] = north\n neighbors[(*east, 'W')] = west\n neighbors[(*west, 'E')] = east\n\n\ndef main():\n T = int(input()) # the number of test cases\n\n for case in range(1, T+1):\n N, R, C, r, c = map(int, input().split())\n instructions = input() # string of N, S, E or W\n neighbors = {}\n\n for i in instructions:\n link_neighbors(r, c, neighbors)\n r, c = get_neighbor(r, c, i, neighbors) # new position\n\n print('Case #{}: {} {}'.format(case, r, c))\n\n\nmain()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-02T07:49:11.843",
"Id": "221524",
"ParentId": "221119",
"Score": "4"
}
},
{
"body": "<p>I have participated in Google kickstart wiggle walk.</p>\n\n<p>I have optimized the solution to be <span class=\"math-container\">\\$\\mathcal{O}(N\\times logN)\\$</span> but it's still getting \"time limit exceeded\".</p>\n\n<pre><code>#include<stdio.h>\n#include<stdlib.h>\nint main()\n{\n int t, n ,*arr, r , c, sr,sc,i=0;\n arr=(int*)malloc(5*sizeof(int));\n char temp;\n scanf(\"%d\",&t);\n int z=1;\n while(z<=t)\n {\n int k=0;\n do {\n scanf(\"%d%c\",arr+k,&temp);\n k++;\n } while(temp!='\\n');\n n=*(arr);\n r=*(arr+1);\n c=*(arr+2);\n sr=*(arr+3);\n sc=*(arr+4);\n char *string;\n string =(char*)malloc(n*sizeof(char));\n int *grid = (int *)malloc(r * c * sizeof(int));\n int *northgrid =(int *)malloc(r * c * sizeof(int));\n int *southgrid = (int *)malloc(r * c * sizeof(int));\n int *eastgrid =(int *)malloc(r * c * sizeof(int));\n int *westgrid = (int *)malloc(r * c * sizeof(int));\n int current_sr,current_sc;\n *(grid + sr*c + sc)=1;\n for(int j=0; j<n; j++)\n {\n scanf(\"%c\",string+j);\n current_sr = sr;\n current_sc = sc;\n\n if(*(string+j)=='N')\n {\n do\n {\n if(*(northgrid + sr*c + sc)==0)\n {\n\n sr--;\n\n }\n else if(*(northgrid + sr*c + sc)!=0)\n {\n while(*(northgrid + sr*c + sc)!=0)\n {\n sr=*(northgrid + sr*c + sc);\n }\n }\n } while(*(grid + sr*c + sc)==1);\n *(grid + sr*c + sc)=1;\n *(southgrid+ sr*c + sc)=current_sr;\n *(northgrid+current_sr*c+current_sc)=sr;\n }\n else if(*(string+j)=='S')\n {\n do\n {\n if(*(southgrid + sr*c + sc)==0)\n {\n\n sr++;\n\n }\n else if(*(southgrid + sr*c + sc)!=0)\n {\n while(*(southgrid + sr*c + sc)!=0)\n {\n sr=*(southgrid + sr*c + sc);\n }\n }\n } while(*(grid + sr*c + sc)==1);\n *(grid + sr*c + sc)=1;\n *(northgrid+ sr*c + sc)=current_sr;\n *(southgrid+current_sr*c+current_sc)=sr;\n }\n else if(*(string+j)=='E')\n {\n do\n {\n if(*(eastgrid + sr*c + sc)==0)\n {\n\n sc++;\n\n }\n else if(*(eastgrid + sr*c + sc)!=0)\n {\n while(*(eastgrid + sr*c + sc)!=0)\n {\n sr=*(eastgrid + sr*c + sc);\n }\n }\n } while(*(grid + sr*c + sc)==1);\n *(grid + sr*c + sc)=1;\n *(westgrid+ sr*c + sc)=current_sc;\n *(eastgrid+current_sr*c+current_sc)=sc;\n }\n else if(*(string+j)=='W')\n {\n do\n {\n if(*(westgrid + sr*c + sc)==0)\n {\n\n sc--;\n\n }\n else if(*(westgrid + sr*c + sc)!=0)\n {\n while(*(westgrid + sr*c + sc)!=0)\n {\n sc=*(westgrid + sr*c + sc);\n }\n }\n } while(*(grid + sr*c + sc)==1);\n *(grid + sr*c + sc)=1;\n *(eastgrid+ sr*c + sc)=current_sc;\n *(westgrid+current_sr*c+current_sc)=sc;\n }\n // printf(\"Values are: %d , %d\",sr,sc);\n }\n printf(\"Case #%d: %d %d\\n\",z,sr,sc);\n\n z++ ;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T19:49:07.447",
"Id": "434145",
"Score": "2",
"body": "Please do something about the formatting. Your entire question is one big code block. That being said, is this an answer to the question? Check out the help center: https://codereview.stackexchange.com/help/how-to-answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T20:15:45.800",
"Id": "434147",
"Score": "2",
"body": "You have presented an alternative solution to the problem in another language, but have not reviewed the code (see [Why are alternative solutions not welcome?](https://codereview.meta.stackexchange.com/q/8403/92478)). And also have a look at [answer], which was already pointed out to you in the previous comment. To me it sounds more like you should ask this as a new question here on Code Review."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T19:40:23.403",
"Id": "223896",
"ParentId": "221119",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "221524",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T14:14:29.837",
"Id": "221119",
"Score": "3",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Solution to Kickstart's Wiggle Walk"
} | 221119 |
<p>An assignment at school required me to print all permutations of a string in lexicographic or dictionary order.</p>
<p>Here is my solution to the task - </p>
<pre><code>from math import factorial
def print_permutations_lexicographic_order(s):
seq = list(s)
for _ in range(factorial(len(seq))):
print(''.join(seq))
nxt = get_next_permutation(seq)
# if seq is the highest permutation
if nxt is None:
# then reverse it
seq.reverse()
else:
seq = nxt
def get_next_permutation(seq):
"""
Return next greater lexicographic permutation. Return None if cannot.
This will return the next greater permutation of seq in lexicographic order. If seq is the highest permutation then this will return None.
seq is a list.
"""
if len(seq) == 0:
return None
nxt = get_next_permutation(seq[1:])
# if seq[1:] is the highest permutation
if nxt is None:
# reverse seq[1:], so that seq[1:] now is in ascending order
seq[1:] = reversed(seq[1:])
# find q such that seq[q] is the smallest element in seq[1:] such that
# seq[q] > seq[0]
q = 1
while q < len(seq) and seq[0] > seq[q]:
q += 1
# if cannot find q, then seq is the highest permutation
if q == len(seq):
return None
# swap seq[0] and seq[q]
seq[0], seq[q] = seq[q], seq[0]
return seq
else:
return [seq[0]] + nxt
s = input('Enter the string: ')
print_permutations_lexicographic_order(s))
</code></pre>
<p>Here are some example inputs/outputs:</p>
<pre><code>Enter the string: cow
>>> cow
cwo
ocw
owc
wco
woc
Enter the string: dogs
>>> dogs
dosg
dsgo
dsog
gdos
gdso
gods
gosd
gsdo
gsod
odgs
odsg
ogds
ogsd
osdg
osgd
sdgo
sdog
sgdo
sgod
sodg
sogd
ogds
ogsd
</code></pre>
<p>So, I would like to know whether I could make my program shorter and more efficient.</p>
<p>Any help would be highly appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T16:16:29.730",
"Id": "427506",
"Score": "0",
"body": "Why the downvote :( Is anything wrong with the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T16:25:36.960",
"Id": "427508",
"Score": "0",
"body": "I didn't downvote, but I notice that the 2nd example is wrong. \"dgos\" and \"dgso\" are missing while \"ogds\" and \"ogsd\" occur twice. Also the tag \"dictionary\" refers to the data structure, not dictionary order."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T16:28:51.907",
"Id": "427510",
"Score": "0",
"body": "I've edited the tags, [tag:performance] doesn't look like an aim, since your code doesn't look to care too much about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T18:03:51.287",
"Id": "427526",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. The moment answers arrive, you stop touching the code. That's the rules. It gets awfully messy otherwise."
}
] | [
{
"body": "<p>And <a href=\"https://codereview.stackexchange.com/a/220814/201170\">in the third time</a> I will recommend you the <a href=\"https://docs.python.org/3/library/itertools.html?highlight=itertools\" rel=\"noreferrer\">itertools</a> module:</p>\n\n<blockquote>\n <p>As I told in another answers, your code is very C/C++ styled, it is not Pythonic. Try to avoid manual iteration with indices as much as possible. Python has an enormous standard library that contains many useful modules. I already recommended you an itertools module. It contains pair of dozens generic functions to work with iterators. One of them - permutations - do 90% of your work:</p>\n</blockquote>\n\n<p>And in the second time I will recommend you the <a href=\"https://docs.python.org/3/library/itertools.html?highlight=itertools#itertools.permutations\" rel=\"noreferrer\">itertools.permutations</a> function that can solve your problem with <em>literally</em> one line of code:</p>\n\n<pre><code>from itertools import permutations\n\ndef get_lexicographic_permutations(s):\n return sorted(''.join(chars) for chars in permutations(s))\n\nprint(get_lexicographic_permutations('dogs'))\n</code></pre>\n\n<blockquote>\n <p><code>['dgos', 'dgso', 'dogs', 'dosg', 'dsgo', 'dsog', 'gdos', 'gdso', 'gods', 'gosd', 'gsdo', 'gsod', 'odgs', 'odsg', 'ogds', 'ogsd', 'osdg', 'osgd', 'sdgo', 'sdog', 'sgdo', 'sgod', 'sodg', 'sogd']</code></p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T16:01:26.277",
"Id": "427502",
"Score": "2",
"body": "Title says he's supposed to use recursion though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T16:14:24.567",
"Id": "427504",
"Score": "1",
"body": "@Sedsarq The question isn't tagged with [tag:reinventing-the-wheel], and doesn't state they have to use recursion. It is also tagged [tag:performance], and this is almost definitely _more performant_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T16:17:58.327",
"Id": "427507",
"Score": "0",
"body": "@Peilonrayz That's a fair point. I read the title to mean that the program *should* involve recursion, but it could just as well mean simply that his version *does*."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T15:13:40.730",
"Id": "221126",
"ParentId": "221122",
"Score": "5"
}
},
{
"body": "<p>I would recommend looking at <a href=\"https://docs.python.org/3/library/itertools.html#itertools.permutations\" rel=\"nofollow noreferrer\">itertools.permutations</a></p>\n\n<pre><code>from itertools import permutations\nfor p in permutations(\"cow\"):\n joined = \"\".join(p)\n print(joined)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>cow\ncwo\nocw\nowc\nwco\nwoc\n</code></pre>\n\n<p>You can use it multiple ways:</p>\n\n<ol>\n<li>Test your algorithm regarding output</li>\n<li>Compare to your algorithm regarding speed</li>\n<li>Check the implementation to get an idea how to it is done</li>\n</ol>\n\n<p>Regarding 3, there is even an equivalent version (optimized but still readable) in the <a href=\"https://docs.python.org/3/library/itertools.html#itertools.permutations\" rel=\"nofollow noreferrer\">docs</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T15:16:29.113",
"Id": "221127",
"ParentId": "221122",
"Score": "1"
}
},
{
"body": "<p>A basic recursive idea is to repeatedly reduce the problem to a simpler version of the same kind, until it reaches a base case which can no longer be reduced. Recursive solutions are often \"simple\" in the sense of not using many lines of code, so that's something to look for.</p>\n\n<p>Let's see how this can be applied to this particular problem. Take the word \"cow\", with the permutations </p>\n\n<blockquote>\n <p>cow, cwo, ocw, owc, wco, woc</p>\n</blockquote>\n\n<p>Notice how the first character stays the same, until all permutations of the \"tail\" has been covered. That's the reduction step you need: For each character in the string, make that the first character, and then call the function again with the <em>rest</em> of the characters. Keep track of the character selection order as that will be the word. Then remember to catch the base case: If there's no characters left in the string, we're done removing characters and the word is complete.</p>\n\n<pre><code>def lexperm(s, word=''):\n if not s:\n print(word)\n for i, char in enumerate(s):\n lexperm(s[:i] + s[i+1:], word + char)\n</code></pre>\n\n<p>Notice how this doesn't require swapping or reversing anything, because we're removing all characters, in every order.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T15:56:32.103",
"Id": "221133",
"ParentId": "221122",
"Score": "2"
}
},
{
"body": "<p>I've read over a couple of your past questions, and I can't really describe how unsightly the code is without violating SE's rules.</p>\n\n<p>Read and follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>.</p>\n\n<p>Skip over the section \"A Foolish Consistency is the Hobgoblin of Little Minds\" as you don't seem to know what good code looks like and you arn't interacting with legacy code. It's better to be a Hobgoblin for now, as you'll produce better code than you are now.</p>\n\n<hr>\n\n<p>Get a couple of linter wrappers, like <a href=\"https://pypi.org/project/flake8/\" rel=\"nofollow noreferrer\">Flake8</a>, <a href=\"https://pypi.org/project/prospector/\" rel=\"nofollow noreferrer\">Prospector</a> or <a href=\"https://pypi.org/project/coala-bears/\" rel=\"nofollow noreferrer\">Coala</a>. Make sure to turn all warnings on, as they don't normally by default.</p>\n\n<p>These will help you know what parts of your code sucks without having to ask others!</p>\n\n<p>Fixing all the errors these tools raise helps keep your code clean and make it so when you produce larger programs it's easier to understand what your code is doing. You may protest and say, \"but people on Code Review understand my code!\"\nAnd you would be right, but that is because you're developing solutions to coding challenges, not real life problems that are more intricate and require larger amounts of code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T16:59:55.490",
"Id": "427521",
"Score": "0",
"body": "I understand. I will keep this in mind. Thank you :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T16:57:58.653",
"Id": "221137",
"ParentId": "221122",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221126",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T14:39:59.217",
"Id": "221122",
"Score": "-1",
"Tags": [
"python",
"python-3.x",
"homework"
],
"Title": "Python program to print all permutations of a string in lexicographic order using recursion"
} | 221122 |
<p>As part of the practice, I created minimalist linked list named <code>SimpleList</code> which can be iterated in two different ways: one element after another or by every second element. </p>
<p>Because I'm beginner I would really appreciate your opinion about my solution. Is it correct? What should I change?</p>
<pre><code>public class SimpleList<T> : IEnumerable<T>
{
protected class Node
{
public T Data { get; set; }
public Node NextNode { get; set; }
public Node(T data, Node nextNode)
{
Data = data;
NextNode = nextNode;
}
}
protected Node Head { get; set; } = null;
public void Add(T data)
{
Head = new Node(data, Head);
}
#region IEnumerable<T> implementation
public IEnumerator<T> GetEnumerator()
{
var current = Head;
while (current != null)
{
yield return current.Data;
current = current.NextNode;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region second iterator implementation
private class EverySecondElementIterator : IEnumerable<T>
{
private readonly Node head;
public EverySecondElementIterator(Node head)
{
this.head = head;
}
public IEnumerator<T> GetEnumerator()
{
var current = head;
while (current != null)
{
yield return current.Data;
current = current.NextNode?.NextNode;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public IEnumerable<T> EverySecondElement => new EverySecondElementIterator(Head);
#endregion
}
</code></pre>
| [] | [
{
"body": "<h2>Terminology</h2>\n\n<p>The <code>Add</code> operation on a <code>List</code> appends the <em>item</em> to that <em>list</em>. Your method should be renamed to <code>Prepend</code>.</p>\n\n<blockquote>\n<pre><code> public void Add(T data)\n {\n Head = new Node(data, Head);\n }\n</code></pre>\n</blockquote>\n\n<pre><code> public void Prepend(T data)\n {\n Head = new Node(data, Head);\n }\n</code></pre>\n\n<h2>Design</h2>\n\n<p>You could keep track of the <code>Tail</code> and have an <code>Add</code> operation.</p>\n\n<blockquote>\n <p><code>protected Node Head { get; set; } = null;</code></p>\n</blockquote>\n\n<pre><code> protected Node Head { get; set; } = null;\n protected Node Tail { get { \n var tail = Head;\n while (tail != null && tail.NextNode != null)\n tail = tail.NextNode;\n return tail;\n }}\n\n public void Add(T data)\n {\n if (Head == null)\n Head = new Node(data, null);\n else\n Tail.NextNode = new Node(data, null);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T16:43:12.167",
"Id": "427516",
"Score": "0",
"body": "Nothing more? I'm worried about this you can alternate list while iterating over it. What if we have two iterators? Should I prevent this e.g. using readonly copies od list? How can I even make such copy? It doesn't use any built in collection so it won't be trivial..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T16:46:32.940",
"Id": "427518",
"Score": "0",
"body": "@wozar It's up to caller code to know how to iterate over IEnumerable instances and how to allow/restrict concurrent access."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T12:52:32.640",
"Id": "427606",
"Score": "0",
"body": "Thank you for naming suggestion. I also noticed that you don't keep tail as simple reference to last added element and I have concerns about performance. Is it necessary if we can manipulate list only with this class' public methods? If I'm correct we can't modify node's `NextNode` property from outside `SimpleList` class so it should be impossible to break this list by adding next node before tail and creating some sort of branching."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T13:29:22.383",
"Id": "427617",
"Score": "0",
"body": "@wozar It's a design decision whether you want to keep track of other properties other than head that could also get calculated on demand. If performance is key, I would store the tail as well. If memory storage should be kept low, I would not."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T15:58:15.877",
"Id": "221134",
"ParentId": "221130",
"Score": "5"
}
},
{
"body": "<h3>Use extension methods</h3>\n<p>I find you did well by implementing the <code>EverySecondElementIterator</code> as a separate class. However, I also think it would be better to turn it into an extension of <code>IEnumerable<T></code> and use <code>MoveNext</code> instead of the internal <code>Node</code>.</p>\n<p>Otherwise if someone suddenly comes up with the idea to skip every third element, you would need to modify the original <code>SimpleList</code> by creating another private class class and another property. We usually try to avoid modifying code that is tested and is working well. This would also violate the <a href=\"http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/\" rel=\"noreferrer\">open/closed principle</a>.</p>\n<p>It's much safer and extendable to create a new and independent extension that you also can resue with any <code>IEnumerable<T></code> and skip every-second-element of any collection.</p>\n<p>Let the <code>SimpleList</code> be closed for modifications by not implementing anything as specific as that enumerator. It is already opend for extension by implementing the <code>IEnumerable<T></code> interface. Make use of it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T12:30:47.360",
"Id": "427602",
"Score": "0",
"body": "You mean something like this: [SimpleList.cs](https://pastebin.com/d3jMbhCc), [IEnumerableExtensions.cs](https://pastebin.com/fmSs9rb6), [Program.cs](https://pastebin.com/aDyVWyxV)?\n\nMy concerns: 1. extension class name starts with capital I but it's not an interface (what's proper naming convention?). 2. Static class can't be generic so my enumerator returns plain objects. Is it ok?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T12:37:40.560",
"Id": "427603",
"Score": "0",
"body": "@techb0t Or should I cast it to desirable type?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T12:48:18.397",
"Id": "427604",
"Score": "0",
"body": "@wozar since you know the `T`, it'd easier be easier when you implemented the generic interface `IEnumerable<T>`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T12:56:24.033",
"Id": "427607",
"Score": "0",
"body": "I'm sorry but where should I implement it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T13:01:34.667",
"Id": "427609",
"Score": "0",
"body": "I mean if I implement generic IEnumerable in my private `EverySecondElementIterator` class I still can't return it without casting to non-generic since static class doesn't know about T"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T13:02:25.643",
"Id": "427610",
"Score": "0",
"body": "Or I simply don't know how"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T13:23:25.840",
"Id": "427615",
"Score": "0",
"body": "@wozar I think you know how to do it because you've already been there, this is what you have shown us in your question: `EverySecondElementIterator : IEnumerable<T>`, all you have to do is to exchange `Node` against `IEnumerable<T>`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:01:35.937",
"Id": "427627",
"Score": "0",
"body": "@wozar what I see here is the simple interface `EverySecondElementIterator : IEnumerable`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:02:23.440",
"Id": "427628",
"Score": "0",
"body": "Oh, I got confused because I forgot to add <T> to method name which returns new EverySecondElementIterator<T>. My bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:10:05.747",
"Id": "427637",
"Score": "0",
"body": "So it works great now. Thank you very much for your help. I really like this approach. Using extension methods makes it easy to extend so I guess it's preferred way to implement many iterators for some type. Am I correct? Or are there any exceptions or restrictions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:19:00.653",
"Id": "427640",
"Score": "0",
"body": "@wozar I'm glad you could solve this _riddle_ ;-) The questions you are asking would be perfect for a follow-up question because there's still room for improvement. In case you are tempted to do so.. please do not modify the code here. A new qeustion would be the right thing to do to ask for feedback about the new code."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T18:48:01.547",
"Id": "221143",
"ParentId": "221130",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T15:37:56.820",
"Id": "221130",
"Score": "5",
"Tags": [
"c#",
"linked-list",
"iterator"
],
"Title": "Simple linked list with two iterators"
} | 221130 |
<p>This is a Target number solution finder which I made with tkinter and is where the user enters a number they want and enters 4 other numbers to find the sum to make the number they want.</p>
<p>This is a screenshot on what the GUI looks like:
<a href="https://i.stack.imgur.com/v3vob.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v3vob.jpg" alt="enter image description here"></a></p>
<p>This is the code for the project:</p>
<pre><code>from tkinter import Tk, Frame, Label, Button, IntVar, Entry, Text, W, N, WORD, INSERT
from itertools import permutations,combinations_with_replacement
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.target_num = IntVar()
self.num1 = IntVar()
self.num2 = IntVar()
self.num3 = IntVar()
self.num4 = IntVar()
# self.title("target number solution")
Label(self,image='', bg="white").grid(row=0, column=0, sticky=W)
Label(self, text="Enter target number:", bg="black", fg="white", font="none 12 bold").grid(row=1, column=0, sticky=N)
self.textentry1 = Entry(self, textvariable=self.target_num, width=20, bg="white")
self.textentry1.grid(row=2, column=0, sticky=N)
Label(self, text="Enter first number:",bg="black", fg="white", font="none 12 bold").grid(row=4, column=0, sticky=N)
self.textentry2 = Entry(self, textvariable=self.num1, width=20, bg="white")
self.textentry2.grid(row=5, column=0, sticky=N)
Label(self, text="Enter second number:",bg="black", fg="white", font="none 12 bold").grid(row=6, column=0, sticky=N)
self.textentry3 = Entry(self, textvariable=self.num2, width=20, bg="white")
self.textentry3.grid(row=7, column=0, sticky=N)
Label(self, text="Enter third number:",bg="black", fg="white", font="none 12 bold").grid(row=8, column=0, sticky=N)
self.textentry3 = Entry(self, textvariable=self.num3, width=20, bg="white")
self.textentry3.grid(row=9, column=0, sticky=N)
Label(self, text="Enter fourth number:",bg="black", fg="white", font="none 12 bold").grid(row=10, column=0, sticky=N)
self.textentry4 = Entry(self, textvariable=self.num4, width=20, bg="white")
self.textentry4.grid(row=11, column=0, sticky=N)
Button(self, text="Solve", width=6, command=self.solver).grid(row=12, column=0, sticky=N)
self.output = Text(self, width=60, height=10, wrap=WORD, background="white")
self.output.grid(row=13, column=0, columnspan=1, sticky=N)
def solver(self):
self.output.delete(1.0, INSERT)
target = self.target_num.get()
number1 = self.num1.get()
number2 = self.num2.get()
number3 = self.num3.get()
number4 = self.num4.get()
numbers = [number1, number2, number3, number4]
operators = ["+","-","*","/"]
groups = ['X+X+X+X', 'X+X+(X+X)', 'X+(X+X)+X', '(X+X+X)+X', '(X+X)+X+X', 'X+(X+X+X)', '((X+X)+X)+X', 'X+(X+(X+X))', 'X+((X+X)+X)', '(X+X)+(X+X)', '(X+(X+X))+X']
seen = set()
for values in permutations(numbers,len(numbers)):
for operCombo in combinations_with_replacement(operators,len(numbers)-1):
for oper in permutations(operCombo,len(numbers)-1):
formulaKey = "".join(str(oper+values))
if formulaKey in seen: continue # ignore variations on parentheses alone
for pattern in groups:
formula = "".join(str(o)+str(p) for o,p in zip([""]+list(oper), pattern.split("+")))
formula = "".join(str(v)+str(p) for v,p in zip([""]+list(values),formula.split("X")))
try:
if eval(formula) == target:
Answer = formula,"=",target
seen.add(formulaKey)
#insert value in output Textbox
self.output.insert(INSERT, Answer)
self.output.insert(INSERT, '\n')
break
elif eval(formula) != target:
self.output.insert(INSERT, 'Solution could not be found')
break
except: pass
root = Tk()
app = Application(master=root)
app.master.title("target number solution")
app.mainloop()
</code></pre>
<p>I just want suggestions on how I can improve this project to make it better.</p>
<p>All suggestions will be greatly appreciated</p>
| [] | [
{
"body": "<p>I am concentrating on the solver method, since my sense for a good UX is close to null. I added inline comments for my changes.</p>\n\n<p>But here some major changes:</p>\n\n<ul>\n<li>Your code was not showing all combinations because you were breaking the loop after first item.</li>\n<li>The two nested fors with combinations_with_replacement and permutations, does the same as <a href=\"https://docs.python.org/2/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\">product()</a>.</li>\n<li>Defined groups and operators as constants (in uppercase) at the beginning of the code.</li>\n<li>Used END instead of INSERT in output so it clears text of previous results.</li>\n<li>Added formula_key right away and not in the condition, it was computing the same formula multiple times.</li>\n<li><a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">Snake case</a> for naming variables convention in python.</li>\n</ul>\n\n<p>Here the code (create_widgets and the constructor stay the same):</p>\n\n<pre><code>from tkinter import Tk, Frame, Label, Button, IntVar, Entry, Text, W, N, WORD, INSERT, END\nfrom itertools import permutations, product\n\n# Define constants\nOPERATORS = [\"+\",\"-\",\"*\",\"/\"]\nGROUPS = ['X+X+X+X', 'X+X+(X+X)', 'X+(X+X)+X', '(X+X+X)+X', '(X+X)+X+X', 'X+(X+X+X)', '((X+X)+X)+X', 'X+(X+(X+X))', 'X+((X+X)+X)', '(X+X)+(X+X)', '(X+(X+X))+X']\n\nclass Application(Frame):\n def __init__(self, master=None):\n # ...\n\n def create_widgets(self):\n # ...\n\n def solver(self):\n self.output.delete(1.0, END) # END removes previous results instead of INSERT\n target = self.target_num.get()\n number1 = self.num1.get()\n number2 = self.num2.get()\n number3 = self.num3.get()\n number4 = self.num4.get()\n numbers = [number1, number2, number3, number4]\n seen = set()\n len_opr = len(numbers) - 1 # Compute once\n for values in permutations(numbers): # No need to specify len\n for oper in product(OPERATORS, repeat=len_opr): # Product does what you want instead of two fors\n formula_key = \"\".join(str(oper + values))\n if formula_key in seen: continue # ignore variations for repeated numbers\n seen.add(formula_key) # Add right away not in the condition\n # if only one operation, do not permute parenthesis\n filtered_groups = [GROUPS[0]] if len(set(oper)) == 1 else GROUPS\n for pattern in filtered_groups:\n formula = \"\".join(str(o)+str(p) for o, p in zip([\"\"] + list(oper), pattern.split(\"+\")))\n formula = \"\".join(str(v)+str(p) for v, p in zip([\"\"] + list(values), formula.split(\"X\")))\n try:\n if eval(formula) == target:\n answer = formula, \"=\", target # vars start by minuscule\n #insert value in output Textbox\n self.output.insert(INSERT, answer)\n self.output.insert(INSERT, '\\n')\n result = True\n # REMOVE this condition or it does not try all groups with parenthesis\n except: pass\n if self.output.get(\"1.0\", END)==\"\\n\":\n self.output.insert(INSERT, 'Solution could not be found')\nroot = Tk()\napp = Application(master=root)\napp.master.title(\"target number solution\")\napp.mainloop()\n</code></pre>\n\n<p>If you have any questions, don't hesitate!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:47:30.193",
"Id": "427779",
"Score": "0",
"body": "Thank you for your answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:54:42.937",
"Id": "427780",
"Score": "0",
"body": "I am getting this error: `self.output.delete(1.0, END) \nNameError: name 'END' is not defined`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:55:31.123",
"Id": "427781",
"Score": "0",
"body": "Check the first line, it has to be imported"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:59:13.730",
"Id": "427782",
"Score": "0",
"body": "Thanks the error is gone but now I get another error:`for oper in product(OPERATORS, repeat=len_opr):`\n`NameError: name 'product' is not defined`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T12:00:31.650",
"Id": "427783",
"Score": "0",
"body": "Check the second line, it has to be imported ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T12:01:20.963",
"Id": "427784",
"Score": "0",
"body": "Yes thanks it works now :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T12:03:24.497",
"Id": "427785",
"Score": "0",
"body": "I have another question, is is possible to remove duplicate solutions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T12:04:05.020",
"Id": "427786",
"Score": "0",
"body": "There are duplicates? For which case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T12:05:08.560",
"Id": "427787",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/94244/discussion-between-palvarez-and-system123456)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T20:40:43.403",
"Id": "221152",
"ParentId": "221132",
"Score": "4"
}
},
{
"body": "<p>is it working now and i have an evil hack in there:</p>\n\n<ul>\n<li>Same values inside a loop</li>\n<li>You do have only 5 groups</li>\n<li>Division by 0 must be escaped</li>\n<li>Not building a string and then eval, just have list of functions, that makes code smaller and runs faster</li>\n<li>No hashing need because results do not repeat unless you do many times the same digits combo...</li>\n<li>Attention, evil hack: Generate combination of functions by increasing some digit \nand viewing its bits : 12, 34, 56 as digits from 0-3 what are function indexes.</li>\n</ul>\n\n<p>There it is:</p>\n\n<pre><code> fa = self.ops [op_bits & 3]\n fb = self.ops [(op_bits & 12) >> 2 ]\n fc = self.ops [(op_bits & 48) >> 4 ]\n</code></pre>\n\n<p>enjoy the crap:</p>\n\n<pre><code> from tkinter import Tk, Frame, Label, Button, IntVar, Entry, Text, W, N, WORD, INSERT\n\n\nclass Application(Frame):\n\n #extract constant fields:\n\n op_str = ['+', '-' , '*' , '/']\n\n ops = [lambda a,b : a+b if (a is not None and b is not None) else None,\n lambda a,b : a-b if (a is not None and b is not None) else None, \n lambda a,b : a*b if (a is not None and b is not None) else None,\n lambda a,b : a/b if (b != 0 and a is not None and b is not None) else None, \n ]\n\n max_combinations = 1 << 6\n\n group_strs = ['((%d%s%d)%s%d)%s%d', '%d%s(%d%s(%d%s%d))', '%d%s((%d%s%d)%s%d)', '(%d%s%d)%s(%d%s%d)', '(%d%s(%d%s%d))%s%d']\n\n #clumsy a lil bit\n groups = [lambda a,b,c,d,fa,fb,fc : fc(fb(fa(a,b),c),d),\n lambda a,b,c,d,fa,fb,fc : fa(a,fb(b,fc(c,d))),\n lambda a,b,c,d,fa,fb,fc : fa(a,fc(fb(b,c),d)),\n lambda a,b,c,d,fa,fb,fc : fb(fa(a,b), fc(c,d)),\n lambda a,b,c,d,fa,fb,fc : fc(fa(a,fb(b,c)),d),\n\n\n ] \n\n\n def __init__(self, master=None):\n super().__init__(master)\n self.pack()\n self.create_widgets() \n\n\n\n\n\n\n\n def create_widgets(self):\n\n self.entries = [] \n self.vars = [IntVar() for _ in range (5)]\n self.texts = ['Enter target number' , \n 'Enter first number', \n 'Enter second number', \n 'Enter third number', \n 'Enter fourth number']\n\n\n for index, var in enumerate(self.vars):\n Label(self, text=self.texts[index], bg=\"black\", fg=\"white\", font=\"none 12 bold\").grid(row=2*index, column=0, sticky=N)\n e = Entry(self, textvariable= self.vars[index] , width=20, bg=\"white\")\n e.grid(row=2*index+1, column=0, sticky=N)\n self.entries.append(e)\n\n Button(self, text=\"Solve\", width=6, command=self.solver).grid(row=12, column=0, sticky=N)\n self.output = Text(self, width=60, height=10, wrap=WORD, background=\"white\")\n self.output.grid(row=13, column=0, columnspan=1, sticky=N) \n\n def solver(self):\n self.output.delete(1.0, INSERT)\n target = self.vars[0].get()\n numbers = [e.get() for e in self.vars[1:]]\n\n\n count = 0\n for gr_num, group in enumerate(self.groups):\n\n\n for op_bits in range(0,self.max_combinations):\n count += 1\n #evil hacks here\n fa = self.ops [op_bits & 3]\n fb = self.ops [(op_bits & 12) >> 2 ]\n fc = self.ops [(op_bits & 48) >> 4 ]\n # or even shorter like\n # fs = [(op_bits & (3 << x)) >> x for x in range(0,self.max_combinations) ]\n\n my_eval = group(*numbers, fa,fb,fc)\n print('my_eval' , my_eval, ' =' , *numbers, fa,fb,fc, )\n if my_eval == target:\n formula = self.group_strs[gr_num] % (numbers[0],self.op_str[op_bits & 3],numbers[1],self.op_str[(op_bits & 12) >> 2],numbers[2],self.op_str[(op_bits & 48) >> 4],numbers[3])\n Answer = formula,\"=\",target , ' found in ' , count , 'iterations'\n #seen.add(formulaKey)\n #insert value in output Textbox\n self.output.insert(INSERT, Answer) \n self.output.insert(INSERT, '\\n')\n return\n\n self.output.insert(INSERT, 'Solution could not be found in ' + str(count) + ' iterations')\n\n\n\n\n\n\nroot = Tk()\napp = Application(master=root)\napp.master.title(\"target number solution\")\napp.mainloop()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:47:19.660",
"Id": "427778",
"Score": "0",
"body": "Thank you for your answer"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T22:44:55.577",
"Id": "221160",
"ParentId": "221132",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221152",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T15:53:26.370",
"Id": "221132",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"tkinter"
],
"Title": "Target number sum finder"
} | 221132 |
<p>I made a function to get a list with numbers around another number. Example: I want to get in a range of 2 numbers around 4. This will return: <code>[2, 6]</code>. You can set a min number and a max_number. That means when I set a min_num, the lower number should not be lower than the min number.</p>
<pre><code>import sys
def get_numbers_around(number: int, min_num: int = None, max_num: int = None, _range: int = 2, on_fail_no_error: bool = False) -> range:
if max_num is None:
max_num = sys.maxsize
if min_num is None:
min_num = -sys.maxsize - 1
diff = max_num - min_num
if diff < _range:
if not on_fail_no_error:
raise ValueError(
"Range is too small. Range is {0} big but difference between max_num and min_num is {1} big! ({0} < {1}".format(
range, max_num - min_num))
else:
return range(number - diff, number + diff)
final_list = [number - _range, number + _range]
if final_list[0] < min_num:
diff = abs(min_num - final_list[0])
final_list[0] = min_num
final_list[1] += diff
if final_list[1] > max_num:
diff = abs(final_list[1] - max_num)
final_list[1] = max_num
final_list[0] -= diff
return range(final_list[0], final_list[1])
print(get_numbers_around(4)) # range(2, 6)
print(get_numbers_around(4, _range=5)) # range(-1, 9)
print(get_numbers_around(0, min_num=0, max_num=1, _range=4, on_fail_no_error=True)) # range(-1, 1)
print(get_numbers_around(0, min_num=0, max_num=1, _range=4)) # ValueError
</code></pre>
<p>I think it is possible to optimize this code but I don't know how. Does anoyne have any idea?</p>
| [] | [
{
"body": "<ul>\n<li>Your code seems really complicated, and so you should follow KISS and YAGNI.</li>\n<li><code>max_num</code> and <code>min_num</code> don't work the way I would expect them to.</li>\n<li>The error goes against what I think is Pythonic. Just return the smaller set.</li>\n</ul>\n\n<pre><code>def get_numbers_around(number, size):\n return range(number - size, number + size)\n</code></pre>\n\n<p>If you then need to implement <code>min_num</code> and <code>max_num</code> create a filter:</p>\n\n<pre><code>def filter_between(values, minimum=float('-inf'), maximum=float('inf')):\n return (v for v in values if minimum <= v <= maximum)\n</code></pre>\n\n<hr>\n\n<pre><code>>>> get_numbers_around(4, 5)\nrange(-1, 9)\n>>> list(filter_between(_, 0))\n[0, 1, 2, 3, 4, 5, 6, 7, 8]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T20:07:02.370",
"Id": "427545",
"Score": "0",
"body": "This interface is much more pythonic. But there is some utility in returning a `range` object; in particular, iterating through a generator should be faster without checking that each values is in range. Why not just return `range(max(values.start, minimum), min(values.stop, maximum))`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T20:11:21.383",
"Id": "427546",
"Score": "0",
"body": "@BenjaminKuykendall I don't know how the code is being used. The person seems to like over-complicating things, and needs YAGNI and KISS in their life. Yes you could do it that way, but I still think YAGNI."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T05:00:56.063",
"Id": "428072",
"Score": "0",
"body": "But with this method there will be missing some numbers. Example: I have the number 1 and I want 2 numbers around. Then I'll get `[-1, 0, 1, 2, 3]` (I have 5 numbers now) . When I filter this, I'll get `[0, 1, 2]` (Now I only have 3 numbers but this should be 5.). The list should be like this: `[0, 1, 2, 3, 4] `."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:01:55.843",
"Id": "428092",
"Score": "0",
"body": "@Myzel394 Yours doesn't do this either. You can even see it in your examples above. `range` doesn't include the last value, like you think it does."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T19:09:07.530",
"Id": "221148",
"ParentId": "221136",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221148",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T16:47:26.160",
"Id": "221136",
"Score": "1",
"Tags": [
"python",
"interval"
],
"Title": "Python function to get numbers around another number"
} | 221136 |
<p>I've implemented a minimal external sort of text file using heapq python module.</p>
<p>On the few tests I did it seems to works well, but I would like to have some advice to have a cleaner and faster code. I do not know much of good practices and I want to learn (May wish to go from academics to industry one day). All remarks, advice and suggestions are warmly welcome.</p>
<p>There are 3 functions: one that splits the big file in smaller files,
one that does the merge, and one main function.</p>
<pre><code>import os
import tempfile
import heapq
import sys
import shutil
# Algorithm based on
# https://github.com/melvilgit/external-Merge-Sort
def split_large_file(starting_file, my_temp_dir, max_line=1000000):
"""
:param starting_file: input file to be splitted
:param my_temp_dir: temporary directory
:param max_line: number of line to put in each smaller file (ram usage)
:return: a list with all TemporaryFile
"""
liste_file = []
line_holder = []
cpt = 0
with open(starting_file, 'rb') as f_in:
for line in f_in:
line_holder.append(line)
cpt += 1
if cpt % max_line == 0:
cpt = 0
line_holder.sort(key=lambda x: x.split(b"\t")[0])
temp_file = tempfile.NamedTemporaryFile(dir=my_temp_dir, delete=False)
temp_file.writelines(line_holder)
temp_file.seek(0)
line_holder = []
liste_file.append(temp_file)
if line_holder:
line_holder.sort(key=lambda x: x.split(b"\t")[0])
temp_file = tempfile.NamedTemporaryFile(dir=my_temp_dir, delete=False)
temp_file.writelines(line_holder)
temp_file.seek(0)
liste_file.append(temp_file)
return liste_file
def merged(liste_file, out_file, col):
"""
:param liste_file: a list with all temporary file opened
:param out_file: the output file
:param col: the column where to perform the sort, being minimal the script will fail
if one column is shorter than this value
:return: path to output file
"""
my_heap = []
for elem in liste_file:
line = elem.readline()
spt = line.split(b"\t")
heapq.heappush(my_heap, [int.from_bytes(spt[col], "big"), line, elem])
with open(out_file, "wb") as out:
while True:
minimal = my_heap[0]
if minimal[0] == sys.maxsize:
break
out.write(minimal[1])
file_temp = minimal[2]
line = file_temp.readline()
if not line:
my_heap[0] = [sys.maxsize, None, None]
os.remove(file_temp.name)
else:
spt = line.split(b"\t")
my_heap[0] = [int.from_bytes(spt[col], "big"), line, file_temp]
heapq.heapify(my_heap)
return out_file
def main(big_file, outfile, tmp_dir=None, max_line=1000000, column=0):
if not tmp_dir:
tmp_dir = os.getcwd()
with tempfile.TemporaryDirectory(dir=tmp_dir) as my_temp_dir:
temp_dir_file_list = split_large_file(big_file, my_temp_dir, max_line)
print("splitted")
merged(liste_file=temp_dir_file_list, out_file=outfile, col=column)
print("file merged, sorting done")
</code></pre>
| [] | [
{
"body": "<p>Nit: running <a href=\"https://pypi.org/project/isort/\" rel=\"nofollow noreferrer\">isort</a> would organize your imports,\nto reduce <code>git merge</code> conflicts.</p>\n<p>The <code>split_large_file()</code> signature might default <code>my_temp_dir</code>.\nConsider renaming it to simply <code>temp_dir</code>.\nFor compatibility with /usr/bin/sort, <code>os.environ['TMPDIR']</code> would be a fair default.</p>\n<p>Consider renaming <code>starting_file</code> to <code>in_file</code> (or <code>input_file</code>).</p>\n<p>Docstrings start with an English sentence, e.g. "Splits a file into pieces."\nIf the intent is "...into sorted pieces," then say so,\nand make the function name match.\nSplitting a file is by itself a valuable service, even without sorting.</p>\n<p>Please say "a list of" rather than "a list with all".</p>\n<p>It appears <code>liste_file</code> has a typo, plus it should simply be <code>files</code>.\nSimplify <code>line_holder</code> to <code>lines</code>.</p>\n<h1>algorithm</h1>\n<ol>\n<li>line budget vs RAM budget</li>\n<li>chunking</li>\n<li>loop style</li>\n</ol>\n<p>You impose a million-line max on each piece.\nBut the true goal was to cap RAM consumption,\nwhich is indirectly related through the average chars-per-line\nfor a given input file.\nConsider adding up line lengths\nrather than incrementing by one for each line.</p>\n<p>Related to this, the line-by-line iteration is on the slow side,\nespecially for input files comprised of short lines.\nConsider doing one or more binary <code>.read()</code>'s,\nand then reading until newline so only complete lines go to the outfile.\n(Or scan backwards through the chunk to find a newline,\nthen <code>seek()</code> to that position before issuing the next read.)</p>\n<p>The <code>if line_holder:</code> line is a code smell,\nit suggests that you didn't quite find a form of <code>while</code> loop\nthat matched your application.\nPerhaps a boolean <code>done</code> flag would help to\nremove the copy-n-pasted 2nd chunk of code.\nIf for some reason you feel it still needs to remain,\nthen definitely extract both copies into a small helper method.\nDRY: <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Don%27t_repeat_yourself</a></p>\n<p>This is correct, but weird:</p>\n<pre><code> if cpt % max_line == 0:\n cpt = 0\n</code></pre>\n<p>If line number <code>cpt</code> (don't know what that stands for) hits limit,\nwe reset the line number and emit a chunk.\nComputing modulo <code>%</code> is more expensive than a comparison <code>></code>.\nUsually modulo would be used if we're <strong>not</strong> going to reset the line number.</p>\n<p>Three comments about the lambda:</p>\n<ol>\n<li>This is the first we've heard about the input file being a <code>.tsv</code>. Improve the docstring.</li>\n<li>The lambda is fine, but consider breaking it out as a named function.</li>\n<li>The <code>.split()</code> copies out the entire line, but it only <em>needs</em> to copy as far as first TAB.</li>\n</ol>\n<p>We evaluate <code>merged()</code> for side effects,\nso we're looking for a verb name rather than an adjective.\nJust call it <code>merge()</code>, or perhaps <code>external_merge()</code>.\nConsider defaulting <code>col=0</code> in the signature.</p>\n<p>Each docstring should start with an English sentence.</p>\n<p>The comment "being minimal the script will fail if one column is shorter than this value" is accurate.\nBut, better to rewrite as a pre-condition on valid inputs:\n"must exist in each input row."</p>\n<pre><code> my_heap = []\n</code></pre>\n<p>Yes, it is your heap.\nBut that's not what is interesting about it.\nBetter to just call it <code>heap</code>.</p>\n<pre><code> for elem in liste_file:\n</code></pre>\n<p>This would more naturally be: <code>for file in files:</code></p>\n<p>You used a hardcoded column zero in <code>split_large_file()</code>,\nbut now you are apparently processing unsorted input\nsince <code>col</code> might be positive.</p>\n<p>Please assign <code>sentinel = sys.maxsize</code>,\nif that is how you're trying to use it.\nOr at least add a comment.\n(It is 0x7FFFFFFFFFFFFFFF, is that what you want?)\nThe <code>break</code> apparently should be raising a fatal exception instead,\nsince the input file apparently is not allowed to contain that sentinel\n(not allowed to contain arbitrary contents).</p>\n<p>The references to <code>minimal[0]</code>, <code>[1]</code>, and <code>[2]</code> are obscure.\nPlease use tuple unpack to put them in <code>val</code>, <code>line</code>, <code>file_temp</code>\nor similarly informative variables.</p>\n<p>The early explicit <code>.remove()</code> is fine.\nIf you had specified <code>delete=True</code> (or let it <a href=\"https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile\" rel=\"nofollow noreferrer\">default</a>)\nthe temp files would be deleted when the interpreter does a normal exit.</p>\n<p>Depending on platform, defaulting <code>tmp_dir</code> to something like <code>/tmp</code>\nmight be more appropriate than to CWD (which might be unwritable).</p>\n<p>Overall, looks pretty good, pretty readable.\nOne can always improve.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:07:31.573",
"Id": "427773",
"Score": "0",
"body": "Thank you a lot! It exactly what I needed. There is a lot of small things to improve that I never really paid attention to."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T19:29:04.383",
"Id": "221217",
"ParentId": "221141",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221217",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T17:37:10.773",
"Id": "221141",
"Score": "6",
"Tags": [
"python",
"performance",
"python-3.x",
"file",
"heap-sort"
],
"Title": "Python 3 simple external sort with heapq"
} | 221141 |
<p>I'd like to know your opinions on this minimal type-checking decorator (with <code>@</code> annotations) to make type checking of a method while debugging like :</p>
<pre class="lang-py prettyprint-override"><code>def typecheck(*tuples, **kwtuples):
def decorator(func):
def function_wrapper(*args, **kwargs):
#print('tuples : ' , tuples)
#print('kwtuples : ' , kwtuples)
#print('args : ' , args)
#print('kwargs : ' , kwargs)
for index, tup in enumerate(tuples):
arg = args[index]
if not isinstance(arg, tup):
raise ValueError('in ' + str(func.__name__) + ' : wrong argument on position ,' + str(index) + ' :' + str(arg) + ' must be of type :' + str(tup) + 'but is' + str(type(arg)) )
for key, tup in kwtuples.items():
arg = kwargs[key]
if not isinstance(args[index], tup):
raise ValueError('in ' + str(func.__name__) + ' : wrong argument ' + str(key) + ' :' + str(arg) + ' must be of type :' + str(tup) + 'but is' + str(type(arg)) )
#print("arguments: ", *args, **kwargs)
func(*args, **kwargs)
return function_wrapper
return decorator
@typecheck(str,(str, float))
def foo2(x,y):
print("Hi, foo has been called with ",str(x) ,y)
foo2('2',3.4)
</code></pre>
<p>The benefit of it is :</p>
<ul>
<li>Custom and detailed description about the wrong argument</li>
<li>Later, you can extend this for custom validation like some item is in some range or structural inspection of an argument.</li>
<li>Easy to write, apply and delete after testing (so it won't consume cpu time) </li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T18:39:34.173",
"Id": "427533",
"Score": "2",
"body": "Have you considered somehow taking advantage of [type hints, introduced in Python 3.5](https://docs.python.org/3.5/library/typing.html)? (And if not, why?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T18:43:59.223",
"Id": "427534",
"Score": "2",
"body": "In addition to @200_success other than using `typing` and mypy/pyre/pyright/pytype for _static type enforcement_, you can also use something like [pytypes](https://pypi.org/project/pytypes/) for run-time type enforcement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T19:08:47.137",
"Id": "427536",
"Score": "0",
"body": "those stuff do not custom value checking or structural checking, dont they? also i want it to be easy removed after testing"
}
] | [
{
"body": "<p>To amplify @200_success’s comment:</p>\n\n<p>Python 3.5 introduces <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type hints</a>. Eg)</p>\n\n<pre><code>>>> def foo2(x:str, y:float) -> None:\n... print(f\"Hi, foo has been called with {x} {y}\")\n... \n>>> foo2(\"2\", 3.4)\nHi, foo has been called with 2 3.4\n>>>\n</code></pre>\n\n<p>These type hints (the <code>x:str</code>, and <code>y:float</code>) are not used by the standard Python interpreter, but they are recorded during the parsing of the code, so they are available to the program.</p>\n\n<pre><code>>>> foo2.__annotations__\n{'return': None, 'x': <class 'str'>, 'y': <class 'float'>}\n>>> \n</code></pre>\n\n<p>Directly accessing the <code>foo2.__annotations__</code> is not that interesting, but accessing <code>func.__annotations__</code> in the <code>@typecheck</code> decorator means you don’t have to provide the argument types to the decorator; the decorator can inspect the argument types directly. Thus you could decorate the function with simply <code>@typecheck</code>, instead of <code>@typecheck(str, float)</code>.</p>\n\n<p>For a variant <code>str</code> or <code>float</code> type argument, you could use the <code>typing</code> module to define your own <code>STR_OR_FLOAT = TypeVar(\"STR_OR_FLOAT\", str, float)</code> type (or a better name if you have one), which you could decorate the argument with.</p>\n\n<p>As a bonus, using type hints to provide argument type checking information — even for your do-it-yourself via a function decorator type check system — also gives you the following benefits:</p>\n\n<ul>\n<li>IDE type hints, as you are writing code</li>\n<li>Can be understood by standard documentation generators</li>\n<li>Only consumes CPU time during parsing of the code; does not affect execution speed</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T03:07:17.373",
"Id": "221171",
"ParentId": "221142",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T18:20:08.543",
"Id": "221142",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"meta-programming",
"type-safety"
],
"Title": "Python simple type checking decorator"
} | 221142 |
<p><strong>Brief Description:</strong> </p>
<p>In my <strong>NodeJS</strong> Application, I have a model called <strong>User</strong>.</p>
<p><strong>User.js</strong></p>
<pre><code>module.exports = {
attributes: {
name: {
type: 'string'
}
}
};
</code></pre>
<p>My application consists users searching functionality using <strong>name</strong> attribute. For that I used find users using exact name as below(I am using <strong>MongoDB</strong> as my Database). My User Controller as below.</p>
<p><strong>UserController.js</strong></p>
<pre><code> var name = req.param('name');
User.find({ name: { 'contains': name } }).exec(function (err, results) {
if (err) {
return res.serverError(err);
}
return res.send(results);
});
</code></pre>
<p>Now I need to enhance my searching functionality.</p>
<p>As an example if my DB contains record as <strong>Michael</strong> and if I searched as <strong>micel</strong>, Michael should be given as a search result.</p>
<p>For that I used Fuzzy Logic Algorithm and I used <strong><a href="https://www.npmjs.com/package/fuzzy" rel="nofollow noreferrer">fuzzy</a></strong> <code>npm</code> package. Now my implementation is as below.</p>
<p><strong>UserController.js</strong></p>
<pre><code>var fuzzy = require('fuzzy');
module.exports = {
search: function (req, res) {
var term = req.param('name');
var thisCtrl = this;
User.find().exec(function (err, users) {
if (err) {
return res.serverError(err);
}
thisCtrl.createSearchQuery(term, users, function (orQuery) {
User.find({or: orQuery}).exec( function (err, finalResulst) {
if (err) {
return res.serverError(err);
}
return res.send(finalResulst)
})
})
});
},
createSearchQuery: function (term, users, cb) {
var userNamesArr = [];
var or = [];
for (var i = 0; i < users.length; i++) {
userNamesArr.push(users[i].name)
}
var results = fuzzy.filter(term, userNamesArr);
var matches = results.map(function(el) { return el.string; });
for (var i = 0; i < matches.length; i++) {
var tempTerm = { name: { 'contains' : matches[i] }};
or.push(tempTerm)
}
cb(or);
}
};
</code></pre>
<p><strong>This is working as I needed.</strong></p>
<p><strong>But My Question is,</strong></p>
<p>I am getting all the users in my DB and create search term using Fuzzy Logic and finding again in <strong>User</strong> collection. Now this is ok if I have only about 100 user records. But the time when User collection contains <strong>Millions</strong> of user records , Will this causes to performance issue to my application or is there a <strong>Better Approach</strong> than this I should follow.</p>
<p><strong>Sorry for my bad English and Suggestions are highly appreciated.</strong></p>
| [] | [
{
"body": "<h2>Question</h2>\n\n<blockquote>\n <p><em>\"Will this causes to performance issue to my application or is there a Better Approach than this I should follow.\"</em></p>\n</blockquote>\n\n<p>Well that will depend on a lot of factors.</p>\n\n<ul>\n<li>1million clients.</li>\n<li><a href=\"https://www.npmjs.com/package/fuzzy\" rel=\"nofollow noreferrer\">fuzzy.js</a> and its performance.</li>\n<li>A single medium level server.</li>\n</ul>\n\n<h2>State of development</h2>\n\n<p>First a quick look at the link you provided to <a href=\"https://www.npmjs.com/package/fuzzy\" rel=\"nofollow noreferrer\">fuzzy</a> and at the bottom of the page you find the ToDo list which contains 2 points of interest</p>\n\n<blockquote>\n <ol start=\"3\">\n <li>Async batch updates so the UI doesn't block for huge sets. Or maybe Web Workers?</li>\n <li>Performance performance performance!</li>\n </ol>\n</blockquote>\n\n<p>Following through to the <a href=\"https://github.com/mattyork/fuzzy\" rel=\"nofollow noreferrer\">gitHub repository</a> and we find that the last activity was 3 years ago. This suggests (not implies) that development has ended. That a key issue recognized by the developers (performance) will not be worked on in the near future.</p>\n\n<h2>Performance</h2>\n\n<p>To try and determine the performance per search entry I went to their demo and timed the search over several differently size lists of names, and search strings. </p>\n\n<p>The performance test shows a slightly below linear complexity (in the range of 628 - 1,250,000 names), however its too close to call and the safe bet is its linear. It searched 1.25million names in ~1 +/- 0.2seconds</p>\n\n<h3>Tests method</h3>\n\n<p>The test was performed in the console running the following snippet many times</p>\n\n<pre><code>t = performance.now();\nres = fuzzy.filter(searchStr, data);\ntotalTime += performance.now() - t;\ncount ++;\n</code></pre>\n\n<p>A complex <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\" rel=\"nofollow noreferrer\">regular expression</a>, on the same data required 1/10th the time.</p>\n\n<pre><code>t = performance.now();\nres = data.filter(name => regExpSearch.test(name));\ntotalTime += performance.now() - t;\ncount ++;\n</code></pre>\n\n<h2>Conclusion</h2>\n\n<p>What Node.js does well is IO, and what is does not do well is processing. </p>\n\n<p>Assuming one medium level server.</p>\n\n<ul>\n<li><p>1 second for a search is a very long time.</p></li>\n<li><p>Fuzzy.js performance is unlikely to change.</p></li>\n<li><p>A response time over a second puts your site in the bottom 20% of services, and is unacceptable.</p></li>\n<li><p>I estimate that at 30 thousand users performance will become a serious problem (see below)</p></li>\n</ul>\n\n<p>If you are serving 1million active users, (using the 20/80 rule) with 20% of users visiting your site one day a year 20% of them once a month and 20% of them once a week (~600,000 searches a year) with users geographically clustered resulting in significant peak times. </p>\n\n<p>It is highly likely that you will regularly have 30+ concurrent queries and a few times a year you can expect 300, in which case your server will be blocked for over 5 minutes.</p>\n\n<p><sup>(<strong>NOTE</strong>) these are very rough estimates based on one search per user per visit.</sup> </p>\n\n<h2>The answers</h2>\n\n<blockquote>\n <p><em>\"Will this causes to performance issue to my application or...\"</em></p>\n</blockquote>\n\n<p>Yes for a very heavy trafficked site this will present a serious performance issue.</p>\n\n<p>No for a very small traffic loads nobody will notice.</p>\n\n<blockquote>\n <p><em>\"...is there a Better Approach than this I should follow.\"</em></p>\n</blockquote>\n\n<p>Yes of course there is, use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\" rel=\"nofollow noreferrer\"><code>regExp</code></a>, and there are many more. But I can not hand out advice on speculation. The information given above is already dubious as it is based on a single request rather than the site/service as a whole.</p>\n\n<h2>Refection</h2>\n\n<p>Well gee... any nerd knows this...</p>\n\n<p>1+ million regular users is cash in the bank.</p>\n\n<p>A service must start somewhere and that is with a few users, with growth being gradual and predictable (once moving). If you are monetizing the service then growth is great and not a problem (if managed well). </p>\n\n<p>Start with the basics and work your way up. Replacing infrastructure (the search methods, upgrading the server/s) is part of the business. Performance is the least of your initial problems.</p>\n\n<p>If you plan for viral growth then you are in the realm of highly speculative investment capital. Outsource a solution to people that have the experience or you <strong>will</strong> miss a lucrative opportunity. </p>\n\n<p>If you plan to provide a free service for 1+ million users, good on you :), but you will need to have a fairly deep pocket.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T04:45:07.153",
"Id": "427737",
"Score": "0",
"body": "Great answer. Thanks a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:49:40.947",
"Id": "221200",
"ParentId": "221144",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221200",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T18:54:51.163",
"Id": "221144",
"Score": "4",
"Tags": [
"javascript",
"performance",
"node.js",
"search",
"mongodb"
],
"Title": "Enhancing search using Fuzzy Logic in NodeJS"
} | 221144 |
<p>I am using PostgreSQL 11.0 and I wrote a PL/pgSQL function to test if a word or phrase is contained within another phrase. This function is called several times within another function to extract some words from a paragraph. The execution of the calling function is slow, and I suspect it is because of this function:</p>
<pre><code>CREATE OR REPLACE FUNCTION public."Contains"(
p_text1 character varying,
p_text2 character varying)
RETURNS boolean
LANGUAGE 'plpgsql'
COST 100
immutable
AS $BODY$
declare
v_res integer := 0;
BEGIN
p_text2:= replace(p_text2, '(','\(');
p_text2:= replace(p_text2, ')','\)');
perform 1
where ( p_text1 similar to '((% )|(%-)|(%\())*'||p_text2||'(( %)|(-%)|(\)%))*' ) or
( replace(p_text1,'-',' ') similar to '((% )|(%\())*'||replace(p_text2,'-',' ')||'(( %)|(\)%))*' ) or
( replace(p_text1,'-','') similar to '((% )|(%\())*'||replace(p_text2,'-','')||'(( %)|(\)%))*' );
return found;
END;
$BODY$;
</code></pre>
<p>Words (or phrase) boundaries could be spaces (<code>' word '</code>), dashes (<code>'-word-'</code>), parentheses (<code>'(word)'</code>) or nothing (like when the word is at the beginning or the end of the phrase).</p>
<p>For example:</p>
<pre><code>select public."Contains"('domain-specific ontology' , 'domain'); -- true
select public."Contains"('domain-specific ontology' , 'ontology'); -- true
select public."Contains"('domain-specific ontology' , 'domain specific'); -- true
select public."Contains"('domain-specific ontology' , 'domain-specific'); -- true
select public."Contains"('information retrieval (IR)' , 'IR'); -- true
select public."Contains"('information retrieval (IR)' , 'information retrieval IR'); -- false
select public."Contains"('domain-specific ontology' , 'domain ontology'); -- false
</code></pre>
<p>This function is called in the outer function this way:</p>
<pre><code>perform 1
from some_table
where public."Contains"(col1, v_word) = true;
</code></pre>
<p><code>some_table</code> has no index on <code>col1</code>.</p>
<p>So, is there a faster alternative to the <code>SIMILAR TO</code> operator to perform the same regular expression matching?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T14:49:00.153",
"Id": "429040",
"Score": "0",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T16:27:39.523",
"Id": "429052",
"Score": "0",
"body": "can you suggest another title, please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T16:31:34.417",
"Id": "429053",
"Score": "1",
"body": "Well, I have only a limited understanding of what you're doing, but perhaps just from the first sentence, \"*a PL/pgSQL function to test if a word or phrase is contained within another phrase*\" could be a possibility? (Any question with [tag:performance] is obviously interested in faster alternatives, so it's redundant to mention that in the title, as well as being against site standards)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T19:08:05.360",
"Id": "221146",
"Score": "3",
"Tags": [
"performance",
"regex",
"postgresql",
"plpgsql"
],
"Title": "PL/pgSQL function to test if a word is contained within a phrase"
} | 221146 |
<p>I came across a question asked <a href="https://crypto.stackexchange.com/q/70068/66911">here</a> and <a href="https://crypto.stackexchange.com/q/68705/66911">here</a> on the <a href="https://crypto.stackexchange.com">Crypto Stack Exchange</a> site, and decided to analyze it as a kind of case study. To demonstrate the concept, I wrote a short python script depicting the proposed encryption scheme. It's mostly list comprehensions or generator expressions and bitwise operations.</p>
<p><span class="math-container">$$C=E_k(m)$$</span>
<span class="math-container">$$C_\alpha = C\oplus m$$</span>
<span class="math-container">$$C_\beta = \overline{C}$$</span>
<span class="math-container">$$C_\Omega = C_\alpha\ ^\frown\ C_\beta$$</span></p>
<pre><code>#!/usr/bin/env python3
from Crypto.Cipher import DES
m = b'secret!!'
k = b'qwerty!!'
E = DES.new(k, DES.MODE_ECB)
C = E.encrypt(m)
C_alpha = int('0b'+''.join([f"{x:08b}" for x in C]), 2) ^ \
int('0b'+''.join([f"{x:08b}" for x in m]), 2)
C_beta = int('0b'+''.join([f"{x:08b}" for x in C]), 2) ^ \
int('0b' + '1' * len(''.join([f"{x:08b}" for x in C])), 2)
C_omega = f"{C_alpha:064b}" + f"{C_beta:064b}"
if __name__ == '__main__':
print(C_omega)
</code></pre>
<hr>
<p>Then I ended up with this alternative version. If you want to try it out, save it as <code>bad_scheme.py</code> so it can work properly with the next script:</p>
<pre><code>#!/usr/bin/env python3
from Crypto.Cipher import DES
m = b'secret!!'
k = b'qwerty!!'
E = DES.new(k, DES.MODE_ECB)
C = E.encrypt(m)
def bitwise_xor(bits_a, bits_b):
bits_out = ''.join([str(int(x)^int(y)) for x, y in zip(bits_a, bits_b)])
return(bits_out)
def bitwise_complement(bits_in):
bits_out = ''.join([str(~int(x)+2) for x in bits_in])
return(bits_out)
def C_alpha():
bits_out = bitwise_xor(''.join([f"{x:08b}" for x in C]),
''.join([f"{x:08b}" for x in m]))
return(bits_out)
def C_beta():
bits_out = bitwise_complement(''.join([f"{x:08b}" for x in C]))
return(bits_out)
def C_omega():
bits_out = C_alpha() + C_beta()
return(bits_out)
if __name__ == '__main__':
print(C_omega())
</code></pre>
<hr>
<p>And here's what is essentially a working exploit of the (hypothetical) proposed encryption scheme's vulnerability; demonstrating the plaintext can be revealed without the key. It imports the final ciphertext and the bitwise functions from the first script, and works backwards, and complements <span class="math-container">\$C_\beta\$</span> to get <span class="math-container">\$C\$</span> (because <span class="math-container">\$C_\beta\$</span> is essentially just <span class="math-container">\$\overline{C}\$</span>), then <span class="math-container">\$C \oplus C_\alpha\$</span> to reveal <span class="math-container">\$m\$</span> without requiring <span class="math-container">\$k\$</span>. So:</p>
<p><span class="math-container">$$\overline{C_\beta}=C$$</span>
<span class="math-container">$$C_\alpha \oplus C=m$$</span></p>
<pre><code>#!/usr/bin/env python3
from bad_scheme import C_omega, bitwise_xor, bitwise_complement
def C_alpha():
bits_out = C_omega()[:int(len(C_omega())/2)]
return(bits_out)
def C_beta:
bits_out = C_omega()[int(len(C_omega())/2):]
return(bits_out)
def C():
bits_out = bitwise_complement(C_beta())
return(bits_out)
def m():
bits_out = bitwise_xor(C_alpha(), C_beta())
return(bits_out)
if __name__ == '__main__':
print(''.join([chr(int(m()[i:i+8],2)) for i in range(0,len(m()),8)]))
</code></pre>
<hr>
<p>So, there it is. Just thought I'd put it out there and see what everyone thinks, which style is better, what's good about it, what's bad about it, and what I can do to improve it. It's not a real encryption scheme or anything, I'm mainly interested in feedback regarding design and execution, the handling of bitwise operations, and the general layout and structure of the code. I tried implementing a <code>class</code> and a few things to make it more robust and useful, but I couldn't pull it off. Also, is it better organized as functions? Or doing the same thing in fewer lines, just defining and operating on variables, and declaring no functions at all.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T19:14:57.840",
"Id": "427538",
"Score": "3",
"body": "To get LaTeX, use `\\$` (notice a backslash)."
}
] | [
{
"body": "<p>The conversions to bit-strings, then ints and back to strings are unnecessary. <code>m</code> and <code>k</code> are bytes, so the elements (e.g., <code>m[0]</code> or <code>k[i]</code>) are already integers in the range 0-255; bitwise operators can be applied to the elements directly.</p>\n\n<p>I think routines in the Crypto library return strings, so the <code>encrypt()</code> return value might need to be encoded before using it.</p>\n\n<pre><code>from Crypto.Cipher import DES\n\nm = b'secret!!'\nk = b'qwerty!!'\nE = DES.new(k, DES.MODE_ECB)\nC = E.encrypt(m)\n\nC = C.encode() # <- needed if encrypt() returns a string (i.e., not bytes)\n\nC_alpha = bytes(x^y for x,y in zip(C, m))\n\nC_beta = bytes(x^0xff for x in C)\n\nC_omega = C_alpha + C_beta\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T06:56:26.750",
"Id": "237950",
"ParentId": "221147",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T19:08:40.317",
"Id": "221147",
"Score": "9",
"Tags": [
"python",
"algorithm",
"security",
"cryptography",
"bitwise"
],
"Title": "Fun crypto problem: Exploiting a vulnerable encryption scheme with Python"
} | 221147 |
<p>Challenge:</p>
<blockquote>
<p>Return the length of the longest word in the provided sentence.</p>
</blockquote>
<p>I've made a solution that works but it is kinda bad since the time complexity is <span class="math-container">\$O(n \log n)\$</span> and it involves mutation.</p>
<pre><code>function findLongestWordLength(str) {
let strSplit = str.split(" ");
let wordLengthArray = [];
for(let i = 0; i < strSplit.length; i++)
{
wordLengthArray.push(strSplit[i].length);
}
wordLengthArray.sort(function(a , b){return a - b});
return wordLengthArray[wordLengthArray.length - 1];
}
</code></pre>
<p>I basically split the string, pushed all the word lengths in an empty array, then used the ascending sort function. After that I returned the last index of the new array which is the longest length.</p>
<p>Test Cases:</p>
<pre><code>findLongestWordLength("The quick brown fox jumped over the lazy dog") should return 6.
findLongestWordLength("May the force be with you") should return 5.
findLongestWordLength("Google do a barrel roll") should return 6.
findLongestWordLength("What is the average airspeed velocity of an unladen swallow") should return 8.
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") should return 19.
</code></pre>
<p>I would appreciate some hints/tips on a better algorithm.</p>
| [] | [
{
"body": "<p>What I'm seeing is that you touch the data twice. This isn't necessary for retrieving a simple fact about the data.</p>\n\n<p>Consider, saving the length of each word and comparing lengths as you go along. Even with a perfectly linear sort function (That is, O(n-1)) this will still cut down on algorithm complexity, simply because you aren't calling a sort function at all.</p>\n\n<p>EDIT: I had a variable saving the word as well as the length, but after reading over your question again, I found that that isn't what you were looking for.\nEDIT2: I removed my code because you said you wanted HINTs. sorry...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T21:02:20.813",
"Id": "221154",
"ParentId": "221153",
"Score": "3"
}
},
{
"body": "<p>You are creating an array of strings (using <code>str.split(\" \")</code>) as well as an array of numbers (<code>wordLengthArray</code>), then sorting <code>wordLengthArray</code>. All three of those operations are wasteful, if you are aiming for performance.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function findLongestWordLength(str) {\n let maxLen = -1;\n for (var i = 0, j; (j = str.indexOf(\" \", i)) != -1; i = j + 1) {\n maxLen = Math.max(maxLen, j - i);\n }\n return Math.max(maxLen, str.length - i);\n}\n\nconsole.log(6 == findLongestWordLength(\"The quick brown fox jumped over the lazy dog\"));\nconsole.log(5 == findLongestWordLength(\"May the force be with you\"));\nconsole.log(6 == findLongestWordLength(\"Google do a barrel roll\"));\nconsole.log(8 == findLongestWordLength(\"What is the average airspeed velocity of an unladen swallow\"));\nconsole.log(19 == findLongestWordLength(\"What if we try a super-long word such as otorhinolaryngology\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Depending on the browser/interpreter, your function is <a href=\"https://jsperf.com/findlongestwordlength/1\" rel=\"nofollow noreferrer\">33% to 86% slower</a> than mine.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T22:04:21.820",
"Id": "221156",
"ParentId": "221153",
"Score": "4"
}
},
{
"body": "<p>Thanks to @Kruga, here is a javascript implementation of my original pseudo code which gives the answer in a single pass. No splits, no arrays, no sorting:</p>\n\n<pre><code>function findLongestWordLength(str) {\n let currentCount = 0;\n let currentMax = 0;\n for(let char of str) {\n if(char != \" \") {\n currentCount += 1;\n }\n else {\n if(currentCount > currentMax) currentMax = currentCount;\n currentCount = 0;\n }\n }\n if(currentCount > currentMax) currentMax = currentCount; // take care of last word\n return currentMax;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T08:17:43.853",
"Id": "427588",
"Score": "0",
"body": "[Here](https://jsfiddle.net/7s3d5Lgt/) is the code written in javascript"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T07:47:47.497",
"Id": "221179",
"ParentId": "221153",
"Score": "3"
}
},
{
"body": "<p>This is like getting biggest number algorithm.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const text = 'The quick brown fox jumped over the lazy dog';\n\nconst longWord = n => {\n let arr = n.split(' ');\n\n let longestWordCount = arr[0];\n\n arr.forEach(element => {\n if (element.length > longestWordCount.length) {\n longestWordCount = element;\n }\n });\n console.log(longestWordCount.length);\n}\n\nlongWord(text);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T01:19:04.807",
"Id": "221232",
"ParentId": "221153",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221156",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T20:50:11.643",
"Id": "221153",
"Score": "3",
"Tags": [
"javascript",
"performance",
"algorithm",
"strings"
],
"Title": "Finding the Longest Word in a String"
} | 221153 |
<p>I'm working on a blog REST API and I would like to get some opinions on where to place the logic for a single operation to filter posts. </p>
<p>I have Category and Post in the model package. A category has a list of posts and a post has a single category.</p>
<p>The wrinkle is that posts can be hidden, meaning if you don't have the correct permission you won't see them. I'm using JPA and don't want vendor specific SQL so I'm doing the filtering after retrieving the posts since I can't join in the JPARepository.</p>
<p>Right now I have the helper method to filter a list of posts as package private in the PostController and the CategoryController autowires it in.</p>
<p>While that's less than ideal I feel like having a PostService for this one method might be overkill and it should be in an object rather than a service.</p>
<p>Other options I considered were having it in the SecurityService (doesn't really fit) or the Post model (it's not part of the model so shouldn't be here).</p>
<p>I also considered some design patterns but I don't think anything really fits here (decorator possibly but again seems like way too much).</p>
<p>This is a personal project so I'd really like to get it 'right'.</p>
<p>Post model</p>
<pre><code>@Entity
//ignore hibernate methods added to object automatically
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Post {
/* Required for hibernate since full constructor is declared for testing, do not remove */
public Post() {}
public Post(String description, String content, Date lastEditedDate, List<String> tags, String title, Category category, boolean isHidden) {
this.description = description;
this.content = content;
this.lastEditedDate = lastEditedDate;
this.tags = tags;
this.title = title;
this.category = category;
this.isHidden = isHidden;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Lob
@Column(length = 100000)
private String description;
@Lob
@Column(length = 100000)
private String content;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM-dd-yyyy")
private Date lastEditedDate;
@ElementCollection
private List<String> tags;
private String title;
@ManyToOne
@JoinColumn
private Category category;
private boolean isHidden;
public Long getId() {
return id;
}
//auto-generated but jackson needs the method for marshalling
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public boolean isHidden() {
return isHidden;
}
public void setHidden(boolean hidden) {
isHidden = hidden;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getLastEditedDate() {
return lastEditedDate;
}
public void setLastEditedDate(Date lastEditedDate) {
this.lastEditedDate = lastEditedDate;
}
}
</code></pre>
<p>Category Model</p>
<pre><code>@Entity
public class Category {
public Category(String name, Post... posts) {
this.name = name;
this.posts = Stream.of(posts)
.collect(Collectors.toList());
this.posts.forEach(post -> post.setCategory(this));
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
@OneToMany(mappedBy = "category")
private List<Post> posts;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Category category = (Category) o;
return id == category.id &&
Objects.equals(name, category.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
</code></pre>
<p>PostsController</p>
<pre><code>@RestController
@RequestMapping("/api/v1/posts")
@CrossOrigin(origins = {"${settings.allowed-origins}"})
public class PostsController {
private PostRepository postRepository;
private SecurityService securityService;
private Logger log = LoggerFactory.getLogger(PostsController.class);
@Autowired
public PostsController(PostRepository postRepository, SecurityService securityService) {
this.postRepository = postRepository;
this.securityService = securityService;
}
@GetMapping
public List<Post> list(Authentication authentication) {
boolean canViewHidden = securityService.hasAuthority(Permissions.Post.VIEWHIDDEN, authentication.getAuthorities());
return filterPosts(canViewHidden, postRepository.findAll());
}
//this is the method I'm looking for a home for
List<Post> filterPosts(boolean canViewHidden, List<Post> posts) {
return posts.stream()
.filter(post -> canViewHidden || !post.isHidden())
.collect(Collectors.toList());
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Post create(@RequestBody Post post) {
post.setLastEditedDate(new Date());
postRepository.save(post);
return post;
}
@GetMapping("/{id}")
public Post get(@PathVariable("id") long id, Authentication authentication) {
try {
Post p = postRepository.getOne(id);
if (!p.isHidden() || securityService.hasAuthority(Permissions.Post.VIEWHIDDEN, authentication.getAuthorities())) {
return p;
}
} catch (EntityNotFoundException e) {
log.info(String.format("Record not found for post id %d", id));
}
return null;
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable("id") long id) {
postRepository.deleteById(id);
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.CREATED)
public Post update(@PathVariable("id") long id, @RequestBody Post post) {
post.setId(id);
post.setLastEditedDate(new Date());
postRepository.save(post);
return post;
}
@RequestMapping(method = RequestMethod.OPTIONS)
@ResponseStatus(HttpStatus.ACCEPTED)
public void options() {
}
}
</code></pre>
<p>CategoryController</p>
<pre><code>@RestController
@RequestMapping("/api/v1/category")
@CrossOrigin(origins = {"${settings.allowed-origins}"})
public class CategoryController {
private CategoryRepository categoryRepository;
private SecurityService securityService;
private PostsController postsController;
private Logger log = LoggerFactory.getLogger(CategoryController.class);
@Autowired
public CategoryController(CategoryRepository categoryRepository, SecurityService securityService, PostsController postsController) {
this.categoryRepository = categoryRepository;
this.securityService = securityService;
this.postsController = postsController;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Category create(@RequestBody Category category) {
categoryRepository.save(category);
return category;
}
@GetMapping
public List<Category> list(Authentication authentication) {
boolean canViewHidden = securityService.hasAuthority(Permissions.Post.VIEWHIDDEN, authentication.getAuthorities());
List<Category> categories = categoryRepository.findAll();
categories.forEach(category -> filterCategoryPosts(canViewHidden, category));
return categories;
}
@GetMapping("/{id}")
public Category get(@PathVariable("id") long id, Authentication authentication) {
try {
boolean canViewHidden = securityService.hasAuthority(Permissions.Post.VIEWHIDDEN, authentication.getAuthorities());
return filterCategoryPosts(canViewHidden, categoryRepository.getOne(id));
} catch (EntityNotFoundException e) {
log.info(String.format("Record not found for post id %d", id));
}
return null;
}
private Category filterCategoryPosts(boolean canViewHidden, Category category) {
if (category == null)
return null;
List<Post> filteredPosts = postsController.filterPosts(canViewHidden, category.getPosts());
category.setPosts(filteredPosts);
return category;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T08:30:31.803",
"Id": "427589",
"Score": "0",
"body": "I think it is possible to make your default constructors private for hibernate. Also put the comment explaining why it is empty inside your constructor.\n\nFurthermore you should put al your variables before the constructor as is convention."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T21:24:24.377",
"Id": "221155",
"Score": "1",
"Tags": [
"java",
"spring"
],
"Title": "Spring boot for a blog REST API"
} | 221155 |
<p>I'm integrating my app with a payment gateway, and have the following code which returns an array to populate the transaction info:</p>
<pre><code>function populate_transaction_info($data)
{
extract($this->extract_model_data($data));
// set to empty array to ensure run-able code
$transaction_info = [];
return array_merge($transaction_info, [
'pan' => $card_data['card_number'],
'expdate' => $this->build_expiry_date_string($card_data['card_exp']),
'cust_id' => $person['email'],
// ... more params here, not relevant for question
]);
}
// shown for context / run-ability
function extract_model_data($data)
{
return [
'person' => $data['Person'],
'card_data' => $data['CreditCard']],
];
}
</code></pre>
<p>My question pertains to the <code>build_expiry_date_string()</code>, defined as:</p>
<pre><code>function build_expiry_date_string($card_expiry)
{
return $card_expiry['month'] . substr($card_expiry['year'], -2);
}
</code></pre>
<p>I'm passing <code>$card_data['card_exp']</code> into the function, but I'm wondering if the function itself should be the only thing that knows that it needs to look in the <code>card_exp</code> index of the array? So for example, should I refactor as:</p>
<pre><code>...
'expdate' => $this->build_expiry_date_string($card_data),
...
function build_expiry_date_string($card_data)
{
return $card_data['card_exp']['month'] . substr($card_data['card_exp']['year'], -2);
}
</code></pre>
<p>If yes, why?</p>
| [] | [
{
"body": "<p>Your first version of <code>build_expiry_date_string()</code> will be able to build an shorter notation date from any date array. I would therefore rename it to <code>build_short_date_string()</code>. </p>\n\n<p>The second version actually is named correctly, but can <em>only</em> convert an expiry date to the shorter notation. </p>\n\n<p>Which is the better version?</p>\n\n<p>Well, clearly, if you need to create a short date string from more than one date array then the first one wins. The second one is more specialized. It will only work for the <code>card_exp</code> date.</p>\n\n<p>In general I don't see the point of overspecializing functions. The more general purpose version does a good job, so I would prefer that one, even if it is, for now, only used for one date array.</p>\n\n<p><strong>Functions should be used to encapsulate functionality that can be reused and therefore make your code easier to maintain.</strong> (<a href=\"https://www.guru99.com/functions-in-php.html\" rel=\"nofollow noreferrer\">reference</a>)</p>\n\n<p>It is the <em>reusability</em> that wins for me here, over any other considerations.</p>\n\n<p>Note that we're talking about simple functions here, not methods that are part of classes. OOP is a whole other can of worms.</p>\n\n<p>Some other remarks about your code (this is code review afterall):</p>\n\n<ul>\n<li>You <code>extract()</code> data at the beginning of <code>populate_transaction_info()</code>. This seems like a nice trick, but it makes your code harder to read and debug. For instance, I have to assume that <code>$person</code> is one of these extracted variables, but for me it appears out of thin air. You could help your code reader by using a prefix whenever your extract something: <code>extract(...., EXTR_PREFIX_ALL, 'model');</code> and then use <code>$model_person</code>, but preferably just explicitly define the person variable in the function.</li>\n<li>Your comment: <em>\"set to empty array to ensure run-able code\"</em> and the subsequent <code>array_merge()</code> make no sense to me. Why not just define the array?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T11:07:28.477",
"Id": "427595",
"Score": "1",
"body": "Amen to not endorsing `extract()`. I have never had a reason to use, nor do I ever hope to use `extract()` in any project, ever."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T13:19:42.933",
"Id": "427611",
"Score": "0",
"body": "Thanks for the feedback, I really appreciate it! I will rename and keep the first version for re-usability. I also knew I was going to get called out for using extract, heh. I will be more explicit about pulling the appropriate variables out of `$data`. Finally, the comment was just for this example... `$transaction_info` is initialized with some data called from another function, but I didn't feel it was super necessary to include here. Sorry for the confusion."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T01:48:43.967",
"Id": "221168",
"ParentId": "221158",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221168",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T22:25:39.033",
"Id": "221158",
"Score": "0",
"Tags": [
"php",
"comparative-review",
"e-commerce"
],
"Title": "Filling in the card expiry date from transaction data"
} | 221158 |
<p>I have an if-else statement in a php class, which works perfectly. I want to know if there could be an any better or faster way to accomplish this?</p>
<pre><code><form method="post" action="">
<input type="text" name="value_1" value="" ><br>
<br>
<input type="text" name="value_2" value="" ><br>
<br>
<input type="submit" value="submit">
</form>
<?php
$value_1 = $_POST['value_1'];
$value_1 = $_POST['value_2'];
$default = 'value_default';
if( !empty($value_1) && empty($value_2)){
echo $value_1;
} elseif( !empty($value_2) && empty($value_1) ){
echo $value_2;
} elseif (!empty($value_1) && !empty($value_2)){
echo $value_1 .' - '. $value_2;
} else {
echo $default;
}
?>
</code></pre>
<p>In my Code, there are 4 conditions, </p>
<ol>
<li>Value 1 is set (in this case value 2 will be empty)</li>
<li>Value 2 is set (in this case value 1 will be empty)</li>
<li>Both the values are set (in this case both values are set)</li>
<li>Both the values are empty (none of the values are set)</li>
</ol>
<p>All the values will be sent to the function via a normal HTML form.</p>
| [] | [
{
"body": "<p>Please note that you should be posting working code in your question, not pseudo code. It is a general rule for Code Review questions.</p>\n\n<p>There is also a problem with your pseudo code. Your <code>function_3</code> will never get executed. Note that the first two <code>if</code> blocks require either <code>$value_1</code> or <code>$value_2</code> to be filled, which is exactly what the third <code>if</code> block states. Since it is in the third position it will never get executed. You would have know this if it was actual code. That's one of the reasons you should post working code.</p>\n\n<p>So it can be rewitten as:</p>\n\n<pre><code>if (empty($value_1)) {\n if (empty($value_2)) {\n function_default(){ }\n }\n else {\n function_2(){ }\n } \n} elseif (empty($value_2)) {\n function_1(){ } \n}\n</code></pre>\n\n<p>But I doubt this is useful to you, since you clearly want to do something else.</p>\n\n<p>Your code suggests you want to define functions depending on certain conditions. I cannot think of any good reason to do this. Can you give me one?</p>\n\n<p>So, can your code be written better? Yes, it clearly can. Can it be made faster? Given the little code you've written, I have to say: No.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T12:26:32.107",
"Id": "427601",
"Score": "0",
"body": "Since downvoters hardly ever tell you why they downvote, I have to assume that they regards any answer to a bad question a bad answer. But is that always true? Or might there be a valid reason for the downvotes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T15:09:32.287",
"Id": "427653",
"Score": "0",
"body": "Hi, Thank you for your reply. I have updated my question. The code I posted works well for me. I just want to make it more robust. Yes, First 2 If require either value_1 or value_2 to be set but my third if require both the value_1 and value_2 to be set/non-empty."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T15:13:57.377",
"Id": "427654",
"Score": "2",
"body": "@KIKOSoftware I’d assume the same, since [you should refrain from answering off-topic questions](https://codereview.meta.stackexchange.com/q/6388/84718)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T15:35:14.123",
"Id": "427655",
"Score": "0",
"body": "@DeepakSingh You're using an `||` (= or) in the third condition, so it says: \"if value1 is set or value2 is set\". It will be false when both are set. Perhaps you intend to use an `&&` (= and)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T15:40:32.203",
"Id": "427656",
"Score": "0",
"body": "@MathiasEttinger There don't seem to be strict rules about this, and voting on an answer based purely on the question seems silly. I used an answer because it is longer than fitted in a comment: 1. don't use psuedo code. 2. There's a bug in your code. 3. Why conditionally create functions? In general there's a lack of good documentation on Code Review. How can someone know how to ask a question when all they have to go on is [this mess](https://codereview.meta.stackexchange.com/questions/2436/how-to-get-the-best-value-out-of-code-review-asking-questions)? (also read next comment)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T15:45:52.733",
"Id": "427657",
"Score": "0",
"body": "@DeepakSingh: Why you start asking a question it says: \"Your question **must contain code that is already working correctly**, and the relevant code sections must be embedded in the question. Please avoid stripping out key details that may be relevant to the review.\". You question still doesn't fulfill this prerequisite."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:09:15.127",
"Id": "427662",
"Score": "3",
"body": "@KIKOSoftware It's not silly to deincentivize answers to off-topic questions - It's not behavior we want. If you need to write a comment that doesn't fit in a comment box, make it a [disposable CW](https://codereview.meta.stackexchange.com/a/6977)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:16:12.223",
"Id": "427667",
"Score": "0",
"body": "@KIKOSoftware I am sorry for the mistake about &&. Yes, It is &&. And I am confused about what more details should I post. I simply posted what is my actual problem. Posting full code will make it just complex, and unrelated. I am not creating function conditionally, instead, I am just executing them conditionally. First I posted it on StackOverflow I got suggestions there to post it here, so I did. Understanding and answering this is very easy, but since tomorrow I am just getting the downvotes and suggestion on how to post instead of getting a solution. BTW, Thank you for your efforts :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T17:42:59.333",
"Id": "427694",
"Score": "0",
"body": "@KIKOSoftware Thank your suggestion worked great for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T22:12:14.673",
"Id": "427729",
"Score": "0",
"body": "@DeepakSingh If you've learned what you needed to know then I wouldn't bother revising the question. Just accept the downvotes, they do happen from time to time. Just remember that Code Review demands working code, and is quite strict about that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T22:15:21.907",
"Id": "427730",
"Score": "0",
"body": "@KIKOSoftware yes, It was my first post here. I will take care of this, from the next time."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T01:05:37.337",
"Id": "221166",
"ParentId": "221159",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": "221166",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T22:34:14.583",
"Id": "221159",
"Score": "-3",
"Tags": [
"php"
],
"Title": "What would be the best way to accomplish this If-else check?"
} | 221159 |
<p>I am a complete beginner when it comes to programming and writing games and this is my first ever game. I made it with python 3 using <code>pygame</code> library. I would appreciate any feedback really. </p>
<pre><code>from __future__ import annotations
from typing import Tuple, List
import pygame
import random
import sys
# screen width & height and block size
bg_width = 500
bg_height = 500
block_size = 10
# direction strings
left = "LEFT"
right = "RIGHT"
up = "UP"
down = "DOWN"
# colors (RGB)
bg_color = black = (0, 0, 0)
yellow = (255, 255, 0)
green = (0, 128, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
# pygame & font initialization
pygame.init()
window = pygame.display.set_mode((bg_width, bg_height))
pygame.display.set_caption("Snake")
font = pygame.font.SysFont('Times New Roman', 20)
text_colour = pygame.Color('White')
fps = pygame.time.Clock()
class Snake:
"""This class represents a snake object. Every snake object consists of a head
and its body.
===Attributes===
head: snake head
color: snake color
body: snake body
direction: direction of head
size: size of snake (head and body)
"""
head: List[int, int]
color: Tuple[int, int, int]
body: List[List[int, int]]
direction: str
size: int
def __init__(self, color: Tuple[int, int, int]) -> None:
self.head = [int(10*block_size), int(5*block_size)]
self.color = color
self.body = [self.head, [9*block_size, 5*block_size]]
self.direction = right
self.size = 2
def change_dir(self, direc: str) -> None:
if self.direction != left and direc == right:
self.direction = right
elif self.direction != right and direc == left:
self.direction = left
elif self.direction != down and direc == up:
self.direction = up
elif self.direction != up and direc == down:
self.direction = down
def move(self) -> None:
if self.direction == right:
self.head[0] += block_size
elif self.direction == left:
self.head[0] -= block_size
elif self.direction == up:
self.head[1] -= block_size
elif self.direction == down:
self.head[1] += block_size
self.body.insert(0, list(self.head))
self.body.pop()
if self.body[0] != self.head:
self.head = self.body[0]
def add_to_tail(self) -> None:
new_part = [self.body[-1][0], self.body[-1][1]]
self.body.append(new_part)
self.size += 1
def get_body(self) -> List[List[int, int]]:
return self.body
class Food:
"""This class represents a food object. Each food object has an x
and a y value, a color and a state.
===Attributes===
x: x-coordinate of food object
y: y-coordinate of food object
color: color of food object
state: whether food object is on screen or not
position: x,y-coordinates pair of food object
"""
x: int
y: int
color: Tuple[int, int, int]
state: bool
position: Tuple[int, int]
def __init__(self, color: Tuple[int, int, int]) -> None:
self.x = random.randint(0, bg_width//block_size - 1)*block_size
self.y = random.randint(0, bg_height//block_size - 1)*block_size
self.color = color
self.state = True
self.position = self.x, self.y
def spawn(self) -> Tuple[int, int]:
if self.state:
return self.x, self.y
else:
self.state = True
self.x = random.randint(0, bg_width // block_size-1) * block_size
self.y = random.randint(0, bg_height // block_size-1) * block_size
return self.x, self.y
def update(self, state) -> None:
self.state = state
def collision(snake_: Snake, food_target_x: int, food_target_y: int) -> int:
snake_rect = pygame.Rect(*snake_.head, block_size, block_size)
food_rect = pygame.Rect(food_target_x, food_target_y, block_size,
block_size)
if snake_rect == food_rect:
snake_.add_to_tail()
return 1
return 0
def wall_collision(s: Snake) -> bool:
if (s.head[0] < 0) or (s.head[0] > bg_width-block_size) or (s.head[1] < 0)\
or (s.head[1] > bg_height-block_size):
return True
return False
def game():
# initialize food and snake
food = Food(blue)
snake = Snake(green)
# initialize loop logic
running = True
is_over = False
# initialize score
score = 0
# game loop
while running:
# Game over Screen
while is_over:
text_on_screen = font.render("You scored: " + str(score) +
", Press R to play again or Q to quit",
True, text_colour)
window.blit(text_on_screen, [55, 225])
for event in pygame.event.get():
pressed_key = pygame.key.get_pressed()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if pressed_key[pygame.K_q]:
pygame.quit()
sys.exit()
if pressed_key[pygame.K_r]:
game()
pygame.display.update()
# check events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pressed = pygame.key.get_pressed()
if pressed[pygame.K_RIGHT] or pressed[pygame.K_d]:
snake.change_dir(right)
elif pressed[pygame.K_LEFT] or pressed[pygame.K_a]:
snake.change_dir(left)
elif pressed[pygame.K_UP] or pressed[pygame.K_w]:
snake.change_dir(up)
elif pressed[pygame.K_DOWN] or pressed[pygame.K_s]:
snake.change_dir(down)
# fill window and draw snake
window.fill(black)
for item in snake.get_body():
pygame.draw.rect(window, snake.color, [item[0], item[1], block_size,
block_size])
# move snake
snake.move()
# check for collision with wall:
collision_with_wall = wall_collision(snake)
if collision_with_wall:
is_over = True
# check if food is still on screen and draw it
food_pos = food.spawn()
collision_ = collision(snake, *food_pos)
if collision_ == 1:
score += 1
food.update(False)
pygame.draw.rect(window, food.color, [food_pos[0], food_pos[1],
block_size, block_size])
# renders display
pygame.display.flip()
# time delay
pygame.time.delay(60)
fps.tick(30)
pygame.quit()
quit()
game()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T00:23:32.133",
"Id": "427560",
"Score": "4",
"body": "It looks good, especially for your first game :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T18:44:31.440",
"Id": "427870",
"Score": "0",
"body": "I barely know Python: would `body: List [Tuple[int,int]]` be better? You have XY pairs, not a list of variable-length lists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-02T07:21:55.777",
"Id": "428338",
"Score": "0",
"body": "Where did you get the `__future__` package from? I can't install it using PyCharm."
}
] | [
{
"body": "<h1>PEP 8</h1>\n\n<p>PEP 8 recommends that constants be written as <a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"noreferrer\">\"all capital letters with underscores separating words.\"</a>. So something like:</p>\n\n<pre><code>yellow = (255, 255, 0)\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>YELLOW = (255, 255, 0)\n</code></pre>\n\n<p>or possibly an <code>enum</code> (more on this later)</p>\n\n<h1>Inconsistent quotations</h1>\n\n<p>Usually a project will stick with either <code>\"\"</code> or <code>''</code> unless you have particular reason not to.<sup>1</sup> But for instance:</p>\n\n<pre><code>pygame.display.set_caption(\"Snake\")\nfont = pygame.font.SysFont('Times New Roman', 20)\ntext_colour = pygame.Color('White')\n</code></pre>\n\n<p>violates the uniformity unnecessarily.</p>\n\n<h1>Enums</h1>\n\n<p>To quote the docs on <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\"><code>enum</code></a>:</p>\n\n<blockquote>\n <p>An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.</p>\n</blockquote>\n\n<p>So for instance:</p>\n\n<pre><code>left = \"LEFT\"\nright = \"RIGHT\"\nup = \"UP\"\ndown = \"DOWN\"\n</code></pre>\n\n<p>becomes: </p>\n\n<pre><code>from enum import Enum\nclass Direction(Enum):\n LEFT = \"LEFT\"\n RIGHT = \"RIGHT\"\n DOWN = \"DOWN\"\n UP = \"UP\"\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/22594360/667648\">See here</a> for more reasons why you should port your stringy code to enums. In addition, there are probably some integer arithmetic tricks you <em>could</em> use to eliminate a lot of the <code>if</code>-<code>elif</code>-<code>else</code> chains. (You will need to do some further refactoring to get this to run without error.)</p>\n\n<h1>Unnecessary Comments</h1>\n\n<p>Consider:</p>\n\n<pre><code># initialize food and snake\nfood = Food(blue)\nsnake = Snake(green)\n\n# initialize loop logic\nrunning = True\nis_over = False\n\n# initialize score\nscore = 0\n\n# game loop\nwhile running:\n</code></pre>\n\n<p>I, personally, would omit all the comments. I could see where a case can be made the game loop comments in the case that someone is trying to understand the code without knowledge of game loops, but I would argue the concept of a game loop is so ubiquitous that those comments get in the way. </p>\n\n<p>If you had to write comments I would instead write:</p>\n\n<pre><code># Initialize entities/data for new game\nfood = Food(blue)\nsnake = Snake(green)\nscore = 0\n\n# Init/start game loop\nrunning = True\nis_over = False\nwhile running:\n ...\n</code></pre>\n\n<p>Even then, I'm not quite satisfied with it, but the moral it to not <a href=\"https://blog.codinghorror.com/code-tells-you-how-comments-tell-you-why/\" rel=\"noreferrer\">add redundant comments</a>. However, there may be some debate on this.</p>\n\n<p>The best example is probably:</p>\n\n<pre><code> # move snake\n snake.move()\n</code></pre>\n\n<p>Really think about what this comment contributes.</p>\n\n<h1>Unnecessary assignments</h1>\n\n<p>I'm not sure why you wrote:</p>\n\n<pre><code> # check for collision with wall:\n collision_with_wall = wall_collision(snake)\n if collision_with_wall:\n is_over = True\n</code></pre>\n\n<p>When:</p>\n\n<pre><code> if wall_collision(snake):\n is_over = True\n</code></pre>\n\n<p>suffices.</p>\n\n<h1>Add a <code>main</code> function</h1>\n\n<p>You should consider adding <a href=\"https://stackoverflow.com/a/20158605/667648\">a <code>main</code> function to your project.</a> This is usually done through the introduction of:</p>\n\n<pre><code>if __name__ == \"__main__\":\n game()\n</code></pre>\n\n<p>This allows for me to <code>import</code> your project and not have it automatically execute the game function at the bottom. Increasing re-usability.</p>\n\n<p><sup>1 For instance, It may be the project defaults to <code>\"\"</code>, but you need to print out <code>\" Hi \"</code> with the quotes, so <code>print('\" Hi \"')</code> may be chosen.</sup></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:27:35.373",
"Id": "427645",
"Score": "0",
"body": "Nice answer! +1 also for the excellent summary of the `main` function. That thread you linked to is a great help, but your quick one sentence summary is one of the best TL;DR's I've seen of that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T09:53:54.247",
"Id": "427766",
"Score": "1",
"body": "In section \"Unnecessary assignments\" is there reason we would want to do `if wall_collision(snake): is_over = True` instead of `is_over = wall_collision(snake)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:01:02.560",
"Id": "427799",
"Score": "2",
"body": "@vakus, those are two different things. Perhaps there are many possible checks above that can also set is_over to True, in which case we don't want to set it back to False which your suggested code would do."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T04:17:31.930",
"Id": "221173",
"ParentId": "221163",
"Score": "45"
}
},
{
"body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/221173/201170\">another answer</a> I will add these places to improve (I will not repeat all things from that answer, my answer is just an addition):</p>\n\n<h3>1. Code inconsistency</h3>\n\n<p>You have several places in your code where your code is inconsistent</p>\n\n<pre><code>def collision():\n...\n return 1\n return 0\n\n\ndef wall_collision():\n...\n return True\n return False\n</code></pre>\n\n<p>Both functions are checking collisions but one returns integer (0/1) and another - boolean (True/False).</p>\n\n<pre><code>self.head = [int(10*block_size), int(5*block_size)]\nself.body = [self.head, [9*block_size, 5*block_size]]\n</code></pre>\n\n<p>For <code>head</code> you convert <code>X*block_size</code> to int (it is unnecessary anyway). For <code>body</code> you don't do it.</p>\n\n<p>I recommend you to always check your code for possible inconsistency.</p>\n\n<h3>2. Names inconsistency</h3>\n\n<p>I moved it to an another point because it is not about how your code works - it is about how another programmers will read your code.</p>\n\n<p>Look at this two lines:</p>\n\n<pre><code>def change_dir(self, direc: str) -> None:\n if self.direction != left and direc == right:\n</code></pre>\n\n<p>You use three different namings for direction entity:</p>\n\n<ul>\n<li><code>dir</code></li>\n<li><code>direct</code></li>\n<li><code>direction</code></li>\n</ul>\n\n<p>It is <strong>far</strong> better to use consistent variable names. If you are using different direction variables, get them names with only one word for directions. Here is the example:</p>\n\n<ul>\n<li><code>snake_direction</code></li>\n<li><code>pokemon_direction</code></li>\n<li><code>some_strange_direction</code></li>\n</ul>\n\n<p>or:</p>\n\n<ul>\n<li><code>enemy_dir</code></li>\n<li><code>arrow_dir</code></li>\n<li><code>some_another_strange_dir</code></li>\n</ul>\n\n<h3>3. Small code improvements</h3>\n\n<p>Sometimes you look at your code and think: \"Hmmm, it is working but looks not good\". Often in these cases you can slightly reorganize your code to make it a bit better :)</p>\n\n<pre><code>for event in pygame.event.get():\n pressed_key = pygame.key.get_pressed()\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if pressed_key[pygame.K_q]:\n pygame.quit()\n sys.exit()\n</code></pre>\n\n<p>can be shortened to:</p>\n\n<pre><code>for event in pygame.event.get():\n pressed_key = pygame.key.get_pressed()\n if event.type == pygame.QUIT or pressed_key[pygame.K_q]:\n pygame.quit()\n sys.exit()\n</code></pre>\n\n<p>This line of code is correct too but it is hard to read:</p>\n\n<pre><code>if (s.head[0] < 0) or (s.head[0] > bg_width-block_size) or (s.head[1] < 0)\\\n or (s.head[1] > bg_height-block_size):\n</code></pre>\n\n<p>But it will be far better to read if you will change it to:</p>\n\n<pre><code>if (s.head[0] < 0 or\n s.head[0] > bg_width-block_size or\n s.head[1] < 0 or\n s.head[1] > bg_height-block_size):\n</code></pre>\n\n<p>or even this (sometimes I use it for really long if's):</p>\n\n<pre><code>is_wall_collision = any([\n s.head[0] < 0,\n s.head[0] > bg_width-block_size,\n s.head[1] < 0,\n s.head[1] > bg_height-block_size\n])\nif is_wall_collision:\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T10:15:54.440",
"Id": "221185",
"ParentId": "221163",
"Score": "23"
}
},
{
"body": "<pre><code> size: int\n...\n\n self.size = 2\n</code></pre>\n\n<p>You never read <code>size</code>, and Python Lists already know their own length in case you did need it.</p>\n\n<p>You're just duplicating functionality that <code>List</code> already gives you by manually keeping <code>size</code> in sync with the list length.</p>\n\n<hr>\n\n<p><strong>Separate game logic from screen rendering details</strong></p>\n\n<p>You keep snake coordinates scaled by pixels. This seems to complicate your code everywhere with <code>block_size</code> instead of <code>1</code>; I suspect it would be easier to keep snake coordinates in units of blocks, and only scale to pixels for drawing purposes.</p>\n\n<p>e.g. then your outer-wall check could be something like <code>s.head[0] >= bg_width</code> instead of<br>\n<code>s.head[0] > bg_width-block_size</code>.</p>\n\n<p><code>1</code> is special for integers because it's the difference between <code>></code> and <code>>=</code></p>\n\n<hr>\n\n<p>I like your <code>add_to_tail</code> idea of putting multiple snake segments in the same place initially, so <code>move</code> on future turns actually makes the snake longer on screen. That high-level design might be worthy of a comment.</p>\n\n<p>The other option would be a \"future growth\" counter that you check (and decrement) every move to decide whether to remove the last tail block. (That's what I was expecting because I hadn't thought of your idea). Your way is more efficient and will still work if you want food to cause multiple segments of growth. You can still do them all when the food is eaten.</p>\n\n<hr>\n\n<p>Keeping a separate <code>head</code>: I'm not sure this is helping you. Functions that want to look at the first segment can do <code>head = snake_.body[0]</code>.</p>\n\n<p>I don't understand why <code>move</code> needs to do this:</p>\n\n<pre><code> if self.body[0] != self.head:\n self.head = self.body[0]\n</code></pre>\n\n<p>when it looks to me like inserting the modified <code>head</code> as a new first element will already create that condition. So either this is redundant (and confusing), or else it's extra work that you wouldn't need to do if you didn't redundantly keep the head coordinates in 2 places. (Front of the List, and in its own object.)</p>\n\n<hr>\n\n<pre><code> direction: str\n</code></pre>\n\n<p><strong>This should be an enum or integer, not a string</strong>. String compares are fairly cheap, but not as cheap as integers. There's no reason that a direction needs to be an arbitrary string when it can take only 1 of 4 possible values. A string isn't making your code any easier to read.</p>\n\n<p>You probably still want the if/elif chain to turn a direction into an x or y offset, but another option for an integer would be a lookup table of <code>[-1, 0]</code> , <code>[1, 0]</code> etc. so you look up the x and y offsets for the given direction and just add them to the head's x and y coordinates without any conditionals.</p>\n\n<p><strong>Or <code>direction</code> could actually <em>be</em> an XY vector, removing the lookup step.</strong></p>\n\n<pre><code> head[0] += direction[0]\n head[1] += direction[1]\n</code></pre>\n\n<p>But that might complicate <code>change_dir</code>. Or give you a different implementation: to check for reversing direction: if <code>new_dir + old_dir == [0,0]</code> then you tried to double back. Otherwise you <em>can</em> set <code>dir = new_dir</code>.</p>\n\n<p>I like your design for having the keyboard-input just call <code>change_dir</code> to check the game-logic of that input. That works very cleanly, and would still work if <code>left</code> was defined as <code>[-1, 0]</code> instead of <code>\"LEFT\"</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T20:21:07.203",
"Id": "221219",
"ParentId": "221163",
"Score": "10"
}
},
{
"body": "<p>Good going on your first game. I completely agree with most of the points made by others. Here are a few more nitpicks. This answer is a bit long-winded, but take it as a complement. :-)</p>\n\n<h2>Unpack the Coordinates</h2>\n\n<p>This is what lines 195-197 currently look like:</p>\n\n<pre><code> for item in snake.get_body():\n pygame.draw.rect(window, snake.color, [item[0], item[1], block_size,\n block_size])\n</code></pre>\n\n<p>Instead of relying on indexing, we can directly unpack <code>item</code> into its respective xy-coordinates. This makes for good brevity and readability.</p>\n\n<pre><code> for x, y in snake.get_body():\n pygame.draw.rect(window, snake.color, [x, y, block_size, block_size])\n</code></pre>\n\n<p>The same can be done for lines 208-214.</p>\n\n<pre><code># Before:\n food_pos = food.spawn()\n collision_ = collision(snake, *food_pos) # \n if collision_ == 1:\n score += 1\n food.update(False)\n pygame.draw.rect(window, food.color, [food_pos[0], food_pos[1], # \n block_size, block_size])\n\n\n# After:\n food_x, food_y = food.spawn()\n # the rest is left as an exercise for the reader\n</code></pre>\n\n<h2>On <code>wall_collision(Snake)</code></h2>\n\n<p>Here's what the <code>wall_collision</code> function currently looks like (lines 137-141):</p>\n\n<pre><code>def wall_collision(s: Snake) -> bool:\n if (s.head[0] < 0) or (s.head[0] > bg_width-block_size) or (s.head[1] < 0)\\\n or (s.head[1] > bg_height-block_size):\n return True\n return False\n</code></pre>\n\n<ol>\n<li>Being a predicate (i.e. a function which returns a boolean), the function can be better named. You can always find a way to name a predicate such that it is prefixed with <code>is</code> or <code>has</code>. Instead of <code>wall_collision</code>, I'd go with <code>is_colliding_with_wall</code> or <code>collides_with_wall</code> to communicate the intention better.</li>\n<li>It could be simplified. <a href=\"https://codereview.stackexchange.com/a/221185/197524\">vurmux's answer</a> suggests a few possible ways. However, there exists an easier (and more readable) way of writing it in one line:</li>\n</ol>\n\n<pre><code> return not ((0 < s.head[0] < bg_width-block_size) and (0 < s.head[1] < bg_height-block_size))\n</code></pre>\n\n<p><sup>I intentionally added the extraneous parentheses to group comparisons.</sup></p>\n\n<p>This is made possible by Python's <a href=\"https://stackoverflow.com/questions/26502775/pycharm-simplify-chained-comparison/\">comparison \"chaining\"</a> along with <a href=\"https://brilliant.org/wiki/de-morgans-laws/\" rel=\"noreferrer\">De Morgan's Laws</a>. For fun, you can try to prove that the two snippets are equivalent.</p>\n\n<h2>Points and Coordinates</h2>\n\n<p>It took a while for me to figure out what the following line meant:</p>\n\n<pre><code>self.head = [int(10*block_size), int(5*block_size)]\n</code></pre>\n\n<p>I'm <em>guessing</em> this is a point/coordinate? Looks like it.</p>\n\n<p>Lists are so prevalent in Python, that they can hold a multitude of meanings. What's more, they are <em>variable-length</em> constructs, which communicates something else: you might be <em>changing</em> the length of the object in the future. This might mean appending, erasing, or inserting into the list.</p>\n\n<p><code>self.body</code> uses a list appropriately, since it will be appended to and popped from in various places. On the other hand, not once does <code>self.head</code> use <code>list.append</code>, <code>list.pop</code>, or <code>list.insert</code> and this raises a question: does it need to be a list at all? It is better made a tuple, which is a fixed-length construct and immediately communicates to the reader that we won't be modifying the length of <code>self.head</code>.</p>\n\n<p>I commend the usage of tuples in <code>Food.spawn()</code> for this very reason. Still, tuples can carry a multitude of different meanings. We can do better by using <code>collections.namedtuple</code> and creating a record-type <code>Point</code> for the purpose of representing xy-coordinates. This can greatly reduce ambiguity and improve readability.</p>\n\n<pre><code>from collections import namedtuple\nPoint = namedtuple('Point', ['x', 'y']) # we now have a Point type \n\nclass Snake:\n ...\n def __init__(self, color: Tuple[int, int, int]) -> None:\n self.head = Point(10*block_size, 5*block_size) # foolproof: self.head is a point \n self.body = [self.head, Point(...)]\n ...\n def add_to_tail(self) -> None:\n self.body.append(Point(self.body[-1][0], self.body[-1][1]))\n self.size += 1\n</code></pre>\n\n<p>The only pain with namedtuple is that we can't explicitly do assignments, which can be solved by making a new object:</p>\n\n<pre><code>def move(self) -> None:\n if self.direction == right:\n\n# Before:\n self.head.x += block_size # AttributeError: can't set attribute \n\n# After:\n self.head = Point(self.head.x + block_size, self.head.y) # preferable\n# or:\n self.head = self.head._replace(x=self.head.x + block_size) # looks hacky \n</code></pre>\n\n<p>You can also use <code>Point</code> as a replacement for <code>Food.position</code>, which isn't being used.</p>\n\n<pre><code>class Food:\n ...\n position: Point\n\n def __init__(self, color: Tuple[int, int, int]) -> None:\n self.position = Point(x=random.randint(0, bg_width//block_size - 1)*block_size\n y=random.randint(0, bg_width//block_size - 1)*block_size)\n\n def spawn(self) -> Point: # more explicit\n if self.state:\n return self.position\n else:\n self.state = True\n self.position = Point(x=random.randint(0, bg_width//block_size - 1)*block_size\n y=random.randint(0, bg_width//block_size - 1)*block_size) \n return self.position\n</code></pre>\n\n<p>I think this is especially useful when used together with <a href=\"https://codereview.stackexchange.com/a/221219/197524\">Cordes's suggestion in his answer</a>, in his <strong>Separate game logic from screen rendering details</strong> section.</p>\n\n<p>Another good thing about namedtuple is that we can still do unpacking.</p>\n\n<pre><code> for x, y in snake.get_body(): # still works\n pygame.draw.rect(window, snake.color, [x, y, block_size, block_size])\n</code></pre>\n\n<h2>Refactor Random-Point Generation</h2>\n\n<p>There are two places where the coordinates of the food are updated with random integers, generated via a special formula. Based on the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">DRY</a> principle, I suggest refactoring the generation of random points to a single function <code>get_random_point()</code>.</p>\n\n<pre><code>def get_random_point():\n return Point(x=random.randint(0, bg_width//block_size - 1)*block_size\n y=random.randint(0, bg_width//block_size - 1)*block_size) \n</code></pre>\n\n<p>Then you can conveniently do <code>self.position = get_random_point()</code> without having to painfully, repetitively type out the above.</p>\n\n<h2>Refactoring <code>Food</code></h2>\n\n<p>Currently, <code>Food</code> updates its position only when <code>spawn()</code> is called and if <code>state</code> is false. Seems a bit long-winded. Even the name <code>update</code> seems to be untruthful as it makes a <em>delayed</em> update.</p>\n\n<p>I suggest updating the position immediately when <code>update()</code> is called.</p>\n\n<pre><code> def spawn(self) -> Tuple[int, int]:\n return self.position\n\n def update(self):\n self.position = get_random_point()\n</code></pre>\n\n<p>Note that <code>Food.state</code> and <code>Food.spawn(self)</code> are redundant now and can be removed. That should be three cheers (less lines of code, yes?).</p>\n\n<h2>On <code>collision(Snake, int, int)</code></h2>\n\n<p>Logically, this section should come first, but I saved it for the last.</p>\n\n<ol>\n<li>The name <code>collision</code> is ambiguous. Can we improve it? Sure! Note that <em>logically speaking</em>, the function returns a boolean, so it's a predicate. Can we prefix it with <code>is</code>? Certainly! I think <code>is_snake_on_food</code> isn't too bad. You could also go with <code>is_food_reached</code> or <code>is_snake_colliding_with_food</code>.</li>\n<li><p>Having changed how positions are stored in the <code>Food</code> class, we can pass in the food's position directly. Thus the signature of the function can be reduced to:</p>\n\n<pre><code>def is_snake_on_food(snake: Snake, food_target: Point):\n</code></pre>\n\n<p>This also saves us from needing unpack <code>*food_pos</code> in line 209.</p>\n\n<pre><code># Before:\ncollision_ = collision(snake, *food_pos)\n\n# After:\ncollision_ = is_snake_on_food(snake, food_pos)\n</code></pre></li>\n<li><p>There is no need to create <code>pygame.Rect</code> just to compare <code>snake_.head</code> and <code>food_target</code>. Currently, lines 128-131 are</p>\n\n<pre><code> snake_rect = pygame.Rect(*snake_.head, block_size, block_size)\n food_rect = pygame.Rect(food_target_x, food_target_y, block_size,\n block_size)\n if snake_rect == food_rect:\n</code></pre>\n\n<p>Instead, the coordinates can be compared directly:</p>\n\n<pre><code> if (*snake_.head,) == (food_target_x, food_target_y):\n</code></pre>\n\n<p>Having passed in <code>food_target</code> as a <code>Point</code>, we can simplify this to</p>\n\n<pre><code> if snake_.head == food_target:\n</code></pre></li>\n</ol>\n\n<p>Hope this helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T14:36:33.263",
"Id": "221346",
"ParentId": "221163",
"Score": "5"
}
},
{
"body": "<p>Thanks for the game. I applied most changes suggested by <a href=\"https://codereview.stackexchange.com/users/82612/dair\">@Dair</a> and <a href=\"https://codereview.stackexchange.com/users/201170/vurmux\">@vurmux</a> as well as partially the suggestions from <a href=\"https://codereview.stackexchange.com/users/50567/peter-cordes\">@Peter Cordes</a> (some of them are not so simple). After that, there were still some things left:</p>\n\n<h3>Game logic</h3>\n\n<p>I'm not sure whether it was intentional, but the snake does not collide with itself. In usual snake games, if the snake bites into her tail, the game is over as well.</p>\n\n<h3>Swallowed keypresses</h3>\n\n<p>When playing the game, I noticed that I sometimes cannot perform a U-turn when I needed to. It seems that the first keypress got lost.</p>\n\n<p>The reason is here:</p>\n\n<pre><code>pressed = pygame.key.get_pressed()\nif pressed[pygame.K_RIGHT] or pressed[pygame.K_d]:\n ...\n</code></pre>\n\n<p>which should be changed to</p>\n\n<pre><code>if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RIGHT or event.key == pygame.K_d:\n snake.change_dir(Direction.RIGHT)\n elif event.key == pygame.K_LEFT or event.key == pygame.K_a:\n snake.change_dir(Direction.LEFT)\n elif event.key == pygame.K_UP or event.key == pygame.K_w:\n snake.change_dir(Direction.UP)\n elif event.key == pygame.K_DOWN or event.key == pygame.K_s:\n snake.change_dir(Direction.DOWN)\n</code></pre>\n\n<p>However, this brings us to an interesting other problem: doing 2 changes without moving the snake makes the snake run into the opposite direction immediately (without hitting itself as noted before).</p>\n\n<p>Since <code>pygame.event.get()</code> consumes all events, it would be up to you, queuing the events yourself and processing them the next frame.</p>\n\n<h3>High CPU usage when game is over</h3>\n\n<p>When the game is over, it uses ~14% CPU time on my machine, which means that 1 core is 100% busy. Adding a <code>pygame.time.delay(60)</code> into the <code>while is_over</code> loop helps.</p>\n\n<h3>Classes in files</h3>\n\n<p>In addition I tried to apply another principle, which is to have each class in a separate file. Doing so is quite simple with an IDE like Pycharm, since it has the move-refactoring. Unfortunately, it doesn't work any more, because of this:</p>\n\n<p>After the refactoring, Food has</p>\n\n<pre><code>from game import bg_width, block_size, bg_height\n</code></pre>\n\n<p>So one's left with a cycle of imports due to the use of global variables. Looking at the food class for possible resolutions, you could pass the necessary dependencies as parameters:</p>\n\n<pre><code>def spawn(self, bg_width:int, bg_height:int, block_size:int) -> Tuple[int, int]:\n</code></pre>\n\n<p>After the refactoring, Snake has</p>\n\n<pre><code>from game import block_size\n</code></pre>\n\n<p>and a similar solution can apply.</p>\n\n<h3>Static members</h3>\n\n<p>Your classes seem to define the properties twice, once in <code>__init__</code> and once as static members. I don't see any usage of the static members, so these can be removed in <code>Snake</code>:</p>\n\n<pre><code>head: List[int, int]\ncolor: Tuple[int, int, int]\nbody: List[List[int, int]]\ndirection: str\nsize: int\n</code></pre>\n\n<p>and in <code>Food</code>:</p>\n\n<pre><code>x: int\ny: int\ncolor: Tuple[int, int, int]\nstate: bool\nposition: Tuple[int, int]\n</code></pre>\n\n<h3>Naming</h3>\n\n<p>Assuming that <code>bg</code> is short for <em>background</em>, I really wonder whether that's the correct term here. The snake is moving on a board, not on a background I'd say. In the comment for that line, you call it <em>screen width and height</em>, which may accidentally be the case as well.</p>\n\n<p>Considering a future version of the game where you add a nice background graphic and display the score below the board, neither <em>background</em> nor <em>screen</em> would match any more.</p>\n\n<h3>Code duplication</h3>\n\n<p>With the change before, I noticed that there's duplicate code in the Food class. Inside <code>__init__</code>, it basically <code>spawn</code>s itself.</p>\n\n<p>This duplication can be removed and adding </p>\n\n<pre><code>food = Food(BLUE)\nfood.spawn(bg_width, bg_height, block_size)\n</code></pre>\n\n<p>It can later be discussed whether or not Food needs to be spawned that early.</p>\n\n<h3>Potential stack overflow in game over mode</h3>\n\n<p>Once the game is over, there's a loop handling the situation:</p>\n\n<pre><code>while is_over:\n</code></pre>\n\n<p>I expected the game to get out of this loop when a new round begins. However, that's not the case. Instead there is</p>\n\n<pre><code>if event.key == pygame.K_r:\n game()\n</code></pre>\n\n<p>This is a recursive call. It's unlikely that it will cause problems in this particular game, but in general, this may cause stack overflows.</p>\n\n<p>It can be resolved by introducing another loop</p>\n\n<pre><code>while running:\n while is_over and running:\n ...\n\n # Initialization code here\n\n while running and not is_over:\n ...\n</code></pre>\n\n<p>Instead of calling <code>game()</code>, you can then set <code>is_over = False</code>. </p>\n\n<h3>Unused variable / unreachable code</h3>\n\n<p>The <code>while running</code> loop can be replaced by a <code>while True</code>, since there's no other assignment to <code>running</code> which would terminate the loop.</p>\n\n<p>This also means that the code after <code>while running</code> will never be reached:</p>\n\n<pre><code>pygame.quit()\nquit()\n</code></pre>\n\n<p>Changing the exit routine to <code>running = False</code>, you save some duplicate code and the code runs to the end. This is e.g. helpful if you later want to implement saving a highscore list etc. If you have many exit points during your program, it will be harder to implement something at the end of the game.</p>\n\n<p>You can also omit <code>quit()</code>, because it is not helpful as the last statement of your code.</p>\n\n<h3>Smaller improvements</h3>\n\n<p><code>food.update()</code> is only called with <code>False</code> as a parameter. It's never called with <code>True</code>. So this argument can be omitted and go hard-coded into the <code>update()</code> method. The code then looks like this:</p>\n\n<pre><code>while running:\n ...\n food_pos = food.spawn(board_width, board_height, block_size)\n if collision(snake, *food_pos):\n score += 1\n food.update()\n</code></pre>\n\n<p>This reads like the food is spawning in a new place with every frame. IMHO it reads better like this:</p>\n\n<pre><code>while running:\n ...\n food_pos = food.??? # whatever \n if collision(snake, *food_pos):\n score += 1\n food.spawn(board_width, board_height, block_size)\n</code></pre>\n\n<p>Because that makes it clear that food only spaws whenever it collided with the snake aka. it was eaten.</p>\n\n<h3>Snake direction change</h3>\n\n<p>Note: <a href=\"https://codereview.stackexchange.com/users/50567/peter-cordes\">@Peter Cordes</a>' vector approach is even more elegant. Perhaps the following might show you a refactoring you can apply in other cases as well when a vector does not fit.</p>\n\n<p>After applying the enum suggestion, the direction check looks like this</p>\n\n<pre><code>def change_dir(self, direction: Direction) -> None:\n if self.direction != Direction.LEFT and direction == Direction.RIGHT:\n self.direction = Direction.RIGHT\n elif self.direction != Direction.RIGHT and direction == Direction.LEFT:\n self.direction = Direction.LEFT\n elif self.direction != Direction.DOWN and direction == Direction.UP:\n self.direction = Direction.UP\n elif self.direction != Direction.UP and direction == Direction.DOWN:\n self.direction = Direction.DOWN\n</code></pre>\n\n<p>Combining <code>self.direction = Direction.RIGHT</code> and <code>direction == Direction.RIGHT</code>, we can simplify</p>\n\n<pre><code>self.direction = direction\n</code></pre>\n\n<p>This applies to all 4 cases, so we end up with</p>\n\n<pre><code>def change_dir(self, direction: Direction) -> None:\n if self.direction != Direction.LEFT and direction == Direction.RIGHT:\n self.direction = direction\n elif self.direction != Direction.RIGHT and direction == Direction.LEFT:\n self.direction = direction\n elif self.direction != Direction.DOWN and direction == Direction.UP:\n self.direction = direction\n elif self.direction != Direction.UP and direction == Direction.DOWN:\n self.direction = direction\n</code></pre>\n\n<p>Now, we can argue that this is duplicate code and remove the duplication:</p>\n\n<pre><code>def change_dir(self, direction: Direction) -> None:\n if (self.direction != Direction.LEFT and direction == Direction.RIGHT) or \\\n (self.direction != Direction.RIGHT and direction == Direction.LEFT) or \\\n (self.direction != Direction.DOWN and direction == Direction.UP) or \\\n (self.direction != Direction.UP and direction == Direction.DOWN):\n self.direction = direction\n</code></pre>\n\n<p>Personally, I'd even prefer</p>\n\n<pre><code>def change_dir(self, direction: Direction) -> None:\n if self.is_opposite_direction(direction, self.direction):\n return\n self.direction = direction\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-02T09:25:13.003",
"Id": "221530",
"ParentId": "221163",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T23:53:00.250",
"Id": "221163",
"Score": "36",
"Tags": [
"python",
"python-3.x",
"pygame",
"snake-game"
],
"Title": "Beginner's snake game using PyGame"
} | 221163 |
<p>Our teacher doesn't give much feedback on our code itself. Was just looking for some feedback on how I could improve on this. This is the method that tests the string against the Turing machine that is built from a file.</p>
<p>The entire project is on <a href="https://github.com/ChristopherDiPilla/TuringMachine/tree/602793d6f3cc8387db8b1d0d12b04d1ff21d5c51" rel="nofollow noreferrer">GitHub</a>.</p>
<pre><code>public boolean run(String input) {
String currentState = startState;
ArrayList<Transition> pT;
ArrayList<Character> chars = new ArrayList<>();
int i = 0;
for (char c : input.toCharArray()) {
if (!inputAlphabet().contains(c)) {
return false;
} else {
chars.add(c);
}
}
tape.setCells(chars);
tape.setHeadPosition(i);
System.out.println(currentState);
while (i != tape.getCells().size()) {
pT = new ArrayList<>();
for (Transition t : transitions) {
if (t.getFromState().equals(currentState)) {
pT.add(t);
}
}
for (int j = 0; j < pT.size(); j++) {
if (tape.getCells().get(i) == pT.get(j).getInputSymbol()) {
if (pT.get(j).getWriteSymbol() != EMPTY_SYMBOL) {
ArrayList<Character> temp;
temp = tape.getCells();
temp.set(i, pT.get(j).getWriteSymbol());
tape.setCells(temp);
}
if (pT.get(j).getDirection().charAt(0) == DIRECTION_RIGHT) {
i++;
tape.setHeadPosition(i);
} else if (pT.get(j).getDirection().charAt(0) == DIRECTION_LEFT) {
i--;
tape.setHeadPosition(i);
}
currentState = pT.get(j).getToState();
System.out.println(currentState);
j = pT.size();
}
}
if (rejectStates.contains(currentState)) {
return false;
}
}
pT = new ArrayList<>();
for (Transition t : transitions) {
if (t.getFromState().equals(currentState)) {
pT.add(t);
}
}
for (int k = 0; k < pT.size(); k++) {
if (pT.get(k).getInputSymbol() == EMPTY_SYMBOL) {
currentState = pT.get(k).getToState();
System.out.println(currentState);
if (pT.get(k).getDirection().charAt(0) == DIRECTION_RIGHT) {
i++;
tape.setHeadPosition(i);
} else if (pT.get(k).getDirection().charAt(0) == DIRECTION_LEFT) {
i--;
tape.setHeadPosition(i);
}
k = pT.size();
}
}
return acceptStates.contains(currentState);
}
</code></pre>
| [] | [
{
"body": "<p>Some grist for the mill:</p>\n\n<p>When variables will not be reassigned, it's helpful to declare them as <code>final</code> to reduce cognitive load on the reader.</p>\n\n<p>When using the Collections API, it's preferable to declare interface types rather than implementations (<code>List</code> instead of <code>ArrayList</code>) unless you need functionality specific to the implementation type.</p>\n\n<p>Declare variables as closely to where they're first used as is possible.</p>\n\n<p>When you <code>return</code> in the <code>if</code> clause, you don't need an <code>else</code> clause.</p>\n\n<p>Calling <code>inputAlphabet().contains()</code> once for every character in the input is very inefficient, especially given that <code>inputAlphabet()</code> is running a loop to create the list. Call <code>inputAlphabet()</code> once and keep a local variable to hold it. And have <code>inputAlphabet()</code> return a <code>Set</code> instead of a <code>List</code>, which gets you <code>contains()</code> at <code>O(1)</code> instead of <code>O(n)</code>.</p>\n\n<p><code>input.toCharArray()</code> is easy to read, which makes it probably correct in this case, but be aware that it's marginally less efficient than using an indexed loop and calling <code>input.charAt(i)</code> because it creates a new <code>char[]</code>.</p>\n\n<p>You don't need to keep a <code>Tape</code> instance variable. Just create a new one in <code>run()</code>. It might be nice if the <code>Tape</code> constructor accepted a list of cells.</p>\n\n<p>Probably not relevant, but your code is not thread-safe. It will break if multiple threads call <code>run</code> at the same time.</p>\n\n<p>Don't reuse a variable (<code>pT</code>) for different things in the same method. It makes it hard for the reader to keep track of what it contains.</p>\n\n<p><code>pT</code> is a poor variable name. I <em>think</em> it means <code>possibleTransitions</code>? Variables should clearly indicate what they're referencing. Another example is <code>t</code> instead of <code>transition</code>. </p>\n\n<p>The loop building the transitions could be extracted into a method.</p>\n\n<p>It's traditional in looping constructs to check <code><=</code>, instead of <code>!=</code> to avoid a possible infinite loop if a bug puts you past the exact value you want to terminate on.</p>\n\n<p>You can localize <code>i</code> and use a <code>for</code> loop, because you know is has to be <code>tape.getCells().size()</code> when you're done looping.</p>\n\n<p>Your code might be easier to read with a guard clause <code>if (.. != .. ) { continue;</code> rather than nesting.</p>\n\n<p>Rather than setting the value of <code>j</code> to break the loop, just use <code>break</code>. Then you can use an enhanced for loop rather than indexing on <code>j</code>.</p>\n\n<p>Your <code>temp</code> dancing is not meaningful. Since <code>Tape</code> is returning an unsafe copy from <code>getCells()</code>, you could just do <code>tape.getCells().set(i, ..)</code>. Even better would be changing the API of Tape to have the methods to access the cells (<code>tape.getCellAt(int)</code>, <code>tape.setCellAt(int, Character)</code> instead of returning the array for you to mess around with. While you're at it, add a method like <code>size()</code> or <code>length()</code> to tape and get rid of <code>getCells</code> altogether. Let <code>Tape</code> hide the fact that it's using a List under the covers, and you can change the implementation later without breaking other code.</p>\n\n<p>It's unclear why a Transition's direction and the current state are treated as Strings when they're only ever one character long.</p>\n\n<p>It also be nice if Transition could be changed so you could do something like <code>i = possibleTransition.applyDirection(i)</code>, and the Transition determines whether to add one, subtract one, or do nothing. Then that <code>if .. else if ..</code> block reduces to <code>i = possibleTransition.applyDirection(i); tape.setHeadPosition(i);</code></p>\n\n<p>Your second <code>for</code> loop with the <code>k</code> index has the same break; issue as the first. You can again use the enhanced <code>for</code> loop.</p>\n\n<p>It's unclear what this loop is doing with <code>Tape</code>, since you're making changes that effectively vanish once the method exists. It looks like that code can just go. In fact, since <code>getHeadPosition</code> is never called in your codebase, I'm not sure why you're tracking it at all.</p>\n\n<p>If you were to make all of these modifications, your code might look something like the code below. This is untested, so I might very well have broken something.</p>\n\n<pre><code>public boolean run(final String input) {\n final List<Character> chars = new ArrayList<>();\n final Set<Character> inputAlphabet = inputAlphabet();\n for (final char c : input.toCharArray()) {\n if (!inputAlphabet.contains(c)) {\n return false;\n }\n chars.add(c);\n }\n\n String currentState = startState;\n\n final Tape tape = new Tape(chars);\n for (int i = 0; i < tape.size(); i++) {\n\n for (final Transition transition : this.possibleTransitions(currentState)) {\n if (tape.getCellAt(i) != transition.getInputSymbol()) {\n continue;\n }\n\n if (transition.getWriteSymbol() != EMPTY_SYMBOL) {\n tape.setCellAt(i, transition.getWriteSymbol());\n }\n\n i = transition.applyDirection(i);\n currentState = transition.getToState();\n break;\n }\n\n if (this.rejectStates.contains(currentState)) {\n return false;\n }\n }\n\n for (final Transition transition : possibleTransitions(currentState)) {\n if (transition.getInputSymbol() == EMPTY_SYMBOL) {\n currentState = transition.getToState();\n break;\n }\n }\n return acceptStates.contains(currentState);\n}\n\nprivate List<Transition> possibleTransitions(final String state) {\n final List<Transition> possibleTransitions = new ArrayList<>();\n for (final Transition transition : transitions) {\n if (transition.getFromState().equals(state)) {\n possibleTransitions.add(transition);\n }\n }\n return possibleTransitions;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T22:52:25.793",
"Id": "427891",
"Score": "0",
"body": "Sadly quite of few of the datatypes for this project were to be defined in a certain per the instructions. Sadly the most tedious one is the lack of being able to use \"break\" to exit a loop. I know this is a commonly used technique but my university doesn't want us to do that. I think a lot of my unused or confusing of things though comes from the Turing Machine actually being implemented incorrectly pointed out by @llmariKaronen. For some reason, I didn't even think of utilizing a Set for the alphabet even though that's exactly what it is, so I appreciate that. Thank you for the feedback!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T02:14:28.373",
"Id": "221234",
"ParentId": "221164",
"Score": "5"
}
},
{
"body": "<p>I agree with Eric Stein that your <code>Tape</code> class as written doesn't provide a useful abstraction. I see two possible ways to fix it:</p>\n\n<ul>\n<li><p>One option would be to get rid of the class entirely, and just use a <code>List<Character></code> to represent the tape and an <code>int</code> to represent the head position in the <code>TuringMachine</code> class. The Java <code>List</code> interface is already a perfectly reasonable representation of an extensible one-dimensional sequence of values, so you can just program to it instead of defining your own.</p></li>\n<li><p>Alternatively, if you'd rather keep the <code>Tape</code> class, you should remove the <code>getCells()</code> method (since it needlessly exposes the internals of the class) and just provide methods to access the values on the tape directly.</p></li>\n</ul>\n\n<p>In fact, you don't even need to allow access to values at arbitrary positions, since a Turing machine tape, by definition, only allows reading and writing to the cell at the current position of the head. So the only methods you <em>really</em> need are something like:</p>\n\n<ul>\n<li><code>public char read()</code>: return the value of the cell at the current head position;</li>\n<li><code>public void write(char value)</code>: set the value of the cell at the current head position;</li>\n<li><code>public void moveHead(int steps)</code>: move the head by <code>steps</code> positions;</li>\n</ul>\n\n<p>and a constructor that accepts a <code>CharSequence</code> and/or a <code>char[]</code> parameter to initialize the content of the tape. (You may also want to provide a <code>toString()</code> method for easier debugging.)</p>\n\n<p>One advantage of going this way is that you can later optimize the internal implementation of the tape without having to change any code that uses it. For example, one simple optimization might be to use a <code>StringBuffer</code> instead of an <code>ArrayList<Character></code> to store the contents of the tape, which should be more efficient. Also, letting the tape extend in both directions could be easily and efficiently implemented by using <em>two</em> <code>StringBuffer</code>s (or <code>ArrayList</code>s) internally.</p>\n\n<hr>\n\n<p>Also, the way you're representing the state machine itself is quite inefficient: at every step, you're looping over all the possible state transitions to find the matching one.</p>\n\n<p>A more efficient method would be to store the state transitions in a <code>Map</code> (implemented e.g. as a <code>HashMap</code> — but you should usually just <a href=\"https://softwareengineering.stackexchange.com/questions/232359/understanding-programming-to-an-interface\">program to the interface</a> whenever possible) to let you look them up efficiently. Since you need to look up the transitions using a combination of two keys (the current state and the character on the tape), you have two options: either use a nested <code>Map<String, Map<Character, Transition>></code> or define a wrapper class to store a (<em>state</em>, <em>input</em>) pair, with a suitable <code>hashCode()</code> method, and use it as the key to a single map.</p>\n\n<p>However, arguably an even more elegant solution would be to introduce a <code>State</code> class that stores all the properties of a single state in your state machine, including both whether or not it's an accepting state and all the possible transitions from that state. Also, the <code>State</code> class should <em>not</em> expose its internal implementation of the transition map (which should probably be something like a <code>HashMap<Character, Transition></code>), but rather should simply provide a method like:</p>\n\n<pre><code>public Transition getTransition(char tapeValue)\n</code></pre>\n\n<p>Also, you should explicitly define and document the behavior of this method in the case where no matching transition is found (which in most standard definitions of a Turing machine indicates that the machine halts). Reasonable behaviors might be either returning <code>null</code> or throwing a specific custom exception, but either way, this should be documented. If you wanted to get fancy with wrapper objects, you could even make the method return an <code>Optional<Transition></code>, although I don't personally see any real added value in that for this particular use case.</p>\n\n<p>I would also make the <code>Transition</code> class store direct references to its source and target <code>State</code> objects instead of string labels, and have <code>getFromState()</code> and <code>getToState()</code> return the states directly. Note that you'd still need to maintain a string-to-state-object map while building the state machine, but you no longer need it after all the states and transitions have been built.</p>\n\n<p>(Also, if you wanted, you could make the <code>State</code> and <code>Transition</code> objects immutable, since there's no need to change them after the state machine has been built. Unfortunately, writing a proper builder class for an immutable state machine would be a somewhat nontrivial exercise all by itself, due to the possibility of circular state transition chains, so just leaving the classes mutable might be easier in practice.)</p>\n\n<hr>\n\n<p>Finally, I should note that the way your \"Turing machine\" works seems kind of unusual. While there are several different (but essentially equivalent) ways of defining a <a href=\"https://en.wikipedia.org/wiki/Turing_machine\" rel=\"nofollow noreferrer\">Turing machine</a>, yours doesn't really seem to match any of them.</p>\n\n<p>Basically, as far as I can tell, your machine uses a finite-length tape (whereas most definitions of a Turing machine allow the tape to extend infinitely in one or both directions) and runs until either:</p>\n\n<ol>\n<li>it reaches one of the states defined as \"rejecting\" (in which case the input is immediately rejected),</li>\n<li>it walks off the right-hand end of the tape (in which case it runs one more step, reading an <code>EMPTY_SYMBOL</code> off the end of the tape, and then uncoditionally halts, accepting the input if the current state is defined as \"accepting\" and rejecting it otherwise), or</li>\n<li>it walks off the left-hand side of the tape (in which case it crashes with an <code>IndexOutOfBoundsException</code>, since you don't have any code to handle that case).</li>\n</ol>\n\n<p>Basically, what you have looks like some kind of a weird hybrid of a Turing machine and a classical finite state machine that reads its input strictly sequentially. Due to the lack of an infinite tape, its computational power is strictly weaker than that of a proper Turing machine (and in fact theoretically equivalent to that of a finite state machine, although in practice your machine can have much more complex behavior than a simple FSM <em>with the same number of states</em> could). If that's not how you <em>intended</em> it to work, then your code would appear to be buggy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T22:04:14.917",
"Id": "427885",
"Score": "0",
"body": "You are correct that is a bug I didn't notice until now. I was using the input as the tape when I should be using the two separately. I'm going to sit down and figure out to do the HashMap for the Transitions, at the time this was being worked on I couldn't think of another way to find the transitions that applied to the current state. Thank you for the feedback, I have a lot to learn still."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T10:47:54.693",
"Id": "427942",
"Score": "0",
"body": "@ChristopherD.: Usually, the input to a Turing machine _is_ provided as the initial contents of the tape. However, the machine is also allowed to read and write to tape cells beyond the original length of the input."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:47:27.427",
"Id": "221266",
"ParentId": "221164",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T23:53:40.770",
"Id": "221164",
"Score": "1",
"Tags": [
"java",
"homework",
"state-machine",
"cellular-automata"
],
"Title": "Turing machine schoolwork"
} | 221164 |
<p><strong>HTML / CSS Slider. No JavaScript.</strong></p>
<p>Wanted to make an all CSS Image Slider. Though there are plenty of pre-made options setup a lot seem clunky or add a lot to load time. Have ideas for some more detailed ones, with and without JavaScript, but wanted to make a basic one first and get any feedback.</p>
<p>CodePen: <a href="https://codepen.io/LouBagel/pen/rgKXeY" rel="noreferrer">https://codepen.io/LouBagel/pen/rgKXeY</a> </p>
<p>HTML:</p>
<pre><code><div class='slider-container'>
<div class='slide'><p>CSS Slider</p></div>
<div class='slide'><p>No JavaScript</p></div>
<div class='slide'><p>Manual Setup</p></div>
<div class='slide'><p>Tedious to Update</p></div>
</div>
</code></pre>
<p>CSS: </p>
<pre><code>.slider-container{
width: 100%;
height: 500px; /* can be set based on design */
background: red; /* to test if background shows */
overflow: hidden; /* to hide slides that are off */
position: relative; /* since slides are absolute */
box-shadow: 0 2px 10px black;
}
.slide{
/* positioning all slides normal position to full size of slider and in view */
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
animation: 12s linear infinite sliderAnimation;
/*
animation-name: sliderAnimation;
animation-duration: 12s;
animation-timing-function: linear;
animation-iteration-count: infinite;
*/
border: 20px solid #1d1e22; /* thought it looked good */
box-sizing: border-box; /* to keep total width at 100% */
box-shadow: inset 0 0 20px black; /* inset shadow on the slides */
display: flex; /* to position the text inside*/
}
.slide:first-of-type{
/* City */
background: no-repeat 50% 20%/cover url('https://i.imgur.com/zN8znQk.jpg');
/* positioning for the text inside */
justify-content: flex-end;
align-items: flex-start;
}
.slide:nth-of-type(2){
/* Nature Bridge */
background: no-repeat center/cover url('https://i.imgur.com/qtwGd3b.jpg');
/* 12s - 9s = 3s... Will start after 3s */
animation-delay: -9s;
}
.slide:nth-of-type(3){
/* Painting */
background: no-repeat center/cover url('https://i.imgur.com/Qxdy5Ue.jpg');
/* Will start after 6s */
animation-delay: -6s;
/* positioning for the text inside */
justify-content: flex-end;
align-items: center;
}
.slide:last-of-type{
/* Coffee */
background: no-repeat bottom/cover url('https://i.imgur.com/UyWlZtO.jpg');
/* Will start after 9s */
animation-delay: -3s;
/* positioning for the text inside */
justify-content: center;
align-items: center;
}
@keyframes sliderAnimation{
/* 4 slides, 20% in place and 5% transition time = 100% */
0%{transform: translateX(0); opacity: 1;} /* starts in view */
20%{transform: translateX(0); opacity: 1;} /* stays in view */
25%{transform: translateX(-100%); opacity: 1;} /* slides out left */
70%{transform: translateX(-100%); opacity: 0;} /* Doesn't matter at what percent: changes to transparent so can't see it travel back across to the right. */
71%{transform: translateX(100%); opacity: 0;} /* Doesn't matter at what percent: moves off right */
95%{transform: translateX(100%); opacity: 1;} /* Becomes transparent and Ready to slide on from the right */
}
.slide p{
/*style for the text*/
margin: 5vw;
font-size: 3vw;
color: white;
text-shadow: 0.1vw 0.1vw black;
font-family: Arial Black, Georgia, Garamond, Palatino, Trebuchet MS, Verdana;
}
.slide:last-of-type p{
/* because white text on white background */
text-shadow: 0 0 15px black;
}
body{
margin: 0;
background: #3f4351;
max-width: 100%;
}
</code></pre>
<p>Note: animation-delays are set to negative values as that causes them to be placed backwards into the animation. If positive values they will sit in starting position and not slide in on first round.</p>
<p><strong>Pros & Cons (IMO)</strong></p>
<p>Pros:</p>
<ul>
<li>Quick Loading</li>
<li>No Repaint (since using transform: translate)</li>
</ul>
<p>Cons:</p>
<ul>
<li>No buttons for user to control</li>
<li>Tedious to make changes, especially if changing quantity of slides</li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T01:16:12.500",
"Id": "221167",
"Score": "10",
"Tags": [
"html",
"css",
"animation"
],
"Title": "CSS image slider (no JavaScript)"
} | 221167 |
<p>I have a program which, at its core, involves repeatedly performing an action on some value, and based on that action also returning a list of new values to perform that action on. The pure version of my function is:</p>
<pre><code>recurse :: (a -> [a]) -> a -> [a]
recurse f a = a : concatMap (recurse f) (f a)
</code></pre>
<p>Which can be used for things like tree traversals, such as:</p>
<pre><code>data Tree a = Node [Tree a] | Leaf a
f (Node ls) = ls
f (Leaf x) = []
recurse f (Node [Leaf 10, Node [Leaf 20, Leaf 3], Leaf 12])
== [Node [..], Leaf 10, Node [..], Leaf 20, Leaf 3, Leaf 12]
</code></pre>
<p>This function becomes more useful if you generalize it to an arbitrary monad:</p>
<pre><code>recurseM :: Monad m => (a -> m [a]) -> a -> m [a]
recurseM f a = do
xs <- f a
rests <- mapM (recurseM f) xs
return $ a : concat rests
</code></pre>
<p>But what I really want to do with it is make it asynchronous, because (a) I do not care about the order the results come in, and (b) I anticipate the actions themselves taking a while waiting on network operations. Here is my first pass at writing the async implementation (without results) of the above functions:</p>
<pre><code>recurseAsync_ :: (a -> IO [a]) -> a -> IO ()
recurseAsync_ f a = do
xs <- f a
mapM_ (forkIO . recurseAsync_ f) xs
</code></pre>
<p>While this works, I'm unfamiliar enough with concurrency in general and in Haskell specifically to be sure that this will actually run all of the code I want in parallel. Also, I'm unsure of how to make this code return the results, but that isn't really the important part of the code.</p>
| [] | [
{
"body": "<p>I think yours works, but <code>async</code> specializes in this stuff.</p>\n\n<pre><code>recurseAsync :: (a -> IO [a]) -> a -> IO [a]\nrecurseAsync f a = do\n xs <- f a\n fmap concat $ mapConcurrently (recurseAsync f) xs\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:39:33.767",
"Id": "221253",
"ParentId": "221172",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T04:12:31.623",
"Id": "221172",
"Score": "2",
"Tags": [
"haskell",
"recursion",
"asynchronous",
"concurrency"
],
"Title": "Performing an action which may return other actions to be performed, concurrently"
} | 221172 |
<p>To practice my <code>JavaScript</code> for future employment, I've decided to take up the challenge of writing a javascript sudoku verifier. This code only verify's one of the nine 3x3 blocks there are. I would like feedback on this portion of the code, so I can continue my development with more knowledge and more efficient code. Also, any feedback on my <code>HTML/CSS</code> is warmly welcome. I'm using a fullscreen chrome browser for development, so the <code>#middle</code> centers the box on my screen, but it might not on yours.</p>
<p><strong>You will have to click on <code>full page -></code> to view the <code>CSS</code> correctly.</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function checkAnswer() {
//reset each time button is clicked
document.getElementById('correct').style.display = 'none';
document.getElementById('incorrect').style.display = 'none';
//add each input into 2D array
let first_row = document.getElementsByClassName('row1');
let second_row = document.getElementsByClassName('row2');
let third_row = document.getElementsByClassName('row3');
let sudoku = [
[first_row[0].value, first_row[1].value, first_row[2].value],
[second_row[0].value, second_row[1].value, second_row[2].value],
[third_row[0].value, third_row[1].value, third_row[2].value]
]
//check if each number is unique in the 2D array
for (let i = 0; i < sudoku.length; i++) {
for (let j = 0; j < sudoku[i].length; j++) {
if(!isUnique(sudoku[i][j], sudoku)) {
document.getElementById('incorrect').style.display = 'block';
return;
}
}
}
document.getElementById('correct').style.display = 'block';
}
function isUnique(num, arr) {
let count = 0;
//check entire array
for(let i = 0; i < arr.length; i++) {
for(let j = 0; j < arr[i].length; j++) {
if(arr[i][j] == num) {
count++;
}
}
}
return count == 1;
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background-color: pink;
}
input {
width: 50px;
height: 50px;
font-size: 20px;
text-align: center;
}
button {
width: 100px;
height: 50px;
font-size: 15px;
margin-left: 40px;
}
#middle {
margin-left: 900px;
margin-top: 300px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset='UTF-8'>
<title>Sudoku</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div id="middle">
<table>
<tr>
<td><input type="text" class="row1" maxlength="1" value="3"></td>
<td><input type="text" class="row1" maxlength="1"></td>
<td><input type="text" class="row1" maxlength="1"></td>
</tr>
<tr>
<td><input type="text" class="row2" maxlength="1"></td>
<td><input type="text" class="row2" maxlength="1" value="2"></td>
<td><input type="text" class="row2" maxlength="1"></td>
</tr>
<tr>
<td><input type="text" class="row3" maxlength="1" value="7"></td>
<td><input type="text" class="row3" maxlength="1"></td>
<td><input type="text" class="row3" maxlength="1"></td>
</tr>
</table>
<br>
<button type="button" onclick="checkAnswer()">Check</button>
<div id="incorrect" style="display: none;">
<h1>Incorrect Entry!</h1>
</div>
<div id="correct" style="display: none;">
<h1>Correct Entry!</h1>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2>Styling</h2>\n\n<p>You can align centered elements relatively to their parent.</p>\n\n<blockquote>\n<pre><code>#middle { \n margin-left: 900px; \n margin-top: 300px; \n}\n</code></pre>\n</blockquote>\n\n<pre><code>#middle {\n position: relative;\n left: 50%;\n transform: translateX(-50%);\n top: 50%;\n transform: translateY(50%);\n}\n</code></pre>\n\n<h2>Naming</h2>\n\n<p>In my opinion, for algorithms it is OK to use short variable names.</p>\n\n<blockquote>\n<pre><code>let first_row = document.getElementsByClassName('row1');\nlet second_row = document.getElementsByClassName('row2');\nlet third_row = document.getElementsByClassName('row3');\nlet sudoku = [\n [first_row[0].value, first_row[1].value, first_row[2].value],\n [second_row[0].value, second_row[1].value, second_row[2].value],\n [third_row[0].value, third_row[1].value, third_row[2].value]\n]\n</code></pre>\n</blockquote>\n\n<pre><code>let r1 = document.getElementsByClassName('row1');\nlet r2 = document.getElementsByClassName('row2');\nlet r3 = document.getElementsByClassName('row3');\nlet sudoku = [\n [r1[0].value, r1[1].value, r1[2].value],\n [r2[0].value, r2[1].value, r2[2].value],\n [r3[0].value, r3[1].value, r3[2].value]\n]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T06:38:45.507",
"Id": "427578",
"Score": "0",
"body": "Wouldn't it be better to cut out the numbers completely from the variable names? Especially considering a full sudoku is 9x9."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T06:53:35.790",
"Id": "427583",
"Score": "1",
"body": "@Mast In a more generalized sudoku solver, that would be my choice also."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T04:58:44.303",
"Id": "221176",
"ParentId": "221175",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221176",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T04:34:49.313",
"Id": "221175",
"Score": "3",
"Tags": [
"javascript",
"array",
"html",
"css",
"sudoku"
],
"Title": "Partial Sudoku Verifier"
} | 221175 |
<p>This is a <a href="https://leetcode.com/problems/the-skyline-problem/" rel="nofollow noreferrer">Leetcode problem</a> - </p>
<blockquote>
<p><em>A city's skyline is the outer contour of the silhouette formed by all
the buildings in that city when viewed from a distance. Now suppose
you are <strong>given the locations and height of all the buildings</strong> as
shown on a cityscape photo (Figure A), write a program to <strong>output the
skyline</strong> formed by these buildings collectively (Figure B).</em></p>
<p><a href="https://i.stack.imgur.com/FHq6p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FHq6p.png" alt="enter image description here"></a> </p>
<p><a href="https://i.stack.imgur.com/NDzqS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NDzqS.png" alt="enter image description here"></a></p>
<p><em>The geometric information of each building is represented by a triplet
of integers <code>[Li, Ri, Hi]</code>, where <code>Li</code> and <code>Ri</code> are the <code>x</code>
coordinates of the left and right edge of the <code>i</code>th building,
respectively, and <code>Hi</code> is its height. It is guaranteed that <code>0 ≤ Li,
Ri ≤ INT_MAX</code>, <code>0 < Hi ≤ INT_MAX</code>, and <code>Ri - Li > 0</code>. You may assume
all buildings are perfect rectangles grounded on an absolutely flat
surface at height <code>0</code>.</em></p>
<p><em>For instance, the dimensions of all buildings in Figure A are recorded
as: <code>[[2, 9, 10], [3, 7, 15], [5, 12, 12], [15, 20, 10], [19, 24,
8]]</code>.</em></p>
<p><em>The output is a list of "<strong>key points</strong>" (red dots in Figure B) in the
format of <code>[[x1,y1], [x2, y2], [x3, y3], ...]</code> that uniquely defines a
skyline. <strong>A key point is the left endpoint of a horizontal line
segment</strong>. Note that the last key point, where the rightmost building
ends, is merely used to mark the termination of the skyline, and
always has zero height. Also, the ground in between any two adjacent
buildings should be considered part of the skyline contour.</em></p>
<p><em>For instance, the skyline in Figure B should be represented as: <code>[[2,
10], [3, 15], [7, 12], [12, 0], [15, 10], [20, 8], [24, 0]]</code>.</em></p>
<p><strong><em>Notes -</em></strong></p>
<p><em>The number of buildings in any input list is guaranteed to be in the
range <code>[0, 10000]</code>.</em></p>
<p><em>The input list is already sorted in ascending order by the left <code>x</code>
position <code>Li</code>.</em></p>
<p><em>The output list must be sorted by the <code>x</code> position.</em></p>
<p><em>There must be no consecutive horizontal lines of equal height in the
output skyline. For instance, <code>[...[2 3], [4 5], [7 5], [11 5], [12
7]...]</code> is not acceptable; the three lines of height 5 should be
merged into one in the final output as such: <code>[...[2 3], [4 5], [12
7], ...]</code>.</em></p>
</blockquote>
<p>Here is my solution to this task using divide and conquer (in Python) -</p>
<blockquote>
<pre><code> class Solution:
def get_skyline(self, buildings):
"""
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
if not buildings:
return []
if len(buildings) == 1:
return [[buildings[0][0], buildings[0][2]], [buildings[0][1], 0]]
mid = len(buildings) // 2
left = self.get_skyline(buildings[:mid])
right = self.get_skyline(buildings[mid:])
return self.merge(left, right)
def merge(self, left, right):
h1, h2 = 0, 0
i, j = 0, 0
result = []
while i < len(left) and j < len(right):
if left[i][0] < right[j][0]:
h1 = left[i][1]
corner = left[i][0]
i += 1
elif right[j][0] < left[i][0]:
h2 = right[j][1]
corner = right[j][0]
j += 1
else:
h1 = left[i][1]
h2 = right[j][1]
corner = right[j][0]
i += 1
j += 1
if self.is_valid(result, max(h1, h2)):
result.append([corner, max(h1, h2)])
result.extend(right[j:])
result.extend(left[i:])
return result
def is_valid(self, result, new_height):
return not result or result[-1][1] != new_height
</code></pre>
</blockquote>
<p>Here is an example output - </p>
<pre><code>#output = Solution()
#print(output.get_skyline([[2, 9, 10], [3, 7, 15], [5, 12, 12], [15, 20, 10], [19, 24, 8]]))
>>> [[2, 10], [3, 15], [7, 12], [12, 0], [15, 10], [20, 8], [24, 0]]
</code></pre>
<p>Here is the time taken for this output -</p>
<pre><code>%timeit output.get_skyline([[2, 9, 10], [3, 7, 15], [5, 12, 12], [15, 20, 10], [19, 24, 8]])
>>> 27.6 µs ± 3.65 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code></pre>
<p>So, I would like to know whether I could make this program more efficient and/or shorter. Any alternatives are welcome.</p>
| [] | [
{
"body": "<p>Nice approach.</p>\n\n<p>It's quite a hard problem to analyse for running time, because the output size is variable. <code>merge</code> has running time linear in the total size of its inputs, which are the output sizes of the subproblems. What we can say is that the base case produces two points for one input point, and <code>merge</code> doesn't create new points, so the number of points merged is at most twice the number of input points. Therefore the recurrence is <span class=\"math-container\">\\$T(n) = 2T(n/2) + O(n)\\$</span> which is the standard recurrence giving <span class=\"math-container\">\\$O(n \\lg n)\\$</span>.</p>\n\n<p>We can also show that this can't be beaten by a reduction from sorting. Given a set <span class=\"math-container\">\\$\\{x_i\\}\\$</span> to sort, we find the maximum <span class=\"math-container\">\\$m\\$</span> and construct buildings <span class=\"math-container\">\\$\\{(0, m + 1 - x_i, x_i)\\}\\$</span>. The output will give the <span class=\"math-container\">\\$x_i\\$</span> sorted in descending order.</p>\n\n<p>So your approach is asymptotically optimal, and moreover elegant. The merge doesn't do anything fancy, so it should have a low constant hidden by the big-O notation.</p>\n\n<hr>\n\n<p>I think that some of the double-indexed array accesses could benefit from introducing names. In particular, I would find</p>\n\n<blockquote>\n<pre><code> return [[buildings[0][0], buildings[0][2]], [buildings[0][1], 0]]\n</code></pre>\n</blockquote>\n\n<p>much more readable as</p>\n\n<blockquote>\n<pre><code> l, r, h = buildings[0]\n return [[l, h], [r, 0]]\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>The three cases in <code>merge</code> can be simplified considerably by using <code><=</code>. I find <code>is_valid</code> inelegant, so I would eliminate it by keeping track of the \"current\" height. Introducing names for <code>left[i][0]</code> and <code>right[j][0]</code> I refactored your code to</p>\n\n<blockquote>\n<pre><code> def merge(self, left, right):\n h1, h2, hcurrent = 0, 0, 0\n i, j = 0, 0\n result = []\n\n while i < len(left) and j < len(right):\n x0 = left[i][0]\n x1 = right[j][0]\n if x0 <= x1:\n h1 = left[i][1]\n i += 1\n if x1 <= x0:\n h2 = right[j][1]\n j += 1\n if max(h1, h2) != hcurrent:\n hcurrent = max(h1, h2)\n result.append([min(x0, x1), hcurrent])\n result.extend(right[j:])\n result.extend(left[i:])\n return result\n</code></pre>\n</blockquote>\n\n<p>It could alternatively be refactored to use a sentinel as so:</p>\n\n<blockquote>\n<pre><code> def merge(self, left, right):\n h1, h2 = 0, 0\n i, j = 0, 0\n result = [[0, 0]]\n\n while i < len(left) and j < len(right):\n x0 = left[i][0]\n x1 = right[j][0]\n if x0 <= x1:\n h1 = left[i][1]\n i += 1\n if x1 <= x0:\n h2 = right[j][1]\n j += 1\n if max(h1, h2) != result[-1][1]:\n result.append([min(x0, x1), max(h1, h2)])\n result.extend(right[j:])\n result.extend(left[i:])\n return result[1:]\n</code></pre>\n</blockquote>\n\n<p>Either way, I think it would be good to add a comment explaining why</p>\n\n<blockquote>\n<pre><code> result.extend(right[j:])\n result.extend(left[i:])\n</code></pre>\n</blockquote>\n\n<p>doesn't need any extra checks to avoid producing two consecutive points at the same height.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T07:52:01.887",
"Id": "221180",
"ParentId": "221178",
"Score": "6"
}
},
{
"body": "<p>In addition to the existing great answer of Peter Taylor I would like to add some thoughts on methods vs. free functions.</p>\n\n<p>Python is a <strong>multiparadigm</strong> language. It is concentrated on, but not only about object oriented programming.\nIt is certainly possible to construct one large <code>Solution</code> class that contains all your methods, but it might be not the best Solution. (höhö)</p>\n\n<p>As a general guideline you can use classes to group data <strong>and</strong> functions acting on that data together.\nIf you simply want to group functions together into one namespace, you should use namespaces i.e. modules in python.</p>\n\n<p>Let's get concrete and have a look at your <code>is_valid</code> method. It never uses self.\nIf you want to keep the class structure, you should make this at least explicit and change it to:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>@staticmethod\ndef is_valid(result, new_height):\n</code></pre>\n\n<p>A <code>staticmethod</code> is basically a free function residing in the namespace of a class.</p>\n\n<p>But (opinionated) it might be even better in terms of reusability to completely \"free\" your function.\nIf you come from a <code>C++</code> background this makes it feel like a template function that you can apply on different inputs independent of the <code>Solution</code> class.</p>\n\n<p>If you \"freed\" <code>is_valid</code> you will realize, that <code>merge</code> does not depend on <code>self</code> either and if you \"freed\" <code>merge</code> you will finally realize that <code>get_skyline</code> is basically a recursive function that calls <code>merge</code> and can be a <code>staticmethod</code> or a free function itself.</p>\n\n<p>In the end you end up with a class of three staticmethods i.e. a namespace with three free functions. The canonical way of implementing this structure is to have those three function in their own module i.e. their own file. </p>\n\n<p>Practically speaking, just delete the <code>class</code> and references to <code>self</code>, dedent the methods and call your file <code>Solutions.py</code>. Then you will be able to call</p>\n\n<pre><code>import Solutions\nSolutions.get_skyline(my_cool_skyline_test_data)\n</code></pre>\n\n<p>which feels very similar in terms of syntax as your class approach but decoupled the functions from each other.</p>\n\n<p>If you think that a function like <code>is_valid</code> is an implementation detail of your module, you can prepend an underscore which makes it private <strong>by convention</strong>. This would allow to switch between an <code>_is_valid</code> function and the manual \"current\" height tracking suggested in the other answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T07:22:50.307",
"Id": "427753",
"Score": "1",
"body": "I think the use of a class is forced by the testing framework OP is working in, but that shouldn't detract from this answer, which gives a great exposition."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T21:21:40.600",
"Id": "221223",
"ParentId": "221178",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221180",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T06:15:27.307",
"Id": "221178",
"Score": "8",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge",
"divide-and-conquer"
],
"Title": "Python program to solve the \"skyline problem\""
} | 221178 |
<p>Posted my first attempt at Tic-Tac-Toe a second ago <a href="https://codereview.stackexchange.com/questions/220597/first-program-tic-tac-toe">here</a>. Got a lot of great and helpful responses. The main things I took away from these responses was to use spell check, and to keep things simple. Wanted to give it a second go before moving on to something a bit bigger. </p>
<p>Learned about the Minimax algorithm from <a href="https://www.neverstopbuilding.com/blog/minimax" rel="nofollow noreferrer">this</a> article. It doesn't work <em>exactly</em> like I'd hope but I can't tell if it's just the pitfalls of the algorithm or my code. </p>
<p>I'm grateful for any critique or pointers. </p>
<p><strong>tictactoe.h</strong></p>
<pre><code>#ifndef TICTACTOE
#define TICTACTOE
#include <bitset>
#include <iostream>
#include <vector>
enum class BoardValue{ none, o, x};
class Board
{
public:
Board() = default;
Board(const Board& board): o_bits(board.o_bits), x_bits(board.x_bits) {};
BoardValue at(int index) const;
bool check_tie() const;
bool check_win(bool) const;
bool place(int, bool);
std::vector<int> possible_moves() const;
private:
std::bitset<9> o_bits{};
std::bitset<9> x_bits{};
std::bitset<9> filled_bits() const{ return o_bits | x_bits; }
};
class AI
{
public:
AI(bool o) : is_o(o) {};
int best_move(const Board&);
private:
int minimax(const Board&, int, bool);
int choice{};
bool is_o; //is the ai playing as 'O'
};
#endif
</code></pre>
<p><strong>tictactoe.cpp</strong></p>
<pre><code>#include "tictactoe.h"
#include <bitset>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>
BoardValue Board::at(int index) const{
if(index < 0 || 8 < index) throw std::out_of_range{ "Index out of Board range" };
if(filled_bits().test(index) == true)
{
return (o_bits.test(index) ? BoardValue::o : BoardValue::x);
}
else return BoardValue::none;
}
bool Board::check_tie() const
{
std::bitset<9> full_board{ "111111111" };
if( full_board == (filled_bits() & full_board) ) return true;
return false;
}
bool Board::check_win(bool o) const
{
const std::bitset<9>& bits = o ? o_bits : x_bits; //bits to be checked
//diagonals
if(bits.test(4) != false) //if middle is not taken no diagonals will pass
{
std::bitset<9> forward_diagonal{ "100010001" }; //bits of '\'
std::bitset<9> backward_diagonal{ "001010100" }; //bits of '/'
if(forward_diagonal == (bits & forward_diagonal)) return true;
if(backward_diagonal == (bits & backward_diagonal)) return true;
}
//columns and rows
std::bitset<9> col_check{ "001001001" }; //bits of the first column/row
std::bitset<9> row_check{ "000000111" };
for(int i = 0; i < 3; ++i) // loop for all 3 columns and rows
{
if(col_check == (bits & col_check)) return true;
if(row_check == (bits & row_check)) return true;
col_check = col_check << 1; //move over a column/row over
row_check = row_check << 3;
}
return false;
}
//returns false if index is occupied
bool Board::place(int index, bool o)
{
if(at(index) != BoardValue::none) return false;
std::bitset<9>& bits = o ? o_bits : x_bits; //bits to be changed
bits.set(index);
return true;
}
//returns indexes of free spaces
//all returned indexes will return true when used in place(int,bool)
std::vector<int> Board::possible_moves() const
{
const std::bitset<9> bits = filled_bits();
std::vector<int> moves{};
//loop through each bit and add the index of the ones that are 0 to possible_moves
for(int i = 0; i < 9; ++i)
{
if( bits.test(i) == false)
{
moves.push_back(i);
}
}
return moves;
}
int AI::best_move(const Board& board)
{
minimax(board, 0, true);
return choice;
}
int AI::minimax(const Board& position, int depth, bool maxPlayer)
{
//check position game state and return score if game is lost, won, or tied
if(position.check_win(!is_o)) //AI loses
{
return depth - 10;
}
else if(position.check_win(is_o)) //AI wins
{
return 10 - depth;
}
else if(position.check_tie())
{
return 0;
}
//do minimax calculation
if(maxPlayer)
{
int max_move{};
int max_move_score{ std::numeric_limits<int>::min()};
for(int move : position.possible_moves())
{
Board possible_position{ position };
possible_position.place(move, is_o);
int score = minimax(possible_position, ++depth, false);
if ( score > max_move_score )
{
max_move = move;
max_move_score = score;
}
}
choice = max_move;//last call to this will be at first call to minimax() from best_move()
return max_move_score; //return max score
}
else
{
int min_move{};
int min_move_score{ std::numeric_limits<int>::max()};
for(int move : position.possible_moves())
{
Board possible_position{ position };
possible_position.place(move, !is_o);
int score = minimax(possible_position, ++depth, true);
if ( score < min_move_score )
{
min_move = move;
min_move_score = score;
}
}
return min_move_score; //return max score
}
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include "tictactoe.h"
#include <array>
#include <ctime>
#include <iostream>
#include <random>
#include <string>
int ask_player_input()
{
bool retry{ false };
int index{};
std::cout << "It's your turn. Where do you want to go(e.g. A1 B3 C2)? ";
do{
if(retry)
{
std::cout << "No, no, no! Input a letter followed by a number: ";
}
retry = false; //reset retry
std::string input;
std::cin >> input;
if(input.size() < 2)
{
retry = true;
continue;
}
//letter input
int col_input{};
switch(input.at(0))
{
case 'A':
case 'a':
col_input = 0;
break;
case 'B':
case 'b':
col_input = 1;
break;
case 'C':
case 'c':
col_input = 2;
break;
default:
retry = true;
continue;
}
//number input
int row_input = input.at(1) - '0'; //converts char '2' to int 2
if(--row_input < 0 || 3 < row_input)
{
retry = true;
continue;
}
index = col_input * 3 + row_input;
} while( retry );
return index;
}
bool ask_turn() //ask who will go first if return true O goes first
{
bool turn{};
std::string input;
std::cout << "Who do you want to be?(X or O)? ";
for(bool valid_input{false}; !valid_input;)
{
std::cin >> input;
switch(input.front()) //input cannot be null at this point
{
case 'x':
case 'X':
valid_input = true;
turn = false;
break;
case '0':
case 'o':
case 'O':
valid_input = true;
turn = true;
break;
default:
std::cout << "Invalid input! Try X or O :";
}
}
return turn;
}
std::ostream& print_board(std::ostream& os,const Board& board)
{
os << " |A|B|C\n";
for(int row = 0; row < 3; ++row)
{
os << std::string( 8, '-') << '\n';
os << row + 1 << '|';
for(int col = 0; col < 3; ++col)
{
char follow_char{ col == 2 ? '\n' : '|' };
char place_char{};
//determine character to print for this board place on the board
BoardValue place_value = board.at(col * 3 + row);
if(place_value == BoardValue::none) place_char = ' ';
else place_char = place_value == BoardValue::o ? 'O' : 'X';
os << place_char << follow_char;
}
}
os << '\n';
return os;
}
std::ostream& operator<<(std::ostream& os,const Board& board)
{
return print_board(os, board);
}
int main(){
std::default_random_engine e{ static_cast<long unsigned int>(time(NULL)) };
bool turn{ e() % 2 };
bool player_turn{ ask_turn() };
Board board{};
AI ai{ !player_turn };
if(turn != player_turn)//player first, turns will be flipped at start of game loop
{
std::cout << "You go first!\n" << board;
}
else
{
std::cout << "Computer gets to go first this time. Good luck!\n";
}
while(board.check_win(turn) == false && board.check_tie() == false)
{
turn = !turn;
if(turn == player_turn)
{
bool input_valid{false};
while(input_valid == false)
{
int input;
input = ask_player_input();
input_valid = board.place(input, turn);
if( input_valid == false )
std::cout << "That place is take! Try again...\n";
}
}
else //AI turn
{
int best_move = ai.best_move(board);
board.place( best_move, turn);
std::cout << board;
//print AI turn
std::array<char,3> col_chars = { 'A', 'B', 'C' };
char col_input = col_chars.at( best_move % 3 );
int row_input = ((best_move + 1) / 3) + 1;
std::cout << "Computer picks " << col_input << row_input << '\n';
}
}
std::cout << board;
if(board.check_tie())
{
std::cout << "Looks like its a tie...\n";
}
else
{
std::cout << (turn == player_turn ? "You won!" : "The computer wins..." ) << '\n';
}
}
</code></pre>
| [] | [
{
"body": "<p>Not time to check all the program, but I still spotted something I want to share:</p>\n\n<p>This:</p>\n\n<pre><code>switch (input.front()) //input cannot be null at this point\n{\ncase 'x':\ncase 'X':\n valid_input = true;\n turn = false;\n break;\ncase '0':\ncase 'o':\ncase 'O':\n valid_input = true;\n turn = true;\n break;\ndefault:\n std::cout << \"Invalid input! Try X or O :\";\n}\n</code></pre>\n\n<p>If you turn your compiler warnings on a high level you probably get complaints that you left out some <code>break</code>-statements. If you use C++17 you should state your intention with <a href=\"https://en.cppreference.com/w/cpp/language/attributes/fallthrough\" rel=\"nofollow noreferrer\">[[fallthrough]]</a>:</p>\n\n<pre><code>switch (input.front()) //input cannot be null at this point\n{\ncase 'x':\n [[fallthrough]]\ncase 'X':\n valid_input = true;\n turn = false;\n break;\ncase '0':\n [[fallthrough]]\ncase 'o':\n [[fallthrough]]\ncase 'O':\n valid_input = true;\n turn = true;\n break;\ndefault:\n std::cout << \"Invalid input! Try X or O :\";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T18:09:59.280",
"Id": "221211",
"ParentId": "221181",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T08:05:53.000",
"Id": "221181",
"Score": "6",
"Tags": [
"c++",
"algorithm",
"tic-tac-toe",
"ai"
],
"Title": "Improved first Tic-Tac-Toe + Minimax AI"
} | 221181 |
<p>I'm building a clone banking app at the moment, and one of the things I'm trying to do is add <em>Split Transaction</em> (which can then be shared with a set of friends paying a given amount each).</p>
<p>Initially, the transaction is split equally amongst friends (unless it doesn't split equally, in which case the remainder gets added on to one unlucky friend). The user can then manually adjust the amount each pays, which then updates the others. If the user has manually adjusted an amount for a friend, this friends <em>split</em> doesn't get updated automatically when the user adjusts another friend's amount (i.e. if the user says friend1 pays £12, it will always be £12 until the user says otherwise).</p>
<p>I've been fiddling for a while trying to make the method as concise and <em>Swifty</em> as possible - but I'd really appreciate any feedback on my approach.</p>
<p>For the purposes here, I'm only trying split the money equally between people (but I still wanted to explain the <em>user-defined split</em> so that the current code makes sense).</p>
<p>I'm using <a href="https://github.com/Flight-School/Money" rel="nofollow noreferrer">https://github.com/Flight-School/Money</a> to represent the transaction value, all within a Transaction class. I need to round quite a bit to ensure the split and remainder stick to 2 decimal places. Here's the relevant code:</p>
<p>A struct to hold an amount along with if the user set it or not (needs to be a custom object for codable reasons):</p>
<pre><code>struct SplitTransactionAmount: Codable {
let amount: Money<GBP>
let setByUser: Bool
}
</code></pre>
<p>A dictionary to hold the friend names, along with their split, and if it's set by the user - also a namesOfPeopleSplittingTransaction array for easy display.</p>
<pre><code>var splitTransaction: [String: SplitTransactionAmount]
var namesOfPeopleSplittingTransaction = [String]()
</code></pre>
<p>And here's the method to split the transaction:</p>
<pre><code>private func splitTransaction(amount: Money<GBP>, with friends: [String]) -> [String: SplitTransactionAmount] {
//First we remove any duplicate names.
let uniqueFriends = friends.removingDuplicates()
//Create an empty dictionary to hold the new values before returning.
var newSplitTransaction = [String: SplitTransactionAmount]()
let totalAmountToSplitRounded = amount.rounded.amount
let numberOfSplitters = uniqueFriends.count
let eachTotalRaw = totalAmountToSplitRounded / Decimal(numberOfSplitters)
let eachTotalRounded = Money<GBP>(eachTotalRaw).rounded.amount
let remainder = totalAmountToSplitRounded - (Decimal(numberOfSplitters) * eachTotalRounded)
if remainder == 0 {
//If the amount to split each goes in to the total with no remainder, everyone pays the same.
for friend in uniqueFriends {
newSplitTransaction[friend] = SplitTransactionAmount(amount: Money(eachTotalRounded), setByUser: false)
}
} else {
for friend in uniqueFriends {
if friend == uniqueFriends.first! {
//Unlucky first friend has to pay a few pence more!
newSplitTransaction[friend] = SplitTransactionAmount(amount: Money(eachTotalRounded + remainder), setByUser: false)
} else {
newSplitTransaction[friend] = SplitTransactionAmount(amount: Money(eachTotalRounded), setByUser: false)
}
}
}
return newSplitTransaction
}
</code></pre>
<p>I think the problem I'm finding is the code makes perfect sense to me, but I'm not sure how clear it is to an outside reader. Any thoughts on my approach would be much appreciated (and sorry for the long question!). And I'd also love to know if there's any way to write this more concisely!</p>
<p>I've also extended array to remove duplicates:</p>
<pre><code>extension Array where Element: Hashable {
func removingDuplicates() -> [Element] {
var addedDict = [Element: Bool]()
return filter {
//When filter() is called on a dictionary, it returns nil if the key is new, so we can find out which items are unique.
addedDict.updateValue(true, forKey: $0) == nil
}
}
//This will change self to remove duplicates.
mutating func removeDuplicates() {
self = self.removingDuplicates()
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T13:23:19.563",
"Id": "427614",
"Score": "1",
"body": "Is it mandatory to have the ***first*** friend pay the extra remainder or should it be random?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T13:50:02.940",
"Id": "427621",
"Score": "1",
"body": "Rounding `eachTotalRaw` may result in a negative `remainder` and in that case, the *first* friend would be the lucky one"
}
] | [
{
"body": "<h3>Separation of concerns</h3>\n\n<p>There is (in my opinion) too much logic in the main function. Splitting an amount “fairly” into <span class=\"math-container\">\\$ n \\$</span> parts is difficult enough. That function should not know about “friends,” that a list of friends might not be unique, or that friends are represented as strings.</p>\n\n<p>I would suggest to define a function </p>\n\n<pre><code>splitAmount(total: numParts: )\n</code></pre>\n\n<p>which takes an amount and a number and returns an array of amounts (the exact signature is discussed later). Your <code>splitTransaction()</code> function can then build on <code>splitAmount()</code>.</p>\n\n<h3>Why only GBP? – Make it generic!</h3>\n\n<p>Your <code>splitTransaction()</code> function takes a <code>Money<GBP></code> amount, i.e. it works only with pound sterling, the British currency. Only minimal changes are required to make the same function work with arbitrary currencies: Change the function type to</p>\n\n<pre><code>func splitTransaction<Currency>(amount: Money<Currency>, with friends: [String]) -> [String: SplitTransactionAmount]\n where Currency: CurrencyType {\n // ...\n}\n</code></pre>\n\n<p>and replace <code>Money<GBP></code> by <code>Money<Currency></code> in the function body.</p>\n\n<p>For the <code>splitAmount()</code> function suggested above that would be</p>\n\n<pre><code>func splitAmount<Currency>(amount: Money<Currency>, numParts: Int) -> [Money<Currency>]\n where Currency: CurrencyType {\n // ...\n}\n</code></pre>\n\n<h3>The algorithm</h3>\n\n<p>Here are two examples how an amount split into 6 parts with your algorithm:</p>\n\n<pre><code>10.04 -> 1.69, 1.67, 1.67, 1.67, 1.67, 1.67\n10.05 -> 1.65, 1.68, 1.68, 1.68, 1.68, 1.68\n</code></pre>\n\n<p>In the first example, the remainder is <span class=\"math-container\">\\$0.02\\$</span>, and a better result would be achieved by splitting that among two friends:</p>\n\n<pre><code>10.04 -> 1.68, 1.68, 1.67, 1.67, 1.67, 1.67\n</code></pre>\n\n<p>In the second example, the remainder is <span class=\"math-container\">\\$-0.03\\$</span>. Again the split is not optimal, in addition the first amount is <em>less</em> then the others, contrary to the description of your method. A better result would be</p>\n\n<pre><code>10.05 -> 1.68, 1.68, 1.68, 1.67, 1.67, 1.67\n</code></pre>\n\n<p>The problem is of course the floating point arithmetic. Even if <code>Money</code> uses the <code>Decimal</code> type which can represent <em>decimal</em> fractions exactly: It still cannot represent the result of a division like <span class=\"math-container\">\\$ 10.05 / 6 \\$</span> exactly. Rounding that fraction to a multiple of <span class=\"math-container\">\\$ 0.01 \\$</span> (the “minor unit” of the currency) can result in a smaller or a larger value (as in the second example).</p>\n\n<p>Actually such calculations are much better done in <em>integer arithmetic.</em> If £10.04 are represented as 1004 (pennies), then we can perform an integer division with remainder</p>\n\n<pre><code>1004 = 167 * 6 + 2\n</code></pre>\n\n<p>so that each part is 167 pennies, plus 1 penny for the first two parts. Similarly:</p>\n\n<pre><code>1005 = 167 * 6 + 3\n</code></pre>\n\n<p>Unfortunately, the <code>Money</code> class does not provide methods to get an amount as integer multiple of the currency's minor unit, but that is not too difficult to implement:</p>\n\n<pre><code>extension Money {\n\n /// Creates an amount of money with a given number of “minor units” of the currency.\n init(units: Int) {\n self.init(Decimal(units) * Decimal(sign: .plus, exponent: -Currency.minorUnit, significand: 1))\n }\n\n /// The amount of money as the count of “minor units” of the currency.\n var units: Int {\n var amount = self.amount \n var rounded = Decimal()\n NSDecimalRound(&rounded, &amount, Currency.minorUnit, .bankers)\n rounded *= Decimal(sign: .plus, exponent: Currency.minorUnit, significand: 1)\n return NSDecimalNumber(decimal: rounded).intValue\n }\n}\n</code></pre>\n\n<p>With these preparations, the <code>splitAmount()</code> function is easily implemented:</p>\n\n<pre><code>func splitAmount<Currency>(amount: Money<Currency>, numParts: Int) -> [Money<Currency>]\n where Currency: CurrencyType {\n let units = amount.units\n let fraction = units / numParts\n let remainder = units % numParts\n\n return Array(repeating: Money<Currency>(units: fraction + 1),\n count: remainder)\n + Array(repeating: Money<Currency>(units: fraction),\n count: numParts - remainder)\n}\n</code></pre>\n\n<p>The above works for non-negative amounts only. If the amounts can be negative as well then a possible implementation would be</p>\n\n<pre><code>func splitAmount<Currency>(amount: Money<Currency>, numParts: Int) -> [Money<Currency>]\n where Currency: CurrencyType {\n let units = amount.units\n let fraction = units / numParts\n let remainder = abs(units) % numParts\n\n return Array(repeating: Money<Currency>(units: fraction + units.signum()),\n count: remainder)\n + Array(repeating: Money<Currency>(units: fraction),\n count: numParts - remainder)\n}\n</code></pre>\n\n<p><strong>Examples:</strong></p>\n\n<pre><code>// Pound Sterling, minor unit is 0.01:\nprint(splitAmount(amount: Money<GBP>(10.04), numParts: 6))\n// [1.68, 1.68, 1.67, 1.67, 1.67, 1.67]\n\n// Iraqi Dinar, minor unit is 0.001:\nprint(splitAmount(amount: Money<IQD>(10.000), numParts: 6))\n// [1.667, 1.667, 1.667, 1.667, 1.666, 1.666]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:06:41.527",
"Id": "427772",
"Score": "0",
"body": "I've had couple of great answers for this - thank you! I've selected this answer as it's the clearest (and most understandable at my level - although that's totally subjective!)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T11:25:53.057",
"Id": "428526",
"Score": "0",
"body": "Out of interest, how would you extend this for negative amounts please? I've tried just using the absolute value for units but I'm not sure if it's as simple as that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T20:47:29.630",
"Id": "428609",
"Score": "1",
"body": "@ADB: I have added a possible implementation which works for both positive and negative amounts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T07:21:04.307",
"Id": "428666",
"Score": "0",
"body": "That's so helpful - thank you so much."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T20:33:35.090",
"Id": "221221",
"ParentId": "221184",
"Score": "4"
}
},
{
"body": "<p>A couple of observations:</p>\n\n<ul>\n<li><p>When <code>splitTransaction</code> is diving into <code>Decimal</code> types and the like, that indicates that you’ve placed algorithms at the wrong level.</p></li>\n<li><p>To that end, let’s give the <code>Money</code> the necessary arithmetic operators so that <code>splitTransaction</code> doesn’t get into the weeds of <code>Decimal</code> or other details of the <code>Money</code> type.</p></li>\n<li><p>You have a <code>rounded</code> computed property. I’d suggest making that a function and allowing the caller to specify the type of rounding to be applied.</p></li>\n<li><p>You have made <code>Currency</code> conform to <code>Codable</code> (which you presumably did so you could make <code>Money</code> also <code>Codable</code>). I don’t think you intended to do that because currencies will have all sorts of properties that you most likely don’t want to encode. That should not be codable, and <code>Money</code> should have the currency code as a property, not the currency itself. That code is presumably the only thing you want <code>Money</code> to encode.</p></li>\n<li><p>Your algorithm assumes there will be one user who picks up the remainder. I’d suggest you spread it around. If the bill is €9.02, rather than sticking the first person with €3.02, let’s give two people €3.01 and the third €3.00.</p></li>\n<li><p>You are applying the remainder to the first user. I’d suggest you randomize it. If the list was sorted, for example, you don’t want the same people always getting the short end of the stick.</p></li>\n<li><p>Your rounding algorithm presumably assumes that you’ll be rounding to the nearest pence. But you should handle currencies that generally don’t use fractional values. In fact, going a step further, you should really handle arbitrary minimum units for the currency. E.g. imagine a world where the US decides it doesn’t want to deal with pennies any more, and makes the nickel the minimum unit. Well, that’s how you should be rounding (to the nearest $0.05), not to two decimal places. Likewise, imagine that Japan decided that they weren’t going to deal with anything smaller than ¥20. Then, again, that’s what you should be rounding to, not to the nearest yen.</p></li>\n<li><p>The <code>splitTransaction</code> should probably be generic.</p></li>\n</ul>\n\n<p>Thus, you end up with something like:</p>\n\n<pre><code>private func splitTransaction<T: Currency>(_ transaction: Money<T>, with friends: [String]) -> [String: SplitTransaction<T>] {\n let uniqueFriends = friends.removingDuplicates()\n\n guard !uniqueFriends.isEmpty else { return [:] }\n\n let currency = transaction.currency\n let minimumUnit = currency.minimumUnit\n let total = transaction.roundedToMinimumUnit()\n let count = uniqueFriends.count\n let baseIndividualAmount = (total / count).roundedToMinimumUnit(.down)\n let remainder = total - baseIndividualAmount * count\n let howManyAdjustments = currency.howManyUnits(remainder)\n\n // split the transaction\n\n var splitTransaction = uniqueFriends.reduce(into: [:]) {\n $0[$1] = SplitTransaction(amount: baseIndividualAmount, setByUser: false)\n }\n\n // adjust random friends based upon remainder\n\n for friend in uniqueFriends.shuffled()[0..<howManyAdjustments] {\n splitTransaction[friend]!.amount = splitTransaction[friend]!.amount + minimumUnit\n }\n return splitTransaction\n}\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>protocol Currency {\n var code: String { get }\n var minimumUnit: Decimal { get }\n var symbol: String { get }\n var decimalPlaces: Int { get }\n init()\n}\n\nextension Currency {\n func howManyUnits<T: Currency>(_ money: Money<T>) -> Int {\n return NSDecimalNumber(decimal: money.value / minimumUnit).intValue\n }\n}\n\nstruct GBP: Currency {\n let code = \"GBP\"\n let symbol = \"£\"\n let decimalPlaces = 2\n let minimumUnit = Decimal(sign: .plus, exponent: -2, significand: 1) // 0.01\n}\n\nstruct EUR: Currency {\n let code = \"EUR\"\n let symbol = \"€\"\n let decimalPlaces = 2\n let minimumUnit = Decimal(sign: .plus, exponent: -2, significand: 1) // 0.01\n}\n\nstruct JPY: Currency {\n let code = \"JPY\"\n let symbol = \"¥\"\n let decimalPlaces = 0\n let minimumUnit = Decimal(sign: .plus, exponent: 1, significand: 2) // 20, for demonstration purposes only\n}\n\nclass Currencies {\n static let shared = Currencies()\n\n let availableCurrencies: [String: Currency] = {\n let array: [Currency] = [GBP(), EUR(), JPY()]\n return Dictionary(grouping: array) { $0.code }\n .mapValues { $0.first! }\n }()\n\n func currency(for code: String) -> Currency {\n return availableCurrencies[code]!\n }\n}\n\nextension Array where Element: Hashable {\n func removingDuplicates() -> [Element] {\n return Array(Set(self))\n }\n\n mutating func removeDuplicates() {\n self = self.removingDuplicates()\n }\n}\n\nstruct Money<T: Currency>: Codable {\n let value: Decimal\n let currencyCode: String\n var currency: Currency { return Currencies.shared.currency(for: currencyCode) }\n\n init(_ value: Decimal) {\n self.value = value\n self.currencyCode = T().code\n }\n\n func roundedToMinimumUnit(_ mode: NSDecimalNumber.RoundingMode = .bankers) -> Money {\n var input = (value / currency.minimumUnit)\n var result = input\n NSDecimalRound(&result, &input, 0, mode)\n return Money(result * currency.minimumUnit)\n }\n\n static func + (lhs: Money, rhs: Money) -> Money {\n return Money(lhs.value + rhs.value)\n }\n\n static func + (lhs: Money, rhs: Decimal) -> Money {\n return Money(lhs.value + rhs)\n }\n\n static func - (lhs: Money<T>, rhs: Money<T>) -> Money<T> {\n return Money(lhs.value - rhs.value)\n }\n\n static func / (lhs: Money<T>, rhs: IntegerLiteralType) -> Money<T> {\n return Money(lhs.value / Decimal(rhs))\n }\n\n static func * (lhs: Money<T>, rhs: IntegerLiteralType) -> Money<T> {\n return Money(lhs.value * Decimal(rhs))\n }\n}\n\nstruct SplitTransaction<T: Currency>: Codable {\n var amount: Money<T>\n let setByUser: Bool\n}\n</code></pre>\n\n<p>Thus:</p>\n\n<pre><code>let money = Money<JPY>(10_040) // with my imaginary rendition where ¥20 is the smallest unit\nlet split = splitTransaction(money, with: [\"fred\", \"george\", \"sue\"])\n</code></pre>\n\n<p>That yields:</p>\n\n<blockquote>\n <p>fred, 3360<br />\n george, 3340<br />\n sue, 3340</p>\n</blockquote>\n\n<p>And </p>\n\n<pre><code>let money = Money<GBP>(9.02)\n</code></pre>\n\n<p>Yields:</p>\n\n<blockquote>\n <p>fred, 3.00<br />\n george, 3.01<br />\n sue, 3.01</p>\n</blockquote>\n\n<p>And in both of these cases, who gets hit with the remainder is randomized.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T21:40:32.480",
"Id": "221226",
"ParentId": "221184",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221221",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T10:14:09.570",
"Id": "221184",
"Score": "5",
"Tags": [
"performance",
"swift",
"formatting",
"hash-map"
],
"Title": "Splitting an amount of money equally between a group of people"
} | 221184 |
<p>I have an asp.net web API and I am using EF6 to connect to a third party rest API which sells online game codes. We made a deal with the company so clients have to call my rest API in order to get the game codes. Clients can list the available games via product method. Initiation is the first step of buying process. Initiation method sends JWT token in order to let client use it and finish purchase of the game code in the confirmation method. And there are reconciliation methods, recon initiation is like the initiation method just for sending back a JWT. Client uses this JWT and call recon confirmation to update a specific purchase like sold, not sold.</p>
<p>Is my usage correct? Would you please guide me? Dbcontext is disposed when the request completed right? And if I pass context to a method inside of another class (Utilities) to make some DB process, after completion of the process does ninject dispose the context? </p>
<p>Here is my sample Dbcontext:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace EPINMiddleWareAPI.Models
{
public class EPINMiddleWareAPIContext : DbContext
{
public EPINMiddleWareAPIContext() : base("name=EPINMiddleWareAPIContext")
{
}
public DbSet<InitiateRequest> InitiateRequests { get; set; }
public DbSet<InitiateResponse> InitiateResponses { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<ConfirmRequest> ConfirmRequests { get; set; }
public DbSet<ConfirmResponse> ConfirmResponses { get; set; }
public DbSet<GameBank> GameBanks { get; set; }
public DbSet<GameCouponBank> GameCouponBanks { get; set; }
}
}
</code></pre>
<p>Here is my ninject:</p>
<pre><code>using EPINMiddleWareAPI.Controllers;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(EPINMiddleWareAPI.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(EPINMiddleWareAPI.App_Start.NinjectWebCommon), "Stop")]
namespace EPINMiddleWareAPI.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using Models;
using Ninject.Web.Common.WebHost;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<EPINMiddleWareAPIContext>().ToSelf().InRequestScope();
}
}
}
</code></pre>
<p>And my controller:</p>
<pre><code>using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using EPINMiddleWareAPI.Models;
using Newtonsoft.Json;
using System.Net;
using EPINMiddleWareAPI.Utility;
using System.Linq;
using System.Data.Entity;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Linq;
namespace EPINMiddleWareAPI.Controllers
{
[System.Web.Http.RoutePrefix("api/v2/pin")]
public class InitiatesController : ApiController
{
private readonly EPINMiddleWareAPIContext context;
public InitiatesController(EPINMiddleWareAPIContext context)
{
this.context = context;
}
// POST: api/Game
//[RequireHttps] For Prod Only
[HttpPost, Route("initiation")]
public async Task<IHttpActionResult> PostInitiate(InitiateRequest initiate)
{
#region Is referenceId Unique?
if (await Utilities.IsUnique(context, initiate) > 0)
{
ModelState.AddModelError("referenceId", "This referenceId has used!");
}
#endregion
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
#region Validate Company
var responseMsg = new HttpResponseMessage();
var isUsernamePasswordValid = false;
//Find Company in our database
var companyCheck =
await (context.Companies.Where(p => p.customerID == initiate.customerID)).SingleOrDefaultAsync();
//Check company password in our database
if (companyCheck != null)
{
isUsernamePasswordValid = Utilities.VerifyPassword(initiate.password, companyCheck.hash, companyCheck.salt);
}
//Send UnAuthorized if we don't know the company
if (!isUsernamePasswordValid)
{
// if credentials are not valid send unauthorized status code in response
responseMsg.StatusCode = HttpStatusCode.Unauthorized;
IHttpActionResult rMessage = ResponseMessage(responseMsg);
return rMessage;
}
#endregion
#region Check Code Bank database
//Check Games in our database - all or nothing
var gameBankResult = await (context.GameBanks.Where(g => g.productCode == initiate.productCode)
.Where(l => l.referenceId == null)
).ToListAsync();
//If we have exact number of games in our database, mark them!
if (gameBankResult.Count() != 0 && gameBankResult.Count() >= initiate.quantity)
{
for (var index = 0; index < initiate.quantity; index++)
{
var item = gameBankResult[index];
item.referenceId = initiate.referenceId;
context.Entry(item).State = System.Data.Entity.EntityState.Modified;
}
//Update marked games
await context.SaveChangesAsync();
//Create token
var token = Utilities.createToken(companyCheck.userName);
//Return marked games in our database
var gameBankResultVM = await (context.GameBanks.Where(g => g.productCode == initiate.productCode)
.Where(l => l.referenceId == initiate.referenceId)
.Take(initiate.quantity)
.Select(g => new GameBankInitiationResponseVM()
{
referenceId = g.referenceId,
productCode = g.productCode,
quantity = initiate.quantity,
initiationResultCode = g.initiationResultCode,
validatedToken = g.validatedToken,
currency = g.currency,
estimateUnitPrice = g.estimateUnitPrice,
version = g.version,
signature = g.signature,
ApplicationCode = g.ApplicationCode,
companyToken = token,
})).ToListAsync();
var resultObj = gameBankResultVM[0];
var initiateResponse = JsonConvert.SerializeObject(resultObj);
var responseDB = JsonConvert.DeserializeObject<InitiateResponse>(initiateResponse);
//Adding Response into database
context.InitiateResponses.Add(responseDB);
await context.SaveChangesAsync();
return Ok(resultObj);
}
#endregion
// Add Signature
initiate = Utilities.CreateSignature(initiate);
#region Insert Request into DB
//Adding Request into database
context.InitiateRequests.Add(initiate);
await context.SaveChangesAsync();
#endregion
#region Call Game
var httpClient = new HttpClient();
//Convert request
var keyValues = initiate.ToKeyValue();
var content = new FormUrlEncodedContent(keyValues);
//Call Game Sultan
var response =
await httpClient.PostAsync("https://test.com/purchaseinitiation",content);
#endregion
//Read response
var htmlResponse = await response.Content.ReadAsStringAsync();
switch (response.StatusCode)
{
case HttpStatusCode.NotFound:
{
return NotFound();
}
case HttpStatusCode.InternalServerError:
{
return InternalServerError();
}
case HttpStatusCode.OK:
{
var initiateResponse = JsonConvert.DeserializeObject<InitiateResponse>(htmlResponse);
//Create Token if the result is SUCCESS
if (initiateResponse.initiationResultCode == "00")
{
//Create TOKEN and set
initiateResponse.companyToken = Utilities.createToken(companyCheck.userName);
}
//Adding Response into database
context.InitiateResponses.Add(initiateResponse);
await context.SaveChangesAsync();
return Ok(initiateResponse);
}
case HttpStatusCode.BadRequest:
{
return BadRequest(htmlResponse);
}
case HttpStatusCode.Unauthorized:
{
return Unauthorized();
}
case HttpStatusCode.RequestTimeout:
{
return InternalServerError();
}
default:
{
htmlResponse = await response.Content.ReadAsStringAsync();
break;
}
}
return Ok(htmlResponse);
}
// POST: api/Game
//[RequireHttps] For Prod Only
[Authorize]
[HttpPost, Route("confirmation")]
public async Task<IHttpActionResult> PostConfirmation(ConfirmRequest confirm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
#region Validate Company
var responseMsg = new HttpResponseMessage();
var isUsernamePasswordValid = false;
//Find Company in our database
var companyCheck =
await (context.Companies.Where(p => p.customerID == confirm.customerID)).SingleOrDefaultAsync();
//Check company password in our database
if (companyCheck != null)
isUsernamePasswordValid = Utilities.VerifyPassword(confirm.password, companyCheck.hash, companyCheck.salt);
//Send UnAuthorized if we don't know the company
if (!isUsernamePasswordValid)
{
// if credentials are not valid send unauthorized status code in response
responseMsg.StatusCode = HttpStatusCode.Unauthorized;
IHttpActionResult rMessage = ResponseMessage(responseMsg);
return rMessage;
}
#endregion
#region Check Code Bank database
//Return marked games in our database
var gameBankResultVM = await (context.GameBanks
.Where(l => l.referenceId == confirm.referenceId)
.Select(g => new GameBankConfirmResponseVM()
{
referenceId = g.referenceId,
paymentId = null,
productCode = g.productCode,
quantity = g.quantity,
deliveredQuantity = g.quantity,
currency = g.currency,
version = g.version,
signature = g.signature,
ApplicationCode = g.ApplicationCode,
productDescription = g.productDescription,
unitPrice = g.unitPrice,
totalPrice = g.totalPrice,
totalPayablePrice = g.totalPrice,
coupons = g.coupons.Select(c => new GameCouponBankVM()
{
Pin = c.Pin,
Serial = c.Serial,
expiryDate = c.expiryDate
}).ToList()
})).ToListAsync();
//If we have games in our database, select them!
if (gameBankResultVM.Count() != 0)
{
if (gameBankResultVM.Count <= 1)
{
//Adding Response into database
var responseNew = JsonConvert.SerializeObject(gameBankResultVM[0]);
var confirmResponse = JsonConvert.DeserializeObject<ConfirmResponse>(responseNew);
context.ConfirmResponses.Add(confirmResponse);
await context.SaveChangesAsync();
return Ok(gameBankResultVM[0]);
}
else if(gameBankResultVM.Count > 1)
{
var gameResult = new GameBankConfirmResponseVM();
var price = 0.0;
var quantity = 0;
foreach (var item in gameBankResultVM)
{
price = price + item.unitPrice;
quantity = quantity + 1;
foreach (var coupons in item.coupons)
{
var gameCouponResult = new GameCouponBankVM
{
expiryDate = coupons.expiryDate,
Pin = coupons.Pin,
Serial = coupons.Serial
};
//Add coupon values
gameResult.coupons.Add(gameCouponResult);
}
}
//Set summed/counted values
gameResult.referenceId = gameBankResultVM[0].referenceId;
gameResult.paymentId = gameBankResultVM[0].paymentId;
gameResult.productCode = gameBankResultVM[0].productCode;
gameResult.quantity = quantity;
gameResult.deliveredQuantity = quantity;
gameResult.currency = gameBankResultVM[0].currency;
gameResult.unitPrice = gameBankResultVM[0].unitPrice;
gameResult.totalPrice = price;
gameResult.purchaseStatusDate = gameBankResultVM[0].purchaseStatusDate;
gameResult.productDescription = gameBankResultVM[0].productDescription;
gameResult.totalPayablePrice = price;
gameResult.version = gameBankResultVM[0].version;
gameResult.signature = null;
gameResult.ApplicationCode = null;
//Adding Response into database
var responseNew = JsonConvert.SerializeObject(gameResult);
var confirmResponse = JsonConvert.DeserializeObject<ConfirmResponse>(responseNew);
context.ConfirmResponses.Add(confirmResponse);
await context.SaveChangesAsync();
return Ok(gameResult);
}
}
#endregion
// Add Signature
confirm = Utilities.CreateSignature(confirm);
// Save Request into Table
context.ConfirmRequests.Add(confirm);
await context.SaveChangesAsync();
var httpClient = new HttpClient();
var keyValues = confirm.ToKeyValue();
var content = new FormUrlEncodedContent(keyValues);
var response =
await httpClient.PostAsync("https://test.com/purchaseconfirmation", content);
var htmlResponse = await response.Content.ReadAsStringAsync();
switch (response.StatusCode)
{
case HttpStatusCode.NotFound:
return NotFound();
case HttpStatusCode.InternalServerError:
return InternalServerError();
case HttpStatusCode.OK:
//Adding Response into database
var newResult = JObject.Parse(htmlResponse);
var confirmResponse = JsonConvert.DeserializeObject<ConfirmResponse>(newResult.ToString());
context.ConfirmResponses.Add(confirmResponse);
await context.SaveChangesAsync();
return Ok(newResult);
case HttpStatusCode.BadRequest:
return BadRequest();
case HttpStatusCode.Unauthorized:
return Unauthorized();
case HttpStatusCode.RequestTimeout:
return InternalServerError();
default:
htmlResponse = await response.Content.ReadAsStringAsync();
break;
}
return Ok(htmlResponse);
}
[HttpPatch, Route("reconInitiation")]
public async Task<IHttpActionResult> PatchReconciliationInitiation(Recon recon)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
#region Validate Company
var responseMsg = new HttpResponseMessage();
var isUsernamePasswordValid = false;
//Company password check
var companyCheck =
await (context.Companies.Where(p => p.customerID == recon.customerID)).SingleOrDefaultAsync();
if (companyCheck != null)
isUsernamePasswordValid = Utilities.VerifyPassword(recon.password, companyCheck.hash, companyCheck.salt);
if (!isUsernamePasswordValid)
{
// if credentials are not valid send unauthorized status code in response
responseMsg.StatusCode = HttpStatusCode.Unauthorized;
IHttpActionResult rMessage = ResponseMessage(responseMsg);
return rMessage;
}
#endregion
//Projection
var reconInitiateVm = new ReconInitiationVM();
//Create TOKEN and set
reconInitiateVm.companyToken = Utilities.createToken(companyCheck.userName);
return Ok(reconInitiateVm);
}
[Authorize]
[HttpPatch, Route("reconConfirmation")]
public async Task<IHttpActionResult> PatchReconciliationConfirmation(Recon recon)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
#region Validate Company
var responseMsg = new HttpResponseMessage();
var isUsernamePasswordValid = false;
//Company password check
var companyCheck =
await (context.Companies.Where(p => p.customerID == recon.customerID)).SingleOrDefaultAsync();
if (companyCheck != null)
isUsernamePasswordValid = Utilities.VerifyPassword(recon.password, companyCheck.hash, companyCheck.salt);
if (!isUsernamePasswordValid)
{
// if credentials are not valid send unauthorized status code in response
responseMsg.StatusCode = HttpStatusCode.Unauthorized;
IHttpActionResult rMessage = ResponseMessage(responseMsg);
return rMessage;
}
#endregion
#region Check Our Database
DateTime? today = DateTime.Today;
var reconResult = await (context.GameBanks.Where(g => g.used == 0)
.Where(l => l.referenceId != null)
.Where(t => System.Data.Entity.DbFunctions.TruncateTime(t.responseDateTime) == today)
).ToListAsync();
if (reconResult.Count() != 0)
{
foreach (var item in reconResult)
{
foreach (var reference in recon.referenceId)
{
if (item.referenceId == reference)
{
item.used = 1;
context.Entry(item).State = System.Data.Entity.EntityState.Modified;
}
}
}
await context.SaveChangesAsync();
}
#endregion
#region Check ConfirmResponse - Razer
var reconResultRazer = await (context.ConfirmResponses.Where(g => g.used == 0)
.Where(l => l.referenceId != null)
.Where(t => System.Data.Entity.DbFunctions.TruncateTime(t.purchaseStatusDate) == today)
).ToListAsync();
if (reconResultRazer.Count() != 0)
{
foreach (var item in reconResultRazer)
{
foreach (var reference in recon.referenceId)
{
if (item.referenceId == reference)
{
item.used = 1;
context.Entry(item).State = System.Data.Entity.EntityState.Modified;
}
}
}
await context.SaveChangesAsync();
}
#endregion
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Game
//[RequireHttps] For Prod Only
[HttpPost, Route("products")]
public async Task<IHttpActionResult> PostProducts(ProductRequest products)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
#region Validate Company
var responseMsg = new HttpResponseMessage();
var isUsernamePasswordValid = false;
//Find Company in our database
var companyCheck =
await (context.Companies.Where(p => p.customerID == products.customerID)).SingleOrDefaultAsync();
//Check company password in our database
if (companyCheck != null)
{
isUsernamePasswordValid =
Utilities.VerifyPassword(products.password, companyCheck.hash, companyCheck.salt);
}
//Send UnAuthorized if we don't know the company
if (!isUsernamePasswordValid)
{
// if credentials are not valid send unauthorized status code in response
responseMsg.StatusCode = HttpStatusCode.Unauthorized;
IHttpActionResult rMessage = ResponseMessage(responseMsg);
return rMessage;
}
#endregion
#region Check Code Bank database
//Return marked games in our database
var productsList = (context.GameBanks.AsEnumerable()
.Where(x => x.used == 0)
.GroupBy(g => new
{
g.productCode,
g.productDescription,
g.unitPrice
//g.used,
})
.Select(gcs => new
{
ProductID = Utilities.ConvertToLong(gcs.Key.productCode),
ProductName = gcs.Key.productDescription,
Price = gcs.Key.unitPrice,
//gcs.Key.used,
StockQuantity = gcs.Sum(g => g.quantity),
IsStockAvailable = Utilities.ConvertToBoolean(gcs.Sum(g => g.quantity) > 0 ? "True" : "False"),
}
)).ToList();
var list1 = productsList;
//var productResult = new ProductsResponse();
//foreach (var item in productsList)
//{
// var productDetailsResult = new Product()
// {
// ProductID = Convert.ToInt64(item),
// ProductName = item.ProductName,
// GameName = item.ProductName,
// Price = item.Price,
// StockQuantity = item.StockQuantity,
// IsStockAvailable = Convert.ToBoolean(item.IsStockAvailable),
// SmallProductImage = "No Image",
// SupplierName = "No Supplier",
// SupplierID = 1,
// GameID = 1
// };
// //Add coupon values
// productResult.Products.Add(productDetailsResult);
//}
// Add Signature
products = Utilities.CreateSignature(products);
var httpClient = new HttpClient();
var keyValues = products.ToKeyValue();
var content = new FormUrlEncodedContent(keyValues);
var response =
await httpClient.PostAsync("https://test.com/Product/", content);
var htmlResponse = await response.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<ProductsResponse>(htmlResponse);
var productsListRazer = model.Products
.Select(gcs => new
{
gcs.ProductID,
gcs.ProductName,
gcs.Price,
gcs.StockQuantity,
gcs.IsStockAvailable
}
).ToList();
var list2 = productsListRazer;
var merged = list1.Concat(list2)
.GroupBy(g => new
{
g.ProductID,
g.ProductName,
g.Price,
//g.StockQuantity,
g.IsStockAvailable
})
.Select(gcs => new
{
gcs.First().ProductID,
gcs.Key.ProductName,
gcs.Key.Price,
StockQuantity = gcs.Sum(g => g.StockQuantity),
gcs.Key.IsStockAvailable
}).ToList();
return Ok(merged);
#endregion
}
protected override void Dispose(bool disposing)
{
context.Dispose();
base.Dispose(disposing);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T17:10:24.950",
"Id": "427687",
"Score": "0",
"body": "I have one last question, I think... is there any particular reason you're not using asp.net-core? Or can't I just recognize it correctly? mhmmm It's such a mess with that asp frameworks ;-] I'm asking because there are several things that can be optimized in a much nicer way if done with asp.net-core... not sure whether I should suggest them. Could be in vain if it's not an option."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T18:26:33.537",
"Id": "427707",
"Score": "0",
"body": "@t3chb0t I am glad you asked this question :) Well I never implemented rest API before. 5 months ago when all this stuff started, this API requirement was urgent so I started with Python Flask but it is not suitable for enterprise I think. So I started reading articles and I am familiar with C# asp.net. I found a couple of step by step articles and now I am here :) At least code is working but I would like to make it better in terms of solid principles and OOP. My next move is to use core but after making this mess better. Are you with me? :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T21:26:25.743",
"Id": "427722",
"Score": "0",
"body": "@Cenk you don't need override the Dispose method with the purpose to dispose the db context. In general if an object does not create a disposable object, then he also doesn't have to dispose it. In this case Ninject is the one that creates the dbcontext and it also disposes it. Also since you pass around the dbcontext object to the Utilities class (that's a form of a dependency injection too), then you should be fine. Also the Utilities class is not part of your Ninject configuration, so there should be no interaction between them, outside your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T05:16:00.587",
"Id": "427912",
"Score": "0",
"body": "is there any good news for me :) @t3chb0t"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T18:33:38.050",
"Id": "428291",
"Score": "0",
"body": "is there any progress @t3chb0t ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-13T06:59:42.157",
"Id": "429939",
"Score": "0",
"body": "did you give up @t3chb0t :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-13T07:03:43.397",
"Id": "429940",
"Score": "0",
"body": "haha, I don't know yet... I took some time off ;-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-13T07:07:15.437",
"Id": "429942",
"Score": "0",
"body": "Alright, hope you help me on this journey @t3chb0t. I read some articles I guess I don't need unit of work, they say Dbcontext already provides this with using `DbContextTransaction`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-18T11:29:03.227",
"Id": "430723",
"Score": "0",
"body": "Let's build this on web API Core @t3chb0t :)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T10:50:25.857",
"Id": "221186",
"Score": "2",
"Tags": [
"c#",
"asp.net",
"dependency-injection",
"asp.net-web-api",
"ninject"
],
"Title": "Ninject binding for Dbcontext"
} | 221186 |
<p>I would like to implement a concurrent (multi-thread, multi-process) queue that is backed by file system. Data is pickled over a file, stored in a directory and given a sequential name.</p>
<p>The sequential name is milliseconds since epoch plus a random number that should prevent clashes. The queue will actually serve few processes and do few operations per second, but I wanted to be more general.</p>
<p>Also, this is thought to work on Linux, and I assumed that the rename of a file is atomic (I am not sure if it is the same on other platforms).
Therefore, I implemented a simple lock mechanism: <code>*.lock</code> files are ignored when popping from the queue, so a file will be locked (.lock suffix added) when being written and locked also when being read, then unlinked.</p>
<p>I think the only major flaw here is that collisions might occur when many threads or processes are being used, which won't happen in my case, but getting reviews from other eyes is definitely going to help.</p>
<pre><code>import os
import time
import pickle
import random
from pathlib import Path
class FSQueue:
def __init__(self, root, fs_wait=0.1, fifo=True):
"""Creates a FSQueue that will store data as pickle files in root."""
self._root = Path(root)
self._root.mkdir(exist_ok=True, parents=True)
self._wait = fs_wait
self._fifo = fifo
def put(self, data):
"""Adds data to the queue by dumping it to a pickle file."""
now = int(time.time() * 10000)
rnd = random.randrange(1000)
seq = f'{now:016}-{rnd:04}'
target = self._root / seq
fn = target.with_suffix('.lock')
pickle.dump(data, fn.open('wb')) # Write to locked file
fn.rename(target) # Atomically unlock
def get(self):
"""Pops data from the queue, unpickling it from the first file."""
# Get files in folder and reverse sort them
while True:
_, _, files = next(os.walk(self._root))
files = sorted(files, reverse=not self._fifo)
for f in files:
if f.endswith('lock'):
continue # Someone is writing or reading the file
try:
fn = self._root / f
target = fn.with_suffix('.lock')
fn.rename(target)
data = pickle.load(target.open('rb'))
target.unlink()
return data
except FileNotFoundError:
pass # The file was locked by another get()
# No files to read, wait a little bit
time.sleep(self._wait)
def qsize(self):
"""Returns the approximate size of the queue."""
_, _, files = next(os.walk(self._root))
n = 0
for f in files:
if f.endswith('lock'):
continue # Someone is reading the file
n += 1
return n
if __name__ == '__main__':
q = FSQueue('/tmp/test_queue')
for i in range(10):
q.put(f'data {i}')
assert q.qsize() == 10
for i in range(11):
print(q.get()) # The last one should wait
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T12:07:10.770",
"Id": "427600",
"Score": "0",
"body": "Ok, to make the file creation a bit more robust, I am now using `x` for file creation instead of `w`, inside a loop with a try-except block."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T11:28:58.050",
"Id": "221189",
"Score": "2",
"Tags": [
"python",
"file-system",
"queue"
],
"Title": "File-system based queue in python"
} | 221189 |
<p><strong><em>database.config.php</em></strong></p>
<pre><code><?php
class Database
{
private $host = "localhost";
private $db_name = "trial";
private $username = "root";
private $password = "";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
?>
</code></pre>
<p><strong><em>class.php</em></strong></p>
<pre><code><?php
include_once 'database.config.php';
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
?>
</code></pre>
<p><strong><em>index.php</em></strong></p>
<pre><code><?php
require_once 'class.php';
$user = new USER();
$teacher_fetch = $user->runQuery("SELECT * FROM teacher WHERE Id=:_id");
$teacher_fetch->execute(array(":_id"=>$_SESSION['teacher_id']));
$fetch_teacher = $teacher_fetch->fetch(PDO::FETCH_ASSOC);
echo $fetch_teacher['Name'];
?>
</code></pre>
<p>As it's a best practice to use <code>close()</code> in last where should I use it in the index.php file?</p>
<p><strong><em>Option 1</em></strong></p>
<pre><code>$teacher_fetch->execute(array(":_id"=>$_SESSION['teacher_id']));
//close connection here
$fetch_teacher = $teacher_fetch->fetch(PDO::FETCH_ASSOC);
echo $fetch_teacher['Name'];
</code></pre>
<p><strong><em>Option 2</em></strong></p>
<pre><code>$teacher_fetch->execute(array(":_id"=>$_SESSION['teacher_id']));
$fetch_teacher = $teacher_fetch->fetch(PDO::FETCH_ASSOC);
//close connection here
echo $fetch_teacher['Name'];
</code></pre>
<p><strong><em>Option 3</em></strong></p>
<pre><code>$teacher_fetch->execute(array(":_id"=>$_SESSION['teacher_id']));
$fetch_teacher = $teacher_fetch->fetch(PDO::FETCH_ASSOC);
echo $fetch_teacher['Name'];
//close connection here
</code></pre>
<p><em>Or Somewhere else?</em></p>
<p>Also, how should I close it?</p>
<p><code>$user->close();</code> <strong><em>OR</em></strong> <code>$teacher_fetch->close();</code> <strong><em>OR</em></strong> <code>$fetch_teacher->close();</code> <strong><em>OR</em></strong> <em>Something else?</em></p>
| [] | [
{
"body": "<p>The fact that mysqli <em>has nothing to do</em> with PDO aside, there are several things about your code at whole:</p>\n\n<ul>\n<li>this \"class Database\" from some article is a dummy. It is absolutely useless and there is not a single reason to prefer it over original PDO. Let alone some flaws in the code inside.</li>\n<li>under no circumstances you should create a new database connection in the constructors of your classes. <em>A single existing instance should be passed as a constructor parameter instead.</em></li>\n<li>runQuery() function is misplaced, misnamed and useless. It just performs PDO::prepare() which you can always call directly. It makes whole User class a dummy as well, just a useless chunk of code.</li>\n<li>some <em>User-related</em> method should be written in this class instead</li>\n</ul>\n\n<p>Given all the above let's rewrite your code</p>\n\n<p><strong>database.config.php</strong> will be a code from my article <a href=\"https://phpdelusions.net/pdo_examples/connect_to_mysql\" rel=\"nofollow noreferrer\">How to connect to MySQL using PDO</a>:</p>\n\n<pre><code><?php\n$host = '127.0.0.1';\n$db = 'test';\n$user = 'root';\n$pass = '';\n$charset = 'utf8mb4';\n\n$options = [\n \\PDO::ATTR_ERRMODE => \\PDO::ERRMODE_EXCEPTION,\n \\PDO::ATTR_DEFAULT_FETCH_MODE => \\PDO::FETCH_ASSOC,\n \\PDO::ATTR_EMULATE_PREPARES => false,\n];\n$dsn = \"mysql:host=$host;dbname=$db;charset=$charset\";\ntry {\n $pdo = new PDO($dsn, $user, $pass, $options);\n} catch (\\PDOException $e) {\n throw new \\PDOException($e->getMessage(), (int)$e->getCode());\n}\n</code></pre>\n\n<p>here it will give you an instance of PDO class.</p>\n\n<p><strong>user.class.php</strong></p>\n\n<pre><code><?php\nclass User\n{ \n private $conn;\n\n public function __construct(PDO $pdo)\n {\n $this->conn = $pdo;\n }\n public function findTeacher($id)\n {\n $stmt = $this->conn->prepare(\"SELECT * FROM teacher WHERE id=?\");\n $stmt->execute([$id]);\n return $stmt->fetch();\n }\n}\n</code></pre>\n\n<p>here you have a findTeacher() method logically placed in the user class.</p>\n\n<p><strong>index.php</strong></p>\n\n<pre><code><?php\nrequire_once 'database.config.php';\nrequire_once 'user.class.php'; \n\n$user = new User($pdo);\n$teacher = $user->findTeacher($_SESSION['teacher_id']);\necho $teacher['Name'];\n</code></pre>\n\n<p>As you can see, this code is much more concise and logical, actually utilizing some basic OOP, as opposed to your current code which could be written (again more concisely) without any classes.</p>\n\n<p>As for your question, in the average PHP script you don't have to close neither the statement nor the connection. PHP will close it for you automatically. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T12:19:32.207",
"Id": "221192",
"ParentId": "221190",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T11:51:22.160",
"Id": "221190",
"Score": "3",
"Tags": [
"php",
"mysql",
"pdo"
],
"Title": "Proper use of mysqli->close();"
} | 221190 |
<p>I decided to implement a Hangman game using an object oriented State Pattern design. This is one of my first actual OOP as I normally write functional code.</p>
<p>Code use:</p>
<pre><code>if __name__ == '__main__':
game = Context('represents', lives=5) # hangman word is represents
game.startGame()
</code></pre>
<p>I'm mostly happy with this but wanted to check:</p>
<ul>
<li>is there a nicer way of having <code>DeadState / WonState</code> where I don't have to use <code>pass</code> for the <code>process</code></li>
<li>I've copied the style of docstrings from Flask Restless Github. Is this correct use of docstrings?</li>
<li>is there better way of combining user input and the <code>Context</code> class than the <code>.startGame()</code> method? I've seen it mentioned on Stack Overflow you shouldn't have input statements inside classes.</li>
</ul>
<pre><code>class Context(object):
"""A class that keeps track of the hangman game context and current state.
This follows a State Design Pattern.
`word` is string. This is the word to guess.
`guessed_letters` is a list containing letters guessed
`lives` is a number that is the number of incorrect guesses allowed.
`state` is class representing the state of the game.
`message` is a string message from processing the letter guess.
The :meth:`.process` method processes guessed letters, updating the
lives, guessed_letters and message for the gameplay.
"""
def __init__(self, word, lives=10):
self.word = word
self.guessed_letters = []
self.lives = lives
self.state = HoldingState()
self.message = ''
def won(self):
"""Tests if all letters of in word are in guessed_letters"""
return all(l in self.guessed_letters for l in self.word)
def lost(self):
"""Tests if we have run out of lives"""
return self.lives <= 0
def hangman_word(self):
"""Returns a string in hangman form where letters are hyphens
or guessed letters. Letters or hyphens are space separated.
`word` is a string. This is the word to be printed in hangman form.
`guessed_letters` is a list of the letters guessed that should be shown.
For example::
>>> hangman_word('bordereau', ['o', 'd', 'e'])
'_ o _ d e _ e _ _'
"""
return ' '.join(l if l in self.guessed_letters else '_' for l in self.word)
def process(self, letter):
"""Requests the state to process the guessed letter.
The State takes care of updating the lives, guessed_letters and providing a
message for the gameplay"""
self.state.process(letter, self)
def startGame(self):
"""Runs the game.
Checks for final states (WonState / DeadState) else shows the hangman
word, letters guessed and takes as input the letter guessed and
processes this.
"""
while True:
if self.state == WonState():
print(f'You win! The word was indeed {self.word}')
return
if self.state == DeadState():
print(f'You lose! The word was {self.word}')
return
print('Hangman Word:', self.hangman_word() + '\n')
print('Letters guessed: ' + ' '.join(sorted(self.guessed_letters)) + '\n')
letter = input('Guess a letter: ')
self.process(letter)
print('\n' + self.message + '\n')
class BaseState(object):
"""Represents a state of the context.
This is an abstract base class. Subclasses must override and
implement the :meth:`.process` method.
The :meth:`.process` method updates the context variables and changes the
context state.
"""
def process(self, letter, context):
"""Updates the context variables and changes the context state..
**This method is not implemented in this base class; subclasses
must override this method.**
"""
raise NotImplementedError
def __eq__(self, other):
"""Overrides the default implementation
Tests equality of states by testing if there are the same class
"""
if isinstance(other, self.__class__):
return True
return False
class HoldingState(BaseState):
"""The default state."""
def process(self, letter, context):
if letter in context.guessed_letters:
context.state = RepeatedGuessState()
elif letter in context.word:
context.state = CorrectGuessState()
else:
context.state = IncorrectGuessState()
# Calls process again to return to HoldingState / WonState / DeadState
context.state.process(letter, context)
class RepeatedGuessState(BaseState):
"""An intermediate state."""
def process(self, letter, context):
context.message = "You've repeated a guess!"
context.state = HoldingState()
class CorrectGuessState(BaseState):
"""An intermediate state."""
def process(self, letter, context):
context.message = "Correct guess!"
context.guessed_letters.append(letter)
if context.won():
context.state = WonState()
else:
context.state = HoldingState()
class IncorrectGuessState(BaseState):
"""An intermediate state."""
def process(self, letter, context):
context.lives -= 1
context.message = f"Incorrect guess! You've lost a life. {context.lives} lives remaining"
context.guessed_letters.append(letter)
if context.lost():
context.state = DeadState()
else:
context.state = HoldingState()
class DeadState(BaseState):
"""A final state representing a lost game."""
def process(self, letter, context):
pass
class WonState(BaseState):
"""A final state representing a game won."""
def process(self, letter, context):
pass
if __name__ == '__main__':
game = Context('represents')
game.startGame()
</code></pre>
| [] | [
{
"body": "<p>Neither <code>BaseState</code> nor any of its derived classes contain any data. You don’t need to keep creating instances of these state objects. You could create one of each as global constants. Then, you wouldn’t need the special <code>__eq__</code> method, since you could simply test identity equality.</p>\n\n<p>You could make <code>BaseState</code> and its derived classes callable objects, by defining a <code>__call__(self, letter, context)</code> method, instead of a <code>process(self, letter, context)</code> method. You could then invoke the state processing by calling <code>self.state(letter, self)</code>.</p>\n\n<p>Of course, an class with no data and only a single function is effectively just a function, and functions are first class objects in Python, so you can ditch the classes all together, and store the function as the “state”. Eg)</p>\n\n<pre><code>def repeated_guess_state(letter, context):\n \"\"\"An intermediate state\"\"\"\n context.message = \"You’ve repeated a guess!\"\n context.state = holding_state\n</code></pre>\n\n<p>But wait! Why are these outside of the <code>Context</code> class? We have to pass <code>context</code> to each state handler. If these were methods defined on the <code>Context</code> class, they’d automatically get <code>self</code>, which is the context, passed to them effectively for free:</p>\n\n<pre><code>class Context:\n\n # ... __init__, won, lost, hangman_word methods omitted\n\n def process(self, letter):\n self.state(letter)\n\n def repeated_guess_state(self, letter):\n \"\"\"An intermediate state\"\"\"\n self.message = \"You’ve repeated a guess!\"\n self.state = self.holding_state\n</code></pre>\n\n<p>Now these state processors (methods) actually part of the <code>Context</code> class, so that don’t have to reach into another class and manipulate the private internals. They have legitimate access to the internal details. So these data members should be declared private ... which in Python is little more than the convention of a leading underscore (eg, <code>self._lives</code>, <code>self._state</code>, and so on).</p>\n\n<hr>\n\n<blockquote>\n <p>is there a nicer way of having <code>DeadState</code> / <code>WonState</code> where I don't have to use <code>pass</code> for the <code>process</code></p>\n</blockquote>\n\n<p>Nothing wrong with using pass. You have a function the does nothing.</p>\n\n<p>You could make the states actually print the win/loss messages, and then transition to a “finished” state. The finished state would likely have the <code>pass</code> statement, though. Alternately, you could use <code>None</code> as the finish state, and loop <code>while self.state:</code> instead of <code>while True:</code></p>\n\n<blockquote>\n <p>I've copied the style of docstrings from Flask Restless Github. Is this correct use of docstrings?</p>\n</blockquote>\n\n<p>The exact format of the docstrings is dependant on the tool you use to automatically generate documentation with. Codes like:</p>\n\n<pre><code>:meth:`.process`\n</code></pre>\n\n<p>are used by <a href=\"http://sphinx-doc.org\" rel=\"nofollow noreferrer\">“Sphinx”</a> documentation generator. See it for details.</p>\n\n<blockquote>\n <p>is there better way of combining user input and the Context class than the .startGame() method? I've seen it mentioned on Stack Overflow you shouldn't have input statements inside classes.</p>\n</blockquote>\n\n<p>There is nothing wrong with asking for input inside of a class. But ...</p>\n\n<p>Separating I/O from game logic allows you to ...</p>\n\n<ul>\n<li>create a text-based console game,</li>\n<li>create a Graphical UI based game, using the same game logic</li>\n<li>test the game code using automated test software</li>\n</ul>\n\n<p>In the first case, the input comes from <code>input()</code> and goes to <code>print()</code> statements, in the second it comes from & goes to (say) TkInter, and the third it comes from and goes to test code.</p>\n\n<p>You’ve mostly separated the I/O already. Wherever the input comes from, you need to pass it to <code>self.process(...)</code>, and the output (mostly) goes to <code>self.message</code>. You just need to factor out the console I/O, and maybe places that into <code>class ConsoleHangman(Context):</code>.</p>\n\n<p><code>class TkInterHangman(Context):</code> left as exercise to student.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T05:01:21.630",
"Id": "221237",
"ParentId": "221191",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221237",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T12:16:23.660",
"Id": "221191",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"game",
"hangman",
"state-machine"
],
"Title": "Implementing Hangman using a State Pattern"
} | 221191 |
<p>I have two questions for you about my code :) </p>
<p>I'm creating an android to connect to ble device. I'm using ble-plx library. </p>
<pre><code>import React, {Component} from 'react';
import { Platform, View, Text } from 'react-native';
import { BleManager } from 'react-native-ble-plx';
export default class Main extends Component {
constructor() {
super();
this.manager = new BleManager()
this.state = {info: "", values: {}}
this.deviceprefix = "Device";
this.devicesuffix_dx = "DX";
this.sensors = {
"0000f0fd-0001-0008-0000-0805f9b34fb0" : "Acc+Gyr+Mg",
"0000f0f4-0000-1000-8000-00805f9b34fb" : "Pressure"
}
}
serviceUUID() {
return "0000f0f0-0000-1000-8000-00805f9b34fb"
}
notifyUUID(num) {
return num
}
model_dx (model) {
return this.deviceprefix + model + this.devicesuffix_dx
}
info(message) {
this.setState({info: message})
}
error(message) {
this.setState({info: "ERROR: " + message})
}
updateValue(key, value) {
this.setState({values: {...this.state.values, [key]: value}})
}
componentWillMount(){
const subscription = this.manager.onStateChange((state) => {
if (state === 'PoweredOn') {
this.scanAndConnect();
subscription.remove();
}
}, true);
}
async requestPermission() {
try {
const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.setState({permissionStatus:'granted'});
}else if(granted === PermissionsAndroid.RESULTS.DENIED) {
this.setState({permissionStatus:'denied'});
}else{
}
} catch (err) {
console.error(err)
}
}
scanAndConnect(){
this.manager.startDeviceScan(null, null, (error, device) => {
if (error) {
return
}
let model = '0030';
if (device.name == this.model_dx(model) ) {
this.manager.stopDeviceScan();
device.connect()
.then((device) => {
this.info("Discovering services and characteristics ")
return device.discoverAllServicesAndCharacteristics()
})
.then((device) => {
this.info("SetupNotification")
return this.setupNotifications(device)
})
.catch((error) => {
this.error(error.message)
});
}
});
}
async setupNotifications(device) {
for (const id in this.sensors) {
const service = this.serviceUUID(id)
const characteristicN = this.notifyUUID(id)
device.monitorCharacteristicForService(service, characteristicN, (error, characteristic) => {
if (error) {
this.error(error.message)
return
}
this.updateValue(characteristic.uuid, characteristic.value)
})
}
}
render() {
return (
<View>
<Text>{this.state.info}</Text>
{Object.keys(this.sensors).map((key) => {
return <Text key={key}>
{this.sensors[key] + ": " + (this.state.values[this.notifyUUID(key)] || "-")}
</Text>
})}
</View>
)
}
}
</code></pre>
<p>I have two question for you:</p>
<p>1) The monitoring give me values like:</p>
<ul>
<li>For example in the case of "Pressure" the value: "ZABIAGYAZwBoAA=="
I should receive a number not string, how it is possible? </li>
</ul>
<p>2)
I print the values using:</p>
<pre><code><Text>{this.state.info}</Text>
{Object.keys(this.sensors).map((key) => {
return <Text key={key}>
{this.sensors[key] + ": " + (this.state.values[this.notifyUUID(key)] || "-")}
</Text>
</code></pre>
<p>But If I wanted to access the "pressure" value directly, how could I do it? To be clear if I wanted to, for example, passing the value that remembers me pressure on another page?
Thank you all for the support!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T13:33:35.560",
"Id": "427618",
"Score": "0",
"body": "Welcome to Code Review! Since your code does not yet [accomplish what you intend to do](https://codereview.stackexchange.com/help/on-topic) with it, it is [not ready to be reviewed](https://codereview.stackexchange.com/help/dont-ask). Please fix the remaining issues first, then come back to ask for possible improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T13:41:49.320",
"Id": "427619",
"Score": "0",
"body": "@AlexV I think that I have write all :)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T12:46:52.313",
"Id": "221194",
"Score": "1",
"Tags": [
"javascript",
"android",
"react-native"
],
"Title": "Monitoring Services And Characteristics on React-Native"
} | 221194 |
<p>I have created a custom class (Generic) in C# for the <a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi" rel="nofollow noreferrer">Hanoi problem</a>. and I am not sure I did the correct thing.</p>
<pre><code>[DebuggerDisplay("Count = {Count}")]
[System.Runtime.InteropServices.ComVisible(false)]
public class HanoiStack<T> : IEnumerable<T>, ICollection, IEnumerable where T : IHanoiStack
{
private T[] _array; // Storage for stack elements
private int _size; // Number of items in the stack.
private int _version; // Used to keep enumerator in sync w/ collection.
private Object _syncRoot;
private const int _defaultCapacity = 4;
static T[] _emptyArray = new T[0];
public HanoiStack()
{
_array = _emptyArray;
_size = 0;
_version = 0;
}
public HanoiStack(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException("Negative Value Exception");
_array = new T[capacity];
_size = 0;
_version = 0;
}
public HanoiStack(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentException("Null Collection");
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{
int count = c.Count;
_array = new T[count];
c.CopyTo(_array, 0);
_size = count;
}
else
{
_size = 0;
_array = new T[_defaultCapacity];
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Push(en.Current);
}
}
}
}
public int Count
{
get { return _size; }
}
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
Object System.Collections.ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
public void Clear()
{
Array.Clear(_array, 0, _size);
_size = 0;
_version++;
}
public bool Contains(T item)
{
int count = _size;
EqualityComparer<T> c = EqualityComparer<T>.Default;
while (count-- > 0)
{
if (((Object)item) == null)
{
if (((Object)_array[count]) == null)
return true;
}
else if (_array[count] != null && c.Equals(_array[count], item))
{
return true;
}
}
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException("Null Array");
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException("Negative Argument Exception");
}
if (array.Length - arrayIndex < _size)
{
throw new ArgumentException("Invalid Argument");
}
Array.Copy(_array, 0, array, arrayIndex, _size);
Array.Reverse(array, arrayIndex, _size);
}
void System.Collections.ICollection.CopyTo(Array array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException("Array Null Exception");
}
if (array.Rank != 1)
{
throw new ArgumentException("Rank Multiple Supported");
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException("Negative Value Exception");
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException("Negative Value Exception");
}
if (array.Length - arrayIndex < _size)
{
throw new ArgumentException("Invalid Argument");
}
try
{
Array.Copy(_array, 0, array, arrayIndex, _size);
Array.Reverse(array, arrayIndex, _size);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException("Argument Invalid Exception");
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
public void TrimExcess()
{
int threshold = (int)(((double)_array.Length) * 0.9);
if (_size < threshold)
{
T[] newarray = new T[_size];
Array.Copy(_array, 0, newarray, 0, _size);
_array = newarray;
_version++;
}
}
public T Peek()
{
if (_size == 0)
throw new Exception("Stack Hanoi is Empty");
return _array[_size - 1];
}
public T Pop()
{
if (_size == 0)
throw new InvalidOperationException("Stack Hanoi is Empty");
_version++;
T item = _array[--_size];
_array[_size] = default(T); // Free memory quicker.
return item;
}
public void Push(T item)
{
if (_size > 0)
{
var _newItem = (IHanoiStack)item;
var _currentItem = (IHanoiStack)this.Peek();
if (_currentItem.Height > _newItem.Height)
{
throw new InvalidOperationException("Height of the previous item is lesser than the new item.");
}
if (_currentItem.Weigth > _newItem.Weigth)
{
throw new InvalidOperationException("Weigth of the previous item is lesser than the new item.");
}
}
if (_size == _array.Length)
{
T[] newArray = new T[(_array.Length == 0) ? _defaultCapacity : 2 * _array.Length];
Array.Copy(_array, 0, newArray, 0, _size);
_array = newArray;
}
_array[_size++] = item;
_version++;
}
public T[] ToArray()
{
T[] objArray = new T[_size];
int i = 0;
while (i < _size)
{
objArray[i] = _array[_size - i - 1];
i++;
}
return objArray;
}
public struct Enumerator : IEnumerator<T>,
System.Collections.IEnumerator
{
private HanoiStack<T> _stack;
private int _index;
private int _version;
private T currentElement;
internal Enumerator(HanoiStack<T> stack)
{
_stack = stack;
_version = _stack._version;
_index = -2;
currentElement = default(T);
}
public void Dispose()
{
_index = -1;
}
public bool MoveNext()
{
bool retval;
if (_version != _stack._version) throw new InvalidOperationException("Stack Hanoi is Empty");
if (_index == -2)
{ // First call to enumerator.
_index = _stack._size - 1;
retval = (_index >= 0);
if (retval)
currentElement = _stack._array[_index];
return retval;
}
if (_index == -1)
{ // End of enumeration.
return false;
}
retval = (--_index >= 0);
if (retval)
currentElement = _stack._array[_index];
else
currentElement = default(T);
return retval;
}
public T Current
{
get
{
if (_index == -2) throw new InvalidOperationException("EnumNotStarted");
if (_index == -1) throw new InvalidOperationException("EnumEnded");
return currentElement;
}
}
Object System.Collections.IEnumerator.Current
{
get
{
if (_index == -2) throw new InvalidOperationException("EnumNotStarted");
if (_index == -1) throw new InvalidOperationException("EnumEnded");
return currentElement;
}
}
void System.Collections.IEnumerator.Reset()
{
if (_version != _stack._version) throw new InvalidOperationException("EnumFailedVersion");
_index = -2;
currentElement = default(T);
}
}
}
public interface IHanoiStack
{
double Height { get; }
double Weigth { get; }
}
</code></pre>
<p>I am trying to use a Generic class for the Hanoi problem. it might be simple for some of you. but I have created this in learning the C# Generics. Please help me to validate the code. </p>
<ol>
<li><p>The Hanoi problem.
This will have a stack of disks of size (n) on a pole and it should be shifted to another among the 3 poles available. But the disks should be in the same order as they were on the previous pole. (Correct?)</p></li>
<li><p>I kind of thought that the "STACK" would help me but it will allow the user to add items in any order. So I created an interface that has Width and Height of the Disk so that I could validate the order based on that Interface.</p></li>
<li><p>I have a question here, is this the correct way to do this or I was wrong.</p></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:06:44.360",
"Id": "427631",
"Score": "3",
"body": "Am I incorrect to assume that this is a slightly modified version of the .NET BCL class `System.Collections.Generic.Stack<T>`? I don't believe we should provide a review for this code, because you are not in a position to justify the design decisions that lead to most all of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:09:23.127",
"Id": "427635",
"Score": "0",
"body": "@VisualMelon To me it looked like a java version trying to be ported to C#."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:11:21.443",
"Id": "427638",
"Score": "1",
"body": "@dfhwze see [the reference source](https://referencesource.microsoft.com/#System/compmod/system/collections/generic/stack.cs). It's essentially the same. (Which the OP has just confirmed)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:12:21.350",
"Id": "427639",
"Score": "2",
"body": "@VisualMelon wow, that's a lame thing to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:23:36.097",
"Id": "427642",
"Score": "0",
"body": "@VisualMelon , as I mentioned below I am just trying to learn Generics in C#. I browsed the Microsoft reference source and find the link I have specified. and wrote the logic on top of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:29:48.037",
"Id": "427646",
"Score": "0",
"body": "The whole point of generics is that you don't need to create type-specific copies of the same logic. If you need a stack that can only store `IHanoiStack` objects, then `var hanoiStack = new Stack<IHanoiStack>()` is all you need to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:35:30.453",
"Id": "427649",
"Score": "4",
"body": "@NavinKumarKSubramanian it's fine to do whatever you want to aid your learning; however, not everything should be posted on CodeReview. You might want to visit the [help centre](https://codereview.stackexchange.com/help/on-topic) to see how best to use the site."
}
] | [
{
"body": "<p>I would have created a simpler version. I have removed my review of the code not written by you.</p>\n<pre><code> public class HanoiStack<T> : Stack<T> where T : IHanoiElement\n {\n public new void Push(T item)\n {\n // null checks ..\n if (Count != 0)\n {\n var top = this.Peek();\n if (item.Height > top.Height || item.Weigth > top.Weigth)\n {\n throw new InvalidOperationException("The item is too big");\n }\n }\n base.Push(item);\n }\n }\n\n public interface IHanoiElement\n {\n double Height { get; }\n double Weigth { get; }\n }\n</code></pre>\n<hr />\n<h2>Naming Conventions</h2>\n<p>I would not call the element type <code>IHanoiStack</code> a stack, rather an element <code>IHanoiElement</code>.</p>\n<blockquote>\n<pre><code> public interface IHanoiStack\n {\n double Height { get; }\n double Weigth { get; }\n }\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:09:25.060",
"Id": "427636",
"Score": "0",
"body": "I tried it but since I was learning C# Generics. I just went through in this website so I replicated the same in my code. https://referencesource.microsoft.com/#System/compmod/system/collections/generic/stack.cs,c5371bef044c6ab6"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:03:51.777",
"Id": "221197",
"ParentId": "221195",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221197",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T12:48:52.220",
"Id": "221195",
"Score": "-4",
"Tags": [
"c#",
".net",
"generics",
"stack",
"queue"
],
"Title": "Generic Custom STACK Class for Hanoi Problem in C#"
} | 221195 |
<p>I am using this code which works fine, but runs painfully slow. </p>
<p>The code filters an Excel Table and then extracts only certain columns and pastes them into another sheet (in a different order).</p>
<p>Could it be sped up perhaps with a multi-dimensional array?</p>
<pre class="lang-vb prettyprint-override"><code>With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
.DisplayAlerts = False
.EnableEvents = False
End With
Set lo_b1 = x_bf1.ListObjects(1)
s_date = CLng(ThisWorkbook.Names("in_fre_m").RefersToRange(1, 1))
s_des = ThisWorkbook.Names("dr_no").RefersToRange(1, 1)
s_code = ThisWorkbook.Names("dr_co").RefersToRange(1, 1)
lastrow_d = lo_dr.Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
Set pasterange1 = x_drill.Range("C" & lastrow_d)
With lo_b1.Range
.AutoFilter Field:=13, Criteria1:=s_code
.AutoFilter Field:=1, Criteria1:="<=" & s_date
End With
lastrow_s = lo_b1.Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
If lastrow_s > 7 Then
Set copyrange1 = x_bf1.Range("D8:D" & lastrow_s) 'Date
Set copyrange2 = copyrange1.Offset(0, 1) 'Description
Set copyrange3 = copyrange1.Offset(0, 16) 'Calculation
Set copyrange5 = copyrange1.Offset(0, 5) 'Classification
Set copyrange6 = copyrange1.Offset(0, 6) 'Notes
Set copyrange7 = copyrange1.Offset(0, 11) '§
Set copyrange8 = copyrange1.Offset(0, 12) 'Code
Set copyrange9 = copyrange1.Offset(0, 20) 'Statutory
Set copyrange10 = copyrange1.Offset(0, 14) 'Ref
copyrange10.SpecialCells(xlCellTypeVisible).Copy 'Ref
pasterange1.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone
copyrange1.SpecialCells(xlCellTypeVisible).Copy 'Date
pasterange1.Offset(0, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone
copyrange5.SpecialCells(xlCellTypeVisible).Copy 'Account Name
pasterange1.Offset(0, 2).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone
copyrange2.SpecialCells(xlCellTypeVisible).Copy 'Notes
pasterange1.Offset(0, 3).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone
copyrange8.SpecialCells(xlCellTypeVisible).Copy 'Code
pasterange1.Offset(0, 4).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone
copyrange7.SpecialCells(xlCellTypeVisible).Copy '§
pasterange1.Offset(0, 5).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone
copyrange3.SpecialCells(xlCellTypeVisible).Copy 'Calculation
pasterange1.Offset(0, 6).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone
copyrange9.SpecialCells(xlCellTypeVisible).Copy 'Statutory
pasterange1.Offset(0, 7).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone
copyrange6.SpecialCells(xlCellTypeVisible).Copy 'Notes
pasterange1.Offset(0, 8).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone
Set copyrange1 = Nothing
Set copyrange2 = Nothing
Set copyrange3 = Nothing
Set copyrange4 = Nothing
Set copyrange5 = Nothing
Set copyrange6 = Nothing
Set copyrange7 = Nothing
Set copyrange8 = Nothing
Set copyrange9 = Nothing
Set copyrange10 = Nothing
End If
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T19:34:29.087",
"Id": "427713",
"Score": "0",
"body": "I don't see why it should be slow? How much time it takes to run? Can you measure which part takes long? (maybe you could write current time to another worksheet after each filter and paste)"
}
] | [
{
"body": "<p>Turn on Option Explicit from the menu via Tools>Options>Editor tab>Require Variable Declaration. This mandates you <code>Dim lastRow as long</code> before using it anywhere. Doing this will save you needless frustration later down the line when you transpose a variable name <code>raom</code> instead of <code>roam</code> and time's wasted till you find it.</p>\n\n<p>If you have two Ranges that are same size and you want to copy the values over you can do <code>Foo.Value2 = Bar.Value2</code> to achieve this without any copying. If you have a Range that is the same size as an array you get the same with <code>Foo.Value2</code> = inMemoryArray`.</p>\n\n<p>Use descriptive variable names. <code>x_bf1</code> doesn't have any meaning, at least to me. If future-you comes back to this code and doesn't know what it means you'll be wishing past-you had used a descriptive name. An example of this being useful is the comments <code>'Date</code> in two locations. Renaming <code>copyrange1</code> to <code>dateArea</code> will cause these comments to become redundant and removable as your code is self documenting already describing <em>what</em> it is doing, save comments for <em>why</em>.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Set copyrange1 = x_bf1.Range(\"D8:D\" & lastrow_s) 'Date\n...\ncopyrange1.SpecialCells(xlCellTypeVisible).Copy 'Date\npasterange1.Offset(0, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone\n</code></pre>\n\n<p>becomes</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>destinationArea.Offset(0, 1).Value2 = dateArea.Value2\n</code></pre>\n\n<p>Tied to naming is the use of <code>_</code> underscore. If you end up using interfaces be aware that this is how interface implementation is done. Double click on your first worksheet then at the dropdowns at the top select <code>Worksheet</code> from the left dropdown, and <code>SelectionChange</code> from the right dropdown. You get <code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)</code> which is an example of the underscore used this way.</p>\n\n<p>You turn off <code>ScreetUpdating</code> and the rest, but it's never turned back on in your provided code. Make sure that is restored.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>With Application\n .ScreenUpdating = False\n .Calculation = xlCalculationManual\n .DisplayAlerts = False\n .EnableEvents = False\nEnd With\n</code></pre>\n\n<p>You're using a named range from a workbook. Every usage of them includes <code>RefersToRange(1, 1)</code>. If your names are single cell Ranges this is redundant.</p>\n\n<hr>\n\n<p>Refactored Code.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Sub Refactor()\n Dim x_bf1 As Worksheet\n Dim lo_b1 As ListObject\n Set lo_b1 = x_bf1.ListObjects(1)\n Dim s_date As Long\n s_date = CLng(ThisWorkbook.Names(\"in_fre_m\").RefersToRange(1, 1))\n Dim s_des As Range\n s_des = ThisWorkbook.Names(\"dr_no\").RefersToRange(1, 1)\n Dim s_code As Range\n s_code = ThisWorkbook.Names(\"dr_co\").RefersToRange(1, 1)\n Dim lastrow_d As Long\n Dim lo_dr As ListObject\n lastrow_d = lo_dr.Range.Columns(1).Cells.Find(\"*\", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1\n\n With lo_b1.Range\n .AutoFilter Field:=13, Criteria1:=s_code\n .AutoFilter Field:=1, Criteria1:=\"<=\" & s_date\n End With\n\n Dim lastrow_s As Long\n lastrow_s = lo_b1.Range.Columns(1).Cells.Find(\"*\", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row\n\n If lastrow_s > 7 Then\n Dim dateArea As Range\n Set dateArea = x_bf1.Range(\"D8:D\" & lastrow_s)\n Dim description As Range\n Set description = dateArea.Offset(0, 1)\n Dim calculationArea As Range\n Set calculationArea = dateArea.Offset(0, 16)\n Dim classification As Range\n Set classification = dateArea.Offset(0, 5)\n Dim notes As Range\n Set notes = dateArea.Offset(0, 6)\n Dim parragraph As Range\n Set parragraph = dateArea.Offset(0, 11)\n Dim code As Range\n Set code = dateArea.Offset(0, 12)\n Dim statutory As Range\n Set statutory = dateArea.Offset(0, 20)\n Dim reference As Range\n Set reference = dateArea.Offset(0, 14)\n\n Dim x_drill As Worksheet\n Dim destinationArea As Range\n Set destinationArea = x_drill.Range(\"C\" & lastrow_d).Resize(dateArea.Rows.Count, 9)\n\n Dim singlePopulationHelper() As String\n singlePopulationHelper = LoadHelperArraywWithValues(reference, _\n dateArea, _\n classification, _\n description, _\n code, _\n parragraph, _\n calculationArea, _\n statutory, _\n notes)\n destinationArea.Value2 = singlePopulationHelper\n End If\nEnd Sub\n\nPrivate Function LoadHelperArraywWithValues(ParamArray values()) As String()\n Dim rowCount As Long\n rowCount = values(0).SpecialCells(xlCellTypeVisible).Cells.Count\n Dim columnCount As Long\n columnCount = UBound(values)\n Dim helperArray() As String\n ReDim helperArray(rowCount, columnCount)\n\n Dim populationColumn As Long\n For populationColumn = 0 To columnCount\n Dim workingColumn As Range\n Set workingColumn = values(populationColumn)\n Dim populationRow As Long\n populationRow = 0\n Dim subArea As Range\n For Each subArea In workingColumn.SpecialCells(xlCellTypeVisible).Areas\n Dim cell As Range\n For Each cell In subArea\n helperArray(populationRow, populationColumn) = cell.Value2\n populationRow = populationRow + 1\n Next\n Next\n Next\n LoadHelperArraywWithValues = helperArray\nEnd Function\n</code></pre>\n\n<p>Alternate copying to temporary worksheet.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Function CopyToTempSheetBeforeLoading(ParamArray values()) As Variant\n Dim populatedColumns As Long\n\n Dim tempSheet As Worksheet\n Set tempSheet = ThisWorkbook.Worksheets.Add\n\n For populatedColumns = 0 To UBound(values)\n values(populatedColumns).SpecialCells(xlCellTypeVisible).Copy\n tempSheet.Range(\"B2\").Offset(ColumnOffset:=populatedColumns).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone\n Next\n CopyToTempSheetBeforeLoading = tempSheet.Range(\"B2\").CurrentRegion\n tempSheet.Delete\nEnd Function\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T19:01:34.883",
"Id": "427712",
"Score": "0",
"body": "IvenBach thank you for all your comments, this is very helpful for me. However, I am a bit worried about the helper function as it iterates through rows, and I have thousands of rows.. One other solution I heard was to copy visible cells of filtered table to a temp sheet and then assign that range to an array. In that way, you avoid iterations. Do you still think your code will run faster than that solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T21:06:15.203",
"Id": "427720",
"Score": "0",
"body": "I dropped the ball and gave an incorrect solution. I've edited my answer to only copy the visible cells into `helperArray`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T21:39:06.680",
"Id": "427725",
"Score": "0",
"body": "Gave you an alternate `CopyToTempSheetBeforeLoading` function. If you want to know which one is faster you can benchmark/test them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T09:29:11.763",
"Id": "427764",
"Score": "0",
"body": "I haven't tested this extensively with the reworked function, but from what I have been reading in other forums, when it comes to autofiltering and copying data to an array, the best solution should be to use a temp sheet/location (as this solves the problem of cycling areas). But I will take everything mentioned onboard hence why I am accepting this answer, for everyone else to find useful."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T18:01:28.020",
"Id": "221209",
"ParentId": "221196",
"Score": "3"
}
},
{
"body": "<p>Answering my own question, this might even run quicker than accepted solution:</p>\n\n<pre><code>If lastrow_s > 7 Then\n\nSet copyrng = lo_b1.AutoFilter.Range.SpecialCells(xlCellTypeVisible)\ncopyrng.Copy Destination:=strng\narr = strng.CurrentRegion.Offset(1, 0)\naRws = Evaluate(\"Row(1:\" & UBound(arr) & \")\")\narr = Application.Index(arr, aRws, Array(14, 1, 6, 2, 13, 12, 18, 16, 7))\n\nWith strng.CurrentRegion\n.ClearContents\n.Interior.Color = xlNone\n.Borders.LineStyle = xlNone\nEnd With\n\npasterange1.Resize(UBound(arr, 1), UBound(arr, 2)).Value = arr\n\nSet copyrng = Nothing\nErase arr\nErase aRws\nlo_b1.AutoFilter.ShowAllData\nEnd If\n</code></pre>\n\n<p>What this does:</p>\n\n<ol>\n<li>copies the auto-filtered range to a temp location</li>\n<li>an array is created from the temp data</li>\n<li>the array is evaluated and only columns of interest are maintained in preferred order</li>\n<li>the array is pasted in desired location</li>\n</ol>\n\n<p>The only problem I am having is that dates are pasted as text, and cannot be filtered as dates in new location. If you have any ideas on how to fix that without looping please let me know.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:05:38.360",
"Id": "221264",
"ParentId": "221196",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221209",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T13:54:10.630",
"Id": "221196",
"Score": "3",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Speed Up Excel Macro - Autofilter Copying"
} | 221196 |
<p>I was given the task to write a code that takes inputs from the user that include the following:</p>
<ul>
<li>length of a certain race</li>
<li>the speed of Achilles (the main participant)</li>
<li>the number of participants excluding Achilles</li>
<li>the head start that each participant will get (a head start from Achilles)</li>
<li>speed of each participant</li>
</ul>
<p>I then was asked to calculate the time that takes Achilles and each participant to finish the race and then the output would be:</p>
<ol>
<li>the time that took Achilles to finish the race</li>
<li>the ones that took a shorter time than Achilles to finish the race</li>
<li>the ones that finished the race after Achilles
(3 & 2 in the same line and the order is the same order of the input. one space between each number excluding the last)</li>
<li>When Achilles finished the race</li>
</ol>
<h2>Example:</h2>
<p>input:</p>
<pre><code>100
9.5
5
20 7.5 90 1.2 10.6 4.25 80 1.7 50 7.3
</code></pre>
<p>output:</p>
<pre><code>10.53
8.33 6.85 10.67 21.04 11.76
3
</code></pre>
<p>I wrote the code and it works fine, although I can't eliminate the last space from the scond line of the output. (in the example above, the line ends <code>11.76 </code>)</p>
<h2>The code:</h2>
<pre><code>#include <stdio.h>
int main()
{
int length,size,cnt1=0,i;
float speed1,speed2[7],distance[7],time1,time2[7],small[7],big[7];
scanf("%d",&length);
scanf("%f",&speed1);
scanf("%d",&size);
time1=(float)length/speed1;
for(i=0;i<size;i++){
scanf("%f%f",&distance[i],&speed2[i]);
}
for(i=0;i<size;i++){
time2[i]=((length-distance[i])/speed2[i]);
}
if(distance[i]>=length)
time2[i]=0;
printf("%.2f",time1);
printf("\n");
for(i=0;i<size;i++){
if(time2[i]<time1){
small[i]=time2[i];
printf("%.2f ",small[i]);
cnt1++;
}
}
for(i=0;i<size;i++){
if(time2[i]>=time1){
big[i]=time2[i];
printf("%.2f",big[i]);
if(i+1<size)
printf(" ");
}
}
printf("\n");
printf("%d",cnt1+1);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T15:54:15.617",
"Id": "427659",
"Score": "3",
"body": "\"now I wrote the code and it works fine but I can't succeed to eliminate the last space from the third line of the output.\" So it doesn't work completely yet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:36:19.213",
"Id": "427776",
"Score": "0",
"body": "it does work. however, the design of the output is not perfect(or as specified)"
}
] | [
{
"body": "<p>The indentation seems to have lost a level for much of the code, which makes it hard to read. I'm guessing something went wrong when you copied the code into the question, and that your source doesn't really look that bad.</p>\n<p>Let's start with the definition of <code>main()</code>. It's generally better to declare <code>main</code> as a function taking no arguments: <code>int main(void)</code>.</p>\n<p>Consider that all I/O may fail. For this program, it's probably acceptable to ignore output errors, but we really must handle input errors correctly, even if it's as simple as</p>\n<pre><code>if (scanf("%d", &length) != 1) {\n fprintf(stderr, "%s:%u: input failed\\n", __FILE__, __LINE__);\n return 1;\n}\n</code></pre>\n<p>We can save some repetition by combining reads:</p>\n<pre><code>if (scanf("%d%f%d", &length, &speed1, &size) != 3) {\n fprintf(stderr, "%s:%u: input failed\\n", __FILE__, __LINE__);\n return 1;\n}\n</code></pre>\n<p>Now we come to reading the other participants' speeds and head starts. The code currently assumes that there are no more than 7 participants, and relies on fixed size arrays to store them. But look at the requirements: we get to print them in the same order that we read them, and we don't need to store any of these values after we've printed them, so we can make a much simpler loop:</p>\n<pre><code>#include <stdio.h>\n\nint main(void)\n{\n double length;\n double achilles_speed;\n unsigned int competitor_count;\n\n if (scanf("%lf%lf%u", &length, &achilles_speed, &competitor_count) != 3) {\n fprintf(stderr, "%s:%u: input failed\\n", __FILE__, __LINE__);\n return 1;\n }\n\n const double achilles_time = length / achilles_speed;\n printf("%.2f\\n", achilles_time);\n\n unsigned int achilles_position = 1; /* start at 1, and increment for each faster competitor */\n\n for (unsigned int i = 0; i < competitor_count; ++i) {\n double head_start, speed;\n if (scanf("%lf%lf", &head_start, &speed) != 2) {\n fprintf(stderr, "%s:%u: input failed\\n", __FILE__, __LINE__);\n return 1;\n }\n\n double time = (length - head_start) / speed;\n printf("%.2f ", time);\n\n if (time < achilles_time) {\n ++achilles_position;\n }\n }\n\n printf("\\n%u", achilles_position);\n\n return 0;\n}\n</code></pre>\n<p>That's starting to look a bit simpler, but I've lost the logic that omits the space after the last finisher's time. One way to change this is to print a character <em>before</em> the time, and change that after the first output:</p>\n<pre><code>printf("%.2f", achilles_time);\n\nchar sep = '\\n';\n\nfor (unsigned int i = 0; i < competitor_count; ++i) {\n ...\n printf("%c%.2f", sep, time);\n sep = ' ';\n ...\n}\n</code></pre>\n<p>Here, we start by printing the newline that ends Achilles' time line on the first iteration, but change that to a space for the subsequent iterations.</p>\n<hr />\n<h1>Complete modified code</h1>\n<pre><code>#include <stdio.h>\n\nint main(void)\n{\n double length;\n double achilles_speed;\n unsigned int competitor_count;\n\n if (scanf("%lf%lf%u", &length, &achilles_speed, &competitor_count) != 3) {\n fprintf(stderr, "%s:%u: input failed\\n", __FILE__, __LINE__);\n return 1;\n }\n\n const double achilles_time = length / achilles_speed;\n printf("%.2f", achilles_time);\n\n unsigned int achilles_position = 1;\n char sep = '\\n';\n\n for (unsigned int i = 0; i < competitor_count; ++i) {\n double head_start, speed;\n if (scanf("%lf%lf", &head_start, &speed) != 2) {\n fprintf(stderr, "%s:%u: input failed\\n", __FILE__, __LINE__);\n return 1;\n }\n\n const double time = (length - head_start) / speed;\n printf("%c%.2f", sep, time);\n sep = ' ';\n\n achilles_position += time < achilles_time;\n }\n\n printf("\\n%u", achilles_position);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T17:07:45.923",
"Id": "221207",
"ParentId": "221199",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221207",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T14:48:04.627",
"Id": "221199",
"Score": "-2",
"Tags": [
"c",
"array"
],
"Title": "Compute the results of a race against Achilles"
} | 221199 |
<p>This is a <a href="https://leetcode.com/problems/split-array-largest-sum/" rel="nofollow noreferrer">Leetcode problem</a> -</p>
<blockquote>
<p><em>Given an array which consists of non-negative integers and an integer
<code>m</code>, you can split the array into <code>m</code> non-empty continuous subarrays.
Write an algorithm to minimize the largest sum among these <code>m</code>
subarrays.</em></p>
<p><strong><em>Note -</em></strong></p>
<p><em>If <code>n</code> is the length of the array, assume the following constraints
are satisfied:</em></p>
<ul>
<li><em>1 ≤ <code>n</code> ≤ 1000</em></li>
<li><em>1 ≤ <code>m</code> ≤ min(50, <code>n</code>)</em></li>
</ul>
</blockquote>
<p>Here is my solution to this challenge - </p>
<blockquote>
<pre><code>class Solution(object):
def __init__(self, nums, m):
self.nums = nums
self.m = m
def split_array(self, nums, m):
"""
:type nums: List[int]
:type m: int
:rtype: int
"""
min_res = max(nums)
max_res = sum(nums)
low, high = min_res, max_res
while low + 1 < high:
mid = low + (high - low)//2
if self.is_valid(nums, m, mid):
high = mid
else:
low = mid
if self.is_valid(nums, m, low):
return low
return high
def is_valid(self, nums, m, n):
count, current = 1, 0
for i in range(len(nums)):
if nums[i] > n:
return False
current += nums[i]
if current > n:
current = nums[i]
count += 1
if count > m:
return False
return True
</code></pre>
</blockquote>
<p>Here, I just optimize the binary search method (technique used to search an element in a sorted list), change the condition of <code>low <= high</code> to <code>low + 1 < high</code> and <code>mid = low + (high - low) / 2</code> in case <code>low + high</code> is larger than the <code>max int</code>.</p>
<p>Here is an example input/output - </p>
<pre><code>output = Solution([7,2,5,10,8], 2)
print(output.split_array([7,2,5,10,8], 2))
>>> 18
</code></pre>
<p><strong>Explanation -</strong></p>
<p>There are four ways to split <code>nums</code> into two subarrays.
The best way is to split it into <code>[7,2,5]</code> and<code>[10,8]</code>,
where the largest sum among the two subarrays is only <code>18</code>.</p>
<p>Here is the time for this output - </p>
<pre><code>%timeit output.split_array([7,2,5,10,8], 2)
12.7 µs ± 512 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code></pre>
<p>So, I would like to know whether I could make this program shorter and more efficient.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:32:05.670",
"Id": "427676",
"Score": "0",
"body": "Thanks for the edit @200_success"
}
] | [
{
"body": "<h1>(Sort of) Unnecessary OOP</h1>\n\n<p>A lot of things like LeetCode will require that the solution is in a <code>class</code> for likely submission reasons, but if we concern ourselves with <em>only</em> the task at hand, I would recommend you get rid of the class and just use functions for this. (And if get rid of the unnecessary class, you'll shorten the code, although, I wouldn't encourage you to be preoccupied with shortening your code.)</p>\n\n<p>Also, if you had to keep the class (for whatever reason), observe:</p>\n\n<pre><code>def __init__(self, nums, m):\n self.nums = nums\n self.m = m\n</code></pre>\n\n<p>When you pass parameters like this, you can reuse them over and over again. They are sort of like pseudo-global variables. So you would need to do:</p>\n\n<pre><code>def is_valid(self, nums, m, n):\n</code></pre>\n\n<p>it would just be:</p>\n\n<pre><code>def is_valid(self):\n</code></pre>\n\n<p>and (in general) you would access <code>self.m</code> and <code>self.n</code>.</p>\n\n<h1>Iterate over the iterables, not over the <code>len</code> of the iterable.</h1>\n\n<p>Unless you are mutating <code>nums</code> (which I don't believe you are) the more idiomatic way of doing this is iterating through the iterable so:</p>\n\n<pre><code>for i in range(len(nums)):\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>for num in nums:\n</code></pre>\n\n<p>and instances of <code>nums[i]</code> are replaced by <code>num</code>, for example <code>if nums[i] > n:</code> becomes <code>if num > n:</code>.</p>\n\n<p>Side note: if you were to need the value <code>i</code> and <code>nums[i]</code>, you might want to consider utilizing <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"nofollow noreferrer\"><code>enumerate</code></a> if you need both.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:12:23.320",
"Id": "221204",
"ParentId": "221201",
"Score": "4"
}
},
{
"body": "<pre><code>if nums[i] > n:\n return False\n</code></pre>\n\n<p>This is unnecesary, you are starting the binary search with max(nums) as minimum, so n will always be at leat equal to max nums[i].</p>\n\n<p>Why is both your constructor and split_array method taking in the parameters of the problem? Either only take them on constructor or make split_array a static method without using constructor.</p>\n\n<p>Why you have min_res and max_res? Either use those in the binary search or just replace them with low and high, no reason to have both those and low/high variables.</p>\n\n<p>If you keep an array of accumulated sums of the array you can change is_valid to do binary search to find the index of the next group. This would change complexity from O(|n| * log(sum(n))) to O(m * log(|n|) * log(sum(n))). For such small amount of n, this is probably not worth doing in this case but its definitly better if you have small m and big n. Instead of reimplementing binary search for this, you could actually use <a href=\"https://docs.python.org/3/library/bisect.html\" rel=\"nofollow noreferrer\">bisect</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:12:27.870",
"Id": "221205",
"ParentId": "221201",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221204",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T15:25:52.247",
"Id": "221201",
"Score": "0",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"programming-challenge"
],
"Title": "Split an array into m subarrays such that the largest subarray sum is minimized"
} | 221201 |
<p>In an app the UI is updated from different threads. To queue this, I have created a utility class</p>
<pre><code>public class AsyncChainedActions
{
private Task _lastTask;
public AsyncChainedActions()
{
_lastTask = Task.Run(() => { });
}
public void AddToAsyncChain(Action action, [CallerMemberName] string
caller = null)
{
_lastTask = _lastTask.ContinueWith(o =>
{
try
{
action();
}
catch (Exception ex)
{
PublishError($"process {caller} message
from service", ex);
}
o.Dispose();
});
}
}
</code></pre>
<p>util class is used as below </p>
<pre><code>public class UpdateManager
{
public ObservableCollection<Person> Persons{get;set;}//bound to a data
//grid
public UpdateManager()
{
Event1.Subscribe(Event1Update);
Event2.Subscribe(Event2Update);
}
private void Event1Update(Person person)
{
_asyncChainedActions.AddToAsyncChain(() =>
{
if(NotValidUpdate(person)) return;
_updateUi.ExecuteOnMainDispatcher(() =>
{
var update = Persons.FirstOrDefault(x => x.Id == person.Id );
if(update!=null)
{
update.Name = person.Name;
update.Age= person.Age;
update.Address= person.Address;
}
});
});
}
</code></pre>
<p>}</p>
<p>The events sometimes happens many times a second. In certain times the values updated on the Person object is not reflected in the UI grid. I confirm the value is indeed updated in the object, but it is just that it is not reflected in the UI. It happens only sometimes. I think it is something to do with the dispatcher updates happening in the chain adn binding delays.</p>
<p>Do you see any issue with the async chain approach?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:14:51.463",
"Id": "427664",
"Score": "0",
"body": "What's the benefit of this over a _plain_ dispatch into the UI thread? As far as I can see you queue actions you will then always execute in the UI thread: you add overhead without visible benefits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:18:52.750",
"Id": "427670",
"Score": "0",
"body": "I just edited the code.There are some checks which need not be done in UI thread, so it is kept outside the dispatcher"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:20:36.243",
"Id": "427671",
"Score": "0",
"body": "This is a question. If it is done in plain dispatcher thread, will the thread honor the order of the events?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:23:55.687",
"Id": "427673",
"Score": "0",
"body": "Yes, the dispatcher will honor the invocation order (unless you specify different priorities). Then you should compare this with a _plain_ `async` method. If your _expansive_ operations are in `if (await NotValidUpdate(person)) return;` then (in WPF) the method will resume in the correct context. In this case you might want to use a blocking collection if you need to queue more than one \"operation\" and to preserve their order (note that dispatching IMHO, should be done in the queue class because we definitely want to simplify caller's code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:30:17.303",
"Id": "427675",
"Score": "0",
"body": "I mean, I see three use-cases: 1) queue actions to perform in the UI thread: just dispatch them. 2) queue a single task, partially in the UI thread: `async`+`await`. 3) Queue multiple tasks:I'd invest some time to make calling code MUCH more easy to read and less verbose, a blocking collection might help (I think)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:35:12.163",
"Id": "427677",
"Score": "1",
"body": "What happened to this part `//.........other updates`? Please post everything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:36:37.530",
"Id": "427678",
"Score": "0",
"body": "Why don't you use the ContinueWith overload that takes a TaskScheduler instance? You can give the UI dispatcher with it, no need for additional UI wrappers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:41:50.950",
"Id": "427680",
"Score": "0",
"body": "@AdrianoRepetti . I hear you. Since the checks outside the dispatcher is not much I can put that in dispatcher . So I guess option 1) should work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:43:28.023",
"Id": "427681",
"Score": "0",
"body": "@t3chb0t edited"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:48:56.603",
"Id": "427682",
"Score": "0",
"body": "Ok I deleted my answer since you require part of the operation to be performed outside the UI thread."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:50:48.483",
"Id": "427683",
"Score": "0",
"body": "In this very specific case...yes, I do not think you need to perform the validation outside the UI thread but...hey, there might be very complex business rules which involve DB calls and network requests (for example to check if person's e-mail is already in use) then you may still have a huge point. What I was trying to say is that you should try to simplify the caller code as much as possible. I'd - personally - use a blocking queue to serialize multiple tasks and `Action action` should be `Func<Task>` because I'd probably use `ConfigureAwait()` to execute the code in the UI thread..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:53:11.977",
"Id": "427684",
"Score": "0",
"body": "...and caller should `await` long operations. Something like: `_pendingJobs.Enqueue(async () => { await PerformSlowValidation(); UpdateUi(); })`. You can keep your `ContineWith()` approach but code will be slightly more complex (with or without blocking queue)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T17:17:57.000",
"Id": "427689",
"Score": "1",
"body": "I'm voting to close this question because the code is still incomplete, e.g. we don't know what `_updateUi` is. There are also other variables/properties that are undefined."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T16:07:22.400",
"Id": "221202",
"Score": "1",
"Tags": [
"c#",
"asynchronous",
"wpf"
],
"Title": "Chaining asynchronous calls to update UI"
} | 221202 |
<p>This is a <a href="https://leetcode.com/problems/concatenated-words/" rel="nofollow noreferrer">Leetcode problem</a> -</p>
<blockquote>
<p><em>Given a list of words (<strong>without duplicates</strong>), write a program that
returns all concatenated words in the given list of words.</em></p>
<p><em>A concatenated word is defined as a string that is comprised entirely
of at least two shorter words in the given array.</em></p>
<p><strong><em>Note -</em></strong></p>
<ul>
<li><em>The number of elements of the given array will not exceed <code>10,000</code>.</em></li>
<li><em>The length sum of elements in the given array will not exceed <code>600,000</code>.</em></li>
<li><em>All the input string will only include lower case letters.</em></li>
<li><em>The returned order of elements does not matter.</em></li>
</ul>
</blockquote>
<p>Here is my solution to this challenge (DFS solution) - </p>
<blockquote>
<pre><code>def find_all_concatenated_words_in_a_dict(words):
"""
:type words: List[str]
:rtype: List[str]
"""
words = set(words)
output = []
for w in words:
if not w:
continue
stack = [0]
seen = {0}
word_len = len(w)
while stack:
i = stack.pop()
if i == word_len or (i > 0 and w[i:] in words):
output.append(w)
break
for x in range(word_len - i + 1):
if w[i: i + x] in words and i + x not in seen and x != word_len:
stack.append(i + x)
seen.add(i + x)
return output
</code></pre>
</blockquote>
<p>Here is an example output -</p>
<pre><code>#print(find_all_concatenated_words_in_a_dict(["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"]))
>>> ['catsdogcats', 'ratcatdogcat', 'dogcatsdog']
</code></pre>
<p><strong>Explanation -</strong></p>
<p><code>"catsdogcats"</code> can be concatenated by <code>"cats"</code>, <code>"dog"</code> and <code>"cats"</code>;</p>
<p><code>"dogcatsdog"</code> can be concatenated by <code>"dog"</code>, <code>"cats"</code> and <code>"dog"</code>;</p>
<p><code>"ratcatdogcat"</code> can be concatenated by <code>"rat"</code>, <code>"cat"</code>, <code>"dog"</code> and <code>"cat"</code>.</p>
<p>Here is the time taken for this output - </p>
<pre><code>%timeit find_all_concatenated_words_in_a_dict(["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"])
41.1 µs ± 2.93 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code></pre>
<p>So, I would like to know whether I could make this program shorter and more efficient.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T03:35:15.253",
"Id": "427732",
"Score": "0",
"body": "I believe there is an `O(n^2)` dynamic programming solution"
}
] | [
{
"body": "<p>I took me a while to understand your code since I didn't know from the beginning what each variable really meant:</p>\n\n<ul>\n<li><code>i</code> is probably an int, maybe an index</li>\n<li><code>x</code> is probably a number (maybe even a float), or something unknown, or a placeholder</li>\n<li><code>seen</code> is a set of something, and this something could really be anything</li>\n<li><code>stack</code> will only be used by calling <code>append</code> and <code>pop</code>, but what does it contain? ints, strings, complex objects? The name <code>stack</code> by itself doesn't give any clue.</li>\n<li><code>w</code> could also be spelled <code>word</code>, but that one is already the best of the variable names</li>\n</ul>\n\n<p>Therefore, to really understand what each variable stands for, I had to run your code using only pen and paper, which was a good exercise since I really don't do that often.</p>\n\n<p>By doing that I noticed:</p>\n\n<ul>\n<li>the only purpose of the <code>if not w: continue</code> is to prevent the empty word from being output</li>\n<li>the only purpose of the <code>w[i:] in words</code> is to speed up the implementation; it is not necessary for the pure algorithm</li>\n<li>the expression <code>i + x</code> appears several times. I wondered whether the Python runtime would be able to apply common subexpression elimination to it, or whether it would make the program faster if that expression were saved into a separate variable</li>\n<li>I wanted to replace the <code>x != word_len</code> with the simpler <code>i != 0</code>, but I quickly noticed that this would break the whole algorithm</li>\n<li>using a stack is great because the larger string indices are pushed at the end, which means they are popped and checked first, which speeds up the program. At least in the <code>catsdogcats</code> case</li>\n<li>the <code>range</code> should not start at 0, but at 1, since for the empty word, <code>seen[i + x]</code> is always <code>True</code></li>\n<li>the code is really efficient</li>\n</ul>\n\n<p>After finishing the manual analysis, each and every little expression made sense. I didn't discover anything superfluous. Therefore: nice work. You should make the variable names a little more suggestive though.</p>\n\n<ul>\n<li><code>i</code> could be <code>left</code></li>\n<li><code>i + x</code> could be <code>right</code></li>\n<li><code>x</code> could be <code>subword_len</code></li>\n<li><code>stack</code> could be <code>indices_to_test</code></li>\n<li><code>seen</code> could be <code>seen_indices</code></li>\n</ul>\n\n<p>One idea I had during the analysis was that the code might become easier to understand if you used a nested function:</p>\n\n<pre><code>def find_all_concatenated_words_in_a_dict(words: List[str]) -> List[str]:\n words = set(words)\n\n def is_concatenated(word: str) -> bool:\n ...\n return True\n\n return [word for word in words if word and is_concatenated(word)]\n</code></pre>\n\n<p>After executing your algorithm using pen and paper, I thought that another implementation might be even more efficient, and maybe lead to shorter code. My idea was:</p>\n\n<pre><code>def is_concatenated(word: str) -> bool:\n word_breaks = [True] + [False] * len(word)\n\n for start in range(len(word_breaks)):\n if word_breaks[start]:\n for sub_len in range(1, len(word_breaks) - start):\n if sub_len != len(word) and word[start:start + sub_len] in words:\n word_breaks[start+sub_len] = True\n\n return word_breaks[-1]\n</code></pre>\n\n<p>This code also starts at the beginning of the long word and marks all reachable word breaks. It uses fewer variables though.</p>\n\n<p>The code can be further optimized:</p>\n\n<ul>\n<li>for the <code>sub_word</code> length, only iterate over the lengths that actually appear in the word set</li>\n<li>return early as soon as <code>word_breaks[-1]</code> becomes <code>True</code></li>\n</ul>\n\n<p>But even with these optimizations, the time complexity stays at <span class=\"math-container\">\\$\\mathcal O({\\text{len}(\\textit{word})}^3)\\$</span>, which is quite much when <span class=\"math-container\">\\$\\text{len}(\\textit{word})\\$</span> can be up to 10_000. Space complexity is <span class=\"math-container\">\\$\\mathcal O(\\text{len}(\\textit{word}))\\$</span>, and the initial part of the <code>word_breaks[:start]</code> list could be thrown away early.</p>\n\n<p>The <span class=\"math-container\">\\$n^3\\$</span> is because of the 2 nested <code>for</code> loops, and deeply nested in these loops is a string comparison of the subword, which also depends on <span class=\"math-container\">\\$\\text{len}(\\textit{word})\\$</span>.</p>\n\n<p>I'd rather have an <span class=\"math-container\">\\$\\mathcal O(n^2)\\$</span> or even <span class=\"math-container\">\\$\\mathcal O(n)\\$</span> algorithm though. I just don't know whether one exists.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T21:35:00.967",
"Id": "221225",
"ParentId": "221208",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221225",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T17:21:28.623",
"Id": "221208",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge",
"depth-first-search"
],
"Title": "Find all concatenated words in a given list of words"
} | 221208 |
<p><strong>The task</strong></p>
<blockquote>
<p>Given an integer n, return the length of the longest consecutive run
of 1s in its binary representation.</p>
<p>For example, given 156, you should return 3</p>
</blockquote>
<p><strong>My function solution 1</strong></p>
<p>Style 1</p>
<pre><code>function findMaxNumberOfConsecOnes(dec){
const countConsecOnes = (acc, x) => [acc[0] < acc[1]
? acc[1]
: acc[0],
x === "1"
? acc[1] + 1
: 0 ];
return [...(dec >>> 0).toString(2)]
.reduce(countConsecOnes, [0,0]);
}
</code></pre>
<p>Style 2</p>
<pre><code>function findMaxNumberOfConsecOnes(dec){
const countConsecOnes = (acc, x) => [acc[0] < acc[1] ? acc[1] : acc[0],
x === "1" ? acc[1] + 1 : 0 ];
return [...(dec >>> 0).toString(2)]
.reduce(countConsecOnes, [0,0]);
</code></pre>
<p><em>Style 1</em> and <em>Style 2</em> have the exact same logic, but different style. My first idea was to write it in <em>Style 1</em>. But I then thought what was said to me <a href="https://codereview.stackexchange.com/a/220570/54442">in this thread</a> about indentation. Therefore I opt for <em>Style 2</em>. But still not sure, whether this is the right way.</p>
<p>Alternatively:</p>
<p><strong>My functional Solution 2</strong></p>
<pre><code>function findMaxNumberOfConsecOnes(dec){
return [...(dec >>> 0).toString(2)]
.reduce((acc, x) => {
const current = x === "1" ? acc[1] + 1 : 0;
const max = Math.max(acc[0], current);
return [max, current];
}, [0,0]);
}
</code></pre>
<p><strong>My imperative Solution</strong></p>
<pre><code>function findMaxNumberOfConsecOnes(dec){
const binStr = (dec >>> 0).toString(2);
let max = 0, current = 0;
for (const s of binStr) {
current = s === "1" ? current + 1 : 0;
max = Math.max(max, current);
}
return max;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T18:52:30.167",
"Id": "427711",
"Score": "0",
"body": "There's nothing wrong with that style of indentation. Many formatters, such as [Prettier](https://prettier.io/) and [Perltidy](http://perltidy.sourceforge.net/), will apply it when using their default settings. Yes, you should be aware of line length but 100 characters is perfectly acceptable."
}
] | [
{
"body": "<h2>Code alignment.</h2>\n<p>I still think this style of indentation is poor. It is particularly ill suited to large code bases where you have literally hundreds of thousands of lines of code to maintain.</p>\n<p>Its about reading the code and our inherently lazy brain. You scroll through the code looking for a problem scanning the lines and then you have code way to the right. Its not good.</p>\n<p>I would write it as</p>\n<pre><code>function findMaxNumberOfConsecOnes(dec) {\n const countConsec = (ac, x) => [\n ac[0] < ac[1] ? ac[1] : ac[0], // or Math.max(...ac)\n x === "1" ? ac[1] + 1 : 0\n ];\n\n return [...(dec >>> 0).toString(2)]\n .reduce(countConsec, [0, 0])[0]; // Returning number rather than array\n}\n</code></pre>\n<p><strike>Note that I added () around the comma separated group and then the second ternary. Not because it is needed, but when you are checking code the IDE will highlight matching braces (I have mine set to bright bold red) saving time and effort when looking for typos in compound expressions..</strike></p>\n<h2>Bug?</h2>\n<p>The functional solutions return differently (an array) from the imperative solution (a number). My guess is you forgot to extract the max from the array.</p>\n<h2>Number V String</h2>\n<p>Numbers always win.</p>\n<p>I assume by the <code>>>> 0</code> you are expecting negative values and that the MSB (most significant bit) the sign bit, is counted.</p>\n<p>Strings are always the slowest way to deal with numbers. You do get an automatic reduction in the number of bits to count as <code>toString(2)</code> drops the leading zeros so it has one handy benefit.</p>\n<h3>Comparing your solutions</h3>\n<p>In terms of performance the imperative solution is the quickest at around 20% faster than the other two (tested on a random set of signed int32). This is almost a given as functional sacrifices performance in hope of less bugs.</p>\n<h3>Using numbers only</h3>\n<p>By avoiding the use of strings you avoid the memory allocation overhead and the slow string compare tests.</p>\n<p>The following example is up to an order of magnitude faster than your imperative solution and can also avoid stepping over the leading bits of negative values.</p>\n<ul>\n<li><code>size = Math.log2(Math.abs(num)) + 1 | 0</code> get the number of bits to count</li>\n<li><code>const leading = num < 0 ? 32 - size : 0</code> If negative gets the number of leading bits</li>\n<li><code>return Math.max(count + leading, max)</code> add any leading bits to the count and check for max</li>\n</ul>\n<p>The rest is straight forward.</p>\n<pre><code>function countBitSeq(num) {\n var max = 0, count = 0, size;\n size = Math.log2(Math.abs(num)) + 1 | 0;\n const leading = num < 0 ? 32 - size : 0;\n while (size --) {\n max = Math.max((num & 1 ? ++count : count = 0), max);\n num >>= 1;\n }\n return Math.max(count + leading, max);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T05:40:32.060",
"Id": "427740",
"Score": "0",
"body": "Are the brackets set correctly? (In the rewritten code)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T09:49:23.830",
"Id": "427765",
"Score": "0",
"body": "@thadeuszlay Yes indeed, I had not yet run your code in my head, did not realize that you where returning the two items. Will fix it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:12:38.577",
"Id": "427775",
"Score": "0",
"body": "Even a master like you can make mistakes"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T21:46:09.737",
"Id": "221227",
"ParentId": "221212",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221227",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T18:12:19.070",
"Id": "221212",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"comparative-review",
"ecmascript-6"
],
"Title": "Length of the longest consecutive run of 1s in its binary representation"
} | 221212 |
<p><a href="https://leetcode.com/explore/learn/card/trie/148/practical-application-i/1052/" rel="nofollow noreferrer">This is a Leetcode problem</a>:</p>
<blockquote>
<p>Design a data structure that supports the following two operations:</p>
<ul>
<li><code>void addWord(word)</code></li>
<li><code>bool search(word)</code></li>
</ul>
<p><code>search(word)</code> can search a literal
word or a regular expression string containing only letters <code>a-z</code> or <code>.</code>.
A <code>.</code> means it can represent any one letter.</p>
<p><strong>Example:</strong></p>
<pre><code>addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
</code></pre>
<p><strong>Note:</strong></p>
<p>You may assume that all words consist of lowercase letters
a - z.</p>
</blockquote>
<p>Here is my solution to this challenge:</p>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TrieQuestions
{
/// <summary>
/// https://leetcode.com/explore/learn/card/trie/148/practical-application-i/1052/
/// </summary>
[TestClass]
public class WordDictionaryTest
{
[TestMethod]
public void AddWordTest()
{
WordDictionary wordDic = new WordDictionary();
wordDic.AddWord("cat");
Assert.IsTrue(wordDic.Search("cat"));
}
[TestMethod]
public void SearchWordDoT()
{
WordDictionary wordDic = new WordDictionary();
wordDic.AddWord("cat");
Assert.IsTrue(wordDic.Search("c.t"));
}
[TestMethod]
public void SearchWordOne()
{
WordDictionary wordDic = new WordDictionary();
wordDic.AddWord("a");
Assert.IsTrue(wordDic.Search("."));
}
[TestMethod]
public void LeetCodeTest()
{
WordDictionary wordDic = new WordDictionary();
wordDic.AddWord("bad");
wordDic.AddWord("dad");
wordDic.AddWord("mad");
Assert.IsFalse(wordDic.Search("pad"));
Assert.IsTrue(wordDic.Search("bad"));
Assert.IsTrue(wordDic.Search(".ad"));
Assert.IsTrue(wordDic.Search("b.."));
}
[TestMethod]
public void LeetCodeTest2()
{
WordDictionary wordDic = new WordDictionary();
wordDic.AddWord("at");
wordDic.AddWord("and");
wordDic.AddWord("an");
wordDic.AddWord("add");
Assert.IsFalse(wordDic.Search("a"));
Assert.IsFalse(wordDic.Search(".at"));
wordDic.AddWord("bat");
Assert.IsTrue(wordDic.Search(".at"));
Assert.IsTrue(wordDic.Search("an."));
Assert.IsFalse(wordDic.Search("a.d."));
Assert.IsFalse(wordDic.Search("b."));
Assert.IsTrue(wordDic.Search("a.d"));
Assert.IsFalse(wordDic.Search("."));
}
}
public class WordDictionary
{
private TrieNode _head;
/** Initialize your data structure here. */
public WordDictionary()
{
_head = new TrieNode();
}
/** Adds a word into the data structure. */
public void AddWord(string word)
{
var current = _head;
foreach (var letter in word)
{
if (!current.Edges.TryGetValue(letter, out var output))
{
output = current.Edges[letter] = new TrieNode();
}
current = output;
}
current.IsTerminal = true;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public bool Search(string word)
{
return Match(word, 0, _head);
}
private bool Match(string word, int i, TrieNode node)
{
if (i == word.Length)
{
return node.IsTerminal;
}
//if this is a regular letter check if it exists and mode on to the next letter
if (word[i] != '.')
{
if (!node.Edges.ContainsKey(word[i]))
{
return false;
}
else
{
return Match(word, i + 1, node.Edges[word[i]]);
}
}
else
{
//if we get a . try all of the different letters in recursion
// if one of them returns true return true, there is a valid path to the next letter
foreach (var currentNode in node.Edges)
{
if (Match(word, i + 1, currentNode.Value))
{
return true;
}
}
}
return false;
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.AddWord(word);
* bool param_2 = obj.Search(word);
*/
}
</code></pre>
<p>Please review my design and performance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T20:51:16.957",
"Id": "427718",
"Score": "1",
"body": "You should reuse the value of `word[i]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T10:48:02.950",
"Id": "436323",
"Score": "0",
"body": "There is a [Meta CR](https://codereview.meta.stackexchange.com/questions/9257/why-was-this-answer-for-add-and-search-word-deleted-without-any-comments) question involving this post"
}
] | [
{
"body": "<p>Short review: not a whole lot to say. I don't think breaking any of the method up any further would really help matters, and none of them should be combined, so the overall design looks reasonable to me.</p>\n\n<h2>Documentation</h2>\n\n<p>I'm guessing the comments next to the methods are provided by the website: you should add proper inline documentation. Even if you are (for some reason) imposing a time limit on how long you spend designing and writing these programs, you should still go to the effort of documenting the API clearly, because it is a valuable skill itself. However, it's often a good idea to write the documentation before even implementing a method or class, so that you are forced to express precisely what it is to do (not how it will do it).</p>\n\n<h2>Naming</h2>\n\n<p>I'm not overly fond of the name <code>output</code> in this line:</p>\n\n<pre><code>if (!current.Edges.TryGetValue(letter, out var output))\n</code></pre>\n\n<p>Output suggests it is outputted: it <em>is</em> outputted by <code>TryGetValue</code>, but that's <code>TryGetValue</code>'s problem: your problem is finding a descendent/child node.</p>\n\n<p><code>currentNode</code> is also a bit confusing: <code>node</code> is the 'current node', <code>currentNode</code> is a <code>KeyValuePair</code>. You might want to call it <code>child</code> and enumerate <code>node.Edges.Values</code>, since you don't need the keys.</p>\n\n<p>I'm not sold on the name <code>Edges</code> either, since it isn't an arbitrary directed graph.</p>\n\n<h2>Misc</h2>\n\n<ul>\n<li><p>The spec says nothing about how to handle invalid data, but both <code>Match</code> and <code>AddWord</code> will throw a mysterious <code>NullReferenceException</code> when confronted with a <code>null</code>: much better to check throw a helpful <code>ArgumentNullException</code>.</p></li>\n<li><p>You might consider making <code>_head</code> <code>readonly</code>, which expresses the intention that it isn't going to change and prevents someone violating this assumption in the future.</p></li>\n<li><p>You might consider making <code>Match</code> static, since it doesn't need access to any state, which would make it easier to maintain because it will be easier to understand and harder to break.</p></li>\n<li><p>This comment is misleading: <code>// if one of them returns true return true, there is a valid path to the next letter</code></p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T23:53:55.403",
"Id": "224847",
"ParentId": "221215",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "224847",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T19:02:30.773",
"Id": "221215",
"Score": "5",
"Tags": [
"c#",
"programming-challenge",
"depth-first-search",
"trie"
],
"Title": "LeetCode: Add and Search Word C#"
} | 221215 |
<p>I am writing VBA in Excel to calculate the distance between an employee's home address and work address using Bing Maps API calls. The process follows this general flow:</p>
<p>1) Convert the employee's address to Lat-Long values using the GetLatLong function</p>
<p>2) Convert the employee's work address to Lat-Long values using the GetLatLong function</p>
<p>3) Calculate the distance between these two points using the GetDistance function</p>
<p>4) Calculate the drive time between these two points using the GetTime function</p>
<p>The spreadsheet looks like this:</p>
<p><a href="https://i.stack.imgur.com/Hqiww.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hqiww.png" alt="enter image description here"></a></p>
<p>The process is working, but it is excruciatingly slow. The employee population is approximately 2300, and it takes almost an hour to execute.</p>
<p>I am not a coder, but I can functionally modify found code to my purposes. This is an amalgamation of multiple different processes found through Google searches. The code pieces in use are:</p>
<pre><code>Public Function GetDistance(start As String, dest As String)
Dim firstVal As String, secondVal As String, lastVal As String
firstVal = "https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?origins="
secondVal = "&destinations="
lastVal = "&travelMode=driving&o=xml&key=<My Key>&distanceUnit=mi"
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
Url = firstVal & start & secondVal & dest & lastVal
objHTTP.Open "GET", Url, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.send ("")
GetDistance = Round(WorksheetFunction.FilterXML(objHTTP.responseText, "//TravelDistance"), 0) & " miles"
End Function
Public Function GetTime(start As String, dest As String)
Dim firstVal As String, secondVal As String, lastVal As String
firstVal = "https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?origins="
secondVal = "&destinations="
lastVal = "&travelMode=driving&o=xml&key=<My Key>&distanceUnit=mi"
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
Url = firstVal & start & secondVal & dest & lastVal
objHTTP.Open "GET", Url, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.send ("")
GetTime = Round(WorksheetFunction.FilterXML(objHTTP.responseText, "//TravelDuration"), 0) & " minutes"
End Function
Public Function GetLatLong(address As String, city As String, state As String, zip As String)
Dim firstVal As String, secondVal As String, thirdVal As String, fourthVal As String, lastVal As String
firstVal = "https://dev.virtualearth.net/REST/v1/Locations?countryRegion=United States of America&adminDistrict="
secondVal = "&locality="
thirdVal = "&postalCode="
fourthVal = "&addressLine="
lastVal = "&maxResults=1&o=xml&key=<My Key>"
Url = firstVal & state & secondVal & city & thirdVal & zip & fourthVal & address & lastVal
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.Open "GET", Url, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.send ("")
GetLatLong = WorksheetFunction.FilterXML(objHTTP.responseText, "//Point//Latitude") & "," & WorksheetFunction.FilterXML(objHTTP.responseText, "//Point//Longitude")
End Function
</code></pre>
<p>To be clear, the process works well, just extremely slowly. Any thoughts on speeding this up?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T21:11:12.197",
"Id": "427721",
"Score": "0",
"body": "As far as I can tell the bulk of the work is spent waiting for synchronous REST API calls - and VBA UDFs don't run asynchronously. The obvious solution is to ditch VBA and use Office-JS. Is this Office 365? Can it be migrated to Excel Online? Otherwise, the only thing I can think of is to implement a \"refresh\" macro with VSTO and leverage `async/await` in .net - populating the sheet as the results come in (or all at once, after everything is done)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:35:29.213",
"Id": "427825",
"Score": "0",
"body": "`MSXML2.ServerXMLHTTP` supports asynchronous requests - does it *have* to be UDFs, or can the code be refactored into a macro that populates the worksheet cells? Leveraging asynchronous requests could *dramatically* cut the time it takes to update this data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:59:53.950",
"Id": "427828",
"Score": "0",
"body": "Ultimately the slowness is caused by the round-trip time of each API call. Since the time for your entire program to run is basically the sum of these calls, you only have 2 options: 1) *Reduce calls/ running time per call by* - sending all requests at once (definitely the fastest, does your api allow sending batches?), caching results (save distance _and_ time for a given start/dest pair), parallel requests (if the api doesn't throttle requests, also if VBA can handle it) etc. 2) *Make running time unimportant* - run in separate thread/async so Excel doesn't freeze - run through a macro etc."
}
] | [
{
"body": "<p><code>GetTime</code> and <code>GetDistance</code> look very, <em>very</em> similar. In fact, they're identical, save for how the XML response is parsed:</p>\n\n<blockquote>\n<pre><code>Public Function GetDistance(start As String, dest As String)\n '...\n GetDistance = Round(WorksheetFunction.FilterXML(objHTTP.responseText, \"//TravelDistance\"), 0) & \" miles\"\nEnd Function\n\nPublic Function GetTime(start As String, dest As String)\n '...\n GetTime = Round(WorksheetFunction.FilterXML(objHTTP.responseText, \"//TravelDuration\"), 0) & \" minutes\"\nEnd Function\n</code></pre>\n</blockquote>\n\n<p>This is great news: it means there's an opportunity to slash the total execution time by a third, by reducing the number of REST API calls you need to wait for by as much.</p>\n\n<p>The first step is to remove all redundancies. Ultimately we want the 3 functions to look something like this:</p>\n\n<pre><code>Public Function GetDistance(ByVal start As String, ByVal dest As String) As Double\n GetDistance = VirtualEarthAPI.DistanceMatrix(start, dest).Distance\nEnd Function\n\nPublic Function GetTravelTime(ByVal start As String, ByVal dest As String) As Date\n GetTravelTime = VirtualEarthAPI.DistanceMatrix(start, dest).TravelTime\nEnd Function\n\nPublic Function GetLatLong(ByVal address As String, ByVal city As String, ByVal state As String, ByVal zip As String) As String\n GetLatLong = VirtualEarthAPI.LocationPoint(address, city, state, zip)\nEnd Function\n</code></pre>\n\n<p>Note that the <code>GetDistance</code> function now return a <code>Double</code>, and leave the formatting of that numeric value up to the client (i.e. the worksheet) - knowing that a number representing distance in miles needs to look like <code>123.45 miles</code> is a concern for the consumer of this function, not the function itself. As a bonus with the distances now understood as the numeric values they are by Excel, you can do math on these numbers and calculate average distances if you need to. The <code>NumberFormat</code> for distance could be <code>#,##0.00 \"miles\"</code>, for example.</p>\n\n<p>Same with <code>GetTravelTime</code>: by returning a <code>Date</code> (using the <code>VBA.DateTime.TimeSerial</code> function to build it from the number of minutes returned by the API), you can have a <code>NumberFormat</code> for these values that looks like <code>hh:mm</code>, and now Excel can perform math on these values, too.</p>\n\n<p>You have all parameters implicitly passed by reference (<code>ByRef</code>), but they should all be passed by value (<code>ByVal</code>); the functions' return type was also implicitly <code>Variant</code> - specifying an explicit return type makes a much cleaner API to use, especially if any VBA code needs to invoke these functions.</p>\n\n<p>You could use a <code>Scripting.Dictionary</code> to cache the responses for <code>DistanceMatrix</code>, keyed with <code>{start}->{dest}</code> strings that would be easy to lookup from the <code>start</code> and <code>dest</code> arguments: if the dictionary contains that key, you return the cached response; otherwise, you make the HTTP request, cache the response, and return it.</p>\n\n<p>But that's still synchronous, and while caching <code>DistanceMatrix</code> responses would essentially cut 33% of the total update time, we're still looking at almost 40 minutes (extrapolated from \"almost an hour\") to update, which makes it a lot of work for relatively little gain. The biggest win would be to change the strategy entirely, and replace the user-defined functions with a macro, which might look like this:</p>\n\n<pre><code>Option Explicit\nPrivate macro As New EmployeeTableUpdaterMacro\n\nPublic Sub UpdateEmployeeTableAsync()\n macro.ExecuteAsync\nEnd Sub\n</code></pre>\n\n<p>The logic would need to move to a new <code>EmployeeTableUpdaterMacro</code> class module that exposes a <code>Public Sub ExecuteAsync()</code> procedure and proceeds to update the data in the employee table using asynchronous HTTP requests, i.e. updating the values as they come, possibly while displaying a <a href=\"https://rubberduckvba.wordpress.com/2018/01/12/progress-indicator/\" rel=\"nofollow noreferrer\">progress indicator</a> (or updating the <code>Application.StatusBar</code>) showing how many requests were sent vs. how many responses were received.</p>\n\n\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:13:34.527",
"Id": "427833",
"Score": "0",
"body": "Worth noting perhaps that while this does reduce running time significantly, there is nothing you can do in VBA or any other language to make your internet connection faster. That means unless there is some way to send a batch of requests at once, the minimum running time of this code will always be dictated by the number of requests (udf/macro, sync/async). I think the main take-away here is that by providing progress indication/ running as a macro, the slow execution becomes manageable and acceptable. Well ok, that 33% reduction is pretty good too I suppose;)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:59:22.923",
"Id": "221281",
"ParentId": "221222",
"Score": "3"
}
},
{
"body": "<p>Depending on what you want to return you can actually leverage just one API method from Bing to retrieve the data you are after, the <code>Driving Route API</code>. Also, as others have pointed out what's killing performance is the synchronous code. </p>\n\n<p>What I've done below is limited the pull to a single request, and made the code asynchronous. </p>\n\n<p>I've also changed this code to a sub, as I'd need to iterate over some sort of collection. For ease of use, I used a range. </p>\n\n<p>I've structured my data as the from address being in the first column of the range, and the destination address being in the column immediately after that. Travel Distance and Travel Duration will be output offset relative to the from address (2 and 3 columns offset respectively).</p>\n\n<p>I did a quick benchmark, this is taking just over 4 seconds for 250 requests. Hope it helps!</p>\n\n<pre><code>Option Explicit\n\nConst BaseURL As String = \"http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0=\"\nConst APIKey As String = \"YOUR_KEY\"\nPrivate Const READYSTATE_COMPLETE As Long = 4\n\nPublic Sub GetDistances(Addresses As Range)\n Dim Server As Object\n Dim ServerItem As Variant\n Dim Servers As Object\n Dim Cell As Range\n Dim URL As String\n\n Set Servers = CreateObject(\"Scripting.Dictionary\")\n\n 'Send all the requests up front, but don't wait for them to complete\n For Each Cell In Addresses\n 'See here: https://docs.microsoft.com/en-us/bingmaps/rest-services/examples/driving-route-example for more details on this api\n URL = BaseURL & Cell & \"&wp.1=\" & Cell.Offset(0, 1) & \"&key=\" & APIKey & \"&DistanceUnit=mi&DurationUnit=min&output=xml\"\n Set Server = CreateObject(\"MSXML2.ServerXMLHTTP\")\n Server.Open \"GET\", URL, True 'Last param will make request async\n Server.setRequestHeader \"User-Agent\", \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\"\n Server.send (\"\")\n Servers.Add Cell.Address, Server\n Next\n\n 'Iterate each XML request sent to see if done\n For Each ServerItem In Servers.Keys()\n Set Server = Servers(ServerItem)\n\n While Server.readyState <> READYSTATE_COMPLETE\n DoEvents\n Wend\n\n 'Parse result\n If Server.Status = 200 Then\n 'Add result to the sheet to an offsetting column\n Addresses.Parent.Range(ServerItem).Offset(0, 2) = WorksheetFunction.FilterXML(Server.ResponseText, \"/Response/ResourceSets/ResourceSet/Resources/Route/TravelDistance\")\n Addresses.Parent.Range(ServerItem).Offset(0, 3) = WorksheetFunction.FilterXML(Server.ResponseText, \"/Response/ResourceSets/ResourceSet/Resources/Route/TravelDuration\") / 60\n 'You can also return the lat/long from this request, see --> https://docs.microsoft.com/en-us/bingmaps/rest-services/examples/driving-route-example\n End If\n Next\n\nEnd Sub\n\nSub ProcessData()\n Dim myRng As Range\n Dim t As Double\n t = Timer\n Set myRng = ThisWorkbook.Sheets(1).Range(\"A1:a250\")\n GetDistances myRng\n Debug.Print Timer - t\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T01:02:19.750",
"Id": "221316",
"ParentId": "221222",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T20:41:18.250",
"Id": "221222",
"Score": "6",
"Tags": [
"vba",
"excel",
"api",
"rest"
],
"Title": "Speeding up Excel distance calculation using Bing API calls"
} | 221222 |
<p>A recent <a href="https://codereview.stackexchange.com/q/221030/92478">question</a> on credit card validation here on Code Review, led me down a dark rabbit hole of check digit algorithms. I took a stop at the <a href="https://en.wikipedia.org/wiki/Verhoeff_algorithm" rel="nofollow noreferrer">Verhoeff algorithm</a> and tried to implement it myself.</p>
<p>That lead to the following piece of code:</p>
<pre class="lang-py prettyprint-override"><code>class Verhoeff:
"""Calculate and verify check digits using Verhoeff's algorithm"""
MULTIPLICATION_TABLE = (
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(1, 2, 3, 4, 0, 6, 7, 8, 9, 5),
(2, 3, 4, 0, 1, 7, 8, 9, 5, 6),
(3, 4, 0, 1, 2, 8, 9, 5, 6, 7),
(4, 0, 1, 2, 3, 9, 5, 6, 7, 8),
(5, 9, 8, 7, 6, 0, 4, 3, 2, 1),
(6, 5, 9, 8, 7, 1, 0, 4, 3, 2),
(7, 6, 5, 9, 8, 2, 1, 0, 4, 3),
(8, 7, 6, 5, 9, 3, 2, 1, 0, 4),
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
)
INVERSE_TABLE = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9)
PERMUTATION_TABLE = (
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(1, 5, 7, 6, 2, 8, 3, 0, 9, 4),
(5, 8, 0, 3, 7, 9, 6, 1, 4, 2),
(8, 9, 1, 6, 0, 4, 3, 5, 2, 7),
(9, 4, 5, 3, 1, 2, 6, 8, 7, 0),
(4, 2, 8, 6, 5, 7, 3, 9, 0, 1),
(2, 7, 9, 3, 8, 0, 6, 4, 1, 5),
(7, 0, 4, 6, 9, 1, 3, 2, 5, 8)
)
@classmethod
def calculate(cls, input_: str) -> str:
"""Calculate the check digit using Verhoeff's algorithm"""
check_digit = 0
for i, digit in enumerate(reversed(input_), 1):
col_idx = cls.PERMUTATION_TABLE[i % 8][int(digit)]
check_digit = cls.MULTIPLICATION_TABLE[check_digit][col_idx]
return str(cls.INVERSE_TABLE[check_digit])
@classmethod
def validate(cls, input_: str) -> bool:
"""Validate the check digit using Verhoeff's algorithm"""
check_digit = 0
for i, digit in enumerate(reversed(input_)):
col_idx = cls.PERMUTATION_TABLE[i % 8][int(digit)]
check_digit = cls.MULTIPLICATION_TABLE[check_digit][col_idx]
return cls.INVERSE_TABLE[check_digit] == 0
</code></pre>
<p>I chose to implement it as a class with two class methods because I plan to include other algorithms as well and structuring the code this way seemed reasonable to me.</p>
<p>I'm particularly interested in your feedback on the following aspects:</p>
<ol>
<li>What do you think about the API? <code>calculate(input_: str) -> str</code> and <code>validate(input_: str) -> bool</code> seem reasonable and symmetric, but I could also imagine using something like <code>calculate(input_: Sequence[int]) -> int</code>/<code>validate(input_: Sequence[int], int) -> bool</code>.</li>
<li>There seems to be reasonable amount of code duplication between the two functions <code>calculate</code>/<code>validate</code>, but I couldn't really wrap my head around how to define one in respect to the other.</li>
</ol>
<hr>
<p>In addition to the class above, I also decided to take a shot at some unit tests for the algorithm using pytest.</p>
<pre class="lang-py prettyprint-override"><code>import string
import itertools
import pytest
from check_sums import Verhoeff
# modification and utility functions to test the check digit algorihm robustness
DIGIT_REPLACEMENTS = {
digit: string.digits.replace(digit, "") for digit in string.digits
}
def single_digit_modifications(input_):
"""Generate all single digit modifications of a numerical input sequence"""
for i, digit in enumerate(input_):
for replacement in DIGIT_REPLACEMENTS[digit]:
yield input_[:i] + replacement + input_[i+1:]
def transposition_modifications(input_):
"""Pairwise transpose of all neighboring digits
The algorithm tries to take care that transpositions really change the
input. This is done to make sure that those permutations actually alter the
input."""
for i, digit in enumerate(input_[:-1]):
if digit != input_[i+1]:
yield input_[:i] + input_[i+1] + digit + input_[i+2:]
def flatten(iterable_of_iterables):
"""Flatten one level of nesting
Borrowed from
https://docs.python.org/3/library/itertools.html#itertools-recipes
"""
return itertools.chain.from_iterable(iterable_of_iterables)
# Verhoeff algoritm related tests
# Test data taken from
# https://en.wikibooks.org/wiki/Algorithm_Implementation/Checksums/Verhoeff_Algorithm
VALID_VERHOEF_INPUTS = [
"2363", "758722", "123451", "1428570", "1234567890120",
"84736430954837284567892"
]
@pytest.mark.parametrize("input_", VALID_VERHOEF_INPUTS)
def test_verhoeff_calculate_validate(input_):
"""Test Verhoeff.calculate/Verhoeff.validate with known valid inputs"""
assert Verhoeff.calculate(input_[:-1]) == input_[-1]\
and Verhoeff.validate(input_)
@pytest.mark.parametrize(
"modified_input",
flatten(single_digit_modifications(i) for i in VALID_VERHOEF_INPUTS)
)
def test_verhoeff_single_digit_modifications(modified_input):
"""Test if single digit modifications can be detected"""
assert not Verhoeff.validate(modified_input)
@pytest.mark.parametrize(
"modified_input",
flatten(transposition_modifications(i) for i in VALID_VERHOEF_INPUTS)
)
def test_verhoeff_transposition_modifications(modified_input):
"""Test if transposition modifications can be detected"""
assert not Verhoeff.validate(modified_input)
</code></pre>
<p>The tests cover known precomputed input and check digit values, as well as some of the basic error classes (single-digit errors, transpositions) the checksum was designed to detect. I decided to actually generate all the modified inputs in the test fixture so that it would be easier to see which of the modified inputs cause a failure of the algorithm. So far I have found none.</p>
<hr>
<p><strong>Note:</strong> There is a thematically related question of mine on <a href="https://codereview.stackexchange.com/q/222100/92478">optimizing the Luhn check digit algorithm</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T13:06:54.387",
"Id": "427981",
"Score": "0",
"body": "Doesn't this heavily hint at simplification of `validate`? `assert Verhoeff.calculate(input_[:-1]) == input_[-1]\\\n and Verhoeff.validate(input_)`"
}
] | [
{
"body": "<p>I've not had much exposure with good tests. So this focuses on the first codeblock.</p>\n\n<ol>\n<li>I think <code>*_TABLE</code> isn't that useful. Instead <code>PERMUTATIONS</code> and <code>INVERSE</code> looks nicer to me.</li>\n<li>Given that <code>calculate</code> and <code>validate</code> are almost duplicate functions you should probably define a private helper to handle the common code.</li>\n</ol>\n\n<pre><code>class Verhoeff:\n ...\n\n @classmethod\n def _find_check_digit(cls, digits):\n check_digit = 0\n for i, digit in digits:\n col_idx = cls.PERMUTATIONS[i % 8][int(digit)]\n check_digit = cls.MULTIPLICATIONS[check_digit][col_idx]\n return check_digit\n\n @classmethod\n def calculate(cls, input_: str) -> str:\n \"\"\"Calculate the check digit using Verhoeff's algorithm\"\"\"\n check_digit = cls._find_check_digit(enumerate(reversed(input_), 1))\n return str(cls.INVERSES[check_digit])\n\n @classmethod\n def validate(cls, input_: str) -> bool:\n \"\"\"Validate the check digit using Verhoeff's algorithm\"\"\"\n check_digit = cls._find_check_digit(enumerate(reversed(input_)))\n return cls.INVERSES[check_digit] == 0\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T14:37:58.410",
"Id": "221783",
"ParentId": "221229",
"Score": "6"
}
},
{
"body": "<p>Your tests look ok. I have three concerns:</p>\n\n<ul>\n<li><s>If I read correctly, your \"single digit modifications\" test cycle is going to have over 1000000000000000000000 cycles. That's... not practical. pick a compromise.</s> </li>\n<li>The positive tests are checking <code>calculate</code> and <code>validate</code>. I see no reason not to check both in your negative tests too. </li>\n<li>You're only checking <em>syntactically valid</em> input. This ties into your question about what the type signature should be. \n\n<ul>\n<li>You have a few options for your type signature. Without going over the compromises in detail, I would suggest that the first line in <code>calculate</code> and <code>validate</code> should be an <a href=\"https://docs.python.org/3/library/stdtypes.html#str.isdigit\" rel=\"nofollow noreferrer\">isdigit()</a> check, and raise an exception if it fails. </li>\n<li>Whatever you do for types, your tests should check that it's handling edge cases <em>as intended</em>, whatever it is you decide you intend.\n\n<ul>\n<li>empty strings</li>\n<li>a single digit (could break <code>validate</code>)</li>\n<li>all zeros</li>\n<li>whitespace in different configurations</li>\n<li>illegal characters</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>You don't <em>have</em> to address all these points, depending on the use-cases of this project, and whatever else is going on in your life, it may be fine to call it good enough as-is.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T18:31:22.530",
"Id": "430961",
"Score": "0",
"body": "Thanks for the feedback! All the tests, including the same test set for some other algorithms I've cooked up, run in under 4 seconds, so thats okay at the moment. Maybe I should check that the modification function actually does what it's supposed to do ;-) Regarding `isdigit()`: as per the docs it's not completely the right fit for the task since it also permits \"digits\" that cannot be handled in base 10 and some other funny stuff. I have some plans for this, but this will go in another question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T18:38:28.950",
"Id": "430963",
"Score": "0",
"body": "Assuming you don't want to worry about Arabic numerals, a regex would serve for input validation. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T18:44:37.690",
"Id": "430964",
"Score": "0",
"body": "I don't _see_ any \"problems\" with the single-modification function, although it is a little convoluted. My actual guess is that pytest isn't completing the iteration for some reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T19:02:46.640",
"Id": "430965",
"Score": "1",
"body": "I just checked the output of the modificication functions and it seems to be what *I* expect. The function modifies the string in one place and one place only. There is no combinatorics involved, so the number of calls scales linearly with the number of digits used in the test (should be 59 at the moment). For every digit, there are 9 ways the digit can be altered (ignoring the rest of the number), so that would be 531 modified inputs."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T18:08:28.317",
"Id": "222598",
"ParentId": "221229",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222598",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T22:24:24.223",
"Id": "221229",
"Score": "10",
"Tags": [
"python",
"algorithm",
"python-3.x",
"unit-testing",
"checksum"
],
"Title": "Verhoeff check digit algorithm"
} | 221229 |
<p>This is a <a href="https://leetcode.com/problems/strong-password-checker/" rel="nofollow noreferrer">Leetcode problem</a> - </p>
<blockquote>
<p><em>A password is considered strong if below conditions are all met -</em></p>
<p><strong>1.</strong> <em>It has at least 6 characters and at most 20 characters.</em></p>
<p><strong>2.</strong> <em>It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.</em></p>
<p><strong>3.</strong> <em>It must <strong>NOT</strong> contain three repeating characters in a row (<code>...aaa...</code> is weak, but <code>...aa...a...</code> is strong, assuming other
conditions are met).</em></p>
<p><em>Write a function <code>strong_password_checker(s)</code>, that takes a string <code>s</code>
as input, and returns the <strong>MINIMUM</strong> change required to make <code>s</code> a
strong password. If <code>s</code> is already strong, return <code>0</code>.</em></p>
<p><em>Insertion, deletion or replacements of any one character are all
considered as one change.</em></p>
</blockquote>
<p>Here is my solution to this challenge - </p>
<blockquote>
<pre><code>def strong_password_checker(s: str) -> int:
def has_lower(s):
for c in s:
if c.islower(): return 1
return 0
def has_upper(s):
for c in s:
if c.isupper(): return 1
return 0
def has_digits(s):
for c in s:
if c.isnumeric(): return 1
return 0
def find_repeats(s):
i = 0
j = 0
repeats = []
while i < len(s) - 1:
if s[i+1] == s[i]:
i += 1
continue
if (i - j + 1) > 2: repeats.append(i - j + 1)
i += 1
j = i
if (i - j + 1) > 2: repeats.append(i - j + 1)
return repeats
def repeats_after_delete(reps, d):
if d >= sum([r - 2 for r in reps]):
return []
reps = sorted(reps, key=lambda d: d%3)
while d > 0:
for i in range(len(reps)):
if reps[i] < 3:
continue
r = reps[i] % 3 + 1
reps[i] -= min(r, d)
d -= r
if d <= 0:
break
return [r for r in reps if r > 2]
def num_repeats_change(repeats):
return sum([r // 3 for r in repeats])
total_changes = 0
format_changes = (1 - has_lower(s)) + (1 - has_upper(s)) + (1 - has_digits(s))
repeats = find_repeats(s)
if len(s) < 6:
repeat_change = num_repeats_change(repeats)
total_changes = max([6 - len(s), format_changes, repeat_change])
elif len(s) > 20:
repeats = repeats_after_delete(repeats, len(s) - 20)
repeat_change = num_repeats_change(repeats)
total_changes = len(s) - 20 + max([repeat_change, format_changes])
else:
repeat_change = num_repeats_change(repeats)
total_changes = max([repeat_change, format_changes])
return total_changes
</code></pre>
</blockquote>
<p>Here are some example outputs - </p>
<pre><code>#print(strongPasswordChecker("aaaaaaaaaaaaAsaxqwd1aaa"))
>>> 6
#Explanation - aa1aa1aa1aAsaxqwd1aa (just an example - delete three characters, add three digits to replace consecutive a's)
</code></pre>
<hr>
<pre><code>#print(strongPasswordChecker("aaaaa"))
>>> 2
#Explanation - aaAaa1 (just an example - add a character (so the length is at least 6), add an uppercase letter to replace consecutive a's)
</code></pre>
<hr>
<pre><code>#print(strongPasswordChecker("aAsaxqwd2aa"))
>>> 0
#Explanation - A strong password (all conditions are met)
</code></pre>
<hr>
<p>Here are the times taken for each output - </p>
<pre><code>%timeit strongPasswordChecker("aaaaaaaaaaaaAsaxqwd1aaa")
>>> 18.7 µs ± 1.75 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit strongPasswordChecker("aaaaa")
>>> 5.05 µs ± 594 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit strongPasswordChecker("aAsaxqwd2aa")
>>> 7.19 µs ± 469 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code></pre>
<p>So, I would like to know whether I could make this program shorter and more efficient.</p>
<p>Any help would be highly appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T08:55:15.580",
"Id": "427756",
"Score": "2",
"body": "It really is too bad they called this a *strong* password checker. It might've been in the 80's, but certainly not anymore."
}
] | [
{
"body": "<p>You can make it shorter:\nuse any and int: for example:</p>\n\n<pre><code>password_contains_digits = int(any(c.isdigit() for c in s))\n</code></pre>\n\n<p>or use set:</p>\n\n<pre><code>password_set = set(s)\ndigits = set(\"1234567890\")\npassword_contains_digits = int(len(password_set & digits) != 0)\n</code></pre>\n\n<p>or use RegEx:</p>\n\n<pre><code>password_contains_digits = len(re.findall(r'[0-9]', s)) != 0\n</code></pre>\n\n<p>Also, regex can help you to find repeating symbols :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T10:55:51.543",
"Id": "221249",
"ParentId": "221241",
"Score": "2"
}
},
{
"body": "<p>You could use this code for checking whether it has an uppercase/lowercase:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if s.lower() == s:\n # doesn't have any uppercase\nif s.upper() == s:\n # doesn't have any lowercase\n</code></pre>\n\n<p>This way, you don't have to iterate through the entire string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:50:57.033",
"Id": "221254",
"ParentId": "221241",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221249",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T06:40:13.727",
"Id": "221241",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge"
],
"Title": "Strong password checker in Python"
} | 221241 |
<p>I am hoping to find a way to make the process a lot faster. The lists are made of rows of 6 numbers, i.e. <code>[[float] * 6, ...]</code>. The intent is to pass a list of cube co-ordinates (only two 3D co-ordinates, which are opposite corners) and get a shorter list of co-ordinates of 3D quadrilaterals.</p>
<pre><code># Merging by creating a list with the first cube and another with the rest.
# If the cube in the first list can be merged with a cube in the second list,
# the cube in the second list is removed and the cube in the first list is
# replaced with the merged shape.
# If there is no suitable merge to be done, the lowest positioned cube in
# the second list is moved to the first list and then we check if
# anything in the second list can be merged with it and so on.
# loops until qbs has been emptied into css
# the condition for merging is matching faces
def xmerge(qbs, css):
tot = len(qbs)
j = 0
while len(qbs) > 0:
i = 0
k = 0
printProgressBar(tot - len(qbs)+1, tot, prefix = ' Merging along x:',
length = 50)
while i < len(qbs):
# first check if faces are touching
if (abs(css[j][0] - css[j][3]) == abs(css[j][0] - qbs[i][0])
and css[j][1] == qbs[i][1]
and css[j][2] == qbs[i][2]
# if true up to here then corners are touching
# below we check if the faces match (same size)
and abs(css[j][1] - css[j][4]) == abs(qbs[i][1] - qbs[i][4])
and abs(css[j][2] - css[j][5]) == abs(qbs[i][2] - qbs[i][5])):
css[j] = [css[j][0],css[j][1],css[j][2],
qbs[i][3],qbs[i][4],qbs[i][5]]
qbs = np.delete(qbs, i, axis=0)
k = 1
i += 1
if k == 0:
css = np.vstack([css, qbs[np.argmin(qbs[:,0])]])
qbs = np.delete(qbs, np.argmin(qbs[:,0]), axis=0)
j += 1
print("")
return css
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:37:41.527",
"Id": "427777",
"Score": "0",
"body": "Welcome to Code Review! Please make your code complete, i.e. provide all the necessary imports (e.g. I see numpy in there) and also the code of other functions (like `printProgressBar`) used in the code. If you didn't write them yourself or exclude them from the review, at least provide a reference where to find them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T12:27:39.777",
"Id": "427792",
"Score": "0",
"body": "This is all the code leading up to the above function: https://pastebin.com/3h9zFmXM"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T12:31:21.383",
"Id": "427793",
"Score": "0",
"body": "Do the input lists have a specific order? I notice if `a = np.array([[0,0,0,1,1,1]])`\nand `b = np.array([[1,0,0,2,1,1]])`, then `xmerge(a, b)` and `xmerge(b, a)` give different results, where the 2nd gave the result I expected (`[0, 0, 0, 2, 1, 1]`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:07:17.843",
"Id": "427801",
"Score": "0",
"body": "There is no particular order. There is an initial lists with all the cube co-ordinates. I take a random one off the top to start the second list and search the first list for something to merge onto that and so on.\n\nxmerge(a, b) and xmerge(b, a) should return the same thing, but the list that is being added to must start with only one set of co-ordinates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:10:10.537",
"Id": "427803",
"Score": "0",
"body": "Doesn't my previous comment show a bug then? Because order seems to matter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T14:18:18.240",
"Id": "427814",
"Score": "0",
"body": "It would since the code is supposed to merge along x. The input is in fact ordered in such a way that the same corners are used to define each cube, so I have not seen this issue come up. What is the output of xmerge(a, b) in your example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T14:49:39.543",
"Id": "427818",
"Score": "0",
"body": "For xmerge(a, b) I get `[[1 0 0 1 1 1]]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T19:06:34.623",
"Id": "427872",
"Score": "0",
"body": "Is this a `numpy` array problem or a Python list one? `css[j][1]` looks like nest list indexing. `css[i,j]` is more idiomatic `numpy`. That said, the repeated use of `vstack` and `delete` is slow. List append is faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T07:16:05.950",
"Id": "427927",
"Score": "0",
"body": "qbs is a numpy array and css is a list. I will look into having them both as lists, thanks."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T09:51:07.140",
"Id": "221245",
"Score": "2",
"Tags": [
"python",
"performance",
"array",
"numpy"
],
"Title": "Python list operation - merge adjacent cubes into minimum number of shapes"
} | 221245 |
<p>I have developed this simple desktop calculator with WPF. Just wondering, what do you guys think of my coding style of this side project and any code refactoring needed to reduce repeat code?</p>
<pre><code>public partial class MainWindow : Window
{
double lastNumber;
string lastNumberString, selectedValue;
LastInputType lastInputType;
bool firstZero;
Button selectedBtn;
private void Init(bool isEqualPressed = false, bool isOperatorPressed = false)
{
if (!isEqualPressed)
resultLabel.Content = "0";
if (!isOperatorPressed)
resultLabelExp.Content = "";
// This reset is similar with after key in operator reset but without the above line
firstZero = false;
lastNumberString = "";
lastNumber = 0;
lastInputType = LastInputType.Operator;
}
public MainWindow()
{
InitializeComponent();
acButton.Click += AcButton_Click;
negativeButton.Click += NegativeButton_Click;
percentageButton.Click += PercentageButton_Click;
equalButton.Click += EqualButton_Click;
Init();
}
private void EqualButton_Click(object sender, RoutedEventArgs e)
{
if (resultLabelExp.Content.ToString().Trim() != "" && lastInputType != LastInputType.Operator)
{
resultLabel.Content = MathBodmas.EvalExpression(resultLabelExp.Content.ToString().ToCharArray()).ToString();
Init(true);
}
}
private void PercentageButton_Click(object sender, RoutedEventArgs e)
{
if (double.TryParse(resultLabel.Content.ToString(), out lastNumber))
{
lastNumber = lastNumber / 100;
resultLabel.Content = lastNumber.ToString();
}
}
private void NegativeButton_Click(object sender, RoutedEventArgs e)
{
if (double.TryParse(resultLabel.Content.ToString(), out lastNumber))
{
lastNumber = lastNumber * -1;
resultLabel.Content = lastNumber.ToString();
}
}
private void AcButton_Click(object sender, RoutedEventArgs e)
{
Init();
}
private void OperationButton_Click(object sender, RoutedEventArgs e)
{
selectedBtn = sender as Button;
selectedValue = selectedBtn.Content.ToString();
if (lastInputType == LastInputType.Operator)
{
if (resultLabelExp.Content.ToString() == "")
{
// Do nothing
}
else
{
ReplaceLastChar(selectedValue);
}
}
else
{
AppendExp(selectedValue);
}
Init(false, true);
}
private void DecimalButton_Click(object sender, RoutedEventArgs e)
{
selectedBtn = sender as Button;
selectedValue = selectedBtn.Content.ToString();
if (lastNumberString.Contains("."))
{
// Do nothing
}
else
{
if (lastNumberString == "")
{
lastNumberString += "0.".ToString();
resultLabelExp.Content += "0.".ToString();
}
else
{
// Append
AppendExp(selectedValue);
}
}
firstZero = false;
}
private void NumberButton_Click(object sender, RoutedEventArgs e)
{
selectedBtn = sender as Button;
selectedValue = selectedBtn.Content.ToString();
switch (lastInputType)
{
case LastInputType.Operator:
case LastInputType.Zero:
// firstZero value is assigned at Zero button click handler
if (firstZero)
{
ReplaceLastChar(selectedValue);
firstZero = false;
}
else
{
// Append
AppendExp(selectedValue);
}
break;
case LastInputType.Number:
// Append
AppendExp(selectedValue);
break;
default:
break;
}
lastInputType = LastInputType.Number;
}
private void ZeroButton_Click(object sender, RoutedEventArgs e)
{
selectedBtn = sender as Button;
selectedValue = selectedBtn.Content.ToString();
if (lastNumberString == "")
{
// First zero assigned
AppendExp(selectedValue);
firstZero = true;
// Do nothing
}
else if (lastNumberString.Length == 1 && lastNumberString == "0")
{
firstZero = true;
// Do nothing
// To block 00
}
else
{
// Append. i.e. 100
AppendExp(selectedValue);
}
lastInputType = LastInputType.Zero;
}
private void AppendExp(string _selectedValue)
{
lastNumberString += _selectedValue.ToString();
resultLabelExp.Content += _selectedValue.ToString();
}
private void ReplaceLastChar(string _selectedValue)
{
// Replace
lastNumberString = _selectedValue;
// Extract whole string without last char using substring.
resultLabelExp.Content = resultLabelExp.Content.ToString().Substring(0, resultLabelExp.Content.ToString().Length - 1);
resultLabelExp.Content += lastNumberString;
}
}
public enum LastInputType
{
Zero, Number, Operator
}
</code></pre>
<p>Full source is available at my github - <a href="https://github.com/ngaisteve1/CalculatorWPF" rel="nofollow noreferrer">https://github.com/ngaisteve1/CalculatorWPF</a></p>
<p>XAML file as requested</p>
<pre><code><Window x:Class="Calculator.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Calculator"
mc:Ignorable="d"
Title="MainWindow" Height="525" Width="350">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label x:Name="resultLabelExp"
Content="0"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Grid.ColumnSpan="4" FontSize="30"
Foreground="Gray" />
<Label x:Name="resultLabel"
Content="0"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Grid.ColumnSpan="4" FontSize="40"
Grid.Row="1"/>
<Button x:Name="acButton"
Style="{StaticResource additionalButtonsStyle}"
Content="AC"
Grid.Row="2"/>
<Button x:Name="negativeButton"
Style="{StaticResource additionalButtonsStyle}"
Content="+/-"
Grid.Row="2"
Grid.Column="1" IsEnabled="False"/>
<Button x:Name="percentageButton"
Style="{StaticResource additionalButtonsStyle}"
Content="%"
Grid.Row="2"
Grid.Column="2" IsEnabled="False"/>
<Button x:Name="divisionButton"
Click="OperationButton_Click"
Style="{StaticResource operatorButtonsStyle}"
Content="/"
Grid.Row="2"
Grid.Column="3"/>
<Button x:Name="sevenButton"
Click="NumberButton_Click"
Style="{StaticResource numberButtonsStyle}"
Content="7"
Grid.Row="3"/>
<Button x:Name="eightButton"
Click="NumberButton_Click"
Style="{StaticResource numberButtonsStyle}"
Content="8"
Grid.Row="3"
Grid.Column="1"/>
<Button x:Name="nineButton"
Click="NumberButton_Click"
Style="{StaticResource numberButtonsStyle}"
Content="9"
Grid.Row="3"
Grid.Column="2"/>
<Button x:Name="multiplicationButton"
Click="OperationButton_Click"
Style="{StaticResource operatorButtonsStyle}"
Content="*"
Grid.Row="3"
Grid.Column="3"/>
<Button x:Name="fourButton"
Click="NumberButton_Click"
Style="{StaticResource numberButtonsStyle}"
Content="4"
Grid.Row="4"/>
<Button x:Name="fiveButton"
Click="NumberButton_Click"
Style="{StaticResource numberButtonsStyle}"
Content="5"
Grid.Row="4"
Grid.Column="1"/>
<Button x:Name="sixButton"
Click="NumberButton_Click"
Style="{StaticResource numberButtonsStyle}"
Content="6"
Grid.Row="4"
Grid.Column="2"/>
<Button x:Name="minusButton"
Click="OperationButton_Click"
Style="{StaticResource operatorButtonsStyle}"
Content="-"
Grid.Row="4"
Grid.Column="3"/>
<Button x:Name="oneButton"
Click="NumberButton_Click"
Style="{StaticResource numberButtonsStyle}"
Content="1"
Grid.Row="5"/>
<Button x:Name="twoButton"
Click="NumberButton_Click"
Style="{StaticResource numberButtonsStyle}"
Content="2"
Grid.Row="5"
Grid.Column="1"/>
<Button x:Name="threeButton"
Click="NumberButton_Click"
Style="{StaticResource numberButtonsStyle}"
Content="3"
Grid.Row="5"
Grid.Column="2"/>
<Button x:Name="plusButton"
Click="OperationButton_Click"
Style="{StaticResource operatorButtonsStyle}"
Content="+"
Grid.Row="5"
Grid.Column="3"/>
<Button x:Name="zeroButton"
Click="ZeroButton_Click"
Style="{StaticResource numberButtonsStyle}"
Content="0"
Grid.Row="6"
Grid.ColumnSpan="2"/>
<Button x:Name="pointButton"
Click="DecimalButton_Click"
Style="{StaticResource numberButtonsStyle}"
Content="."
Grid.Row="6"
Grid.Column="2" IsEnabled="true"/>
<Button x:Name="equalButton"
Style="{StaticResource operatorButtonsStyle}"
Content="="
Grid.Row="6"
Grid.Column="3"/>
</Grid>
</code></pre>
<p></p>
<p>In progress to change to stack to improve performance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T10:36:52.217",
"Id": "427768",
"Score": "1",
"body": "What is MathBodmas? And could you also paste the designer code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T10:44:45.413",
"Id": "427769",
"Score": "4",
"body": "You should apply MVVM: https://www.c-sharpcorner.com/UploadFile/nipuntomar/mvvm-in-wpf/ , https://intellitect.com/getting-started-model-view-viewmodel-mvvm-pattern-using-windows-presentation-framework-wpf/ , https://intellitect.com/getting-started-model-view-viewmodel-mvvm-pattern-using-windows-presentation-framework-wpf/ , https://stackoverflow.com/questions/1405739/mvvm-tutorial-from-start-to-finish , etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:26:01.413",
"Id": "427809",
"Score": "0",
"body": "MathBodmas is the class which has some method to evaluate math string according to Bodmas sequence. Anyway, that class is from a third party source"
}
] | [
{
"body": "<h3>Tips</h3>\n<ul>\n<li>Use the M-V-VM pattern when designing WPF applications.</li>\n<li>Post all the code you want to get reviewed, even if a link is provided.</li>\n</ul>\n<h3>Cleanup Your Code</h3>\n<ul>\n<li>Don't make empty clauses just for comments.</li>\n<li>Don't add comments when the code is self-explaining.</li>\n<li>Don't check <code>string</code> against <code>""</code>.</li>\n<li>Don't call an irrelevant <code>.ToString()</code> on <code>string</code>.</li>\n</ul>\n<p><em>snippet 1</em></p>\n<blockquote>\n<pre><code> if (lastInputType == LastInputType.Operator)\n {\n if (resultLabelExp.Content.ToString() == "")\n {\n // Do nothing\n }\n else\n { \n ReplaceLastChar(selectedValue);\n }\n }\n else\n {\n AppendExp(selectedValue);\n }\n</code></pre>\n</blockquote>\n<pre><code> if (lastInputType == LastInputType.Operator)\n {\n if (resultLabelExp.Content.ToString().Any())\n { \n ReplaceLastChar(selectedValue);\n }\n }\n else\n {\n AppendExp(selectedValue);\n }\n</code></pre>\n<p><em>snippet 2</em></p>\n<blockquote>\n<pre><code> if (lastNumberString.Contains("."))\n {\n // Do nothing\n }\n else\n {\n if (lastNumberString == "")\n {\n lastNumberString += "0.".ToString();\n resultLabelExp.Content += "0.".ToString();\n }\n else\n {\n // Append\n AppendExp(selectedValue); \n }\n }\n</code></pre>\n</blockquote>\n<pre><code> if (!lastNumberString.Contains("."))\n {\n if (!lastNumberString.Any())\n {\n lastNumberString += "0.";\n resultLabelExp.Content += "0.";\n }\n else\n {\n AppendExp(selectedValue); \n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:22:33.177",
"Id": "427808",
"Score": "0",
"body": "Thanks a lot for the code review. Appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:52:25.247",
"Id": "427810",
"Score": "4",
"body": "Personally I think replacing `str == \"\"` with `!str.Any()` makes the intent of the code less clear. If you must replace it, then I'd go for `string.IsNullOrEmpty(str)` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:15:10.363",
"Id": "427819",
"Score": "1",
"body": "@PieterWitvoet I thought about the IsNullOrEmpty, but right before there is another check on the object. So checking Is'Null'OrEmpty seemed a bit stupid purely from a semantic point of view."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T01:00:33.547",
"Id": "427899",
"Score": "0",
"body": "Just wondering why MVVM is needed for Calculator? I mean the Model layer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T08:11:31.707",
"Id": "427929",
"Score": "1",
"body": "@Steve MathBodmas is your model layer."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:13:22.283",
"Id": "221251",
"ParentId": "221247",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221251",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T10:21:06.030",
"Id": "221247",
"Score": "1",
"Tags": [
"c#",
"wpf"
],
"Title": "Simple Desktop Calculator with WPF"
} | 221247 |
<p>I have to <strong>load/unload models from a specific URL based on player position</strong>. For this reason I am checking player position from model and then load/unload a related piece of model in an Update event which runs on every frame.</p>
<p>Here is the update that validates some checks before loading/unloading. I added this check for optimization purposes as the main loading/unloading loop is heavy:</p>
<pre><code>private void Update()
{
//If this feature is disable don't load/unload
if (enableThisFeature == false) return;
//if player is moving, dont load//unload
if (Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0)
{
//do nothing when player is moving
return;
}
DeactivateDistantTiles();
}
</code></pre>
<p>After this I am checking player postion and calling model load/unload:</p>
<pre><code>private void DeactivateDistantTiles()
{
playerPosition = transform.position;
playerPosition = cameraController.currentActiveCam.transform.position; //transform.position;
checkPlayerPositionChangeing = playerPosition.z != playerLastPos.z || playerPosition.x != playerLastPos.x;
if (checkPlayerPositionChangeing)
{
ABLoadUnloadLoopCall();
}
playerLastPos = cameraController.currentActiveCam.transform.position;
}
Vector3 tilePosition;
float xDistance;
float zDistance;
public void ABLoadUnloadLoopCall()
{
//old
//foreach (SingleABLoader tile in tiles)
//{
// Debug.Log("ABLoadUnloadLoopCall 123");
// Vector3 tilePosition = tile.gameObject.transform.position + (tileSize / 2f);
// float xDistance = Mathf.Abs(tilePosition.x - playerPosition.x);
// float zDistance = Mathf.Abs(tilePosition.z - playerPosition.z);
// if (xDistance + zDistance > maxDistance)
// {
// /*If you don't want to destroy the object on unload then use below line otherwise use DestroyBundleObject with true pararmeter */
// //tile.DestroyBundleObject();
// tile.DestroyBundleObject(true);
// }
// else
// {
// tile.StartDownloadingAB();
// }
//}
//new
for(int i = 0; i < tiles.Length; i++)
{
tilePosition = tiles[i].gameObject.transform.position + (tileSize / 2f);
xDistance = Mathf.Abs(tilePosition.x - playerPosition.x);
zDistance = Mathf.Abs(tilePosition.z - playerPosition.z);
if (xDistance + zDistance > maxDistance)
{
/*If you don't want to destroy the object on unload then use below line otherwise use DestroyBundleObject with true pararmeter */
//tiles[i].DestroyBundleObject();
tiles[i].DestroyBundleObject(true);
}
else
{
tiles[i].StartDownloadingAB();
}
}
}
</code></pre>
<p>I found that <code>ABLoadUnloadLoopCall</code> making GC allocations in KBs is very high. Is there any way available that my code can be optimized and make fewer allocations? My initial research suggest to use a <code>for</code> loop instead of a <code>foreach</code>, therefore in <code>ABLoadUnloadLoopCall</code> I am using a <code>for</code> loop instead of <code>foreach</code> but my game still lags/freezes for some minutes after loading the model.</p>
<p>Here is the Bundle/Model loading code:</p>
<pre><code>public IEnumerator DownloadAB()
{
if (isBundleLoading == true)
yield return false;
BundleLoadStatus = BundleLoadStatusEnum.bundlesLoading;
isBundleLoading = true;
www = UnityWebRequestAssetBundle.GetAssetBundle(finalABLoaderURL);
yield return www.SendWebRequest();
if (www.error != null)
{
Debug.LogError("assetBundleURL : " + finalABLoaderURL);
Debug.LogError("www error : " + www.error);
www.Dispose();
www = null;
yield break;
}
bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle;
//GameObject bundlePrefab = null;
//bundlePrefab = (GameObject)bundle.LoadAsset(bundle.name);
//bundlePrefab = (GameObject)bundle.LoadAsset(bundle.GetAllAssetNames()[0]);
AssetBundleRequest bundlePrefabAsync = bundle.LoadAssetAsync(bundle.name, typeof(GameObject));
//yield return bundlePrefab;
yield return bundlePrefabAsync;
// if we got something out
if (bundlePrefabAsync != null)
//if (bundlePrefab != null)
{
//First Off the Origin S***fting
environmentOriginSetter.EnvironmentOriginSetterFeatureActive(false);//TODO
//assetBundleToLoadObj = (GameObject)Instantiate(bundlePrefab);
//Then Instantiate the Bundel Object and make it child to environment parent object.
assetBundleToLoadObj = Instantiate(bundlePrefabAsync.asset as GameObject);
assetBundleToLoadObj.transform.parent = envParent.transform;
//assetBundleToLoadObj.transform.parent.transform.position = this.transform.localPosition;//new
//Then Enable the Origin Setter feature again
environmentOriginSetter.EnvironmentOriginSetterFeatureActive(true);
//disable the floor L7 Mesh
floorL7MeshRenderer.enabled = false;//TODO
}
www.Dispose();
www = null;
// try to cleanup memory
//Resources.UnloadUnusedAssets();//TODO open if memory problem occur
bundle.Unload(false);//TODO open if memory problem occur
bundle = null;
isBundleLoading = false;
BundleLoadStatus = BundleLoadStatusEnum.bundlesHasLoaded;
}
</code></pre>
<p>For Unloading, I am destroying the object:</p>
<pre><code> public void DestroyBundleObject(bool isDestroy)
{
//bundle was loaded completely, write a bool, if it is true then loaded completely
//bundle is loading, isBundleLoading
//bundle is not load yet,
if (bundleObjectsDeleted == false && BundleLoadStatus == BundleLoadStatusEnum.bundlesHasLoaded)
{
//BundleObjectActive(false);
bundleObjectsDeleted = true;
if (assetBundleToLoadObj)
{
Destroy(assetBundleToLoadObj);
}
//bundle.Unload(true);
//bundle = null;
BundleLoadStatus = BundleLoadStatusEnum.bundleNotLoadedYet;
//Resources.UnloadUnusedAssets();//TODO Open it.
}
}
</code></pre>
<p>Before loading the bundle I Enque the bundle in a list and download it one by one:</p>
<pre><code>public void EnqueABDownloading(SingleABLoader abToDownload)
{
if (!singleAbLoader.Contains(abToDownload))
{
Debug.Log("Enque " + abToDownload.gameObject.name);
singleAbLoader.Enqueue(abToDownload);
if (isDownloadStarted == false)
{
StartCoroutine(StartDownloading());
}
}
}
public IEnumerator StartDownloading()
{
isDownloadStarted = true;
Application.runInBackground = true;//enforce background loading.
imgBlockClicks.SetActive(true);
textLoading.SetActive(true);
loadingSlider.gameObject.SetActive(true);
while (singleAbLoader.Count > 0)
{
float sliderIncrementValue = 1f / singleAbLoader.Count;
SingleABLoader singleAbLoaderCurrent = singleAbLoader.Dequeue();
Debug.Log("Starting to call " + singleAbLoaderCurrent.gameObject.name);
yield return singleAbLoaderCurrent.DownloadAB();
Debug.Log("Finsihed to call " + singleAbLoaderCurrent.gameObject.name);
//Debug.Log("Finished next loop");
//singleAbLoaderCurrent.CallDownloadAB();
//Debug.Log("download call for "+ singleAbLoaderCurrent.name);
loadingSlider.value = sliderIncrementValue;
}
isDownloadStarted = false;
textLoading.SetActive(false);
imgBlockClicks.SetActive(false);
//Application.runInBackground = false;
loadingSlider.gameObject.SetActive(false);
loadingSlider.value = 0;
}
</code></pre>
<p>I tried to profile on editor and found something like this:</p>
<p><a href="https://i.stack.imgur.com/lyejU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lyejU.jpg" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T02:21:27.603",
"Id": "427900",
"Score": "0",
"body": "Is this a code review, or a question of how to do something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T06:59:44.150",
"Id": "427925",
"Score": "0",
"body": "Its code review Ben! I want to optimzie the given code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T10:13:45.953",
"Id": "427938",
"Score": "0",
"body": "Replacing a `foreach` loop with a `for` loop will rarely make a difference - it's what you're doing inside of that loop that matters. But there's very little we can say about that without knowing roughly how many tiles there are, what they contain and what those `DestroyBundleObject` and `StartDownloadingAB` methods do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T10:17:22.700",
"Id": "427939",
"Score": "0",
"body": "Also, it's not clear what the actual problem is: you mention 'GC alloc' (?), but loading a model into memory obviously involves memory allocation. You also mention 'lag/freeze for some minutes', but does that mean that the game freezes for several minutes (which would happen if you download a model synchronously), or does it lag for several minutes (as in occasional drops in fps, which might be caused by heavy GC pressure)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T10:48:18.880",
"Id": "427943",
"Score": "0",
"body": "@PieterWitvoet I have added more code. Please check"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T10:49:44.133",
"Id": "427944",
"Score": "0",
"body": "@PieterWitvoet yeah game freeze for several minutes after loading the bundles. It make sense that game will freeze during loading the bundle as WebGL is single thread but the problem is i am facing greate amount of freeze even after loading the bundle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:45:52.737",
"Id": "428107",
"Score": "1",
"body": "At this point the question is more 'how can I solve this problem' than 'how can I improve this code', and as such I don't think it belongs here on Code Review. You're probably better off asking this on a Unity-specific forum."
}
] | [
{
"body": "<p>Add hysteresis to the unload. That way the unload doesn't happen immediately when the player move out of range where if he dances along the boundary line he could a lot of loading and unloading otherwise.</p>\n\n<pre><code>if (xDistance + zDistance > unloadDistance)\n{\n tiles[i].DestroyBundleObject(true);\n}\nif (xDistance + zDistance < startLoadDistance)\n{\n tiles[i].StartDownloadingAB();\n}\n</code></pre>\n\n<p>Also ensure that <code>StartDownloadingAB()</code> can early out and do nothing when the tile is already loaded. </p>\n\n<p>If memory becomes tight you can add the player velocity to the distance logic to prioritize the tiles ahead over the tiles to the side.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:44:13.977",
"Id": "427826",
"Score": "0",
"body": "Thanks I will check that but do u think that it will be impactful?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T09:52:42.237",
"Id": "427934",
"Score": "0",
"body": "Thanks for recommendation but it didn't make any performance impact."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T11:32:28.100",
"Id": "221252",
"ParentId": "221248",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T10:31:00.093",
"Id": "221248",
"Score": "1",
"Tags": [
"c#",
"unity3d"
],
"Title": "Load/unload models from a specific URL based on player position"
} | 221248 |
<p>C++11 introduced the new standard library function <code>std::stoi</code>, unfortunately there is no equivalent function to convert an unsigned number inside an std::string to its numeric value. Moreover, there is no direct way to convert a string to a signed/unsigned <code>short</code> and <code>char</code>.</p>
<p>The standard library from GNU uses the function <code>__gnu_cxx::__stoa</code> to implement <code>std::stoi</code>. Although not portable, this can be used to implement these functions:</p>
<pre><code>namespace gnu_np {
inline int
stoi(const string& __str, size_t* __idx = 0, int __base = 10)
{ return __gnu_cxx::__stoa<long, int>(&std::strtol, "stoi", __str.c_str(),
__idx, __base); }
inline short
stos(const string& __str, size_t* __idx = 0, int __base = 10)
{ return __gnu_cxx::__stoa<long, short>(&std::strtol, "stos", __str.c_str(),
__idx, __base); }
inline char
stoc(const string& __str, size_t* __idx = 0, int __base = 10)
{ return __gnu_cxx::__stoa<long, char>(&std::strtol, "stoc", __str.c_str(),
__idx, __base); }
inline unsigned
stou(const string& __str, size_t* __idx = 0, int __base = 10)
{ return __gnu_cxx::__stoa<unsigned long, unsigned>(&std::strtoul, "stou", __str.c_str(),
__idx, __base); }
inline unsigned short
stous(const string& __str, size_t* __idx = 0, int __base = 10)
{ return __gnu_cxx::__stoa<unsigned long, unsigned short>(&std::strtoul, "stous", __str.c_str(),
__idx, __base); }
inline unsigned char
stouc(const string& __str, size_t* __idx = 0, int __base = 10)
{ return __gnu_cxx::__stoa<unsigned long, unsigned char>(&std::strtoul, "stouc", __str.c_str(),
__idx, __base); }
} // namespace gnu_np
</code></pre>
<p>Besides not being portable, it seems to work.</p>
<p>Do you see any reason why one or more of these functions should not work?</p>
<p>There is a simpler portable way to implement these functions?</p>
<p>Should we expect <code>__gnu_cxx::__stoa</code> remain stable in future glibc versions?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T12:16:57.660",
"Id": "427790",
"Score": "0",
"body": "Another possibility if `sizeof (long) > sizeof (int)` is to use `std::stoul()` and then narrow to `unsigned int`, else `std::stoull()` if `sizeof (long long) > sizeof (int)`. Only where `long long` and `int` are the same size will there be no implementation. That excludes fewer platforms than depending on GNU compilers. If using GCC, then it might be simpler to upgrade to get C++17 support, then use `std::from_chars()`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T12:53:59.757",
"Id": "427797",
"Score": "0",
"body": "@TobySpeight unfortunately I'm stuck on C++14 but I will certainly reimplement the functions with std::from_chars() as soon as our platform will move to a newer GCC version"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T12:10:48.260",
"Id": "221257",
"Score": "1",
"Tags": [
"c++",
"c++11"
],
"Title": "Functions like std::stoi for unsigned and shorter types using __gnu_cxx::__stoa"
} | 221257 |
<p>I'm using a <a href="https://github.com/samjudson/flickr-net" rel="nofollow noreferrer">.NET library</a> which uses a pre-async/await type of asynchronicity. That is, it provides asynchronous (non-awaitable) method with a callback parameter.</p>
<p>I'm trying to write <em>awaitable</em> extension methods which will wrap some of those methods to make it easier to use with the async/await fashion but I'm not sure if this is the right approach.</p>
<p>Here's an example of <a href="https://github.com/samjudson/flickr-net/blob/160efd285dc7aafe7fe865f8be5f9019aaf124f7/FlickrNet/Flickr_OAuthAsync.cs#L15" rel="nofollow noreferrer">one of those methods</a>:</p>
<pre><code>public void OAuthGetRequestTokenAsync(string callbackUrl, Action<FlickrResult<OAuthRequestToken>> callback)
{
CheckApiKey();
string url = //...
Dictionary<string, string> parameters = OAuthGetBasicParameters();
// [Code to add parameters]
FlickrResponder.GetDataResponseAsync(this, url, parameters, (r) =>
{
var result = new FlickrResult<OAuthRequestToken>();
if (r.Error != null)
{
if (r.Error is System.Net.WebException)
{
var ex = new OAuthException(r.Error);
result.Error = ex;
}
else
{
result.Error = r.Error;
}
callback(result);
return;
}
result.Result = FlickrNet.OAuthRequestToken.ParseResponse(r.Result);
callback(result);
});
}
</code></pre>
<p>And here's what I came up with to provide an awaitable extension method which wraps the one above:</p>
<pre><code>static class FlickrExtensions
{
public static Task<OAuthRequestToken> OAuthGetRequestTokenAsync(this Flickr flickr,
string callbackUrl)
{
var tcs = new TaskCompletionSource<OAuthRequestToken>();
flickr.OAuthGetRequestTokenAsync(callbackUrl, r =>
{
if (r.HasError)
tcs.TrySetException(r.Error);
else
tcs.TrySetResult(r.Result);
});
return tcs.Task;
}
// More extension methods to be added.
}
</code></pre>
<p><strong>Are there any problems with my code or any downsides to this implementation?</strong></p>
<p><strong>Also, is there a better (more standard?) way to achieve this goal?</strong></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:12:52.697",
"Id": "427804",
"Score": "1",
"body": "Your extension method looks pretty standard for what you are trying to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T18:50:13.157",
"Id": "428032",
"Score": "0",
"body": "@Nkosi Thanks for the validation! Does that make the question off-topic or anything?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T20:10:21.423",
"Id": "428044",
"Score": "1",
"body": "@AhmedAbdelhameed doesn't make it off topic. Just might not get an answer since nothing really to improve."
}
] | [
{
"body": "<h2>Error Handling</h2>\n\n<p>You are relying on <code>OAuthGetRequestTokenAsync</code> to catch all exceptions for you.</p>\n\n<blockquote>\n<pre><code>flickr.OAuthGetRequestTokenAsync(callbackUrl, r =>\n{\n if (r.HasError)\n tcs.TrySetException(r.Error);\n else\n tcs.TrySetResult(r.Result);\n});\n</code></pre>\n</blockquote>\n\n<h3>Unhandled errors</h3>\n\n<p>However, <code>OAuthGetRequestTokenAsync</code> internally calls <code>FlickrResponder.GetDataResponseAsync</code>, which as you can see in the <a href=\"https://github.com/samjudson/flickrnet-experimental/blob/master/src/Internals/FlickrResponderAsync.cs\" rel=\"nofollow noreferrer\">Reference Source</a> does not catch all exceptions.</p>\n\n<p>Most exceptions are caught and provided to the <em>callback</em>:</p>\n\n<blockquote>\n<pre><code>// .. snippet from FlickrNet.Internals.FlickrResponder.GetDataResponseAsync()\nif (e.Error != null)\n{\n result.Error = e.Error;\n callback(result);\n return;\n}\n</code></pre>\n</blockquote>\n\n<p>But some are thrown to the caller:</p>\n\n<blockquote>\n<pre><code>// .. snippet from FlickrNet.Internals.FlickrResponder.GetDataResponseAsync()\nusing (var responseReader = new StreamReader(response.GetResponseStream()))\n{\n string responseData = responseReader.ReadToEnd();\n\n throw new OAuthException(responseData, ex);\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h3>Refactored Code</h3>\n\n<p>To wrap this call in an async task, I would also catch these exceptions and handle them in the <code>Task.TrySetException</code>. In addition, since you provide a public API, I suggest to avoid <code>NullReferenceException</code> and check required arguments against <code>null</code>. Perhaps <code>callbackUrl</code> should also be checked early against <code>null</code>. I'm not sure about this, you'd have to verify.</p>\n\n<pre><code>public static Task<OAuthRequestToken> OAuthGetRequestTokenAsync(\n this Flickr flickr, string callbackUrl)\n{\n if (flickr == null) throw new ArgumentNullException(nameof(flickr));\n var tcs = new TaskCompletionSource<OAuthRequestToken>();\n try\n {\n flickr.OAuthGetRequestTokenAsync(callbackUrl, r =>\n {\n if (r.HasError)\n tcs.TrySetException(r.Error);\n else\n tcs.TrySetResult(r.Result);\n });\n } \n catch (Exception uncaughtError)\n {\n tcs.TrySetException(uncaughtError);\n }\n\n return tcs.Task;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T16:03:07.407",
"Id": "225771",
"ParentId": "221261",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:00:46.583",
"Id": "221261",
"Score": "4",
"Tags": [
"c#",
"error-handling",
"asynchronous",
"async-await",
"callback"
],
"Title": "Wrap a callback method in an awaitable method"
} | 221261 |
<p><strong>Task</strong></p>
<p>Find the smallest number of cuts required to break a string into a set of valid palindromes.
<em>For example:</em> </p>
<ul>
<li>ababbbabbababa becomes a|babbbab|b|ababa (cuts = 3)</li>
<li>partytrapb becomes partytrap|b (cuts = 1)</li>
</ul>
<p>Note: all strings of length 1 are palindromes as a single character reads the same forward and backward</p>
<pre><code>import re
def find_paritions(lst, word, running=[]):
for (index,item) in enumerate(lst):
if index > 0:
running.pop()
running = running + [item]
if item[1] == len(word):
complete_paths.append(running)
return
to_explore = []
end = item[1]
for item_next in list_parition_index:
if item_next[0] == end:
to_explore.append(item_next)
if len(to_explore) == 0:
return
find_paritions(to_explore,word,running)
return complete_paths
complete_paths=[]
word = "ababbbabbababa"
start = 0
end = 1
parition_count =0
list_parition_index = []
for start in range (len(word)):
end=start+1
while end < len(word) + 1:
if word[start:end] == word[start:end][::-1]:
list_parition_index.append([start,end])
end +=1
else:
end +=1
list_zeroes = [x for x in list_parition_index if x[0] == 0]
x = find_paritions (list_zeroes,word)
print(f"The total number of divisions required is {len(min(x,key=len))-1}")
print(min(x,key=len))
</code></pre>
| [] | [
{
"body": "<p>You definitely want to take a <a href=\"https://www.cs.cmu.edu/~avrim/451f09/lectures/lect1001.pdf\" rel=\"nofollow noreferrer\">dynamic programming</a> approach to this problem, as explained by Justin, if only to make the code more readable. I've included a solution based on this approach at the end.</p>\n\n<hr />\n\n<h2>Structure</h2>\n\n<p>I found the code fairly difficult to read due to the way it is structured. In its present form it wont be very re-usable, due to the use of global variables and the lack of any overall encapsulation.</p>\n\n<p>For example, the following section, which finds all palindromic substrings, should be encapsulated in a function. And, it would be best for <code>find_partitions</code> to somehow make its own call to this function, rather than to rely on a result stored in a global variable.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for start in range (len(word)):\n end=start+1\n while end < len(word) + 1:\n if word[start:end] == word[start:end][::-1]:\n list_parition_index.append([start,end])\n end +=1\n else:\n end +=1\n\n</code></pre>\n\n<h2>Correctness</h2>\n\n<p>I wasn't able to determine the correctness of the program from inspection, but it appears to produce correct answers, except for inputs that are already palindromes (i.e. require zero cuts), in which case it throws an error.</p>\n\n<p>Also, there's a <a href=\"https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments\" rel=\"nofollow noreferrer\">subtle problem with way you've specified the default value for <code>running</code></a>.</p>\n\n<h2>Efficiency</h2>\n\n<p>Again, I wasn't able to fully analyse the efficiency by inspection. However it seems to perform about as well as my solution.</p>\n\n<h2>Style</h2>\n\n<ul>\n<li>Redundancy:\n\n<ul>\n<li>You import <code>re</code> but don't use it</li>\n<li>Initialising <code>start</code> and <code>end</code> isn't necessary</li>\n<li>This section\n\n<pre class=\"lang-py prettyprint-override\"><code>if ...:\n ...\n end +=1\nelse:\n end +=1\n</code></pre>\n\ncould be replaced with\n\n<pre class=\"lang-py prettyprint-override\"><code>if ...:\n ...\nend +=1\n</code></pre></li>\n</ul></li>\n<li><p>On naming variables:</p>\n\n<ul>\n<li>I think <code>paritions</code> is a spelling mistake. Did you mean <code>partitions</code>?</li>\n<li>Some of the names could be made more descriptive, such as <code>lst</code>, <code>item</code>, <code>item_next</code>, and <code>running</code>.</li>\n</ul></li>\n<li><p>The use of whitespace is a little bit inconsistent. I would make the following changes based on the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">python style guide</a>:</p>\n\n<ul>\n<li><code>(index,item)</code> -> <code>(index, item)</code></li>\n<li><code>find_paritions(to_explore,word,running)</code> -> <code>find_paritions(to_explore, word, running)</code></li>\n<li><code>complete_paths=[]</code> -> <code>complete_paths = []</code></li>\n<li><code>parition_count =0</code> -> <code>parition_count = 0</code></li>\n<li><code>range (len(word))</code> -> <code>range(len(word))</code></li>\n<li><code>[start,end]</code> -> <code>[start, end]</code></li>\n<li><code>end=start+1</code> -> <code>end = start + 1</code></li>\n<li><code>end +=1</code> -> <code>end += 1</code></li>\n<li><code>find_paritions (list_zeroes,word)</code> -> <code>find_paritions(list_zeroes, word)</code></li>\n<li><code>min(x,key=len)</code> -> <code>min(x, key=len)</code></li>\n</ul></li>\n<li><p>It wasn't clear to me that <code>running = running + [item]</code> served the role of duplicating running before appending <code>item</code>, so I ended up correcting it to <code>running.append(item)</code> which of course broke the code. Maybe a comment here would be worthwhile, or this statement could be written in such a way that it draws attention to the duplication (e.g. <code>new_running = running + [item]</code>, then you wouldn't have to use <code>pop</code> on each successive iteration).</p></li>\n</ul>\n\n<hr />\n\n<p>For comparison, here is a solution that uses dynamic programming:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def least_palin_cuts(string, memo=None):\n \"\"\"Return the minimum number of cuts required to break string into \n palindromic substrings.\n\n >>> least_palin_cuts('ababbbabbababa') # a|babbbab|b|ababa\n 3\n >>> least_palin_cuts('partytrapb') # partytrap|b\n 1\n >>> least_palin_cuts('kayak') # kayak (no cuts needed)\n 0\n \"\"\"\n if memo is None:\n memo = dict()\n if string not in memo:\n if is_palindrome(string):\n memo[string] = 0\n else:\n memo[string] = min(\n least_palin_cuts(left, memo) + 1 + least_palin_cuts(right, memo)\n for (left, right) in splits(string)\n )\n return memo[string]\n\ndef is_palindrome(string):\n \"\"\"Return True if string is a palindrome, else False.\"\"\"\n return all(c1 == c2 for (c1, c2) in zip(string, reversed(string)))\n\ndef splits(string):\n \"\"\"Generate each way of splitting string into two non-empty substrings.\n\n >>> list(splits('abc'))\n [('a', 'bc'), ('ab', 'c')]\n \"\"\"\n for i in range(1, len(string)):\n yield (string[:i], string[i:])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:07:16.103",
"Id": "427945",
"Score": "1",
"body": "For is_palindrome, why not just `return string == string[::-1]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T13:06:51.347",
"Id": "427980",
"Score": "0",
"body": "My thought was that `string == string[::-1]` might not terminate early if, say, `string[0] != string[-1]`, whereas `all` will stop at the first non-true value. It does seem to make a difference, but only for very large strings: with `s = 'b' + 'a' * 1_000_000`, I got `1.1 ms ± 4.53 µs per loop` for `%timeit s == s[::-1]` and `958 ns ± 4.74 ns per loop` for `%timeit all(...)`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T23:51:36.903",
"Id": "221315",
"ParentId": "221267",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T13:56:19.317",
"Id": "221267",
"Score": "3",
"Tags": [
"python",
"algorithm",
"strings",
"palindrome"
],
"Title": "Palindromic partitions solution"
} | 221267 |
<p>I'm working with some code left from other developers. Here we have several projects we can work with. The project object is instantiated at the runtime. Then it used in other classes. There are no methods in Projects and the class holds pure configuration values.</p>
<p>Is subclassing a proper way to define configuration for different Projects? Isn't it better to create one class and get values from configuration file?</p>
<pre><code>class BaseProject(metaclass=ABCMeta):
"""
abstract class for projects
concrete version of this needed only to keep transition IDs in case of custom workflow.
"""
@property
@abstractmethod
def project_id(self):
pass
@property
@abstractmethod
def transition_id(self):
pass
@staticmethod
def by_name(name):
for prj in BaseProject.__subclasses__():
if name.lower() == prj.__name__.lower():
return prj()
return Project3()
@staticmethod
def by_card_name(name):
for prj in BaseProject.__subclasses__():
if name.split("-")[0].lower() == str(prj.__name__).lower():
return prj()
return Project3()
# concrete projects
class Project1(BaseProject):
project_id = 12334
transition_id = 444
class Project2(BaseProject):
project_id = 4451
transition_id = 88
class Project3(BaseProject):
project_id = 12346
transition_id = 88
</code></pre>
<p>It looks good in term of open/closed principle. But I'm a little confused that values are in classes themself not in configuration.</p>
<p>BTW we don't expect any more projects in future and existing are hardly to change.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:21:32.163",
"Id": "427820",
"Score": "1",
"body": "Pseudo-code is off-topic. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:21:54.847",
"Id": "427821",
"Score": "0",
"body": "This might be more on-topic over at [SoftwareEngineering](https://SoftwareEngineering.StackExchange.com/), but before posting there please [**follow their tour**](https://SoftwareEngineering.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://SoftwareEngineering.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://SoftwareEngineering.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://SoftwareEngineering.StackExchange.com/help/dont-ask)."
}
] | [
{
"body": "<p>There is a very famous quote in software engineering: The only fixed thing in software is change.</p>\n\n<p>So if it doesn't seem to you face any change in the future, that not means that you won't face any change in the future.</p>\n\n<p>But there is something in your code. The instances of your class have no property for themselves. All values are <code>static</code>. This doesn't seem good. If you have a real object in your code that represents a project, so that object should has its own values. </p>\n\n<p>So I think you should remove that <code>static</code> notations from your code and make those properties owned by instance. If it's applicable for you, then inheritance for creating different kinds of <code>Project</code>s are a really good thing to do.</p>\n\n<p>But If you think you should not remove those <code>static</code> values, inheriting is still a good idea. Because you can pass different types of Projects in your code without modifying it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:51:59.007",
"Id": "427827",
"Score": "0",
"body": "Thank you. I think you right I also would like to move the attributes to the object itself. But my idea was to store values in configuration. Something like\n`class Project:\n def __init__(self, project_name):\n self.project_id, self._transition_id = Config.get_project_config(project_name)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T12:06:30.953",
"Id": "427965",
"Score": "0",
"body": "That is another way for doing this, But I think, in that case, it's also better that `get_project_cofig` returns an instance of `Project`. But if you want to do this, I think `Project` class is redundant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T16:10:54.993",
"Id": "428009",
"Score": "1",
"body": "Yes, in configuration I store them as named tuples and `get_project_config` just looks up a right one. By the some reason I think it's more readable. Thank you for helping me"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:17:35.800",
"Id": "221272",
"ParentId": "221268",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "221272",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T14:24:44.303",
"Id": "221268",
"Score": "-2",
"Tags": [
"python",
"inheritance",
"configuration"
],
"Title": "Is it ok to use subclasses to define just a couple of attributes?"
} | 221268 |
<p>As part of job interview, I was asked to write a cli script that takes a list of phone numbers to validate from a file and as an option in the command line.
It will then produce a CSV file with three columns “phone number”, “carrier”, “status”.</p>
<p>The status column should indicate if the phone number is valid or not valid. The carrier field should contain the carrier name if the phone number is valid.</p>
<p>I am using libphonenumber-for-php and <a href="https://github.com/splitbrain/php-cli" rel="nofollow noreferrer">https://github.com/splitbrain/php-cli</a></p>
<p>They asked me to show knowledge in PHP programming using the latest techniques and open source technologies available. Can anybody see obvious improvements where I am not doing this?</p>
<p>So far I have come up with the following which works:</p>
<pre><code>require 'vendor/autoload.php';
use splitbrain\phpcli\CLI;
use splitbrain\phpcli\Options;
use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberToCarrierMapper;
use libphonenumber\PhoneNumberType;
class mobileValidator extends CLI
{
// override the default log level
protected $logdefault = 'info';
// register options and arguments
protected function setup(Options $options)
{
$options->setHelp('This script takes a list of phone numbers from a file (or as an option) and validates them as UK mobile numbers.');
$options->registerOption('file', 'The file containing a list of phone numbers to validate', 'f', 'filename');
$options->registerOption('numbers', 'List of numbers passed in as an option (numbers should separated by a comma).', 'n', 'numbers');
}
/**
* The main Program
* Arguments and options have been parsed when this is run
* @param Options $options
* @return void
*/
protected function main(Options $options)
{
if (!$options->getOpt('file') && !$options->getOpt('numbers')) {
$this->error('No files or numbers have been supplied - Cannot Continue.');
exit();
}
$this->notice('Validation Process Started');
//Get options
$opNum = $options->getOpt('numbers');
$file = $options->getOpt('file');
$numbersFromOp = array();
$numbersFromFile = array();
//Set country code uk
$countryCode = 44;
//Set regions codes to Uk, Guernsey, Jersey and Isle of Man
$regionCodes = array('GB', 'GG', 'JE', 'IM');
//get validator dependencies
$phoneUtil = PhoneNumberUtil::getInstance();
$carrierMapper = PhoneNumberToCarrierMapper::getInstance();
$phoneNumberType = PhoneNumberType::MOBILE;
//Get numbers from passed in option
if ($opNum) {
$numbersFromOp = explode(',', $opNum);
}
//Check if files is set and actually exists
if ($file) {
if(file_exists($file)) {
$numbersFromFile = file($file);
}
else {
$this->warning("File not found ".$file);
if(!$opNum){
$this->critical('File not found and no numbers have been supplied - Cannot Continue.');
exit();
}
}
}
//marge all number arrays to be validated
$phoneNumbers = array_merge($numbersFromFile, $numbersFromOp);
//Validate the numbers
$validator = new validator($phoneNumbers, $phoneUtil, $carrierMapper, $phoneNumberType, $countryCode, $regionCodes);
$results = $validator->validateNumbers();
//write numbers to the csv file
$this->generateCSV($results);
$this->success('Validation process completed successfully');
}
/**
* generateCSV
* Simple function to write a csv file
* @param array $results
* @return void
*/
protected function generateCSV(array $results){
// Open a file to write to
$fp = fopen('output/phone_numbers_'. date('d-M-Y-H-i').'.csv' , 'wb');
$headerRow = array ('Phone Number', 'Carrier', 'Status');
$i = 0;
foreach( $results as $fields ){
if( $i === 0 ){
fputcsv($fp, $headerRow ); // First write the headers
}
fputcsv($fp, $fields); // Then write the fields
$i++;
}
fclose($fp);
}
/**
* Override log function
* Added error_log
* @param string $level
* @param string $message
* @param array $context
*/
public function log($level, $message, array $context = array())
{
// is this log level wanted?
if (!isset($this->loglevel[$level])) return;
/** @var string $prefix */
/** @var string $color */
/** @var resource $channel */
list($prefix, $color, $channel) = $this->loglevel[$level];
if (!$this->colors->isEnabled()) $prefix = '';
$message = $this->interpolate($message, $context);
error_log($message);
$this->colors->ptln($prefix . $message, $color, $channel);
}
}
// execute it
$cli = new mobileValidator();
$cli->run();
</code></pre>
<p>The validator class:</p>
<pre><code>use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberToCarrierMapper;
use libphonenumber\NumberParseException;
class validator
{
private $phoneNumbers;
private $phoneUtil;
private $carrierMapper;
private $phoneNumberType;
private $countryCode;
private $regionCodes;
private const VALID = 'Valid';
private const INVALID = 'Invalid';
function __construct( array $phoneNumbers, PhoneNumberUtil $phoneUtil, PhoneNumberToCarrierMapper $carrierMapper, $phoneNumberType, $countryCode, $regionCodes)
{
$this->phoneNumbers = $phoneNumbers;
$this->phoneUtil = $phoneUtil;
$this->carrierMapper = $carrierMapper;
$this->phoneNumberType = $phoneNumberType;
$this->countryCode = $countryCode;
$this->regionCodes = $regionCodes;
}
/**
* Returns validated results
* Loops through the phone numbers and validates as uk mobile numbers (including the channel islands).
* Results returned as an array( number, carrier, valid)
* @return array $results
*/
public function validateNumbers(){
$results = array();
//loop through supplied phone numbers
foreach ($this->phoneNumbers as $phoneNumber) {
$number = trim($phoneNumber);
try {
$phoneNumberObject = $this->phoneUtil->parse($number, 'GB');
}
catch (NumberParseException $e) {
$results[] = array($number,'', self::INVALID);
error_log($e);
continue;
}
//get country code and region code
$countryCode = $phoneNumberObject->getCountryCode();
$regionCode = $this->phoneUtil->getRegionCodeForNumber($phoneNumberObject);
$valid = false;
//Number is considered valid if the country code matches supplied country code
// and the region code matches one of the supplied region codes
if($countryCode === $this->countryCode && in_array($regionCode, $this->regionCodes)){
$valid = $this->phoneUtil->isValidNumber($phoneNumberObject);
}
$type = $this->phoneUtil->getNumberType($phoneNumberObject);
$carrier = '';
$validMobile = self::INVALID;
//if the number is valid and the type is mobile attempt to get the carrier
if ($valid && $type === $this->phoneNumberType) {
$carrier = $this->carrierMapper->getNameForNumber($phoneNumberObject, 'en');
if ($carrier === '') {
$carrier = 'unknown';
}
$validMobile = self::VALID;
}
//add to the results array
$results[] = array($number,$carrier, $validMobile);
}
return $results;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:35:46.547",
"Id": "427847",
"Score": "0",
"body": "This was part of a technical test that i passed as part of a job interview."
}
] | [
{
"body": "<p>I looked through your code, but to be honest, I don't see much to review. Believe it or not; That's actually a good thing. I think. </p>\n\n<p>You're basically using two libraries in two classes. But you haven't paid much attention to structuring your own code.</p>\n\n<p>You could, for instance, have take a bit more effort in the <code>validator</code> class, splitting it up in methods for validating the various aspects of a phone number. Now it is all inside one big <code>validateNumbers()</code> method. It works, but as a <code>validator</code> it is far less useful than it could be. I almost start to wonder why this is a class in the first place? The same is true for <code>mobileValidator</code>, almost everything is cramped inside the <code>main()</code> method. </p>\n\n<p><strong>In general a method should perform a <em>single task</em> in the context of its class.</strong></p>\n\n<p>That means it should concentrate on the details of that single task. In your <code>validator</code> class <code>validateNumbers()</code> deals with all the aspects of the phone numbers. Were you to split it up a bit more, you could end up with methods like this:</p>\n\n<pre><code>__construct($phoneUtil, $carrierMapper, $phoneNumberType)\nrestrictCountryAndRegionCodes($countryCode, $regionCodes)\nvalidateNumbers($phoneNumbers)\nvalidateNumber($phoneNo)\ncleanNumber($phoneNo)\nisMobileNumber($phoneNo)\ngetCarrier($phoneNo)\n</code></pre>\n\n<p>These are, of course, just examples. Notice how I detached the phone numbers completely from the class constructor. That way you can feed it one, or many, numbers, several times.</p>\n\n<p>The point is: Your <code>validator</code> class is very specifically made for one job and only for that job. It cannot do anything else. It cannot easily be modified, expanded, or reused. As a class it is <em>not flexible</em>. By breaking up the code, into its functional parts, it becomes more flexible, and easier to read, refactor, debug and test.</p>\n\n<p>This is basically the <em>Single Responsibility</em> principle, of the <a href=\"https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design\" rel=\"nofollow noreferrer\">SOLID principles</a>, applied to methods. Although these princicles are rather abstract, they do have real benefits when applied consistently.</p>\n\n<p>If I were to write your code, I would first think about the main entities that it deals with; The files and the phone number. </p>\n\n<p>This almost automatically suggests to me that there should be a class called 'PhoneNumber'. This class then gets various methods like <code>getNumber()</code> and <code>setNumber()</code>, and, of course, it could have a method called <code>isValidMobileNumber()</code>. It would deal with only one phone number. </p>\n\n<p>The next class I can see is the file with the phone numbers. A class name for that could be simply: <code>DataFile</code>, and it would deal with the details of that file. </p>\n\n<p>The last class is the <code>CSV</code> file.</p>\n\n<p>These three classes are used by my extended CLI class like this:</p>\n\n<pre><code>class PhoneNoValidatorCLI extends CLI\n{\n private $phoneData = [];\n\n private function __construct()\n {\n $this->phoneNo = new PhoneNumber(.....);\n $this->addPhoneData(\"Phone Number\", \"Carrier\", \"Status\"); // header\n parent::__construct();\n }\n\n public function addPhoneData($number, $carrier, $status)\n {\n $this->phoneData[] = [$number, $carrier, $status];\n }\n\n public function writeData2CSV($filename)\n {\n $csv = new CSV($filename);\n $csv->writeData($this->phoneData);\n }\n\n protected function main(Options $options)\n {\n $file = new DataFile(.....);\n while ($number = $file->nextLine()) {\n $this->phoneNo->setNumber($number);\n $this->addPhoneData($this->phoneNo->getNumber(),\n $this->phoneNo->getCarrier(),\n $this->phoneNo->getStatus());\n }\n $file->close();\n $this->writeData2CSV(\"phone_numbers_\" . date('d-M-Y-H-i'));\n }\n}\n</code></pre>\n\n<p>This is just a very crude example, lacking many details, but I hope you get the idea. In <a href=\"https://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">OOP</a> you first try to find the logical objects you're dealing with, and then write your code around them. You had two libraries and wrote your code around those, without thinking about the possible objects in your own task. </p>\n\n<p>One last thing. You extend the <code>CLI</code> class. It is considered \"bad practice\" to extend classes <em>you do not own</em>. Your extension could break their class. However, I also see that the library itself tells you to use it like that. So forget about this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T16:14:28.207",
"Id": "428178",
"Score": "0",
"body": "Thanks that was very helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T12:27:17.797",
"Id": "221338",
"ParentId": "221270",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221338",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:00:01.883",
"Id": "221270",
"Score": "5",
"Tags": [
"php",
"interview-questions",
"validation",
"csv"
],
"Title": "PHP program to validate phone numbers from a file"
} | 221270 |
<p>I've implemented a <code>div_by_power_of_2()</code> function, which lets me force the compiler to use left-shifting rather than proper division, in cases when the developer know the divisor will be a power of 2, but does not know which power of 2; and the compiler cannot prove to itself that this is the case.</p>
<pre><code>template <typename P> constexpr P log2_of_power_of_2(P non_negative_power_of_2) noexcept
{
static_assert(std::is_integral<P>::value, "Only integral types are supported");
static_assert(sizeof(P) <= sizeof(unsigned long long), "Unexpectedly large type");
using cast_target_type = typename
std::conditional<sizeof(P) <= sizeof(unsigned),
unsigned,
typename std::conditional<sizeof(P) <= sizeof(unsigned long),
unsigned long,
unsigned long long
>::type
>::type;
return log2_of_power_of_2<cast_target_type>(
static_cast<cast_target_type>(non_negative_power_of_2));
}
template <>
constexpr unsigned
log2_of_power_of_2<unsigned>(unsigned non_negative_power_of_2) noexcept
{ return __builtin_ctz (non_negative_power_of_2); }
template <>
constexpr unsigned long
log2_of_power_of_2<unsigned long>(unsigned long non_negative_power_of_2) noexcept
{ return __builtin_ctzl (non_negative_power_of_2); }
template <>
constexpr unsigned long long
log2_of_power_of_2<unsigned long long>(unsigned long long non_negative_power_of_2) noexcept
{ return __builtin_ctzll(non_negative_power_of_2); }
template <typename I, typename P>
constexpr I div_by_power_of_2(I dividend, P power_of_2_divisor) noexcept
{ return dividend >> log2_of_power_of_2(power_of_2_divisor); }
</code></pre>
<p>Questions:</p>
<ul>
<li>Is my approach to covering the possible types of power_of_2 appropriate? Can it perhaps be made less verbose but with the same effect?</li>
<li>Am I reinventing the wheel with this code?</li>
<li>Currently, this depends on certain compiler intrinsics available in GCC and clang but not necessarily elsewhere. I could generalize it a bit using <a href="https://stackoverflow.com/a/20468180/1593077">this method</a> to also support MSVC. Is there a better approach to generalizing the code?</li>
<li>Should I change the return type of <code>log2_of_power_of_2</code> functions to be uniform rather than <code>I</code>? e.g. an <code>unsigned</code>?</li>
<li>Any other comments/suggestions are welcome.</li>
</ul>
<p>Notes:</p>
<ul>
<li>This is intended to be C++11; obviously with C++17 I could simplify it further</li>
<li>The <code>constexpr</code> qualifier is not very meaningful, since in a constexpr context we could just do plain division, but I've tacked it on nonetheless. To make the use of these utility function(s) more uniform.</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:31:29.047",
"Id": "427840",
"Score": "0",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:34:02.413",
"Id": "427845",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ: But I didn't change my code; the edit was just a clarification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T23:47:13.520",
"Id": "427894",
"Score": "0",
"body": "I think this is a waste of time. The compiler is already smart enough to use the fastest method for division (if this is a shift left it will already do it). If your compiler is not using this optimization it obviously does not think it is worth it so why do you think you know better than the compiler. As the maintainer of the code I would not trust another human over the compiler and probably remove the hack above to let the compiler do its job."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T00:56:41.353",
"Id": "427898",
"Score": "1",
"body": "The edit in question was the addition of `#include <type_traits>` after it was mentioned in the answer. Please don't make such modifications after an answer has been posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T16:27:49.850",
"Id": "428016",
"Score": "0",
"body": "This question discussed on meta: https://codereview.meta.stackexchange.com/questions/9185/an-edit-of-mine-was-rolled-back-and-the-question-locked"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T16:40:24.773",
"Id": "428018",
"Score": "0",
"body": "@Martin, I think that compilers generally make that optimisation when dividing by a *constant*. I don't know whether any compilers can read `assert((q & q-1)==0); return p/q;` and use the assertion to optimise the division to a shift - perhaps you have better knowledge there?"
}
] | [
{
"body": "<p>The code is missing <code>#include <type_traits></code>; it would have been nice to have had the test cases too.</p>\n<p>It would be nice to be able to check the argument restriction using <code>assert</code>. Unfortunately, this doesn't fit nicely with C++11 <code>constexpr</code> functions, which may contain only a single <code>return</code> statement. If you might also compile against a newer standard, we could perhaps conditionally test it:</p>\n<pre><code>#include <cassert>\n\ntemplate <typename I, typename P>\nconstexpr I div_by_power_of_2(I dividend, P power_of_2_divisor) noexcept\n{\n#if __cplusplus >= 201402L\n assert((power_of_2_divisor & power_of_2_divisor - 1) == 0);\n#endif\n return dividend >> log2_of_power_of_2(power_of_2_divisor);\n}\n</code></pre>\n<p>I don't see why we have a template and specializations, rather than simple overloading of <code>log2_of_power_of_2</code>, particularly as we don't widen signed types to preserve sign.</p>\n<p>Contrary to your comment, the <code>constexpr</code> <em>is</em> valuable, as it allows this function to be called from within another <code>constexpr</code> function, whether or not that one is being called with constant arguments.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>static constexpr unsigned\nlog2_of_power_of_2(unsigned non_negative_power_of_2) noexcept\n{ return __builtin_ctz (non_negative_power_of_2); }\n\nstatic constexpr unsigned long\nlog2_of_power_of_2(unsigned long non_negative_power_of_2) noexcept\n{ return __builtin_ctzl (non_negative_power_of_2); }\n\nstatic constexpr unsigned long long\nlog2_of_power_of_2(unsigned long long non_negative_power_of_2) noexcept\n{ return __builtin_ctzll(non_negative_power_of_2); }\n\nstatic constexpr int\nlog2_of_power_of_2(int non_negative_power_of_2) noexcept\n{ return __builtin_ctz (non_negative_power_of_2); }\n\nstatic constexpr long\nlog2_of_power_of_2(long non_negative_power_of_2) noexcept\n{ return __builtin_ctzl (non_negative_power_of_2); }\n\nstatic constexpr long long\nlog2_of_power_of_2(long long non_negative_power_of_2) noexcept\n{ return __builtin_ctzll(non_negative_power_of_2); }\n\n\n#include <cassert>\n\ntemplate <typename I, typename P>\nconstexpr I div_by_power_of_2(I dividend, P power_of_2_divisor) noexcept\n{\n#if __cplusplus >= 201402L\n assert((power_of_2_divisor & power_of_2_divisor - 1) == 0);\n#endif\n return dividend >> log2_of_power_of_2(power_of_2_divisor);\n}\n</code></pre>\n\n<pre><code>#include <iostream>\nint main()\n{\n std::cout << div_by_power_of_2(15ul, 4) << '\\n';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:29:23.763",
"Id": "427837",
"Score": "0",
"body": "Also, would I, in this case, not also need to have implementations for char, unsigned char, short etc?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:39:18.783",
"Id": "427848",
"Score": "0",
"body": "Why would you want different implementations for narrower types, unless there are different intrinsics to use in them? Remember that overloads work with *best match* (unlike templates, which take *exact match*)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:43:10.897",
"Id": "427850",
"Score": "0",
"body": "@TobySpeight: To avoid the case of multiple overloads with the same priority"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T17:01:47.347",
"Id": "427856",
"Score": "0",
"body": "I'm still not sure what you mean - changing `15ul` to `(short)15` in my test program has no ambiguity (it promotes to `int`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T21:32:29.087",
"Id": "427880",
"Score": "0",
"body": "@TobySpeight: Hmm. Maybe I'm wrong about that. Anyway, +1 for your suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T13:10:11.663",
"Id": "427985",
"Score": "0",
"body": "The question [is being discussed on meta](https://codereview.meta.stackexchange.com/q/9185/120114)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:57:10.177",
"Id": "221280",
"ParentId": "221273",
"Score": "6"
}
},
{
"body": "<p>Moving to an answer:</p>\n\n<p>My knowledge on compilers is 20 years old. So I could be wrong. But a compiler can do a lot of the maths on const values (and now contexpr) at compile time (which is when all template code is also evaluated).</p>\n\n<p>I have seen compilers check to see if this was a division by 2 (or multiple of 2) and do shifts (if the shifts are actually faster on that platform (the compiler I worked on explicitly did this test as part of validation and did not plant the the shifts on the SOC chip we had)).</p>\n\n<p>I believe I have read (so this is more speculative) that the chips were baking in this optimization into the hardware circuitry. OK. The old chips did not do it like the Z80 and x86 but chip optimizations have come along way (and it has been a long time since I kept up with the trades but this is a simple hardware optimization).</p>\n\n<p><strong>BUT that is not my main issue</strong>. My issue is with programmer micro optimization. You are unlikely to beat the compiler, but you can. The Problem is that your optimization just locked you into a technique that the compiler probably can't optimize around and thus you are pesimizing your code in the long run.</p>\n\n<p>Over time compiler will improve (or your code will be moved to another architecture) because you have locked in one technique you are probably preventing the compiler from taking advantage of some new technique or hardware appropriate optimization.</p>\n\n<p>Compilers are extremly good at micro (peephole) optimization. Trying to beat the compiler is counterproductive in the long run. Compilers are very bad at algorithmic optimizations (humans are very good at this. So concentrate your optimizations at the algorithm level).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T17:24:18.410",
"Id": "428020",
"Score": "0",
"body": "Given that Z80 (and, I think, 6502) don't have hardware divide, it's unsurprising that they don't have the optimisation. ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T19:50:23.967",
"Id": "428043",
"Score": "0",
"body": "I'm only interested in _non-const_ values. Now, it's true that a compiler could check whether a division is by a power-of-2 and do shifts in that case, but that check has its cost; and I think it's unlikely compilers would want to do this. Now, you're right that programmer micro-optimization is a problem... but sometimes you write code specifically intended specifically for the \"tight-loop\", where micro-optimization is reasonable."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T17:21:54.850",
"Id": "221357",
"ParentId": "221273",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:24:11.803",
"Id": "221273",
"Score": "5",
"Tags": [
"c++",
"c++11",
"integer",
"bitwise"
],
"Title": "Templated division by a power of 2"
} | 221273 |
<p>I am reading a book call <em>Front end Web Development "The big nerd ranch guide"</em>, in which I came across a silver challenge:</p>
<blockquote>
<p>Go to your favorite search engine and search for "<code>anything</code>".</p>
<p>Open the DevTools to the console.</p>
<p>With the functions you wrote in this chapter as a reference, attach event listeners to all of the links and disable their default click functionality.</p>
</blockquote>
<p>Here's what I wrote:</p>
<pre><code>function selectLink() {
'use strict'
var links = document.querySelectorAll('a');
var linksArray = [].slice.call(links);
return linksArray;
}
function disableClick (dis) {
'user strict';
dis.addEventListener('click', function (event) {
event.preventDefault();
});
}
function click() {
'use strict';
var link = selectLink();
link.forEach(disableClick);
}
click();
</code></pre>
<p>I don't know whether this is the correct method to do it, since there is no solution on the book for it.</p>
<p>Can I do better?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:26:32.520",
"Id": "427835",
"Score": "0",
"body": "Sorry but we review code, the goal of this site isn't to explain how code works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:43:14.707",
"Id": "427851",
"Score": "0",
"body": "There is no correct way, if it works, then it works. You could just do `addEventListener(\"click\",e=>e.composedPath().some(el=>el.tagName==\"A\") && e.preventDefault());` Which checks to see if an anchor is involved via the global this. There are many more ways it can be done, which is correct who knows???"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:59:12.397",
"Id": "427960",
"Score": "2",
"body": "Mini review: I expect `'user strict'` is meant to be `'use strict'`."
}
] | [
{
"body": "<p>Refactoring is commonly seen as \"moving out repeating code into reusable functions\". But it can also easily mean \"moving code that's only ever used once back to where it's being used\". Although the book led you to writing individual functions, you don't have to split all this code up.</p>\n\n<p>Also, if you're just turning a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/NodeList\" rel=\"noreferrer\"><code>NodeList</code></a> into an array just to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"noreferrer\"><code>array.forEach()</code></a>, then this conversion is unnecessary. <code>NodeList</code> already comes with a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach\" rel=\"noreferrer\"><code>forEach</code></a> method (unless you still care about IE).</p>\n\n<p>Your code could be as short as:</p>\n\n<pre><code>document.querySelectorAll('a').forEach(link => {\n link.addEventListener('click', event => event.preventDefault())\n})\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:09:33.803",
"Id": "221282",
"ParentId": "221275",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "221282",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:26:09.067",
"Id": "221275",
"Score": "1",
"Tags": [
"javascript",
"html",
"html5"
],
"Title": "Console.log challenge change all of the links on a search results page so that they do not go anywhere?"
} | 221275 |
<p><strong>Note:</strong> Not a native English speaker.</p>
<p>I have attempted to make a class similar to vectors in c++ (Though, I now know that it's just a (doubly) linked list). Just wanna know, how good or efficient my program is, how well I am as a programmer. What about my coding style. Is it messy to read? constructive criticism is welcomed and appreciated.</p>
<pre><code>#include <iostream>
struct node
{
int num;
node* next = NULL;
node* prev = NULL;
};
class _vector
{
node *n1 = new node();
node *n = n1;
public:
void push_back(int num)
{
node* temp = new node();
this->n1->num = num;
this->n1->next = temp;
temp->prev = n1;
this->n1 = temp;
}
void pop_back()
{
n1 = n1->prev;
n1->next = NULL;
}
void display()
{
while(n->next != NULL)
{
std::cout<<n->num<<'\n';
n = n->next;
}
}
};
int main()
{
_vector v;
for(int i=0;i<100;i++)
v.push_back(i);
v.pop_back();
v.pop_back();
v.pop_back();
v.pop_back();
v.pop_back();
v.display();
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T21:17:04.677",
"Id": "427879",
"Score": "1",
"body": "I'd recommend reading through the countless linked-list posts on this site. You're bound to learn a lot from them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:43:07.583",
"Id": "427956",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Modifying the code after it has been reviewed may lead to multiple reviews of multiple versions of the same code in the same question. That gets terribly messy very fast. Feel free to post a follow-up question if you've improved your original code in a significant manner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T13:54:12.633",
"Id": "427987",
"Score": "0",
"body": "Okay thanks. I was not aware of that. But I made a very minor change. Everyone still be able to follow."
}
] | [
{
"body": "<p>If we continue with the idea that this is a doubly linked list rather than a vector, I'd say your <code>push_back</code> and <code>pop_back</code> are a good start. Your Struct is also perfect for the groundwork of a doubly linked list.</p>\n\n<p>However, on that note, you're missing a few operations for this data structure to be considered a proper doubly linked list.</p>\n\n<p>A doubly linked list should provide these operations (to the best of my memory):</p>\n\n<ul>\n<li>Insert (front/back/after index)</li>\n<li>Delete (front/back/at index)</li>\n<li>Traverse</li>\n</ul>\n\n<p>Currently you've only implemented insert and delete from the back. As for traversal, I could see <code>display</code> being a traversal in a sense, but I'd argue that displaying is not an operation strictly inherent to data structures. I would also like to point out that your current implementation of display would not allow you to traverse and display the list more than once.</p>\n\n<p>Overall though, I'd like to point out again that you have a very strong start. It's easy enough to provide alternative <code>push_front</code>, <code>push_after</code>, <code>pop_front</code>, and <code>pop</code> functions from what you have; and I'd recommend changing <code>display</code> to some sort of traversal method instead (maybe an iterator pattern) and move the displaying to your main function all together.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T22:01:46.387",
"Id": "427884",
"Score": "0",
"body": "Another alternative to `display` is an overloaded `operator<<` friend that allows the linked list to simply be fed to an output stream (e.g., `cout`)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T20:06:37.050",
"Id": "221302",
"ParentId": "221278",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:53:53.487",
"Id": "221278",
"Score": "3",
"Tags": [
"c++",
"linked-list"
],
"Title": "Double Linked List"
} | 221278 |
<p>A simple code which takes the given number as input and gives all of its prime factors raised to their respective powers...works well upto 10<sup>6</sup> after that it slows down greatly for some numbers..but works smoothly if the numbers don't have many prime factors</p>
<p>Here's the code:</p>
<pre><code>x=int(input("Enter number:"))
c=[] #load the exponential powers here
b=[] #load the primes here
i,k,f=0,0,2
l=100
def primes(i,n): #returns all primes between i and n
primes = []
for possiblePrime in range(i,n+1):
isPrime = True
for num in range(2, int(possiblePrime ** 0.5) + 1):
if possiblePrime % num == 0:
isPrime = False
break
if isPrime:
primes.append(possiblePrime)
return(primes)
while x!=1:
try:
while x%b[k]==0: #extract every prime from the number and store their resp exp powers
i+=1 #counts the power of the prime stored in b[k]
x=x//b[k] #Removes the prime number from the given number
k+=1
c.append(i)
i=0
except IndexError: #if list of primes are not enough...add more of them
b=b+primes(f,l)
l+=10000
print("Prime Numbers: ",[b[i] for i in range(len(c)) if c[i]!=0]) #prints the primes
c=[c[i] for i in range(len(c)) if c[i]!=0]
print("Respective Powers: ",c) #prints their respective powers
</code></pre>
<p><strong>Sample Output:</strong> (I just took a random number)</p>
<blockquote>
<p>Enter number: <code>23412</code><br>
Prime Numbers: <code>[2, 3, 1951]</code><br>
Respective Powers: <code>[2, 1, 1]</code></p>
</blockquote>
<p><strong>This means</strong> 23412 = 2<sup>2</sup> × 3<sup>1</sup> × 1951<sup>1</sup></p>
<p>Also, all optimizations and improvements or suggestions are welcome.</p>
| [] | [
{
"body": "<p>The problem with your prime generator is that you don't use the previously generated primes to check if a number is prime. The idea is that every non-prime number can be \"prime factorized\". Which also means that if a number can't be divided by the primes smaller than it, it's a prime number. For example, if you want to see if 13 is prime, you can check if it can be divided by <code>2,3,5,7,11</code> and since it can't be divided by any of those, it's prime. That's not a big improvement for small numbers, but for big numbers, it becomes a really good improvement since you already have those primes at hand. But for this to work, you need to generate primes from 2, not from <code>i</code>. It's also pretty standard that limits are exclusive when you pass integer intervals, so I've changed <code>n+1</code> to <code>n</code> in the range, but feel free to undo this.</p>\n\n<pre><code>def gen_primes(n):\n #Let's give us an head start.\n primes = [2]\n\n for possiblePrime in range(3,n): \n for p in primes:\n if possiblePrime % p == 0:\n primes.append(possiblePrime)\n\n return primes\n</code></pre>\n\n<p>Now, you could modify this algorithm to check for <code>[p for p in primes if p < n ** 0.5]</code>, but you'd need to check that this list isn't empty (for example if <code>n = 3</code> when <code>primes = [2]</code>) and add the prime to your list. If you decide to implement this, you could use a more suited algorithm to filter the primes because your array is always sorted, which opens nice possibilities. Finally, to make this algorithm even smarter, we could transform it into a generator using the <code>yield</code> keyword. This way, you maybe wouldn't need to generate all primes to <code>n</code> if it's not necessary.</p>\n\n<pre><code>def gen_primes(n):\n #Let's give us an head start.\n primes = [2]\n yield 2\n\n for possiblePrime in range(3,n): \n for p in primes:\n if possiblePrime % p == 0:\n primes.append(possiblePrime)\n yield possiblePrime\n</code></pre>\n\n<p>This way, for example, if you use <code>gen_primes(512)</code> to find the prime factorization of the number 512, you would only <code>yield 2</code> and not all other primes between 2 and 514 (because <span class=\"math-container\">\\$512 = 2^9\\$</span> That's a great improvement!</p>\n\n<p>The rest of your algorithm would change to something like this :</p>\n\n<pre><code>n = int(x ** 0.5)\nprime_factors = []\nprime_exponants = []\n\nfor prime in gen_primes(n):\n if x == 1:\n return\n\n e = 0\n while x % prime == 0:\n e += 1\n x /= prime\n\n if e > 0:\n prime_factors.append(prime)\n prime_exponants.append(e)\n</code></pre>\n\n<p>The main advantage of this is that you only generated the primes you need, no more, no less.</p>\n\n<p>Now let's talk coding style : The python standard is <code>snake_case</code>, you used <code>camelCase</code>. It's not the end of the world, but standards are important. At least you're consistent (you didn't mix styles), which in my opinion makes it okay.</p>\n\n<p>You use a lot of single letter variable names in your algorithm, it makes it harder to read. You shouldn't be shy to use meaningful names it's much easier for everyone (including yourself) to understand and debug the code.</p>\n\n<p>Last thing it that I think the order in which your code is is confusing. You have code -> functions -> code, I think it'd be clearer if you defined your functions at the top of your file (obviously, after <code>import</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T16:02:29.807",
"Id": "225726",
"ParentId": "221279",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "225726",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T15:54:41.330",
"Id": "221279",
"Score": "6",
"Tags": [
"python",
"performance",
"algorithm",
"primes"
],
"Title": "Decompose any number to its prime factors raised to their respective powers"
} | 221279 |
<p>I'm making my way through the <em><a href="https://rads.stackoverflow.com/amzn/click/com/0262519631" rel="nofollow noreferrer" rel="nofollow noreferrer">Intro to Computation and Programming</a></em> test by John Guttag and he gives these small exercises to practice gearing up into computational thinking. As of Ch.2, we've covered basic input and print commands as well as some simple iteration stuff. </p>
<p>The question is as follows: </p>
<blockquote>
<p>Write a piece of code that asks the user to input 10 integers, and
then prints the largest odd number that was entered. If no odd number
was entered, it should print a message to that effect.</p>
</blockquote>
<pre><code>counter = 0
ans = 0
even=0
while counter < 10:
x=int(raw_input('Please enter an integer: '))
if x%2!=0: #Checks if the input is odd
if ans < x: #If it is, is the input larger than the held value for 'ans'?
ans = x #If yes, replace the value for 'ans' with the input
counter +=1 #Move the counter up by one, ending at 10
else: #If it wasn't odd, add 1 to the even counter and to the integer counter, keeping ans the same
even+=1
counter+=1
if even == 10: #if all numbers entered were even, this counter would be 10, and thus would give this response
print 'All numbers were even'
else: #if at least 1 odd number was entered, the even counter would not be 10 and it would print the answer
print 'the largest odd number entered was ', ans
</code></pre>
<p>Is there a more efficient way of writing this out? I wonder if I can word my if statements to include more parameters to cut down on the number of <code>if/else</code> statements? Also keep in mind this text uses python 2.7 and that I'm not super far into the book. I'm mainly trying to get the whole computational thinking thing down. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:31:48.637",
"Id": "427842",
"Score": "0",
"body": "I have edited your tags. I'm not sure you really wanted to put machine-learning there because your question isn't related to it. If you feel like this edit wasn't good you can rollback it. Otherwise I think this is a great first question, congratulations and welcome to Code Review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:51:58.593",
"Id": "427855",
"Score": "0",
"body": "Thank you! I appreciate you looking out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T04:35:44.700",
"Id": "427907",
"Score": "2",
"body": "If you're just starting to learn Python now, I suggest learning Python 3. Python 2 is obsolete."
}
] | [
{
"body": "<p><strong>Python 2.x vs. Python 3.x</strong></p>\n\n<p>As a start, welcome to code review and since this is your first time here, well done, you did a good job here for a first post. One of the most confusing topics for beginner programmers is to choose which version of Python to learn. However there are more benefits to learn Python 3.x since it's the current version of Python and very soon there will be no future security or bug fixes for Python 2.x. and most of the developers nowadays are using Python 3.x, and as I'm familiar with the book you indicated, I know it's written in Python 2.x therefore I suggest you try to look things up and try to apply the same logic you encounter in exercises in Python 3.x (you will just be using a slightly different syntax).</p>\n\n<p>Besides Python 3.x contains a bunch of new features that you'll eventually start using:</p>\n\n<ul>\n<li>the print function</li>\n<li>f strings</li>\n<li>integer division</li>\n<li>and many other features</li>\n</ul>\n\n<p><strong>Style</strong></p>\n\n<p>Here's a reference style guide (pep8) <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a>, the official Python guide to style you could read and here are a few comments about style:</p>\n\n<ul>\n<li><p>If an assignment has a right hand side, then the equality sign should have exactly one space on both sides.</p>\n\n<p><code>even=0</code></p>\n\n<p><code>x=int(raw_input('Please enter an integer: '))</code></p>\n\n<p><code>if x%2!=0:</code></p></li>\n<li><p>Use inline comments sparingly.</p></li>\n<li>An inline comment is a comment on the same line as a statement.\nInline comments should be separated by at least two spaces from the\nstatement. They should start with a # and a single space.</li>\n<li>Use f-strings for better formatting.</li>\n</ul>\n\n<p>ex: <code>print(f'largest odd: {odd_num}')</code></p>\n\n<p><strong>The if elif else statements:</strong></p>\n\n<p>An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.</p>\n\n<p>The else statement is an optional statement and there could be at most only one else statement following if.</p>\n\n<p><strong>The use of functions and lists:</strong></p>\n\n<p>You can use functions in programming to bundle a set of instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a sub-program and called when needed. That means that a function is a piece of code written to carry out a specified task. To carry out that specific task, the function might or might not need multiple inputs. When the task is carried out, the function can or can not return one or more values.</p>\n\n<p>You can also use lists when you have more than a few items to do operations on.\nA list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ]</p>\n\n<p><strong>The code can be simplified as follows:</strong></p>\n\n<pre><code>def get_odd_max(n):\n \"\"\"Return maximum odd number from n numbers, print a message for no odds\"\"\"\n odds = []\n evens = []\n for _ in range(n):\n # the use of try and except to catch illegal types without stopping the code execution.\n try:\n number = int(input('Enter an integer: '))\n if number % 2 == 0:\n evens.append(number)\n if number % 2 != 0:\n odds.append(number)\n except ValueError:\n print('Expected int.')\n if odds:\n # f-strings for a cleaner code\n # usually a function does not print anything(it's for the sake of the example)\n print(f'Maximum odd value: {max(odds)}')\n return max(odds)\n else:\n print('No odds found.')\n return 0\n\n\nif __name__ == '__main__':\n print(get_odd_max(10))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T02:35:21.693",
"Id": "225629",
"ParentId": "221284",
"Score": "1"
}
},
{
"body": "<h2>Bug</h2>\n\n<p>If the user enters the values <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, <code>1</code>, ... they would expect the program to eventually stop asking me for input, but it won't. When the input is odd, the <code>counter</code> variable only increments when the value entered is larger than <code>ans</code>. The increment statement should be outdented one level, so it executes even when an odd number is not greater than <code>ans</code>:</p>\n\n<pre><code> if x%2!=0:\n if ans < x:\n ans = x\n counter +=1 # <-- outdented to level of \"x%2 != 0\" test\n else:\n even+=1\n counter+=1\n</code></pre>\n\n<h2>DRY: Don't Repeat Yourself</h2>\n\n<p>In contrast to WET (Write Everything Twice).</p>\n\n<p>You have two <code>counter += 1</code> statements, one in each path of the <code>if ... else</code> statement. Since you are counting up by one in both paths, this code should be moved out of the <code>if ... else</code> statement, so it can be written just once:</p>\n\n<pre><code> if x%2!=0:\n if ans < x:\n ans = x\n else:\n even+=1\n\n counter += 1 # Executed regardless of which branch of if/else is taken.\n</code></pre>\n\n<hr>\n\n<p>In programming, there are 3 kinds of numbers: zero, one, and many. Zero and one are generally fine when written as constants through-out a program. \"Many\" is an exception; you don't want to write it more than once.</p>\n\n<p>If you are asked to change the program to allow up to 20 integer to be input, you would have to change two statements: <code>while counter < 10:</code> and <code>if even == 10:</code>. This is frowned up on; when you have more than one, it is easy to miss one. One approach is to create a constant for each different kind of \"many\" value:</p>\n\n<pre><code>LIMIT = 10\n# ...\n\nwhile count < LIMIT:\n # ...\n\nif even == LIMIT:\n # ...\nelse:\n # ...\n</code></pre>\n\n<p>Now, you just have to change the <code>LIMIT = 10</code> statement if you want to change the number of values to be input.</p>\n\n<p>But there is another way. Instead of checking if all the values were even (<code>even == LIMIT</code>), we could count the number of odd values:</p>\n\n<pre><code>counter = 0\nans = 0\nodd = 0\nwhile counter < 10:\n x = int(raw_input('Please enter an integer: '))\n if x % 2 != 0: \n if ans < x:\n ans = x\n odd += 1\n counter += 1\n\nif odd > 0:\n print 'the largest odd number entered was ', ans\nelse:\n print 'All numbers were even'\n</code></pre>\n\n<p>Now we are counting the number of odd values, and the test at the end checks if any odd numbers were given. And \"any odd numbers\" simply means the count of odd numbers is greater than zero ... which is an \"ok\" constant to write directly into the code.</p>\n\n<h2>Sentinels</h2>\n\n<p>We still may have a bug. If the user enters <code>-3</code>, <code>2</code>, <code>-5</code>, <code>4</code>, <code>6</code>, <code>-7</code>, <code>-8</code>, <code>4</code>, <code>-10</code>, <code>-8</code>, the program will reply:</p>\n\n<blockquote>\n <p>the largest odd number entered was 0</p>\n</blockquote>\n\n<ol>\n<li><code>0</code> isn't \"odd\".</li>\n<li>We never entered the value <code>0</code>.</li>\n</ol>\n\n<p>The problem here stems from initializing <code>ans = 0</code>, and hoping that some odd value will be larger than that value, so it will be overwritten.</p>\n\n<p>A better approach is to initialize <code>ans</code> to a sentinel value, and when the first odd value is encountered, update <code>ans</code> to that value instead of checking whether the first odd value is larger than <code>ans</code>. Actually, <code>0</code> is a perfectly fine sentinel value, when looking for an odd value, but <code>None</code> is a more common value:</p>\n\n<pre><code>counter = 0\nans = None # Sentinel value\nwhile counter < 10:\n x = int(raw_input('Please enter an integer: '))\n if x % 2 != 0: \n if ans is None or ans < x: # Check now includes sentinel value\n ans = x\n counter += 1\n\nif ans is not None:\n print 'the largest odd number entered was ', ans\nelse:\n print 'All numbers were even'\n</code></pre>\n\n<p>Note that the sentinel value performs double duty. If <code>ans</code> is still the sentinel value at the end of the loop, then no odd values were found. The <code>odd</code> count is unnecessary and has been eliminated.</p>\n\n<p>Alternatively, you could initialize <code>ans</code> to a value smaller than any value the user could possibly enter. Unfortunately, Python's integer range is not bounded, so they could enter any arbitrarily large negative integer. However, we're not limited to integers, so we could initialize <code>ans = float(\"-inf\")</code>. Any integer the user enters will be greater than that, so the sentinel would not need to be checked inside the loop. The test at the end could use <code>if not math.isinf(ans):</code> to detect if any odd values were entered.</p>\n\n<h2>Loop Like a Native</h2>\n\n<p>The expression \"Loop Like a Native\" comes from a <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">PyCon 2013 presentation</a>, which contains advance topics, like generators. Caution: sharp learning curve ahead if you follow that link.</p>\n\n<p>But Python developers rarely write <code>while</code> loops with counters to loop a fixed number of times; they use a <code>for</code> loop.</p>\n\n<pre><code>ans = None\nfor _ in range(10):\n x = int(raw_input('Please enter an integer: '))\n if x % 2 != 0: \n if ans is None or ans < x:\n ans = x\n\nif ans is not None:\n print 'the largest odd number entered was ', ans\nelse:\n print 'All numbers were even'\n</code></pre>\n\n<h2>Minutiae</h2>\n\n<ul>\n<li>Python2.x's <a href=\"https://www.python.org/dev/peps/pep-0373/\" rel=\"nofollow noreferrer\">End Of Life</a> (EOL) is January 1, 2020. If it is not a job/class requirement to study Python 2.x, you should learn Python 3.x</li>\n<li>Follow the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> style guide when writing Python. There are many tool to help you check compliance, such as PyLint, PyChecker, PyFlakes to name a few.</li>\n<li><code>ans</code> is not a good variable name; it suggests \"answer\", but answer to what? <code>greatest_odd_value</code> is much more descriptive, but perhaps too verbose. <code>odd_max</code> would be a good balance between brevity and descriptiveness.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T16:29:35.983",
"Id": "225660",
"ParentId": "221284",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T16:20:51.157",
"Id": "221284",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-2.x"
],
"Title": "Guttag's Finger Exercises: Enter 10 integers, find largest odd integer and print result"
} | 221284 |
<p>This my solution to this <a href="https://www.careercup.com/question?id=5712067743449088" rel="nofollow noreferrer">Good Range Coding Challenge</a></p>
<blockquote>
<p>There is a number space given from 1 to N. And there are M queries followed by that. In each query, we were given a number between 1 to N (both inclusive). We add these number one by one into a set.</p>
<p>Good range: A range in which there is exactly one element present from the set.</p>
<p>For each query, we need to find the good ranges. We need to return the sum of boundry of all good ranges.</p>
<p>Input:</p>
<p>First line will take two integer for input N and M.
Then following m lines would be numbers between 1 and N (both inclusive).</p>
<p>Output:</p>
<p>Following M lines contains sum of boudaries of good ranges.</p>
<p>Note:</p>
<p>Range can consist of single element and represented as (x-x) where boundary sum will be x+x.</p>
<p>Example:</p>
<p>Input:</p>
</blockquote>
<pre><code>10 4
2
5
7
9
</code></pre>
<blockquote>
<p>Output:</p>
</blockquote>
<pre><code>11
18
30
46
</code></pre>
<blockquote>
<p>Explaination:</p>
</blockquote>
<pre><code>step-1) set: 2
good range: (1-10)
sum: 1+10=11
step-2) set: 2 5
good range: (1-4), (3-10)
sum: 1+4+3+10=18
step-3) set: 2 5 7
good range: (1-4), (3-6), (6-10)
sum: 1+4+3+6+6+10=30
step-4) set: 2 5 7 9
good range: (1-4), (3-6), (6-8), (8-10)
sum: 1+4+3+6+6+8+8+10=46
</code></pre>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <set>
using namespace std;
class Solution
{
public:
Solution(const unsigned int _N, const unsigned int _M) : N(_N), M(_M) {}
void solve()
{
for(unsigned int i=0; i<M; ++i)
{
unsigned int v;
cin >> v;
cout << "New Element = " << v << endl;
q.insert(v);
print_res();
cout << endl;
}
}
void print_res()
{
unsigned int left=1;
auto it=q.begin();
unsigned int last = *it;
for(++it; it!=q.end(); ++it)
{
const unsigned int curr = *it;
const unsigned int right = curr-1;
cout << "[" << left << ", "<< right << "] contains " << last << " and sum = " << (left+right) << endl;
left = last+1;
last = curr;
}
const unsigned right = N;
cout << "[" << left << ", "<< right << "] contains " << last << " and sum = " << (left+right) << endl;
}
private:
unsigned int N;
unsigned int M;
set<unsigned int> q;
};
int main() {
// your code goes here
unsigned int N=0;
unsigned int M=0;
cin >> N >> M;
Solution sol(N,M);
sol.solve();
return 0;
}
</code></pre>
<p><strong>Note</strong>: I am aware I'm returning more information than required by the problem description but I have chosen to do it to include also debugging information</p>
| [] | [
{
"body": "<p>No comments on the algorithm itself. But I have many style improvements a interviewer probably looks for.</p>\n\n<pre><code>int main() {\n ...\n return 0;\n}\n</code></pre>\n\n<p>Unlike in C the statement <code>return 0</code> is automatically generated for <code>main</code>. So its common to omit it.</p>\n\n<p>then this line in the main is problematic as well:</p>\n\n<pre><code>unsigned int N = 0;\nunsigned int M = 0;\ncin >> N >> M;\n</code></pre>\n\n<p>You expect you get an unsigned integer from the input. But who says the user types it?</p>\n\n<p>You should better read in as <code>std::string</code> and convert the result to integer after if possible:</p>\n\n<pre><code>for (;;) {\n std::string input;\n std::cin >> input;\n\n if (is_convertible_to_integer(input)) { // write a function to check if is convertible to unsigned int\n // convert to int\n break;\n }\n}\n</code></pre>\n\n<p>This can be probably in a function as well like <code>unsigned int read_unsigend_int();</code></p>\n\n<p>Then a classic mistake in C++. Don't use <code>using namespace std</code>. It is not a good habit. Read about it here: <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice</a>.</p>\n\n<p>The next thing I wonder. Do you really need unsigned int? Often it is not worth the hassle. It can introduce hard to spot errors: <a href=\"https://stackoverflow.com/questions/22587451/c-c-use-of-int-or-unsigned-int\">https://stackoverflow.com/questions/22587451/c-c-use-of-int-or-unsigned-int</a></p>\n\n<p>Then you create a class just for solving basically some computations. In this case I think its over-engineering. It could be simply solved by using free standing functions.\nUnlike in some other Programming languages where everything is a class you can just use free standing functions.</p>\n\n<p>However it is a good idea to wrap your functions and classes in its own namespace to prevent name clashes. So do something like:</p>\n\n<pre><code>namespace good_range {\n\n // youre functions and classes\n}\n</code></pre>\n\n<p>Another small thing:</p>\n\n<pre><code>Solution(const unsigned int _N, const unsigned int _M) : N(_N), M(_M) {}\n</code></pre>\n\n<p>No need to use const here since you have the values by value copied anyway.</p>\n\n<p>Also you should not use <code>std::endl</code> for a newline. I even saw it in many wrong books. <code>std::endl</code> gives you a newline and an expensive flushing operation of the buffer. Instead just use <code>\\n</code>.</p>\n\n<p>A opinion based thing. This line:</p>\n\n<pre><code> cout << \"[\" << left << \", \" << right << \"] contains \" << last << \" and sum = \" << (left + right) << endl;\n</code></pre>\n\n<p>I would split it into two:</p>\n\n<pre><code> cout << \"[\" << left << \", \" << right << \"] contains \" << last \n << \" and sum = \" << (left + right) << endl;\n</code></pre>\n\n<p>why? It is easier to read and you have the option to open two source files on one screen next to each other. I personally stick usually with 80 spaces per line. But some people user 100 or 120. To see a discussion about it:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/276022/line-width-formatting-standard\">https://stackoverflow.com/questions/276022/line-width-formatting-standard</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T18:18:41.910",
"Id": "427865",
"Score": "0",
"body": "Thanks for your feedback \nI appreciate all the comments make sense but let me say here my focus was on solving the algorithmic challenge so I have not paid much attention to good practices"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T18:33:45.697",
"Id": "427868",
"Score": "1",
"body": "im sorry i don't have the time at the moment to check the algorithm. But I still wanted to contribute the style stuff I could spot right away. I think is alway important to write a good style. It shows youre professionalism."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T19:03:44.483",
"Id": "427871",
"Score": "2",
"body": "@NicolaBernini Hint: do not compute the sum from scratch every time; each insertion affects at most two ranges, and the sum can be updated in a constant time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T02:28:53.543",
"Id": "427901",
"Score": "0",
"body": "I disagree that omitting the `return` is \"common\" in C++. Sure, it happens, and it's something to be aware of, but I certainly wouldn't think anything of an interview candidate who included it. I write it myself, and I think it's excellent for clarity. Personally, though, I prefer `return EXIT_SUCCESS` if that's what you actually mean (or, conversely, `return EXIT_FAILURE`) from `<cstdlib>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:16:08.600",
"Id": "427951",
"Score": "0",
"body": "@NicolaBernini Definitely you should pay attention to good practices. They are no less important than algorithms."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T18:12:14.560",
"Id": "221294",
"ParentId": "221289",
"Score": "5"
}
},
{
"body": "<ol>\n<li><p>Don't force a <code>class</code> where a function is perfectly fine.</p></li>\n<li><p>The namespace <code>std</code> is not designed for wholesale importation, see \"<em><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std” considered bad practice?</a></em>\" for more detail.</p></li>\n<li><p><a href=\"https://en.cppreference.com/w/cpp/language/identifiers\" rel=\"nofollow noreferrer\">Identifiers starting with an underscore followed by an uppercase letter are reserved.</a></p></li>\n<li><p>Input is generally unreliable. But you don't test for error at all.</p></li>\n<li><p>Always recomputing the current result from first principles, instead of just updating it with the newest addition, is a waste of time.</p></li>\n<li><p>Flushing is expensive, so avoid <code>std::endl</code> and explicitly request it with <code>std::flush</code> where unavoidable.</p></li>\n<li><p>You should probably follow the requested output-format...</p></li>\n<li><p>You know that <code>int</code> in <code>unsigned int</code> is implicit?</p></li>\n<li><p>In C++ and C99+, <code>return 0;</code> is implicit for <code>main()</code>.</p></li>\n<li><p>I wonder why you sometimes surround binary operators with space, and sometimes don't.</p></li>\n<li><p>Having over-long lines is very cumbersome to read. Admittedly, you need not make a hard cut at 79 nowadays.</p></li>\n<li><p>You should double-check whether duplicate inputs can occurr (there are none in the example), and if so whether they should cause anything but repeated output.<br>\nI assumed duplicated possible, and they only cause output.</p>\n\n<ul>\n<li>Duplicates have an effect would destroy ranges instead of adding them, thus needing an ordered <code>std::set</code>.</li>\n<li>Duplicates not possible would mean the <code>std::unordered_set</code> can be dispensed with.</li>\n</ul></li>\n</ol>\n\n<pre><code>#include <cstdlib>\n#include <iostream>\n#include <unordered_set>\n\nint main() {\n unsigned n, m, x;\n std::cin >> n >> m;\n if (!std::cin || !n) {\n std::cerr << \"Bad Input!\\n\";\n return EXIT_FAILURE;\n }\n std::unordered_set<unsigned> nums;\n auto r = 0ULL;\n while (--m) {\n std::cin >> x;\n if (!std::cin || x < 1 || x > n) {\n std::cerr << \"Bad Input!\\n\";\n return EXIT_FAILURE;\n }\n auto [iter, created] = nums.insert(x);\n if (created)\n r += 2 * x;\n std::cout << r << '\\n';\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T05:40:22.963",
"Id": "427918",
"Score": "1",
"body": "13) As set is not unordered_set, it keeps the keys ordered while iterating over its content (not implemented with hash but with tree)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T05:42:46.760",
"Id": "427919",
"Score": "1",
"body": "4) As it is an algorithmic interview question the goal is on the algo (implementation, complexity, ...) so reasonable assumptions on the input are typically used in order to avoid a bunch of trivial sanity checks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T05:44:41.433",
"Id": "427920",
"Score": "1",
"body": "2) I know this but as it is an algorithmic interview question I simply wanted to avoid a bunch of std::aaa (saves time typing)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T08:48:11.430",
"Id": "427931",
"Score": "1",
"body": "re 2+4: As a matter of course, you should at least mention that you left did so and why, unless you want to be marked down. re 13: It was about whether the algorithm can be drastically simplified, but considering the algorithm too restrictively formulated. Folded into 12 and reformulated to ask only what is relevant. No idea why I didn't switch to a `std::unordered_set` after I had the best algorithm figured out..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T19:33:12.977",
"Id": "221301",
"ParentId": "221289",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T17:29:25.840",
"Id": "221289",
"Score": "6",
"Tags": [
"c++",
"programming-challenge",
"interval"
],
"Title": "Coding Challenge Solution - Good Range"
} | 221289 |
<p><strong>Explaining the idea and first steps</strong></p>
<p>Today, I had the idea to do a website which displays my current position. I searched in the App Store for an App and found <a href="https://itunes.apple.com/de/app/sendlocation/id377724446?mt=8" rel="nofollow noreferrer">one</a> named <a href="https://itunes.apple.com/de/app/sendlocation/id377724446?mt=8" rel="nofollow noreferrer">SendLocation</a>. This App provides an interface for sending <code>GET</code> requests to an server with some geometrical data. This is how the data gets send:</p>
<pre><code>http://yourserver.com/yourscript.php?lat=***&lon=***&speed=***&heading=***&vacc=***&hacc=***&altitude=***&deviceid=**&battery=***&ts=***&quick=***&background=***
</code></pre>
<p><strong>File Structure</strong></p>
<pre><code>./location.php
./data.json
./index.html
</code></pre>
<p><strong>Writing the server side script</strong></p>
<p>After setting the app up and achieving the connection, I wrote an php script to get the data and store it into an <code>JSON</code> file to use it for example on a website. I don't want to set up a database for this and want to have this in an accessible file, so storing it in a <code>.json</code> file was totally easy and fast.</p>
<pre class="lang-php prettyprint-override"><code><?php
if (file_exists('data.json')) {
$current_data = file_get_contents('data.json');
$array_data = json_decode($current_data, true);
$formdata = array(
'lat' => $_GET['lat'],
'lon' => $_GET['lon'],
'speed' => $_GET['speed'],
'heading' => $_GET['heading'],
);
$array_data[] = $formdata;
$final_data = json_encode($array_data);
if (file_put_contents('data.json', $final_data)) {
echo 'Data saved successfully';
}
} else {
echo 'JSON File not exits';
}
</code></pre>
<p><strong>Access the data from the frontend</strong></p>
<p>I am going on with parsing the <code>.json</code> file and get the data of the last entry which is my current likely position. After, with the <code>lat</code> and <code>lon</code>, I do a Google Maps API call and get my real name position and log it to the console (yet).</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>This is my location</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
$.getJSON("data.json").then(function (json) {
// get latest position
var lastElement = json[json.length - 1];
// extract coordinates from position
var lat = lastElement.lat;
var lon = lastElement.lon;
console.log(lat);
// get name of coordinates
getAddress(lat, lon);
// get adress from google
function getAddress(latitude, longitude) {
var key = "api-key-goes-here";
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," +
longitude + "&key=" + key,
function (json) {
console.log(json);
console.log(json.results[9].formatted_address);
});
}
});
});
</script>
</body>
</html>
</code></pre>
<p><strong>Screenshots of console output</strong></p>
<p><a href="https://i.stack.imgur.com/or9Uw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/or9Uw.png" alt="screenshot of console"></a></p>
<p><strong>My questions</strong></p>
<ol>
<li>How can I hide the API key of the Google Map service to make it more secure?</li>
<li>Which improvements can be made to make the <code>GET</code> writing the <code>.json</code> more safe? I though about limit the writing to 3 a day or similar.</li>
<li>How can I hide the <code>data.json</code> from Google or normal visitors of my page, that only my code can access the file, is this even possible?</li>
<li>What can I do to make the JS faster and maybe more secure?</li>
<li>What else can be done? </li>
</ol>
<p><strong>Any feedback really appreciated.</strong></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T06:55:37.113",
"Id": "428498",
"Score": "0",
"body": "To the close voters: this is not a feature request. This is a request for review with specific questions because the OP has thought well enough ahead and acknowledges the issues the code currently has."
}
] | [
{
"body": "<ol>\n<li><p>One thing you can do to secure your Google API key is to make the whole request to Google Map API on the server. So, instead of having a call from the frontend to Google API, you create a new <code>GET</code> request on the server that just wraps the call to Google API. And then, from your website, just make a request to your server instead to Google API.</p></li>\n<li><p>If by <em>safe</em> you mean \"I want <strong>every</strong> request to be written in the file and not to lose any data because of parallel requests\", then you need some sort of locking mechanism. I'm not a PHP developer, and I'm not sure what's the best way to achieve this. A quick search on the internet for <em>PHP lock</em> resulted in <a href=\"https://stackoverflow.com/questions/325806/best-way-to-obtain-a-lock-in-php\">this</a> and <a href=\"https://github.com/php-lock/lock\" rel=\"nofollow noreferrer\">this</a>. So once you have some way of locking, you just need to surround your the <code>true</code> part of your condition with the locking mechanism.</p></li>\n<li><p>You can do so by configuring your web server. If you're using Apache, then you can take a look at <a href=\"https://stackoverflow.com/questions/2679524/block-direct-access-to-a-file-over-http-but-allow-php-script-access\">this SO question</a>.</p></li>\n<li><p>I don't see any problem with your JS. You are using JQuery for making requests to the server and I guess this is fine. If you would to query for some HTML element, then I think that native APIs outperform JQuery, so that would be a thing to take into consideration. Maybe consider using native <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\" rel=\"nofollow noreferrer\">Fetch API</a> if you use JQuery only for the server call. This will only speed up the page load time, since the browser won't need to load the remote library.</p></li>\n<li><p>I don't have anything else to add.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T19:13:25.313",
"Id": "427875",
"Score": "0",
"body": "thank you very much, the help is really appreciated. maybe there are some other answers and I leave this answer for now with not marking it as the accepted one. will do that if there are no other answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T19:14:25.447",
"Id": "427876",
"Score": "1",
"body": "I'm not here for the \"most accepted answers\", I'm here to spread the knowledge, so no worries :) Glad you find it helpful."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T19:08:47.747",
"Id": "221297",
"ParentId": "221292",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221297",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T18:07:45.413",
"Id": "221292",
"Score": "1",
"Tags": [
"javascript",
"php",
"ios",
"google-maps"
],
"Title": "App sends location data to website"
} | 221292 |
<p>I'm trying to learn javascript (especially the OOP part) and made this simple game. I'm looking for advice and ways to improve my code. </p>
<ul>
<li>Did I handle OOP well enough?</li>
<li>What's the best way to create a new object of a given class (<code>object.assign</code>, new <code>Object()</code> etc)? There are a lot of them</li>
<li>Which variables should be named using only uppercase letters</li>
<li>Did I make a mistake by defining variables like <code>score</code> globaly?</li>
<li><code>foodEaten() {
score++;
food = new Food();
}</code>
Is it a good way to override an object? How can I do this using "this" keyword?</li>
<li>Should I stick to <code>window.requestAnimationFrame(gameLoop);</code> or just use the function with given interval?</li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');
let score, food, player, board;
class Board {
constructor(width, height, backgroundColor) {
this.height = height;
this.width = width;
this.backgroundColor = backgroundColor;
}
drawBoard(score) {
ctx.clearRect(0, 0, this.width, this.height) //clears board
ctx.fillStyle = this.backgroundColor; //sets background color
ctx.fillRect(0, 0, this.width, this.height); //background
ctx.font = "30px Arial";
ctx.fillStyle = "red";
ctx.fillText(score, 10, 30);
}
}
class Player {
constructor(positionx, positiony, size, color, dx, dy) {
this.x = positionx;
this.y = positiony;
this.size = size;
this.color = color;
this.dx = dx;
this.dy = dy;
}
playerMove() {
this.x += this.dx;
this.y += this.dy;
}
drawPlayer() {
ctx.strokeStyle = this.color;
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.size, this.size);
ctx.stroke();
}
checkCollision() {
this.x + this.size > canvas.width || this.x < 0 ||
this.y + this.size > canvas.height || this.y < 0 ?
newGame() : null;
}
changeDirection(direction) {
switch (direction) {
case 1: //up
this.dx = 0;
this.dy = -2;
break;
case 2: //left
this.dx = -2;
this.dy = 0;
break;
case 3: //down
this.dx = 0;
this.dy = 2;
break;
case 0: //right
this.dx = 2;
this.dy = 0;
break;
}
}
checkCollisionFood(food) {
(food.x > this.x - food.size && food.x < this.x + this.size) &&
(food.y > this.y - food.size && food.y < this.y + this.size)
? food.foodEaten() : null
}
}
class Food {
constructor() {
this.size = 20;
this.x = Math.floor(Math.random() * (canvas.width - this.size + 1));
this.y = Math.floor(Math.random() * (canvas.height - this.size + 1));
this.color = "red";
}
drawFood() {
ctx.strokeStyle = this.color;
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.size, this.size);
ctx.stroke();
}
foodEaten() {
score++;
food = new Food();
}
}
function gameLoop() {
board.drawBoard(score);
player.drawPlayer();
player.playerMove();
player.checkCollision();
player.checkCollisionFood(food);
food.drawFood();
window.requestAnimationFrame(gameLoop);
}
newGame();
window.requestAnimationFrame(gameLoop);
function newGame() {
score = 0;
food = new Food();
player = new Player(40, 40, 40, "blue", 0, 0);
board = new Board(c.width, c.height, "green");
}
document.addEventListener('keydown', (event) => {
switch (event.keyCode) {
case 87: //"w" key
player.changeDirection(1);
break;
case 83: //"s" key
player.changeDirection(3);
break;
case 68: //"d" key
player.changeDirection(0);
break;
case 65: //"a" key
player.changeDirection(2);
break;
default:
break;
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>canvas</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<canvas id="c" width="300px" height="400px">
</body>
<script src="main.js"></script>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>Thanks for the specific questions. It really helps guide feedback.</p>\n\n<blockquote>\n <p>Did I handle OOP well enough?</p>\n</blockquote>\n\n<p>This seems pretty good, although a little more thinking about the \"responsibilities\" of a class will help.</p>\n\n<blockquote>\n <p>What's the best way to create a new object of a given class (object.assign, new Object() etc)? There are a lot of them</p>\n</blockquote>\n\n<p><code>new Foo()</code> is the standard way.</p>\n\n<blockquote>\n <p>Which variables should be named using only uppercase letters</p>\n</blockquote>\n\n<p>Usually just constants, which include class names.</p>\n\n<blockquote>\n <p>Did I make a mistake by defining variables like score globaly?</p>\n</blockquote>\n\n<p>Yes, generally it's good to avoid globals.</p>\n\n<blockquote>\n <p><code>foodEaten() {</code> ... Is it a good way to override an object? How can I do this using \"this\" keyword?</p>\n</blockquote>\n\n<p>You need to step back and look at the design a little bit. Some fn/object/class should be responsible for keeping track of the food, and therefore it would \"own\" the <code>food</code> variable (as <code>this.food</code>). It would be responsible for creating the original food and replenishing as needed after <code>foodEaten</code> is called. You can sometimes figure this out by passing the variables into where they are needed until you get to the code that can simply define a local variable... and sometimes it takes a little more refactoring.</p>\n\n<blockquote>\n <p>Should I stick to window.requestAnimationFrame(gameLoop); or just use the function with given interval?</p>\n</blockquote>\n\n<p>These are basically the same, and probably not worth fretting about. There does probably need some sort of event loop that has locally scoped variables for the game and perhaps food... that's how you would refactor out the global variables. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T20:52:11.233",
"Id": "221505",
"ParentId": "221296",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T18:54:32.737",
"Id": "221296",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"object-oriented",
"canvas",
"snake-game"
],
"Title": "JS Simple game in canvas"
} | 221296 |
<p>This code uses the <a href="https://www.geeksforgeeks.org/rabin-karp-algorithm-for-pattern-searching/" rel="nofollow noreferrer">Rabin-Karp</a> algorithm to compare two text files. It takes a few minutes when both files contain around 1000 words. How can it be improved?</p>
<pre><code>class RollingHash:
def __init__(self, text, sizeWord):
self.text = text
self.hash = 0
self.sizeWord = sizeWord
for i in range(0, sizeWord):
#subtract out the ASCII value of "a" to start the indexing at zero
self.hash += (ord(self.text[i]) - ord("a")+1)*(26**(sizeWord - i -1))
#start index of current window
self.window_start = 0
#end of index window
self.window_end = sizeWord
def move_window(self):
if self.window_end <= len(self.text) - 1:
self.hash -= (ord(self.text[self.window_start]) - ord("a")+1)*26**(self.sizeWord-1)
self.hash *= 26
self.hash += ord(self.text[self.window_end])- ord("a")+1
self.window_start += 1
self.window_end += 1
def window_text(self):
return self.text[self.window_start:self.window_end]
def rabin_karp(word, text):
if word == "" or text == "":
return None
if len(word) > len(text):
return None
rolling_hash = RollingHash(text, len(word))
word_hash = RollingHash(word, len(word))
word_hash.move_window()
for i in range(len(text) - len(word) + 1):
if rolling_hash.hash == word_hash.hash:
if rolling_hash.window_text() == word:
return i
rolling_hash.move_window()
return None
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T23:30:04.823",
"Id": "427897",
"Score": "0",
"body": "It is not Rabin-Karp but longest common substring what you need, look it in https://www.geeksforgeeks.org/longest-common-substring-dp-29/ And your implementation is realy messy. Look in https://www.geeksforgeeks.org/rabin-karp-algorithm-for-pattern-searching/ And afaik (sorry it was long time ago) Rabin-Karp is not the best for substring search, google for suffix trees."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T04:35:36.947",
"Id": "427906",
"Score": "0",
"body": "@user8426627 My assignment required me to solve using Rabin-Karp. After using the code from geeksforgeeks.org/rabin-karp-algorithm-for-pattern-searching that you had mentioned above, the compile time reduce from 1m51sec to 44sec. Is it possible to modify the code to reduce more the compile time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T05:56:10.500",
"Id": "427921",
"Score": "1",
"body": "\"This code uses the Rabin-Karp algorithm to compare two text files.\" No, it does not -- I suppose you use this code as part of a solution that compares files. Posting the whole program and some data for testing might be a good idea."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T17:55:26.223",
"Id": "221298",
"Score": "5",
"Tags": [
"python",
"beginner",
"algorithm",
"strings",
"search"
],
"Title": "Rabin-Karp algorithm implementation"
} | 221298 |
<p>Given the following two interfaces what would the proper way to set up the two actual classes?</p>
<pre><code>public interface IPortfolio
{
string FirstName { get; set; }
string LastName { get; set; }
string Name { get; set; }
int Id { get; set; }
List<IDocument> Documents { get; set; }
}
public interface IDocument
{
string ExtensionType { get; set; }
int Id { get; set; }
DateTime? DateFiled { get; set; }
int? Size { get; set; }
int? SortOrder { get; set; }
}
</code></pre>
<p>The actual classes:</p>
<pre><code> public class Portfolio : IPortfolio
{
public Portfolio()
{
Documents = new List<IDocument>();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Name { get; set; }
public int Id { get; set; }
public List<IDocument> Documents { get; set; }
}
public class Document : IDocument
{
public Document()
{
Pages = new List<IPage>();
}
public string ExtensionType { get; set; }
public int Id { get; set; }
public DateTime? DateFiled { get; set; }
public int? Size { get; set; }
public List<IPage> Pages { get; set; }
public int? SortOrder { get; set; }
}
</code></pre>
<p>When using the code above I get an error about not being able to implicitly convert <em><code>List<Document> to List<IDocument></code></em></p>
<p>This is a learning project to understand the concept of Interfaces and how they should best be used.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T22:41:49.560",
"Id": "427889",
"Score": "2",
"body": "It sounds like you plan to create only one implementation per interface. If that's the case, then what's the reason for having those interfaces?"
}
] | [
{
"body": "<p>There no such thing like an interface class (term used in initial version of post). You have interfaces and classes implementing the interfaces.</p>\n\n<p>I don't see any <code>List<Document></code> in your code, but If you have defined the list as <code>List<IDocument></code>, you must stick to this definition. You cannot assign it a <code>List<Document></code>. But you can add <code>Document</code> objects to this list.</p>\n\n<p>Generally two types <code>T<A></code> and <code>T<B></code> are not assignment compatible, even if <code>A</code> and <code>B</code> are assignment compatible. An exception is when the <code>in</code> or <code>out</code> keywords are used in generic interfaces. But this can only be done if the generic type occurs exclusively as input or exclusively as output as explained in <a href=\"https://www.codeproject.com/Articles/86419/Variance-in-C-NET-4-0-Covariance-and-Contravarianc\" rel=\"nofollow noreferrer\">Variance in C#.NET 4.0 Covariance and Contravariance</a>.</p>\n\n<p>I would convert the list properties <code>Documents</code> and <code>Pages</code> to getter-only properties.</p>\n\n<pre><code>public interface IPortfolio\n{\n string FirstName { get; set; }\n string LastName { get; set; }\n string Name { get; set; }\n int Id { get; set; }\n List<IDocument> Documents { get; }\n}\n</code></pre>\n\n<p>And create the class like this</p>\n\n<pre><code>public class Portfolio : IPortfolio\n{\n public string FirstName { get; set; }\n public string LastName { get; set; }\n public string Name { get; set; }\n public int Id { get; set; }\n public List<IDocument> Documents { get; } = new List<IDocument>();\n}\n</code></pre>\n\n<p>This makes the <code>Documents</code> property read-only. The list itself remains read/write.</p>\n\n<pre><code>var portfolio = new Portfolio();\nportfolio.Documents.Add(new Document());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T21:53:24.490",
"Id": "221305",
"ParentId": "221304",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221305",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T21:24:38.653",
"Id": "221304",
"Score": "0",
"Tags": [
"c#",
"object-oriented",
".net",
"interface"
],
"Title": "proper structure of classes using interface classes"
} | 221304 |
<p>I have a Responder class whose <code>prepare</code> method takes an entity, checks it with a validator, and returns a response or errorResponse based on the results of validator. </p>
<pre><code>class CreatorResponder implements ResponderInterface
{
private $validator;
private $repositoryFactory;
private $httpResponseFactory;
public function __construct(
ValidatorInterface $validator,
RepositoryFactoryInterface $repositoryFactory,
HttpResponseFactoryInterface $httpResponseFactory
){
$this->validator = $validator;
$this->repositoryFactory = $repositoryFactory;
$this->httpResponseFactory = $httpResponseFactory;
}
public function prepare(AbstractEntity $entity) : SimpleHttpResponseInterface
{
$validatorResponse = $this->validator->validate($entity);
if ($validatorResponse->isValid()) {
$repository = $this->repositoryFactory->create($entity);
$repository->persist($entity);
return $this->getSuccessResponse($entity);
}
return $this->getFailureResponse($validatorResponse->getErrors());
}
protected function getSuccessResponse(AbstractEntity $entity): SimpleHttpResponseInterface
{
$response = $this->httpResponseFactory->create(200, $entity);
return $response;
}
protected function getFailureResponse(array $errors): SimpleHttpResponseInterface
{
$response = $this->httpResponseFactory->create(422, $errors);
return $response;
}
}
</code></pre>
<p>The code is pretty simple, but its unit test is just pain in the ass. It is too big, hard to read, hard to maintain. That is because of mocking. Even repositoryFactory class is mocked, and it return a repository that is again mocked, so a mock is returning a mock. </p>
<pre><code>class CreatorResponderTest extends ResponderTestBase
{
public function testPrepare_withValid() : void
{
$validator = $this->getValidator(
true,
[$this->responseContent]
);
$repositoryFactory = $this->getRepositoryFactory();
$entity = $this->getEntity();
$httpResponseFactory = $this->getHttpResponseFactory(
$this->validStatusCode,
$this->responseContent
);
$responder = new CreatorResponder($validator, $repositoryFactory, $httpResponseFactory);
$response = $responder->prepare($entity);
$this->assertInstanceOf(SimpleHttpResponseInterface::class, $response);
$this->assertEquals($this->validStatusCode, $response->getStatusCode());
$this->assertEquals(
$this->responseContent,
$response->getContent()
);
}
public function testPrepare_withInvalid() : void
{
$validator = $this->getValidator(
false,
[$this->responseContent]
);
$repositoryFactory = $this->getRepositoryFactory();
$entity = $this->getEntity();
$httpResponseFactory = $this->getHttpResponseFactory(
$this->invalidStatusCode,
$this->responseContent
);
$responder = new CreatorResponder($validator, $repositoryFactory, $httpResponseFactory);
$response = $responder->prepare($entity);
$this->assertInstanceOf(SimpleHttpResponseInterface::class, $response);
$this->assertEquals($this->invalidStatusCode, $response->getStatusCode());
$this->assertEquals(
$this->responseContent,
$response->getContent()
);
}
}
</code></pre>
<p>The base class of tests actually creates all these mocks. </p>
<pre><code>class ResponderTestBase extends TestCase
{
protected $responseContent = 'some random content string!';
protected $validStatusCode = 200;
protected $invalidStatusCode = 422;
protected function getValidator(bool $isValid, $content)
{
$validatorWithValidResponseStub = $this->createMock(
ValidatorInterface::class
);
$validatorResponse = new ValidatorResponse($isValid, $content);
$validatorWithValidResponseStub->method('validate')
->willReturn($validatorResponse);
return $validatorWithValidResponseStub;
}
protected function getEntity()
{
$entityStub = $this->createMock(
AbstractEntity::class
);
$entityStub->method('getId')
->willReturn(1);
return $entityStub;
}
protected function getRepositoryFactory()
{
$repositoryMock = $this->createMock(
RepositoryFactoryInterface::class
);
$repositoryMock->expects($this->any())
->method('persist')
->with($this->isInstanceOf(AbstractEntity::class));
return $repositoryMock;
}
protected function getRepository()
{
$repositoryMock = $this->createMock(
RepositoryInterface::class
);
$repositoryMock->expects($this->any())
->method('persist')
->with($this->isInstanceOf(AbstractEntity::class));
return $repositoryMock;
}
protected function getHttpResponseFactory(int $httpStatusCode, $content)
{
$httpResponseFactoryStub = $this->createMock(
HttpResponseFactoryInterface::class
);
if (!is_string($content)) {
$content = json_encode($content);
}
$httpResponseFactoryStub->method('create')
->willReturn($this->getSimpleHttpResponse($httpStatusCode, $content));
return $httpResponseFactoryStub;
}
protected function getSimpleHttpResponse(int $httpStatusCode, $content)
{
return new SimpleHttpResponse($httpStatusCode, $content);
}
}
</code></pre>
<p>This whole problem is all because of mocking. Everytime I touch something in the class, I have to come to test and find the thing that disturbed it and it takes a lot more time to deal with this test. I think if I just don't mock <code>repositoryFactory</code> and <code>httpResponseFactory</code> here, a lot of my problem will be solved. I will not have mocks returning mocks. My unit tests will get more focused on behaviour instead of implementation. <strong>But I will lose isolation</strong> and it will turn into an integrated test. What is your take on that and how can I improve it?</p>
<p>I also tried not mocking <code>repositoryFactory</code>, but to create its instance, I will to bring in <code>EntityManager</code> that goes in <code>repositoryFactory</code> constructor. Again, this will need either mocking or accessing service container. So, not mocking is not good either. I think my design is bad. What's better?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T19:17:51.317",
"Id": "429629",
"Score": "0",
"body": "The convention for Code Review is for question titles to state what the code accomplishes, rather than what your primary concern is about the code. See [ask]."
}
] | [
{
"body": "<p>I ended up writing a builder for the test. The builder made the unit test a lot more readable and maintainable. I am not exactly where I wanted to get, but I am close. Find below the the test with builder. </p>\n\n<pre><code>class CreatorResponderBuilder extends TestCase\n{\n private $validator;\n private $repositoryFactory;\n private $httpResponseFactory;\n\n public static function getInstance(): CreatorResponderBuilder\n {\n return new self();\n }\n\n public function __construct()\n {\n $this->validator = $this->createMock(ValidatorInterface::class);\n $this->repositoryFactory = $this->createMock(\n RepositoryFactoryInterface::class\n );\n $this->httpResponseFactory = $this->createMock(\n HttpResponseFactoryInterface::class\n );\n\n\n }\n\n public function withValidValidatorResponse() : self\n {\n $validatorResponse = new ValidatorResponse(true, []);\n\n $this->validator->method('validate')\n ->willReturn($validatorResponse);\n\n $this->withHttpResponseFactoryForValidResponse();\n\n return $this;\n }\n\n private function withHttpResponseFactoryForValidResponse(): void\n {\n $this->httpResponseFactory->method('create')\n ->willReturn(new SimpleHttpResponse(200, 'Test content.'));\n\n }\n\n public function withInvalidValidatorResponse(): self\n {\n $validatorResponse = new ValidatorResponse(false, ['An error message.']);\n\n $this->validator->method('validate')\n ->willReturn($validatorResponse);\n\n $this->withHttpResponseFactoryForInvalidResponse();\n\n return $this;\n }\n\n private function withHttpResponseFactoryForInvalidResponse(): void\n {\n $this->httpResponseFactory->method('create')\n ->willReturn(new SimpleHttpResponse(422, 'An error message.'));\n }\n\n public function withRepositoryFactory() : self\n {\n $this->repositoryFactory->expects($this->any())\n ->method('create')\n ->with($this->isInstanceOf(AbstractEntity::class))\n ->willReturn(\n $this->createMock(RepositoryInterface::class)\n );\n\n return $this;\n }\n\n public function build() : CreatorResponder\n {\n $this->withValidValidatorResponse()\n ->withRepositoryFactory();\n\n return new CreatorResponder(\n $this->validator,\n $this->repositoryFactory,\n $this->httpResponseFactory\n );\n }\n}\n</code></pre>\n\n<p>And the test:</p>\n\n<pre><code>class CreatorResponderTest extends TestCase\n{\n public function testPrepareForValidEntity(): void\n {\n $creatorResponder = CreatorResponderBuilder::getInstance()\n ->withValidValidatorResponse()\n ->build();\n\n $response = $creatorResponder->prepare(\n $this->createMock(AbstractEntity::class)\n );\n\n $this->assertInstanceOf(SimpleHttpResponseInterface::class, $response);\n $this->assertEquals(200, $response->getStatusCode());\n $this->assertEquals('Test content.', $response->getContent());\n }\n\n public function testPrepareForInvalidEntity(): void\n {\n $creatorResponder = CreatorResponderBuilder::getInstance()\n ->withInvalidValidatorResponse()\n ->build();\n\n $response = $creatorResponder->prepare(\n $this->createMock(AbstractEntity::class)\n );\n\n $this->assertEquals(422, $response->getStatusCode());\n $this->assertEquals('An error message.', $response->getContent());\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T21:30:09.803",
"Id": "221369",
"ParentId": "221307",
"Score": "0"
}
},
{
"body": "<p>The thing is, there is not much to test in your code. You have added several abstractions to a simple statement:</p>\n\n<pre><code>if (isValid($data)) {\n doSomething($data);\n return makeResponse(200);\n} else {\n return makeResponse(422);\n}\n</code></pre>\n\n<p>So, your unit is a single <code>if</code> statement, and all actions -- condition, <code>then</code> branch, <code>else</code> branch -- everything is passed as parameter. There is literally nothing to test.</p>\n\n<p>Still, in attempt to test that <code>if</code> statement, you need to execute it somehow, and thus you need to prepare all these mocks etc. to just make that <code>if</code> work.</p>\n\n<p>Basically, I'm in the same boat as you because the level of abstraction you have demonstrated is what I usually do. It always ends badly...</p>\n\n<p>I have no \"cure\" for this ATM, but I think starting with famous <a href=\"https://medium.com/javascript-scene/mocking-is-a-code-smell-944a70c90a6a\" rel=\"nofollow noreferrer\">Mocking is a Code Smell</a> would be nice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T19:03:00.793",
"Id": "222045",
"ParentId": "221307",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T22:19:22.713",
"Id": "221307",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"unit-testing",
"mocks",
"phpunit"
],
"Title": "PHP unit test to confirm that a validator is being called correctly"
} | 221307 |
<p>Let's take these two objects as an exemple:</p>
<pre><code>let objA = {
key1 : "whatever",
key2 : "whatever",
key3 : "whatever",
key4 : "whatever",
key5 : {
subKey1: "whatever",
subKey2: "whatever"
}
}
let objB = {
key1 : "whatever",
key2 : "whatever",
key3 : "whatever",
key5 : {
subKey1: "whatever"
}
}
</code></pre>
<p>I want to delete all the properties of objA if they are not present in objB. <strong>The values of the properties do not matter, only the keys themselves</strong>. The challenge, of course, is for it to work with any object, no matter how deeply nested they can be.</p>
<p>I came up with this solution based on <a href="https://stackoverflow.com/a/41802431/5941620">this answer to a similar question</a>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let objA = {
key1 : "whatever",
key2 : "whatever",
key3 : "whatever",
key4 : "whatever",
key5 : {
subKey1: "whatever",
subKey2: "whatever"
}
}
let objB = {
key1 : "whatever",
key2 : "whatever",
key3 : "whatever",
key5 : {
subKey1: "whatever"
}
}
const deepSameKeys = (o1, o2) => {
const o1keys = Object.keys(o1).sort();
return o1keys.every(key => {
const v1 = o1[key];
const v2 = o2[key];
let goDeeper = true;
if (o2[key] == undefined) {
console.log('@found a key to delete: ', key);
delete o1[key];
goDeeper = false;
}
const t1 = typeof v1;
return t1 === "object" && goDeeper ? deepSameKeys(v1, v2) : true;
});
};
let result = deepSameKeys(objA, objB)
console.log(result)
console.log(objA) // no more key4 nor subKey2</code></pre>
</div>
</div>
</p>
<p>So far so good, but I wonder if someone can come up with something better or a situation where my solution would fail.</p>
| [] | [
{
"body": "<h2>Bugs and Problems</h2>\n\n<p>There are a few problems with your code</p>\n\n<ol>\n<li><p>Crash when <code>o1</code> references <code>null</code>. </p>\n\n<p>Reason <code>typeof null === \"object\"</code> is true. </p>\n\n<p><code>null</code> is an object when inspected with <code>typeof</code> however <code>Object.keys(null)</code> will throw the error <code>\"Can not convert null to Object\"</code> so if you have any properties that are <code>null</code> your code will throw an error.</p></li>\n<li><p>Crash when both objects have similar cyclic references. </p>\n\n<p>Many objects have references to themselves (are cyclic). Your code does not check if there is a cyclic reference and will continue to recurse until the call stack overflows (which is a thrown error)</p></li>\n</ol>\n\n<h2>General</h2>\n\n<p>Always aim to keep the code complexity as low as possible.</p>\n\n<ul>\n<li><p>The variable <code>goDeeper</code> is not needed. You can <code>return true</code> where you set it to false</p></li>\n<li><p>I do not see why you would need the keys sorted. Sorts are expensive operations, you should always ask yourself \"Do I need to sort?\" before using it.</p></li>\n<li><p>The function <code>deepSameKeys</code> will always return <code>true</code> so why return a value at all?</p></li>\n<li><p>It is unclear if you want to remove undefined properties, or all properties that evaluate to <code>undefined</code>. As you have it you remove all that evaluate to <code>undefined</code>.</p>\n\n<p>I.E. the object <code>{a: undefined}</code> contains a property named <code>a</code> while <code>{}</code> does not contain the property <code>a</code> yet both will evaluate <code>a</code> as <code>undefined</code>.</p>\n\n<p>You can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in\" rel=\"nofollow noreferrer\"><code>in</code></a> operator which will eval to true for the first object and false for the second. <strong>Note</strong> this also checks the prototype chain so you may want to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty\" rel=\"nofollow noreferrer\"><code>Object.hasOwnProperty</code></a> if this will be an issue</p></li>\n<li><p>The naming is very poor, not indecipherable but could be a lot better.</p></li>\n<li><p>When using recursive functions you should try to avoid using iterators that use anonymous functions EG <code>Array.every</code></p>\n\n<p>Most recursive functions are just an alternative way to implement a stack to hold the current item's state as you search deeper. </p>\n\n<p>This state is held in the function context (variables scoped to the function) \nand stored on the JS heap.</p>\n\n<p>Defining a function inside that context means that a second copy of the state is created as a closure, and also another context for the anonymous function.</p>\n\n<p>The additional state per item is a lot of unneeded overhead (and halves the max depth of recursion).</p>\n\n<p>If you use a <code>for</code>, <code>while</code>, or <code>do</code> loop you avoid the overhead .</p></li>\n</ul>\n\n<h3>Solutions</h3>\n\n<p><strong>Bug 1</strong> the solution is to change the lines...</p>\n\n<pre><code> const t1 = typeof v1;\n return t1 === \"object\" && goDeeper ? deepSameKeys(v1, v2) : true;\n</code></pre>\n\n<p>...to include a check for <code>null</code> and have the variable store a bool.</p>\n\n<pre><code> const isObject = v1 !== null && typeof v1 === \"object\";\n return isObject ? deepSameKeys(v1, v2) : true;\n</code></pre>\n\n<p><sup><strong>Note</strong> I have removed <code>goDeeper</code></sup></p>\n\n<p><strong>Bug 2</strong> There are a few options here. </p>\n\n<ol>\n<li><p>If the objects are parsed directly from JSON files then they can not be cyclic and the is no danger of error. This can also be an unenforced condition of the call (no cyclic object) and let the caller deal with the error is the breach the condition.</p></li>\n<li><p>Limit the recursion depth. JavaScript's <code>Array.map</code> function uses this method to protect against cyclic references and simply counts the depth down per call and the up on exit. It will not go deeper is this count is <code><= 0</code></p></li>\n<li><p>Track objects recursed using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\"><code>Set</code></a>. On each call check if the current object is in the Set, if it is return, if not then put it into the set and process the object. </p></li>\n</ol>\n\n<h2>Rewrite</h2>\n\n<p>I am assuming you only want to delete missing properties not properties referencing <code>undefined</code> and the return is not needed.</p>\n\n<p>There are a few versions. After the first I have reduced the variable name lengths to keep the code compact for CR snippet container.</p>\n\n<ul>\n<li>Delete undefined properties in reference from dirty. DOES not remove if property references <code>undefined</code>.</li>\n<li>Function returns <code>undefined</code></li>\n<li>Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\" rel=\"nofollow noreferrer\">Object.entries</a> to get at the key and value at the same time.</li>\n</ul>\n\n<hr>\n\n<p>Keeping the same (almost) behavior and cyclic bug.</p>\n\n<pre><code>const removeMissingProps = (dirty, reference) => {\n Object.entries(dirty).forEach(([key, val]) => {\n if (key in reference) {\n val !== null && typeof val === \"object\" && removeMissingProps(val, reference[key]);\n } else { delete dirty[key] }\n return true;\n });\n};\n</code></pre>\n\n<hr>\n\n<p>To provide a deeper call stack and avoid double state capture. Using for loop.</p>\n\n<pre><code>function remProps(dirty, ref) {\n for (const [key, val] of Object.entries(dirty)) {\n if (key in ref) {\n val !== null && typeof val === \"object\" && remProps(val, ref[key]);\n } else { delete dirty[key] }\n }\n};\n</code></pre>\n\n<hr>\n\n<p>To protect against call stack overflow by depth count</p>\n\n<pre><code>function remProps(dirty, ref, depth = 10) {\n if (depth > 0) {\n for (const [k, v] of Object.entries(dirty)) {\n if (k in ref) {\n v !== null && typeof v === \"object\" && remProps(v, ref[k], depth - 1);\n } else { delete dirty[k] }\n }\n }\n};\n</code></pre>\n\n<hr>\n\n<p>Uses a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet\" rel=\"nofollow noreferrer\">WeakSet</a> to check for repeated references.</p>\n\n<pre><code>function remProps(dirty, ref) {\n const checked = new WeakSet();\n remProps(dirty, ref);\n function remProps(dirty, ref) { \n if (!checked.has(dirty)) {\n checked.add(dirty);\n for (const [k, v] of Object.entries(dirty)) {\n if (k in ref) { \n v !== null && typeof v === \"object\" && remProps(v, ref[k]);\n } else { delete dirty[k] }\n }\n }\n };\n};\n</code></pre>\n\n<hr>\n\n<p><strong>Update</strong> I forgot to add the last one.</p>\n\n<p>Almost all the recursion functions I see are just implementations of stacks. Recursion has two drawbacks, small stack size (limited to the size of the call stack) and the needless capture of unrelated state.</p>\n\n<p>The following example uses an array rather than the call stack. Its behavior is slightly different (more intuitive) from the function above if you have cyclic references.</p>\n\n<p>There can be significant performance gains using stacks.</p>\n\n<pre><code>function remProps(dirty, ref) {\n const push = (v, ref) => !chk.has(v) && (chk.add(v), stack.push([v, ref]));\n const stack = [[dirty, ref]], chk = new WeakSet([dirty]); \n while (stack.length) {\n [dirty, ref] = stack.pop();\n for (const [k, v] of Object.entries(dirty)) {\n k in ref ? \n v !== null && typeof v === \"object\" && push(v, ref[k]):\n delete dirty[k];\n }\n }\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T00:47:49.417",
"Id": "428062",
"Score": "0",
"body": "I know the pattern is present in the original code too, but I'm a bit doubtful that `v !== null && typeof v === \"object\" && remProps(v, ref[k]);` (and similar constructs) are a great idea - they're expressions that go unused, which linters often warn against, for good reason, they can be confusing. IMO, better to use `if`/`else` for readability, leave the golfing for the minifier. For the last part, rather than repeating the `remProps` function, to give `checked` a persistent scope, you might consider a 3rd argument https://gist.github.com/CertainPerformance/e74974aceb95eecdb03c741670bc6222"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T05:23:21.930",
"Id": "428075",
"Score": "0",
"body": "@CertainPerformance I go by the principle that programmers are skilled professionals, if there is cause for confusion then the fault is that of the readers inexperience. If we teach such to accommodate at the lowest level we do our profession and those that are keen to learn a disservice,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T16:24:16.877",
"Id": "428274",
"Score": "0",
"body": "I just wanna say thanks @Blindman67, this answer exceeds my expectations."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T16:29:57.093",
"Id": "221353",
"ParentId": "221308",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221353",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T22:26:20.160",
"Id": "221308",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Deleting object properties if they are not found in another object. (javascript)"
} | 221308 |
<p>The following class is a wrapper for <code>Microsoft.Win32.SaveFileDialog</code>. I've implemented the usage of <code>Microsoft.Win32.SaveFileDialog</code> this way because I'm using the <code>ISaveFileDialog</code> interface as a dependency throughout my code base.</p>
<pre class="lang-cs prettyprint-override"><code>public class SaveFileDialog : ISaveFileDialog
{
public bool Save(string content, string suggestedFileExtension = null, string suggestedFileExtensionName = null, string suggestedFileName = null)
{
string filter = "All Files|*.*";
if (suggestedFileExtension != null)
{
filter = $"{suggestedFileExtensionName ?? string.Empty}|*{suggestedFileExtension}|" + filter;
}
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog
{
FileName = suggestedFileName ?? string.Empty,
DefaultExt = suggestedFileExtension ?? string.Empty,
Filter = filter
};
switch (dlg.ShowDialog())
{
case true:
return WriteFile(dlg.FileName, content);
default:
return false;
}
}
private bool WriteFile(string filePath, string content)
{
try
{
File.WriteAllText(filePath, content);
return true;
}
catch (PathTooLongException)
{
return false;
}
catch (DirectoryNotFoundException)
{
return false;
}
catch (IOException)
{
return false;
}
catch (UnauthorizedAccessException)
{
return false;
}
catch (System.Security.SecurityException)
{
return false;
}
}
}
</code></pre>
<p>While this works, I'm struggling to refactor this class to allow for unit testing as currently there's no way to mock/stub the <code>Microsoft.Win32.SaveFileDialog</code> - have I missed a trick here? Or is there genuinely no nice way to unit test this and I should be relying on integration tests?</p>
<hr>
<p>I know that I could refactor the catch blocks to either be</p>
<pre class="lang-cs prettyprint-override"><code>catch (Exception)
{
return false;
}
</code></pre>
<p>Or even to be</p>
<pre class="lang-cs prettyprint-override"><code>catch (Exception ex) when (ex is PathTooLongException
|| ex is DirectoryNotFoundException
........ )
{
return false;
}
</code></pre>
<p>But I would like to keep them the way that they are because I would like to avoid catching all exceptions and I'm using <a href="https://marketplace.visualstudio.com/items?itemName=YoavFrandzel.CheckedExceptions" rel="nofollow noreferrer">a Visual Studio plugin</a> to help me manage exceptions and it complains when using the second option.</p>
<p>Thanks for any help!</p>
| [] | [
{
"body": "<h2>unit tests</h2>\n\n<p>You can use <a href=\"https://docs.microsoft.com/en-us/visualstudio/test/isolating-code-under-test-with-microsoft-fakes?view=vs-2019\" rel=\"nofollow noreferrer\">fakes</a> (stubs vs shims) to mock third-party classes. It is not as lightweight as your regular mocks, but it does the job.</p>\n\n<hr>\n\n<h2>exception handling</h2>\n\n<blockquote>\n<pre><code>catch (Exception)\n{\n return false;\n}\n</code></pre>\n</blockquote>\n\n<p>Why don't you do something like Microsoft tends to do often in their framework? You make some internal convenience method <code>IsCriticalException</code> that checks whether to rethrow the exception or swallow it.</p>\n\n<pre><code>catch (Exception ex)\n{\n if (IsCriticalException(ex)) throw;\n return false;\n}\n</code></pre>\n\n<h2>clean code</h2>\n\n<p>Use <code>var</code> when you can.</p>\n\n<blockquote>\n <p><code>Microsoft.Win32.SaveFileDialog dlg = new\n Microsoft.Win32.SaveFileDialog</code></p>\n</blockquote>\n\n<pre><code> var dlg = new Microsoft.Win32.SaveFileDialog\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:08:10.233",
"Id": "427947",
"Score": "0",
"body": "Why should I use var wherever I can?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:15:05.300",
"Id": "427949",
"Score": "1",
"body": "@TobySmith To avoid redundant code and improve readability. It's a mere semantic optimization. https://stackoverflow.com/questions/209199/whats-the-point-of-the-var-keyword"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T08:18:35.387",
"Id": "221326",
"ParentId": "221309",
"Score": "2"
}
},
{
"body": "<p>I think you are unit testing the wrong code. You should be looking to unit test your code and not Microsofts code. It's a good place to write interfaces around their code for testing so you can switch out MS code with your own test implementation. You didn't show what your interface looked like but I would suggest that if you want to replace SaveFileDialog then you should have an interface just for that and not also have SaveFileDialog also write the file. </p>\n\n<p>Something along the lines of </p>\n\n<pre><code>public interface ISaveFileDialog\n{\n string GetFileName(string suggestedFileExtension = null, string suggestedFileExtensionName = null, string suggestedFileName = null);\n}\n\npublic class SaveFileDialog : ISaveFileDialog\n{\n public string GetFileName(string suggestedFileExtension = null, string suggestedFileExtensionName = null, string suggestedFileName = null)\n {\n string filter = \"All Files|*.*\";\n\n if (suggestedFileExtension != null)\n {\n filter = $\"{suggestedFileExtensionName ?? string.Empty}|*{suggestedFileExtension}|\" + filter;\n }\n\n Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog\n {\n FileName = suggestedFileName ?? string.Empty,\n DefaultExt = suggestedFileExtension ?? string.Empty,\n Filter = filter\n };\n\n switch (dlg.ShowDialog())\n {\n case true:\n return dlg.FileName;\n default:\n return null;\n }\n }\n}\n\npublic interface IWriteFile\n{\n bool WriteText(string fileName, string content);\n}\n\npublic class WriteFile : IWriteFile\n{\n public bool WriteText(string fileName, string content)\n {\n try\n {\n File.WriteAllText(fileName, content);\n }\n // Just a simple catch to show example\n catch (Exception ex)\n {\n return false;\n }\n return true;\n }\n}\n\npublic class SaveFile\n{\n private readonly ISaveFileDialog saveFileDialog;\n private readonly IWriteFile writer;\n public SaveFile(ISaveFileDialog saveFileDialog, IWriteFile writer)\n {\n this.saveFileDialog = saveFileDialog;\n this.writer = writer;\n }\n\n public bool Save(string content, string suggestedFileExtension = null, string suggestedFileExtensionName = null, string suggestedFileName = null)\n {\n var fileName = saveFileDialog.GetFileName(suggestedFileExtension, suggestedFileExtensionName, suggestedFileName);\n if (fileName == null)\n {\n return false;\n }\n\n return writer.WriteText(fileName, content);\n\n }\n}\n</code></pre>\n\n<p>Now we wrapped MS code in interfaces that we want to test. For unit test you can now have a mock of both ISaveFileDialog and IWriteFile. </p>\n\n<p>Unit test against SaveFile could be the following:</p>\n\n<ol>\n<li>Verify that if GetFileName return null that WriteText never got hit </li>\n<li>GetFileName return a string that WriteText did get hit</li>\n<li>SaveFile returns true if WriteText returns true</li>\n<li>SaveFile returns false if WRiteText returns false</li>\n<li>if GetFileName returns null that SaveFile returns false</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T13:42:11.350",
"Id": "221341",
"ParentId": "221309",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "221326",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T22:29:07.693",
"Id": "221309",
"Score": "1",
"Tags": [
"c#",
"unit-testing",
"dependency-injection",
"moq"
],
"Title": "Wrapper class for system dialog to allow for dependency injection"
} | 221309 |
<p>I wish to transpose a square matrix, permanently overwriting it.<br>
This is not the same as creating a 2nd matrix with the transposed contents of the 1st matrix.</p>
<p>I call the procedure with 3 parameters: the address of the original matrix, its rank, and the address of a scratch buffer that is large enough.<br>
First, all the elements are spread out over the scratch buffer. Later the scratch buffer is copied back to the original storage.</p>
<p>How can I optimize this code?</p>
<pre class="lang-none prettyprint-override"><code>; TransposeSquareMatrix(Address, Rank, Scratch)
Q: push ebp
mov ebp, esp
push ecx edx esi edi
mov esi, [ebp+8] ; Address
mov edx, [ebp+12] ; Rank
mov edi, [ebp+16] ; Scratch buffer
lea eax, [edx-1] ; Additional address increment
.a: push edi ; (1)
mov ecx, [ebp+12] ; Rank
.b: movsb ; Spreading out the elements of one row
add edi, eax
dec ecx
jnz .b
pop edi ; (1)
inc edi
dec edx
jnz .a ; Repeating it for every row
mov edi, [ebp+8] ; Address
mov ecx, [ebp+12] ; Rank
imul ecx, ecx
mov esi, [ebp+16] ; Scratch buffer
rep movsb ; Overwriting the original matrix
pop edi esi edx ecx
pop ebp
ret 12
; --------------------------
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T23:50:31.293",
"Id": "427895",
"Score": "0",
"body": "Below is a self-answer. Please don't let that stop you from writing a review. Code improvements or perhaps suggesting an alternative approach?"
}
] | [
{
"body": "\n\n<h2>20+ percent faster using the stack for the extra buffer.</h2>\n\n<pre class=\"lang-none prettyprint-override\"><code>Matrix Question Answer(1) Faster\n-------------------------------------------\n16 x 16 3.62 µsec 2.62 µsec 27.6 %\n13 x 13 2.67 µsec 2.05 µsec 23.2 %\n10 x 10 1.77 µsec 1.35 µsec 23.7 %\n 7 x 7 1.02 µsec 0.77 µsec 24.5 %\n 4 x 4 0.56 µsec 0.44 µsec 21.4 %\n</code></pre>\n\n<p>Setting up a temporary scratch buffer in the stack proved to be a winner. A decent speed increase, no need for the 3rd parameter, and with a single branch target, applying code alignment could be a bit easier.</p>\n\n<p>This pushes the same 5 registers but delays assigning <code>EBP</code> so it can be used as an EndOfBuffer marker. A minor drawback is that the easy recognizable <code>EBP</code>-offsets for the parameters (+8, +12, ...) are gone. Requires some more attention to detail like in the <code>ESP</code>-offsets of today.</p>\n\n<p>Nothing is pushed on the stack below the local stack buffer and so keeping <code>ESP</code> dword-aligned is not needed.</p>\n\n<p>This is cleaner code. I think addressing the parameters several times over, looked a bit untidy.</p>\n\n<p><a href=\"https://i.stack.imgur.com/o1UFP.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/o1UFP.gif\" alt=\"Transpose via copying\"></a></p>\n\n<pre class=\"lang-none prettyprint-override\"><code>; TransposeSquareMatrix(Address, Rank)\nA1: push ecx edx esi edi ebp\n mov ebp, esp\n mov esi, [ebp+24] ; Address\n mov edx, [ebp+28] ; Rank\n mov ecx, edx\n imul ecx, ecx ; -> Size of matrix\n sub esp, ecx ; Local buffer\n mov edi, esp\n lea eax, [edx-1] ; (Rank - 1)\n.a: movsb ; -> EDI += 1\n add edi, eax ; -> EDI += (Rank - 1)\n cmp edi, ebp ; Until end of local buffer\n jb .a\n sub edi, ecx ; Back to start of current column\n inc edi ; Go to start next column\n dec edx\n jnz .a ; Repeat rank times\n sub esi, ecx ; Copy to original storage\n mov edi, esi ; -> EDI is Address\n mov esi, esp ; -> ESI is local buffer\n rep movsb\n mov esp, ebp\n pop ebp edi esi edx ecx\n ret 8\n; --------------------------\n</code></pre>\n\n<h2>50+ percent faster without even using an extra buffer.</h2>\n\n<pre class=\"lang-none prettyprint-override\"><code>Matrix Question Answer(2) Faster\n-------------------------------------------\n16 x 16 3.62 µsec 1.80 µsec 50.1 %\n13 x 13 2.67 µsec 1.22 µsec 54.3 %\n10 x 10 1.77 µsec 0.77 µsec 56.0 %\n 7 x 7 1.02 µsec 0.44 µsec 56.9 %\n 4 x 4 0.56 µsec 0.23 µsec 58.9 %\n</code></pre>\n\n<p>The elements on the main diagonal are never touched. All the other elements are flipped across the main diagonal.</p>\n\n<p><a href=\"https://i.stack.imgur.com/sa53o.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sa53o.gif\" alt=\"Transpose via swapping\"></a></p>\n\n<pre class=\"lang-none prettyprint-override\"><code>; TransposeSquareMatrix(Address, Rank)\nA2: push ebx ecx edx esi edi ebp\n mov ebx, [esp+28] ; Address\n mov ecx, [esp+32] ; Rank\n mov ebp, ecx\n dec ecx\n jz .c ; It's a (1 x 1) matrix\n.a: push ecx ; (1)\n mov esi, ebx ; Column address\n mov edi, ebx ; Row address\n.b: inc esi ; To next element in this row\n add edi, ebp ; To next element in this column\n mov al, [esi] ; Swap 2 elements\n mov dl, [edi]\n mov [edi], al\n mov [esi], dl\n dec ecx\n jnz .b\n add ebx, ebp ; To next element on main diagonal\n inc ebx\n pop ecx ; (1)\n dec ecx\n jnz .a ; Continu until (1 x 1) matrix\n.c: pop ebp edi esi edx ecx ebx\n ret 8\n; --------------------------\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T23:11:15.833",
"Id": "221313",
"ParentId": "221312",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221313",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T23:11:15.833",
"Id": "221312",
"Score": "3",
"Tags": [
"performance",
"algorithm",
"matrix",
"assembly",
"x86"
],
"Title": "Transposing a square matrix (n x n)"
} | 221312 |
<p>I have been trying to teach myself C++ recently and would like to have some general feedback and comments on how to improve my code so far. Furthermore, since I am more experienced with other (garbage-collected) languages like Python and Java, I would like to know if I am handling memory correctly or making any fundamental rookie mistakes.</p>
<p>I have attempted to make an implementation of a linked list, given below in <code>LinkedList.h</code>.</p>
<pre><code>#pragma once
#include <stdexcept>
#include <ostream>
/*
This is a generic-type linked list implemented without using the C++ STL.
Member functions:
void append(const T&)
bool contains(const T&) const
const T& get(int) const
void insert(int, const T&)
int length() const
void prepend(const T&)
T remove(int)
bool removeValue(const T&)
*/
template <typename T>
class LinkedList {
public:
// Appends element to the end of the list
void append(const T& data) {
insert(len, data);
}
// Returns data element at given index
// Throws std::out_of_range if index is invalid
const T& get(int index) const {
if (index < 0 || index >= len)
throw std::out_of_range("Invalid index in LinkedList::get(int)");
Node *ptr = Head;
// Traverse up to the matching node
for (; index-- ;)
ptr = ptr -> next;
return ptr -> data;
}
// Prepends element to the start of the list
void prepend(const T& data) {
insert(0, data);
}
// Removes element at a given index, if possible, and returns it
// Throws std::out_of_range if index is invalid
T remove(int index) {
if (index < 0 || index >= len)
throw std::out_of_range("Invalid index in LinkedList::remove(int)");
Node *old;
if (index == 0) { // Deleting the head
old = Head; // Save the removed node to free later
Head = Head -> next; // Skip over the node
}
else {
Node *ptr = Head;
for (; --index ;) // Traverse up to just before the matching node
ptr = ptr -> next;
old = ptr -> next; // Save the removed node to free later
ptr -> next = old -> next; // Skip over the node
}
T ret = old -> data; // Save the removed data to return later
delete old; // Delete the node from memory
len--;
return ret;
}
// Removes element by value, if found, and return whether or not it was successful
bool removeValue(const T& data) {
Node *ptr = Head;
if (!ptr) // Empty list
return false;
Node *old;
if (ptr -> data == data) { // Deleting the head
old = Head; // Save the removed node to free later
Head = old -> next; // Skip over the node
}
else {
// Advance until the end of the list, or just before the object is found
while (ptr -> next && ptr -> next -> data != data)
ptr = ptr -> next;
if (!ptr -> next) // End of the list
return false;
// Object was found
Node *old = ptr -> next; // Save the removed node to free later
ptr -> next = old -> next; // Skip over the node
}
delete old; // Delete the node from memory
len--;
return true;
}
// Inserts element at a given index
// Throws std::out_of_range if index is invalid
void insert(int index, const T& data) {
if (index < 0 || index > len)
throw std::out_of_range("Invalid index in LinkedList::insert(int, const T&)");
if (index == 0)
Head = new Node(data, Head);
else {
Node *ptr = Head;
// Traverse up to one node prior to the insertion
for (; --index ;)
ptr = ptr -> next;
ptr -> next = new Node(data, ptr -> next);
}
len++;
}
// Returns whether or not the list contains a given element
bool contains(const T& data) const {
Node *ptr = Head;
while (ptr != nullptr) {
if (ptr -> data == data)
return true;
ptr = ptr -> next;
}
return false;
}
// Returns the length of the list
int length() const {
return len;
}
// Deletes all Nodes in the list
~LinkedList() {
Node *ptr = Head, *next;
// Iterate through the list
while (ptr) {
next = ptr -> next;
delete ptr;
ptr = next;
}
}
private:
class Node { public:
const T data;
Node *next;
Node(const T& data, Node* next = nullptr) : data(data), next(next) { }
};
int len = 0;
Node *Head = nullptr;
template <typename S>
friend std::ostream& operator<<(std::ostream&, const LinkedList<S>&);
};
template <typename S>
std::ostream& operator<<(std::ostream& os, const LinkedList<S>& ls) {
os << "[ ";
typename LinkedList<S>::Node *ptr = ls.Head, *next;
// Iterate through the list
while (ptr) {
os << ptr -> data;
next = ptr -> next;
if (next) // If not at the end of the list
os << ", ";
ptr = next;
}
os << " ]";
return os;
}
</code></pre>
<p>Additionally, I have written some code for testing most of the features, which I called <code>LinkedList.cpp</code>.</p>
<pre><code>#include <iostream>
#include <iterator>
#include "LinkedList.h"
// Note that this file uses features from the C++17 standard, namely std::size.
int main() {
LinkedList<int> *L = new LinkedList<int>;
// This can be done without pointers, too:
// LinkedList<int> L2;
// Test append head
int x = 3;
L -> append(x);
// L2.append(x);
std::cout << "Expected: 3 \tActual: " << L -> get(0) << std::endl << std::endl;
// std::cout << "Expected: 3\tActual: " << *(L2.get(0)) << std::endl << std::endl;
// Test repeated append
int arr[] = {45, 10, 32, 12, 11, 12, 1, -1, 0, 56};
for (unsigned int i = 0; i < std::size(arr); i++)
L -> append(arr[i]);
for (unsigned int i = 0; i < std::size(arr); i++)
std::cout << "Expected: " << arr[i] << " \tActual: " << L -> get(i + 1) << std::endl;
std::cout << std::endl;
// Test remove and length
x = L -> remove(3);
std:: cout << "Expected: 32\tActual: " << x << std::endl;
int newArr[] = {3, 45, 10, 12, 11, 12, 1, -1, 0, 56};
for (int i = 0; i < L -> length(); i++)
std::cout << "Expected: " << newArr[i] << " \tActual: " << L -> get(i) << std::endl;
std::cout << std::endl;
// Test insert and prepend
L -> prepend(arr[0]);
L -> insert(1, arr[1]);
for (int i = 0; i < 2; i++)
std::cout << "Expected: " << arr[i] << " \tActual: " << L -> get(i) << std::endl;
// Test contains
std::cout << "Expected: 1 \tActual: " << L -> contains(arr[1]) << std::endl;
std::cout << "Expected: 0 \tActual: " << L -> contains(arr[2]) << std::endl;
std::cout << "Expected: 1 \tActual: " << L -> contains(arr[3]) << std::endl;
std::cout << std::endl;
// Test output operator
std::cout << "Actual: \t[ 45, 10, 3, 45, 10, 12, 11, 12, 1, -1, 0, 56 ]" << std::endl;
std::cout << "Expected:\t" << *L << std::endl;
std::cout << std::endl;
// Test removeValue
std::cout << "Expected: 1\tActual: " << L -> removeValue(0) << std::endl;
std::cout << "Expected: 0\tActual: " << L -> removeValue(9000) << std::endl;
std::cout << "Expected: 1\tActual: " << L -> removeValue(45) << std::endl;
std::cout << "Expected: 1\tActual: " << L -> removeValue(45) << std::endl;
std::cout << "Expected: 1\tActual: " << L -> removeValue(3) << std::endl;
std::cout << "Expected: 0\tActual: " << L -> removeValue(3) << std::endl;
std::cout << "Expected: 1\tActual: " << L -> removeValue(56) << std::endl;
std::cout << "Actual: \t[ 10, 10, 12, 11, 12, 1, -1 ]" << std::endl;
std::cout << "Expected:\t" << *L << std::endl;
std::cout << std::endl;
delete L;
return 0;
}
</code></pre>
<p>Thank you very much! I appreciate any advice or comments.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T03:23:36.833",
"Id": "427903",
"Score": "1",
"body": "Why is `data` `const` in `Node`? That places some unnecessary restrictions on how your class can be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T04:01:11.257",
"Id": "427904",
"Score": "0",
"body": "@1201ProgramAlarm I made `data` a `const` member variable because it allows me to put objects of type `const T&` into the list, which should catch both lvalue and rvalue expressions in one go (without overloading). Also, the list theoretically should never need to modify one of the `Node`s it contains, when you can instead `remove` it and `insert` a new value in its place. (If any of the terminology I use is incorrect, please let me know for future reference.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:17:48.420",
"Id": "427952",
"Score": "2",
"body": "It's probably worth reading the interface of `std::list` and trying to be compatible with that. For instance, there's no reason to write `int length() const` instead of `std::size_t size() const`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T16:11:01.147",
"Id": "428010",
"Score": "2",
"body": "Why are you doing this new? `LinkedList<int> *L = new LinkedList<int>;` A basic rule is that if you call `new` you are probably doing something wrong. C++ has other techniques that make its memory management automatic. We have what is called fine grained deterministic garbage collection built into the language (smart pointers and containers). You can of course do it manually with new but there is very little need to do this apart from in very specialized cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T16:15:33.507",
"Id": "428012",
"Score": "0",
"body": "Simply use: `LinkedList<int> L;`"
}
] | [
{
"body": "<h1>Memory check</h1>\n\n<p>Running the provided test program under Valgrind reveals quite a few problems:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>valgrind --leak-check=full ./221317 \n==9150== Memcheck, a memory error detector\n==9150== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.\n==9150== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info\n==9150== Command: ./221317\n==9150== \nExpected: 3 Actual: 3\n\nExpected: 45 Actual: 45\nExpected: 10 Actual: 10\nExpected: 32 Actual: 32\nExpected: 12 Actual: 12\nExpected: 11 Actual: 11\nExpected: 12 Actual: 12\nExpected: 1 Actual: 1\nExpected: -1 Actual: -1\nExpected: 0 Actual: 0\nExpected: 56 Actual: 56\n\nExpected: 32 Actual: 32\nExpected: 3 Actual: 3\nExpected: 45 Actual: 45\nExpected: 10 Actual: 10\nExpected: 12 Actual: 12\nExpected: 11 Actual: 11\nExpected: 12 Actual: 12\nExpected: 1 Actual: 1\nExpected: -1 Actual: -1\nExpected: 0 Actual: 0\nExpected: 56 Actual: 56\n\nExpected: 45 Actual: 45\nExpected: 10 Actual: 10\nExpected: 1 Actual: 1\nExpected: 0 Actual: 0\nExpected: 1 Actual: 1\n\nActual: [ 45, 10, 3, 45, 10, 12, 11, 12, 1, -1, 0, 56 ]\nExpected: [ 45, 10, 3, 45, 10, 12, 11, 12, 1, -1, 0, 56 ]\n\n==9150== Conditional jump or move depends on uninitialised value(s)\n==9150== at 0x4837041: operator delete(void*, unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==9150== by 0x109FE6: LinkedList<int>::removeValue(int const&) (221317.cpp:84)\n==9150== by 0x1097A2: main (221317.cpp:212)\n==9150== \n==9150== Invalid free() / delete / delete[] / realloc()\n==9150== at 0x483708B: operator delete(void*, unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==9150== by 0x109FE6: LinkedList<int>::removeValue(int const&) (221317.cpp:84)\n==9150== by 0x1097A2: main (221317.cpp:212)\n==9150== Address 0x1fff0006d0 is on thread 1's stack\n==9150== in frame #2, created by main (221317.cpp:166)\n==9150== \nExpected: 1 Actual: 1\nExpected: 0 Actual: 0\nExpected: 1 Actual: 1\n==9150== Conditional jump or move depends on uninitialised value(s)\n==9150== at 0x4837041: operator delete(void*, unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==9150== by 0x109FE6: LinkedList<int>::removeValue(int const&) (221317.cpp:84)\n==9150== by 0x1098A1: main (221317.cpp:215)\n==9150== \n==9150== Invalid free() / delete / delete[] / realloc()\n==9150== at 0x483708B: operator delete(void*, unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==9150== by 0x109FE6: LinkedList<int>::removeValue(int const&) (221317.cpp:84)\n==9150== by 0x1098A1: main (221317.cpp:215)\n==9150== Address 0x1fff0006d0 is on thread 1's stack\n==9150== in frame #2, created by main (221317.cpp:166)\n==9150== \nExpected: 1 Actual: 1\n==9150== Conditional jump or move depends on uninitialised value(s)\n==9150== at 0x4837041: operator delete(void*, unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==9150== by 0x109FE6: LinkedList<int>::removeValue(int const&) (221317.cpp:84)\n==9150== by 0x1098F6: main (221317.cpp:216)\n==9150== \n==9150== Invalid free() / delete / delete[] / realloc()\n==9150== at 0x483708B: operator delete(void*, unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==9150== by 0x109FE6: LinkedList<int>::removeValue(int const&) (221317.cpp:84)\n==9150== by 0x1098F6: main (221317.cpp:216)\n==9150== Address 0x1fff0006d0 is on thread 1's stack\n==9150== in frame #2, created by main (221317.cpp:166)\n==9150== \nExpected: 1 Actual: 1\nExpected: 0 Actual: 0\n==9150== Conditional jump or move depends on uninitialised value(s)\n==9150== at 0x4837041: operator delete(void*, unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==9150== by 0x109FE6: LinkedList<int>::removeValue(int const&) (221317.cpp:84)\n==9150== by 0x1099A0: main (221317.cpp:218)\n==9150== \n==9150== Invalid free() / delete / delete[] / realloc()\n==9150== at 0x483708B: operator delete(void*, unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==9150== by 0x109FE6: LinkedList<int>::removeValue(int const&) (221317.cpp:84)\n==9150== by 0x1099A0: main (221317.cpp:218)\n==9150== Address 0x1fff0006d0 is on thread 1's stack\n==9150== in frame #2, created by main (221317.cpp:166)\n==9150== \nExpected: 1 Actual: 1\nActual: [ 10, 10, 12, 11, 12, 1, -1 ]\nExpected: [ 10, 10, 12, 11, 12, 1, -1 ]\n\n==9150== \n==9150== HEAP SUMMARY:\n==9150== in use at exit: 64 bytes in 4 blocks\n==9150== total heap usage: 16 allocs, 16 frees, 73,952 bytes allocated\n==9150== \n==9150== 16 bytes in 1 blocks are definitely lost in loss record 2 of 3\n==9150== at 0x4835DEF: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==9150== by 0x109D94: LinkedList<int>::insert(int, int const&) (221317.cpp:95)\n==9150== by 0x109B27: LinkedList<int>::append(int const&) (221317.cpp:21)\n==9150== by 0x109233: main (221317.cpp:173)\n==9150== \n==9150== 48 (32 direct, 16 indirect) bytes in 2 blocks are definitely lost in loss record 3 of 3\n==9150== at 0x4835DEF: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==9150== by 0x109DEB: LinkedList<int>::insert(int, int const&) (221317.cpp:101)\n==9150== by 0x109B27: LinkedList<int>::append(int const&) (221317.cpp:21)\n==9150== by 0x109316: main (221317.cpp:181)\n==9150== \n==9150== LEAK SUMMARY:\n==9150== definitely lost: 48 bytes in 3 blocks\n==9150== indirectly lost: 16 bytes in 1 blocks\n==9150== possibly lost: 0 bytes in 0 blocks\n==9150== still reachable: 0 bytes in 0 blocks\n==9150== suppressed: 0 bytes in 0 blocks\n==9150== \n==9150== For counts of detected and suppressed errors, rerun with: -v\n==9150== Use --track-origins=yes to see where uninitialised values come from\n==9150== ERROR SUMMARY: 10 errors from 10 contexts (suppressed: 0 from 0)\n</code></pre>\n\n<p>All these problems are caused by shadowing <code>old</code> here:</p>\n\n<blockquote>\n<pre><code> Node *old;\n if (ptr -> data == data) {\n old = Head;\n ...\n }\n else {\n ...\n Node *old = ptr -> next;\n ...\n }\n delete old; // Delete the node from memory\n</code></pre>\n</blockquote>\n\n<p>Changing to <code>else { ... old = ptr -> next; ... }</code> fixes them.</p>\n\n<h1>Rule of Five</h1>\n\n<p>The class has a non-trivial destructor and an owning raw pointer member. Those are both signs that we need to proved user-defined copy/move constructors and assignment operators.</p>\n\n<p>Without those, consider what happens when a <code>LinkedList</code> is copied. Both lists now share the same <code>Head</code>. If we delete one of the lists, it cleans up its memory, so the other one now has a dangling pointer. That's a recipe for Undefined Behaviour (in its destructor, if not earlier).</p>\n\n<p>A small amendment to the test program will soon expose the problem:</p>\n\n<pre><code>{\n LinkedList<char> s;\n s.append('a');\n auto s2 = s;\n}\n</code></pre>\n\n<p>It's worth running the new test under Valgrind (or other memory checker) so that you learn to recognise the symptoms there (which will help if you come across similar bugs in future):</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> Invalid read of size 8\n at 0x10A0F9: LinkedList<char>::~LinkedList() (221317.cpp:127)\n by 0x109AD0: main (221317.cpp:226)\n Address 0x4d75528 is 8 bytes inside a block of size 16 free'd\n at 0x483708B: operator delete(void*, unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n by 0x10A111: LinkedList<char>::~LinkedList() (221317.cpp:128)\n by 0x109AC1: main (221317.cpp:228)\n Block was alloc'd at\n at 0x4835DEF: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n by 0x10A1E6: LinkedList<char>::insert(int, char const&) (221317.cpp:95)\n by 0x10A147: LinkedList<char>::append(char const&) (221317.cpp:21)\n by 0x109A96: main (221317.cpp:227)\n\n Invalid free() / delete / delete[] / realloc()\n at 0x483708B: operator delete(void*, unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n by 0x10A111: LinkedList<char>::~LinkedList() (221317.cpp:128)\n by 0x109AD0: main (221317.cpp:226)\n Address 0x4d75520 is 0 bytes inside a block of size 16 free'd\n at 0x483708B: operator delete(void*, unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n by 0x10A111: LinkedList<char>::~LinkedList() (221317.cpp:128)\n by 0x109AC1: main (221317.cpp:228)\n Block was alloc'd at\n at 0x4835DEF: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n by 0x10A1E6: LinkedList<char>::insert(int, char const&) (221317.cpp:95)\n by 0x10A147: LinkedList<char>::append(char const&) (221317.cpp:21)\n by 0x109A96: main (221317.cpp:227)\n</code></pre>\n\n<p>The thing to pick up here is that the second memory block in the report was deleted in <code>~LinkedList()</code> and again in <code>~LinkedList()</code>, at the same line. That suggests that two objects have deleted the same memory (unless we knew that some code was explicitly calling destructors, but that's rare, and we tend to inspect such code very carefully). The first block is also relevant - that's us attempting to access <code>ptr->next</code> from <code>s2</code>'s destructor after <code>s</code> was deleted.</p>\n\n<p>At a minimum, we could write:</p>\n\n<pre><code>LinkedList(const LinkedList&) = delete;\nLinkedList& operator=(const LinkedList&) = delete;\n</code></pre>\n\n<p>A more useful fix would be to actually implement these, and probably also the versions that accept rvalue references (because we can simply move the contents much more efficiently than copying would be):</p>\n\n<pre><code>LinkedList(const LinkedList&);\nLinkedList(LinkedList&&);\nLinkedList& operator=(const LinkedList&);\nLinkedList& operator=(LinkedList&&);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T02:19:49.547",
"Id": "428066",
"Score": "0",
"body": "Thank you so much! I had not heard of Valgrind before, so I will look into that to help me diagnose problems with my code in the future. I had not heard of the \"Rule of Five,\" either, but that also looks like something that will definitely come in handy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:31:19.883",
"Id": "428081",
"Score": "1",
"body": "Yes, Valgrind is a really useful tool, and it helps me often. It is (unavoidably) resource hungry, as the cost of recording every allocation \"just in case\" means that your code runs very slowly and eats memory - it's best applied to unit tests where possible, rather than full applications. I primarily use it on Linux; not sure what the alternatives are on non-Unix platforms, but I expect that comparable tools exist."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:31:31.920",
"Id": "428082",
"Score": "1",
"body": "You'll find some good reading if you search for \"**Rule of Zero**\" - or try CPPReference's [rule of three/five/zero](https://en.cppreference.com/w/cpp/language/rule_of_three) page."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:27:50.817",
"Id": "221331",
"ParentId": "221317",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "221331",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T02:46:34.063",
"Id": "221317",
"Score": "5",
"Tags": [
"c++",
"linked-list",
"c++17"
],
"Title": "C++ Implementation of Linked List"
} | 221317 |
<p>I am new to programming and currently learning Python using "Automate the Boring" by Al Sweigart. I've just completed the "Comma Code" task in <a href="https://automatetheboringstuff.com/chapter4/" rel="noreferrer">Chapter 4</a> and would like some feedback on my solution. The task is:</p>
<blockquote>
<p>Say you have a list value like this:</p>
<pre><code>spam = ['apples', 'bananas', 'tofu', 'cats']
</code></pre>
<p>Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and space, with <em>and</em> inserted before the last item. For example, passing the previous <code>spam</code> list to the function would return <code>'apples, bananas, tofu, and cats'</code>. But your function should be able to work with any list value passed to it.</p>
</blockquote>
<p>I tried to come up with something that mostly sticks to what you learn by this point in the book, but I did use <code>.join()</code> which is from a few chapters later. I also tried to make sure my code works with lists containing strings and/or integers, and for the output to be correct independent of list size (no comma when the list has two items, etc.).</p>
<pre><code>your_list = ['item1', 'item2', 3, 'item4', 'item5', 'item6', 7, 'item8', 9]
def list_concatenator(your_list):
items = len(your_list)
if items == 0:
return 'Your list is empty'
elif items == 1:
return "'" + str(your_list[0]) + "'"
elif items == 2:
return "'" + str(your_list[0]) + ' and ' + str(your_list[1]) + "'"
else:
your_list_split1 = (', '.join((map(str,your_list[:-1]))))
return "'" + your_list_split1 + ', and ' + str(your_list[-1]) + "'"
list_concatenator(your_list)
</code></pre>
<p>I realize these exercises have been answered before, I'm just looking for some feedback on my solution.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T12:02:36.833",
"Id": "427963",
"Score": "5",
"body": "For a two-element list like `['apples', 'bananas']`, your code skips the comma and returns `'apples and bananas'` rather than `'apples, and bananas'` like the spec seems to ask for. Is that intentional? (Also, I suspect you're not supposed to actually wrap the output string in quotes; that's just how the book writes string literals. But I might be mistaken.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T15:37:01.550",
"Id": "427994",
"Score": "0",
"body": "@IlmariKaronen - OP is actually trying to implement [this](https://en.wikipedia.org/wiki/Serial_comma)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T15:43:06.903",
"Id": "427996",
"Score": "0",
"body": "@Justin No they're not. \"Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item.\" -> `', '.join(...)` and `list[-1] = 'and ' + list[-1]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T15:44:11.613",
"Id": "427997",
"Score": "0",
"body": "@Peilonrayz - Judging from OP's code, I meant. Take a look at Graipher's comments below."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T15:57:10.397",
"Id": "428000",
"Score": "0",
"body": "@Peilonrayz - `elif items == 2: return \" ' \" + str(your_list[0]) + ' and ' + str(your_list[1]) + \" ' \"` in OP's code implements the Oxford comma. Also, it is mentioned in the question - \"no comma when list has two items\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T00:07:09.730",
"Id": "428060",
"Score": "2",
"body": "Don’t signal an error by returning an error message, throw an exception instead. The calling code will know better how exactly to notify the user of the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T05:16:10.383",
"Id": "428074",
"Score": "0",
"body": "@Ilmari Karonen - Good points about the quotes, and also about the change I made for two item lists. The task doesn't actually say to do anything different in such cases, so you're right. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T10:37:07.600",
"Id": "428117",
"Score": "5",
"body": "@IlmariKaronen That is almost certainly a failure in the specification. Such formatting would be obviously incorrect punctuation. The description doesn't contain any specific instructions on the case of a two item list and provides only an example of four items. Note that the description doesn't describe what to do in the case of empty or single item lists, either. The OP has *extended* the specification to handle edge cases that were left unspecified. Another valid approach would be to just throw an error for less than three items."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-02T10:23:29.167",
"Id": "428356",
"Score": "2",
"body": "Don't `return 'Your list is empty'`, throw an error!"
}
] | [
{
"body": "<p>You’ve got too many <code>()</code>’s in this statement:</p>\n\n<pre><code>your_list_split1 = (', '.join((map(str,your_list[:-1]))))\n</code></pre>\n\n<p>You don’t need the parenthesis around the entire expression, nor for the argument inside of the <code>join(...)</code> function. You should also add a space after the comma, to be PEP-8 compliant:</p>\n\n<pre><code>your_list_split1 = ', '.join(map(str, your_list[:-1]))\n</code></pre>\n\n<p>I’m not sure if it was a requirement of the question or not, but generally with lists, you do not include a comma between the second last item and the word “and”. If that comma is not required by the assignment, then if you remove it, the <code>items == 2</code> case is unnecessary, as the final <code>else</code> clause will properly handle 2 items. <strong>Edit</strong>: Or since the comma appears to be required, if it is acceptable for 2 items (<code>'item1, and item2'</code>), keep the comma in the <code>else:</code> and the <code>items == 2</code> case is still unnecessary.</p>\n\n<p>If you are learning Python 3, you should probably jump right to Python 3.7, and take advantage of f-strings, where you can put formatting codes for variables/expressions directly into the strings:</p>\n\n<pre><code>else:\n return f\"'{your_list_split1}, and {your_list[-1]}'\"\n</code></pre>\n\n<hr>\n\n<p>Don’t intermix code and function definitions.</p>\n\n<pre><code>def list_concatenator(your_list):\n # ... etc ...\n\nyour_list = [ ... ]\nlist_concatenator(your_list)\n</code></pre>\n\n<hr>\n\n<p>Avoid using global variable names as function argument names. In longer functions, the reader might get confused between whether a global variable is being referenced or not. </p>\n\n<hr>\n\n<p>As it presently stands, your code does some work, gets a result, and then does nothing with it. You probably want to assign the returned value to a variable, or print it, or both.</p>\n\n<hr>\n\n<p>You are calling <code>str(...)</code> alot throughout your function, to ensure that the item you are referencing in your list is a string which can be concatenated with other strings. You should instead just do it once, at the top of the function:</p>\n\n<pre><code>def list_concatenator(your_list):\n your_list = list(map(str, your_list))\n # remainder of the code, without the need for any str( ) calls.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T15:18:36.523",
"Id": "427991",
"Score": "7",
"body": "The Oxford comma is required in the assignment, as shown in the example output (whether we like it or not...)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T15:22:12.303",
"Id": "427992",
"Score": "2",
"body": "And `your_list = map(str, your_list)` can be a problem, depending on what you want to do with it afterwards, since it is a generator-like object. So no `[-1]` to get the last element, no falsiness if it is empty, only being able to iterate over it once, etc. All of which you can remove by wrapping it with `list()`, of course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T15:26:46.377",
"Id": "427993",
"Score": "1",
"body": "If it is required in the two item case as well (`'item1, and item2'`), the comma can be included in the f-string and the `items == 2` special case can still be removed. It is only when it is not required for two items and required for 3 or more that the extra case becomes necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T15:40:24.487",
"Id": "427995",
"Score": "0",
"body": "@AJNeufeld - OP is actually trying to implement [this](https://en.wikipedia.org/wiki/Serial_comma)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T18:00:43.053",
"Id": "428028",
"Score": "2",
"body": "`generally with lists, you do not include a comma between the second last item and the word “and”.` According to https://en.wikipedia.org/wiki/Serial_comma, \"Opinions among writers and editors differ on whether to use the serial comma, and usage also differs somewhat between regional varieties of English. Generally (with few exceptions), British English does not make use of this comma, while on the other hand it is common and even mandatory in American English.[6] ... This practice is controversial and is known as the serial comma or Oxford comma. ...\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T20:36:09.817",
"Id": "428045",
"Score": "1",
"body": "@AJNeufeld - The `items == 2` special case is still needed. The question says - \"no comma when list has two items\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T20:41:09.040",
"Id": "428046",
"Score": "3",
"body": "@Justin Actually that is the OP’s addition to the problem; it is not mentioned in the chapter 4 problem text (which is now included in the question post verbatim)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T20:45:55.500",
"Id": "428047",
"Score": "2",
"body": "@AJNeufeld - Yes, according to OP's stated question (with the addition), I meant."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T04:50:49.840",
"Id": "221320",
"ParentId": "221318",
"Score": "9"
}
},
{
"body": "<p>Your code is well-built and covers everything stated in the task, but could be made much shorter by using the <a href=\"https://www.geeksforgeeks.org/python-format-function/\" rel=\"nofollow noreferrer\"><em>.format()</em></a> function. </p>\n\n<blockquote>\n <p><em><code>str.format()</code> is one of the string formatting methods in Python 3, which\n allows multiple substitutions and value formatting. This method lets\n us concatenate elements within a string through positional formatting.</em></p>\n</blockquote>\n\n<p>Your code can, therefore, be made shorter and more concise this way. Here is what your code might look like - </p>\n\n<pre><code>def list_concatenator(your_list):\n\n if not your_list:\n return \"Your list is empty!\"\n\n elif len(your_list) == 1:\n return str(your_list[0])\n\n elif len(your_list) == 2:\n return '{0} and {1}'.format(your_list[0], your_list[1])\n\n else:\n body = \", \".join(map(str, your_list[:-1]))\n return '{0}, and {1}'.format(body, your_list[-1])\n</code></pre>\n\n<p>I have used <code>{0} and {1}</code> so that positional arguments can be placed in the order you want them to be in, though it is not necessary to do so.</p>\n\n<p><strong>OR</strong></p>\n\n<p>Another way to format in Python 3 is to use <a href=\"https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/\" rel=\"nofollow noreferrer\"><em>f-strings</em></a>.</p>\n\n<blockquote>\n <p><em>The idea behind <code>f-strings</code> is to make string interpolation simpler. To create an <code>f-string</code>, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with <code>str.format()</code>. <code>f-strings</code> provide a concise and convenient way to embed python expressions inside string literals for formatting.</em></p>\n</blockquote>\n\n<p>Here's how your code would look like with <code>f-strings</code> (much shorter) - </p>\n\n<pre><code>def list_concetenator(your_list):\n\n if not your_list:\n return \"Your list is empty!\"\n\n elif len(your_list) == 1:\n return str(your_list[0])\n\n elif len(your_list) == 2:\n return f'{your_list[0]} and {your_list[1]}'\n\n else:\n body = \", \".join(map(str, a_list[:-1]))\n return f'{body}, and {your_list[-1]}'\n</code></pre>\n\n<p>Here are some example outputs -</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>your_list = ['item1', 'item2', 3, 'item4', 'item5', 'item6', 7, 'item8', 9]\n\nprint(list_concatenator(['item1', 'item2', 3, 'item4', 'item5', 'item6', 7, 'item8', 9]))\n>>> item1, item2, 3, item4, item5, item6, 7, item8, and 9\n\nprint(list_concatenator(['item1', 'item2', 3]))\n>>> item1, item2, and 3\n\nprint(list_concatenator(['item1', 3]))\n>>> item1 and 3\n\nprint(list_concatenator(['item1']))\n>>> item1 \n\nprint(list_concatenator([]))\n>>> Your list is empty!\n</code></pre>\n\n<p>The program also takes care of the Oxford comma, where lists with <em>two</em> items do not have commas (e.g. <code>apples and bananas</code>) but lists with <em>more than</em> two items are separated with commas (<code>apples, bananas, and cakes</code>). Here are some useful links that help us understand what Oxford commas really are and when they should be used - </p>\n\n<ol>\n<li><p><em><a href=\"https://www.grammarly.com/blog/comma-before-and/\" rel=\"nofollow noreferrer\">https://www.grammarly.com/blog/comma-before-and/</a></em></p></li>\n<li><p><em><a href=\"https://en.wikipedia.org/wiki/Serial_comma\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Serial_comma</a></em></p></li>\n</ol>\n\n<p>Overall, I believe formatting was the main problem in your code.</p>\n\n<hr>\n\n<p><strong>EDIT -</strong> </p>\n\n<p>In the comments section above, @Ilmari Karonen correctly mentions that the usage of \" <code>'</code> \" in the book is the book's way of writing string literals. Therefore, I have edited my answer to make this change (i.e. remove unnecessary quotes). But if you require these quotes, then you could always wrap the string in double quotes, like this - <code>f\"'{your_list[0]} and {your_list[1]}'\"</code> or this - <code>\"'{0} and {1}'\".format(your_list[0], your_list[1])</code>. </p>\n\n<p>Another let-down in your code is the use of inconsistent parentheses here,</p>\n\n<p><code>(', '.join((map(str,your_list[:-1]))))</code> </p>\n\n<p>which could just be written as -</p>\n\n<p><code>', '.join(map(str,your_list[:-1]))</code>. </p>\n\n<p>To remain concise and immaculate in writing programs, I suggest you have a look at <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\"><em>PEP 8</em></a>, which is Python's official style guide.</p>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T12:31:34.950",
"Id": "428258",
"Score": "1",
"body": "forgot to comment earlier and say thanks, I did find your answer very useful too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T13:04:23.207",
"Id": "428536",
"Score": "0",
"body": "@benb - I'm glad my answer helped you. Just wondering why you unaccepted my answer :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T04:08:02.113",
"Id": "428642",
"Score": "0",
"body": "Sorry about that, there's nothing wrong with your answer. I've actually started using f-strings because of your advice, thank you. It was difficult to pick ONE answer, and I decided on AJNeufelds because other beginners reading this would probably benefit from the extra things his answer covers (e.g., not to use global variable names as function names etc.)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T04:13:52.727",
"Id": "428643",
"Score": "1",
"body": "@benb - No worries. Just so know, I've also provided a link to PEP 8, which is Python's official style guide. It should help you with formatting and style in every possible way."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T04:53:19.477",
"Id": "221321",
"ParentId": "221318",
"Score": "13"
}
},
{
"body": "<ol>\n<li><p>If you need to add <code>''</code> then you should do this outside of the function. This can be fairly easy knowing the output is always a string.</p>\n\n<pre><code>>>> print(repr(list_concatenator('a')))\n'a'\n</code></pre>\n\n<p>By default the IDLE prompt does this automatically.</p>\n\n<pre><code>>>> list_concatenator('a')\n'a'\n</code></pre></li>\n<li><p>Rather than using <code>len(your_list) == 0</code> you can use <code>not your_list</code>.</p>\n\n<pre><code>if not your_list:\n return 'Your list is empty'\n</code></pre></li>\n<li><p>You can use <code>str.join</code> to join the rest of your lists.</p></li>\n</ol>\n\n<pre><code>def list_concatenator(your_list, comma=', ', conjunction=' and '):\n if not your_list:\n return 'Your list is empty'\n\n your_list = [str(i) for i in your_list]\n if len(your_list) > 1:\n your_list[:-1] = [comma.join(your_list[:-1])]\n return conjunction.join(your_list)\n\n>>> list_concatenator(['item1', 'item2', 3, 'item4', 'item5', 'item6', 7, 'item8', 9])\n'item1, item2, 3, item4, item5, item6, 7, item8 and 9'\n>>> list_concatenator('abcde', conjunction=' or ')\n'a, b, c, d or e'\n>>> list_concatenator('abcde', conjunction=', or ')\n'a, b, c, d, or e'\n>>> list_concatenator('ab')\n'a and b'\n>>> list_concatenator('a')\n'a'\n</code></pre>\n\n<hr>\n\n<p>It should be noted that the challenge says to seperate each value with a <code>', '</code>, and so you could simplify this by mutating the last value with the conjunction, and just use one <code>str.join</code>.</p>\n\n<pre><code>def list_concatenator(your_list, comma=', ', conjunction='and'):\n if not your_list:\n return 'Your list is empty'\n\n your_list = [str(i) for i in your_list]\n if len(your_list) > 1:\n your_list[-1] = conjunction + ' ' + your_list[-1]\n return comma.join(your_list)\n\n>>> list_concatenator(['item1', 'item2', 3, 'item4', 'item5', 'item6', 7, 'item8', 9])\n'item1, item2, 3, item4, item5, item6, 7, item8, and 9'\n>>> list_concatenator('abcde', conjunction='or')\n'a, b, c, d, or e'\n>>> list_concatenator('ab')\n'a, and b'\n>>> list_concatenator('a')\n'a'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:18:18.800",
"Id": "428095",
"Score": "1",
"body": "Posting on behalf of a_faulty_star.\na_faulty_star: P.S: I have noticed that the outputs in Peilonrayz's answer have single quotes for every element of the input list, which is not the desired output. As I don't have 150 reputation, I can't comment :( But if someone who has 150 reputation notices this, please inform them! Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:22:42.560",
"Id": "428098",
"Score": "1",
"body": "@benb It was in your original code. You should be able to see how to remove them if you need to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:41:40.307",
"Id": "428106",
"Score": "2",
"body": "In my original code the output looked like 'item1, item2' etc., with the whole string having ' ' around it. What a_faulty_star is pointing out is in the above code the output is 'item1', 'item2' two etc., with each item having it's own quotes. As you said, you can fix it by taking out the double quotes \"\" in your_list = [f\"'{i}'\" for i in your_list]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T09:01:49.737",
"Id": "428109",
"Score": "2",
"body": "Ah, I misread your `' and '` as `\"' and '\"`. I've changed it now."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T14:10:16.933",
"Id": "221344",
"ParentId": "221318",
"Score": "9"
}
},
{
"body": "<p>I used the following function for achieving the task. I am new here, so please feel free to comment anything you feel is wrong!</p>\n\n<p>In the function, firstly, I check if the given list is empty or not. </p>\n\n<p>If it is, then I return an empty string. </p>\n\n<p>Otherwise, I first store the length of string in a variable. Then, I use list comprehension to convert all the elements in the list to string format, because some of them may be non-string and cause an error while using join function. Then, I join the strings in the list, separated by a comma and space, by using the join function on all elements of the list except the last. Then, I add an 'and' if the list has three or more elements. I have added the Oxford comma and a space before 'and' because the question has mentioned it.</p>\n\n<p>Here is the function:</p>\n\n<pre><code>>>> def list_concatenator(your_list):\n if not your_list:\n return ''\n your_list = [str(i) for i in your_list]\n p = len(your_list)\n return ', '.join(your_list[:-1]) + (',' if p>2 else '') + (' and ' if p>1 else '') + your_list[-1]\n</code></pre>\n\n<p>Here are some outputs:</p>\n\n<pre><code>>>> li = []\n>>> print(list_concatenator(li))\n\n\n>>> li2 = ['apples']\n>>> print(list_concatenator(li2))\napples\n\n>>> li3 = ['apples', 'bananas']\n>>> print(list_concatenator(li3))\napples and bananas\n\n>>> li4 = ['apples', 'bananas', 'tofu', 'cats']\n>>> print(list_concatenator(li4))\napples, bananas, tofu, and cats\n\n>>> li5 = ['item1', 'item2', 3, 'item4', 'item5', 'item6', 7, 'item8', 9]\n>>> print(list_concatenator(li5))\nitem1, item2, 3, item4, item5, item6, 7, item8, and 9\n</code></pre>\n\n<p>P.S: I have noticed that the outputs in Peilonrayz's answer have single quotes for every element of the input list, which is not the desired output. As I don't have 150 reputation, I can't comment :( But if someone who has 150 reputation notices this, please inform them! Thanks!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:21:35.597",
"Id": "428097",
"Score": "2",
"body": "I think this is a great solution. I will leave @AJNeufeld comment as the answer as I think it provides a lot of useful information for a beginner, but your solution seems to do everything required while also being very concise. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T12:38:48.923",
"Id": "428135",
"Score": "1",
"body": "@a_faulty_star - You have not implemented the Oxford comma in your answer. An Oxford comma is where lists with two items do not have commas but lists with more than two items are separated with commas. Here is the link - https://en.wikipedia.org/wiki/Serial_comma. Therefore, if you *are* using the Oxford comma, then your third output should be - `apples and bananas`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T12:39:18.387",
"Id": "428136",
"Score": "1",
"body": "@benb ofcourse, the selected answer is helpful in accordance to the code you have typed.. I just offered an alternate solution :) Good luck!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T12:42:03.547",
"Id": "428137",
"Score": "1",
"body": "@Justin thanks for pointing it out! I thought the Oxford comma is for two or more words.. I'll fix it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T13:04:00.817",
"Id": "428141",
"Score": "0",
"body": "I just realized that this is 'Code Review' and not 'Stack Overflow'. My first attempt to answer and it's already a disaster, as always. Great. I should have just reviewed the code you wrote, not answer my own! :\\\n\nBTW, I just found out that this question has already been asked before in SO, and here's the link:\nhttps://stackoverflow.com/questions/32008737/how-to-efficiently-join-a-list-with-commas-and-add-and-before-the-last-element\n\nThe top answer is great, check it out!\n\nSorry for my mistakes!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T13:21:27.003",
"Id": "428144",
"Score": "3",
"body": "@a_faulty_star - No worries. Your answer is pretty close to a code review and you have already received 3 upvotes, which is amazing for a first attempt. As benb said, your solution is very concise, so it did help him. Kudos for writing your first answer on Code Review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T13:55:09.690",
"Id": "428147",
"Score": "2",
"body": "Thank you @Justin. You and benb are too kind :')"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:40:29.547",
"Id": "221392",
"ParentId": "221318",
"Score": "5"
}
},
{
"body": "<p>Here are a few mostly stylistic points.</p>\n\n<pre><code> def list_concatenator(your_list):\n</code></pre>\n\n<p>\"list_concatenator\" is a poor choice for a function name. I'd rather expect \"concatenator\" to be a class that provides concatenation. A function name is, more commonly, a verb, that tells what the function does (e.g. <code>sort</code>) or a noun describing what the function returns (e.g. <code>sqrt</code>). Besides, \"concatenate a list\" is a very vague description of the task at hand. Therefore I'd suggest to name your function like \"join_with_serial_comma\" or \"oxford_comma_concat\" or even \"oxfordize\" ;)</p>\n\n<p>\"your_list\" is bad too (who's this \"you\" exactly?). It's just some list, so name it \"some_list\" or \"a_list\" or \"lst\". Moreover, since you're only using <code>len</code> and <code>[]</code> in your code, there's no reason to restrict your function to lists specifically, just make it accept any <a href=\"https://docs.python.org/3.7/glossary.html#term-sequence\" rel=\"nofollow noreferrer\">sequence</a> and name your argument like \"sequence\" or \"seq\"</p>\n\n<pre><code> items = len(your_list)\n</code></pre>\n\n<p>Again, poor variable naming. <code>items</code> is what the list contains (cf. <code>dict.items</code>), what you mean here is <code>length</code>, <code>size</code>, <code>number_of_items</code> and so on.</p>\n\n<pre><code> if items == 0:\n return 'Your list is empty'\n</code></pre>\n\n<p>An empty list is an exceptional situation for your function, and you can't and shouldn't return any value in this case. Much better option would be to raise an exception (<code>ValueError</code> would be a good choice), better yet, just remove this condition, the rest of the code is going to break anyways if the argument is empty (or not a sequence at all, for that matter). <a href=\"https://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain\">Ask forgiveness, not permission</a>.</p>\n\n<pre><code> elif items == 1:\n return \"'\" + str(your_list[0]) + \"'\"\n</code></pre>\n\n<p>If the previous condition ends with <code>return</code> or <code>raise</code>, there's no need for <code>elif</code>, just <code>if</code> would be more readable.</p>\n\n<pre><code> elif items == 2:\n return \"'\" + str(your_list[0]) + ' and ' + str(your_list[1]) + \"'\"\n</code></pre>\n\n<p>As said in other posts, <code>format</code> or f-strings are usually more readable than concatenation.</p>\n\n<pre><code> else:\n your_list_split1 = (', '.join((map(str,your_list[:-1]))))\n return \"'\" + your_list_split1 + ', and ' + str(your_list[-1]) + \"'\"\n</code></pre>\n\n<p>Yet again, <code>your_list_split1</code> is a weird variable name, and doesn't reflect what the variable actually contains.</p>\n\n<p>Since you always <code>return</code> from other branches, you can remove <code>else</code> here and reduce the indentation.</p>\n\n<p>Comprehensions are usually more readable in python than <code>map</code>:</p>\n\n<pre><code> head = ', '.join(str(item) for item in sequence[:-1])\n</code></pre>\n\n<p>A more \"pythonic\" alternative to <code>-1</code> indexing would be an unpacking assignment:</p>\n\n<pre><code> *head, tail = seq\n head_joined = ', '.join(str(p) for p in head)\n return f'{head_joined}, and {tail}'\n</code></pre>\n\n<p>Hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:35:27.893",
"Id": "221397",
"ParentId": "221318",
"Score": "3"
}
},
{
"body": "<p>Slicing the list would allow you to get all except the last element. Testing the list length will indicate what needs to go before the final element.</p>\n\n<pre><code>if len(your_list) > 0:\n if len(your_list) > 2: ander = ',' # if passive comma needed\n if len(your_list) > 1: ander += ' and '\n ', '.join(your_list[0:-1]) + ander + thelist[-1]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T19:00:27.763",
"Id": "221441",
"ParentId": "221318",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221320",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T03:09:34.860",
"Id": "221318",
"Score": "18",
"Tags": [
"python",
"beginner",
"python-3.x",
"strings"
],
"Title": "Comma Code - Ch. 4 Automate the Boring Stuff"
} | 221318 |
<p>I'm creating an application that requires multiple tkinter windows. The code below works the way how I want it to work, but I'm not sure if I'm doing it in the proper way.</p>
<p>The first window (and in this case, the main window as well) contains three buttons as of now, 1 label which acts as a title, and a treeview.</p>
<p>The "Add Member" button is the only button that has functionality as of now. When clicked, it will pop a new window. That said window contains label.</p>
<p>To sum it up, I would like to humbly ask if I'm doing it properly, or there is a better and more accurate way of writing this code.</p>
<pre><code>class Application(tk.Frame):
def __init__(self,parent,*args,**kwargs):
tk.Frame.__init__(self,parent)
self.parent = parent
self.parent.title("Senior Citizen Association")
ttk.Label(text="SENIOR CITIZEN ASSOCIATION").grid(row=0,column=0,columnspan=5,sticky="n")
ttk.Button(text="Add",command=self.add_member).grid(row=1,column=0,sticky="w")
ttk.Button(text="Delete").grid(row=2,column=0,sticky="w")
ttk.Button(text="Exit",command=lambda:self.parent.destroy()).grid(row=3,column=2,sticky="se")
self.tree = ttk.Treeview(height=15,column=("First Name","Middle Initial","Last Name"))
self.tree.heading("#0",text="First Name",anchor="w")
self.tree.heading("#1",text="Middle Initial",anchor="w")
self.tree.heading("#2",text="Last Name",anchor="w")
self.tree.heading("#3",text="Status",anchor="w")
self.tree.grid(row=1,column=1,rowspan=2,columnspan=2,sticky="nsew")
def add_member(self):
self.addMemberWindow = tk.Toplevel(self.parent)
self.addClass = NewMember(self.parent,self.addMemberWindow)
class NewMember(tk.Frame):
def __init__(self,parent,child,*args,**kwargs):
tk.Frame.__init__(self,child)
self.parent = parent
self.child = child
self.child.title("Add Member")
ttk.Label(self.child,text="Add Member").grid(row=0,column=0,sticky="nsew")
if __name__ == "__main__":
app = tk.Tk()
Application(app)
app.mainloop()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T02:16:43.700",
"Id": "479511",
"Score": "0",
"body": "You can find the solution at below given link <br> https://stackoverflow.com/questions/16115378/tkinter-example-code-for-multiple-windows-why-wont-buttons-load-correctly"
}
] | [
{
"body": "<p>For me, it is a pretty piece of code. I learned much from it. Also, I'm not sure if it is a proper way. But, it works fine and is easy to read :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T16:54:06.387",
"Id": "448135",
"Score": "2",
"body": "Welcome to Code Review! Could you expand upon this? Perhaps explain what makes it easy to read..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T16:32:34.263",
"Id": "230172",
"ParentId": "221325",
"Score": "-2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T07:32:14.777",
"Id": "221325",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"gui",
"tkinter",
"tk"
],
"Title": "Tkinter application with multiple windows"
} | 221325 |
<h1>Overview</h1>
<p>This is my solution to the following <a href="https://www.careercup.com/question?id=5702311087702016" rel="nofollow noreferrer">Coding Challenge - Find Num of Elements in a Range in <span class="math-container">\$O(1)\$</span> with Preprocessing</a> -</p>
<blockquote>
<p>Given an array and max element in the array, find the number of elements present
between a given range in <span class="math-container">\$O(1)\$</span>. You can do one-time processing of an array.</p>
</blockquote>
<h1>Solutions</h1>
<h2>Solution1</h2>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution
{
public:
Solution(vector<int>& v)
{
sort(v.begin(), v.end());
for(unsigned int i=0; i<v.size(); ++i) m[v[i]] = i;
}
unsigned int count(const int a, const int b)
{
if(!(a < b)) throw runtime_error("Wrong Order");
if( (m.find(a) == m.end()) || (m.find(b) == m.end()) ) throw runtime_error("Not Found");
return m[b] - m[a] + 1;
}
private:
unordered_map<int, unsigned int> m;
};
int main() {
// your code goes here
int N;
cin >> N;
vector<int> data;
for(int i=0; i<N; ++i)
{
int temp;
cin >> temp;
data.push_back(temp);
}
Solution sol(data);
const auto left = 1;
const auto right = 3;
const auto res = sol.count(left, right);
cout << "Left = " << left << ", Right = " << right << " --> Res = " << res << endl;
return 0;
}
</code></pre>
<p>Input </p>
<pre><code>10
1 3 5 7 9 6 2 8 12 22
</code></pre>
<p><strong>Notes</strong> </p>
<ul>
<li>Even if typically for Algorithmic Coding Challenges a free function is good enough and using a class is over-engineering, in this specific I went for the class on purpose in order to possibly amortize the pre-processing cost by multiple calls to the <code>count()</code> method. </li>
</ul>
<h2>Solution2</h2>
<p>This is an <strong>Edit</strong> in order to propose an alternative solution based on @peter-taylor comment about the range </p>
<p>This solution does not throw an exception in case the values in the input range are not in the array and it is still $O(1)$ in time, just added more space complexity </p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution
{
public:
Solution(vector<int>& v)
{
sort(v.begin(), v.end());
start = v[0];
end = v[v.size()-1];
unsigned int count=1;
unsigned int j=1;
for(int i=start; i<end; ++i)
{
if(i==v[j])
{
count++;
j++;
}
m[i] = count;
}
}
unsigned int count(const int a, const int b)
{
if(!(a < b)) throw runtime_error("Wrong Order");
return get_num(b) - get_num(a);
}
private:
unordered_map<int, unsigned int> m;
int start;
int end;
unsigned int get_num(const int a)
{
if(a < start) return 0 ;
if(a >= end) return m.size();
return m[a];
}
};
int main() {
// your code goes here
int N;
cin >> N;
vector<int> data;
for(int i=0; i<N; ++i)
{
int temp;
cin >> temp;
data.push_back(temp);
}
Solution sol(data);
const auto left = 0;
const auto right = 3;
const auto res = sol.count(left, right);
cout << "Left = " << left << ", Right = " << right << " --> Res = " << res << endl;
return 0;
}
</code></pre>
<p><strong>Notes</strong></p>
<ul>
<li>In this implementation the number of elements is computed in a <code>(a,b]</code> range (so first not counted) as this is not violating anything in the specs </li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:17:11.143",
"Id": "428078",
"Score": "0",
"body": "This looks obviously buggy to me - the spec says nothing to justify the `throw`. What test cases did you use to test it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T18:15:22.613",
"Id": "428196",
"Score": "0",
"body": "Why buggy? \nAs the specs do not specify that case it's undefined behaviour (and I managed it in a reasonable way). \nIt does not make sense to test undefined behaviours in test cases"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T19:51:59.957",
"Id": "428205",
"Score": "0",
"body": "The spec says \"*a given range*\". It's not reasonable to say that since it doesn't *explicitly* say \"*a given range whose endpoints might not be in the array*\" it *must* mean \"*a given range whose endpoints are in the array*\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T07:02:34.107",
"Id": "428233",
"Score": "0",
"body": "OK @PeterTaylor I have added Solution 2 according to your observation: still O(1) in time but more space complexity"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T08:21:15.120",
"Id": "221327",
"Score": "2",
"Tags": [
"c++",
"programming-challenge",
"hash-map"
],
"Title": "Coding Challenge Solution - Find Number of Elements in a range in \\$O(1)\\$ with preprocessing"
} | 221327 |
<p>This is a <a href="https://leetcode.com/problems/24-game/" rel="nofollow noreferrer">Leetcode problem</a> -</p>
<blockquote>
<p><em>You have 4 cards each containing a number from <code>1</code> to <code>9</code>. You need to
judge whether they could be operated through <code>*</code>, <code>/</code>, <code>+</code>, <code>-</code>, (<code>,</code>)
to get the value of <code>24</code>.</em></p>
<p><strong><em>Note -</em></strong></p>
<p><em>1. The division operator <code>/</code> represents real division, not integer division. For example, <code>4 / (1 - 2/3) = 12</code>.</em></p>
<p><em>2. Every operation done is between two numbers. In particular, we cannot use <code>-</code> as a unary operator. For example, with <code>[1, 1, 1, 1]</code>
as input, the expression <code>-1 - 1 - 1 - 1</code> is not allowed.</em></p>
<p><em>3. You cannot concatenate numbers together. For example, if the input is <code>[1, 2, 1, 2]</code>, we cannot write this as <code>12 + 12</code>.</em></p>
</blockquote>
<p>Here is my solution to this challenge -</p>
<blockquote>
<pre><code>class Solution(object):
def judge_point_24(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) == 1:
return nums[0] == 24 or abs(nums[0] - 24.0) <= 0.1
for i in range(len(nums)):
for j in range(len(nums)):
if i == j:
continue
indexes = set([x for x in range(len(nums))])
indexes.remove(i)
indexes.remove(j)
operations = []
operations.append(float(nums[i]) + float(nums[j]))
operations.append(float(nums[i]) - float(nums[j]))
operations.append(float(nums[j]) - float(nums[i]))
operations.append(float(nums[i]) * float(nums[j]))
if nums[j] != 0:
operations.append(float(nums[i] / float(nums[j])))
if nums[i] != 0:
operations.append(float(nums[j] / float(nums[i])))
next_items = [nums[index] for index in indexes]
for x in operations:
if self.judge_point_24(next_items + [x]) == True:
return True
return False
</code></pre>
</blockquote>
<p><strong>Explanation</strong> - My solution is to reduce the <code>nums</code> size until it becomes the size of one. Once it is the size of one, check if we have reached <code>24</code> or close enough. Basically, I tried to pick two elements from the array and apply all the possible computations and recursively call itself now with the array that has the result of the computation and the rest. As soon as I see <code>True</code> from the call, I return <code>True</code> as well.</p>
<p>Here are some example outputs -</p>
<pre><code>#output = Solution()
#print(output.judge_point_24([4, 1, 8, 7]))
>>> True
#Explanation - (8-4) * (7-1) = 24
</code></pre>
<hr>
<pre><code>#output = Solution()
#print(output.judge_point_24([1, 2, 1, 2]))
>>> False
</code></pre>
<p>Here are the times taken for these outputs -</p>
<pre><code>%timeit output.judge_point_24([4, 1, 8, 7])
2.16 ms ± 46 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit output.judge_point_24([1, 2, 1, 2])
43 ms ± 902 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code></pre>
<p>Here is my Leetcode result -</p>
<p><a href="https://i.stack.imgur.com/10ND6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/10ND6.png" alt="Leetcode results"></a></p>
<p>So, I would like to know whether I could make this program shorter and more efficient.</p>
<p>Any help would be highly appreciated. </p>
| [] | [
{
"body": "<h2>Docstring</h2>\n\n<p>Is <code>nums</code> really of type <code>List[int]</code>? Perhaps the first time it is, but after the first step, it is going to turn into a <code>List[float]</code>.</p>\n\n<hr>\n\n<h2>Efficiency</h2>\n\n<p>Assuming <code>nums</code> is a list of numbers (<code>int</code> or <code>float</code>), you never need to call <code>float()</code> on any of the values. If you expect a list of 4 strings (<code>\"1\"</code>, through <code>\"9\"</code>) from the contest input, turn them into numbers using <code>int(_)</code> and then pass the <code>List[int]</code> to your judge function.</p>\n\n<hr>\n\n<p>The test <code>nums[0] == 24 or abs(nums[0] - 24.0) <= 0.1</code> could be simplified to just <code>abs(nums[0] - 24.0) <= 0.1</code>.</p>\n\n<hr>\n\n<p>Your doing a lot more work than you think you are. This code is looping through your list, finding pairs of values:</p>\n\n<pre><code> for i in range(len(nums)):\n for j in range(len(nums)):\n if i == j:\n continue\n</code></pre>\n\n<p>For each pair, i & j, you compute all possible combinations of those values, including reverse subtraction and reverse division.</p>\n\n<p>And later, you'll encounter the same pair only as j & i! And you'll compute all possible combinations of those values a second time.</p>\n\n<p>If your inner loop started at one index after the current outer loop index, then you'd never generate a pair of indices with <code>i > j</code> ... or even <code>i == j</code>, so you can omit that test as well. Finally, since the inner loop starts at 1 index above the outer loop, the outer loop should end one index early:</p>\n\n<pre><code> for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n</code></pre>\n\n<hr>\n\n<p>You could also use <code>enumerate( )</code> to loop over the values along with their indices at the same time.</p>\n\n<pre><code> for i, a in enumerate(nums[:-1]):\n for j, b in enumerate(nums[i+1:], i+1):\n</code></pre>\n\n<p>And then you can refer to <code>a</code> instead of <code>nums[i]</code>, and <code>b</code> instead of <code>nums[j]</code>, which will prevent repeated indexing into the <code>nums[]</code> array, which will result in decreased performance.</p>\n\n<hr>\n\n<p>Management of remaining values:</p>\n\n<pre><code> indexes = set([x for x in range(len(nums))])\n indexes.remove(i)\n indexes.remove(j)\n next_items = [nums[index] for index in indexes]\n</code></pre>\n\n<p>First <code>set([x for x in range(len(nums))])</code> could simply be <code>set(range(len(nums)))</code>. There is no need for the list comprehension.</p>\n\n<p>But this is still a lot of extra work. Simply copy the numbers to a new list, and then delete the i-th & j-th entries. Since <code>i < j</code> is guaranteed, deleting the j-th element first won't change the location of the i'th element:</p>\n\n<pre><code> next_items = nums[:]\n del next_items[j]\n del next_items[i]\n</code></pre>\n\n<p>Or, build up the new list with just the elements you want by omitting the i-th and j-th elements:</p>\n\n<pre><code> next_items = nums[:i] + nums[i+1:j] + nums[j+1:]\n</code></pre>\n\n<hr>\n\n<p><code>2+2 == 2*2</code> and <code>1*1 == 1/1 == reverse_div(1,1)</code>. It is a small optimization, but instead of making a list of all possible <code>operations</code> values, you could make a <code>set()</code> of the values, which would eliminate some redundant recursive steps.</p>\n\n<hr>\n\n<p>If you don't need this to be a <code>class</code> as a requirement of the leetcode automated judging, you can gain some efficiency by not passing an extra <code>self</code> argument all the time. This can simply be a function.</p>\n\n<hr>\n\n<h2>Reworked Code</h2>\n\n<pre><code>def judge_point_24(nums):\n\n for i, a in enumerate(nums[:-1]):\n for j, b in enumerate(nums[i+1:], i+1):\n operations = {a+b, a*b, a-b, b-a}\n if a:\n operations.add(b/a)\n if b:\n operations.add(a/b)\n\n if len(nums) > 2:\n next_items = nums[:i] + nums[i+1:j] + nums[j+1:]\n for x in operations:\n if judge_point_24(next_items + [x]) == True:\n return True\n else:\n return any(abs(x-24) < 0.1 for x in operations)\n\n return False\n\nif __name__ == '__main__':\n\n def test(expected, nums):\n print(nums, judge_point_24(nums))\n assert judge_point_24(nums) == expected\n\n test(True, [4, 1, 8, 7])\n test(False, [1, 2, 1, 2])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T19:20:28.333",
"Id": "428037",
"Score": "0",
"body": "Upvoted! Thanks @AJNeufeld. Your answer really helped me a lot. Again, thanks for your time and patience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T19:30:34.570",
"Id": "428039",
"Score": "0",
"body": "Here's the Leetcode result for your amazing code - `Runtime: 64 ms, faster than 88.47% of Python 3 online submissions for 24 Game`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T19:18:11.577",
"Id": "221362",
"ParentId": "221328",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221362",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T08:53:37.243",
"Id": "221328",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge",
"depth-first-search"
],
"Title": "(Leetcode) 24 game in Python"
} | 221328 |
<p>I am doing Kickstart's problem Wiggle Walk. I have tried to code with matrix, dictionary and nested dictionary but the time exceeds the limit in each submition. Can anyone help me optimize it better or is there any algorithm which I may have overlooked.
The problem statement is </p>
<blockquote>
<p>Problem
Banny has just bought a new programmable robot. Eager to test his coding skills, he has placed the robot in a grid of squares with R rows (numbered 1 to R from north to south) and C columns (numbered 1 to C from west to east). The square in row r and column c is denoted (r, c).</p>
<p>Initially the robot starts in the square (SR, SC). Banny will give the robot N instructions. Each instruction is one of N, S, E or W, instructing the robot to move one square north, south, east or west respectively.</p>
<p>If the robot moves into a square that it has been in before, the robot will continue moving in the same direction until it reaches a square that it has not been in before. Banny will never give the robot an instruction that will cause it to move out of the grid.
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case starts with a line containing the five integers N, R, C, SR and SC, the number of instructions, the number of rows, the number of columns, the robot's starting row and starting column, respectively.</p>
<p>Then, another line follows containing a single string of N characters; the i-th of these characters is the i-th instruction Banny gives the robot (one of N, S, E or W, as described above).</p>
</blockquote>
<p>My code is as follows:</p>
<pre><code>for j in range(int(input())):
instructions,rows,cols,startRow,startCol = map(int,input().split())
a=input()
dict={}
startRow-=1
startCol-=1
dict[startRow]={startCol:1}
i=0
while i <len(a):
if a[i]=="N":
if startRow-1 not in dict:
dict[startRow-1]={startCol:1}
i+=1
elif startCol not in dict[startRow-1]:
dict[startRow-1][startCol]=1
i+=1
startRow-=1
elif a[i]=="S":
if startRow+1 not in dict:
dict[startRow+1]={startCol:1}
i+=1
elif startCol not in dict[startRow+1]:
dict[startRow+1][startCol]=1
i+=1
startRow+=1
elif a[i]=="W":
if startRow not in dict:
dict[startRow]={startCol-1:1}
i+=1
elif startCol-1 not in dict[startRow]:
dict[startRow][startCol-1]=1
i+=1
startCol-=1
elif a[i]=="E":
if startRow not in dict:
dict[startRow]={startCol+1:1}
i+=1
elif startCol+1 not in dict[startRow]:
dict[startRow][startCol+1]=1
i+=1
startCol+=1
print("Case #{0}: {1} {2}".format(j+1,startRow+1,startCol+1))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T12:52:52.683",
"Id": "427975",
"Score": "0",
"body": "What have you tried yourself so far? Any time complexity analysis? What are example inputs when it's too slow?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T13:06:34.223",
"Id": "427979",
"Score": "0",
"body": "I have tried implementing it using 2d arrays, dictionaries. Inputs are not available as this is the question of competition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T13:08:18.960",
"Id": "427983",
"Score": "0",
"body": "And what are time complexities for those approaches? Can you construct input for which your code is too slow? If you don't have answers to these two questions, you're just shooting in the dark."
}
] | [
{
"body": "<p>At first glance, you code appears to have a lot of complicated and repetitive sections. That's a <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"noreferrer\">bad smell</a>, and often a hint that you should either split the repetitive parts off into a function or otherwise reorganize your code to get rid of the repetition. (Sometimes, one option can be to just simplify the code until the repetitive parts become trivial.)</p>\n\n<p>A lot of the complexity in the repetitive parts of your code seems to come from your decision to store the grid as a dictionary of dictionaries. There's a couple of ways to simplify that:</p>\n\n<ul>\n<li><p>In Python, dictionary keys can be tuples. So you can just do:</p>\n\n<pre><code>visited = {}\n# ...\nif (row, col) not in visited:\n # do something\n visited[row, col] = True\nelse:\n # do something else\n</code></pre>\n\n<p>(Also, you shouldn't name your dictionary <code>dict</code>, both because it's <a href=\"https://docs.python.org/3/library/stdtypes.html#dict\" rel=\"noreferrer\">the name of the dictionary type in Python</a> and also because it's an uninformative name that doesn't explain what you're using the dictionary for. Call its something meaningful like <code>visited_cells</code> or just <code>visited</code> instead.)</p></li>\n<li><p>Also, since you're really only using the dictionary as a set, why not make it one? The code can look exactly the same as above, except that you'll start with <code>visited = set()</code> instead of <code>visited = {}</code>, and mark cells as visited with <code>visited.add((row, col))</code>.</p></li>\n<li><p>Alternatively, instead of using a dictionary or a set, you could just use a two-dimensional array (implemented e.g. as a list of lists) of booleans, initialized to all <code>False</code>, something like this:</p>\n\n<pre><code>visited = [[False] * cols for row in range(rows)]\n# ...\nif not visited[row][col]:\n # do something\n visited[row][col] = True\nelse:\n # do something else\n</code></pre>\n\n<p>I suspect this is what the exercise is actually expecting you to do. However, I do rather like your idea of using a dictionary (or a set) instead, and I'm only mentioning this alternative for the sake of completeness.</p></li>\n</ul>\n\n<p>One advantage of using a dictionary or a set to store the visited cells is that it means you don't actually need to care about the boundaries of the grid, since the dictionary can accommodate arbitrary large or small coordinates. In particular, you don't actually need to adjust the input coordinates from one-based to zero-based indexing (and back again for output), so you can just eliminate those parts of your code.</p>\n\n<hr>\n\n<p>Another way to reduce the repetitiveness of your code is to observe that all the sections for handling movement in different directions look basically the same, except for the index (row or column) being changed and the step size (+1 or -1) it's being changed by. If you defined a dictionary that mapped the N/S/E/W direction letters to the corresponding coordinate offsets, something like this:</p>\n\n<pre><code>directions = {\n 'N': (-1, 0),\n 'S': (+1, 0),\n 'W': (0, -1),\n 'E': (0, +1),\n}\n</code></pre>\n\n<p>then you could combine all those sections into a single one, something like this:</p>\n\n<pre><code>row = start_row\ncol = start_col\nvisited = {(row, col)} # loop below assumes current square is always marked as visited\n\nfor compass_heading in instructions:\n row_step, col_step = directions[compass_heading]\n\n while (row, col) in visited:\n row += row_step\n col += col_step\n\n visited.add((row, col))\n</code></pre>\n\n<p>(Note that I renamed a few of your variables here. You should not use variables named <code>startRow</code> and <code>startCol</code> to store the <em>current</em> row and column, since that's just plain misleading, and in any case variable names in Python should be written in <code>snake_case</code> instead of <code>camelCase</code>. And <code>a</code> is just an awful variable name, so I renamed it to <code>instructions</code>. You already have a variable named that, but it's completely unnecessary and unused. You could just <a href=\"https://stackoverflow.com/questions/9532576/ignore-part-of-a-python-tuple\">use the dummy variable <code>_</code> in the list assignment</a> instead.)</p>\n\n<hr>\n\n<p>As for making the code faster, I see no obvious trivial opportunities there. Using a single set instead of a dictionary of dictionaries is probably somewhat faster, perhaps even twice as fast if your running time is dominated by dictionary lookups, but not <em>orders of magnitude</em> faster. A list of lists of booleans <em>might</em> be even faster for small grids, but the time to initialize it scales with the size of the grid, whereas the time to set up a single-element set (or dictionary) is basically constant. Anyway, I'd suggest first focusing on cleaning up your code, and only worrying about optimization if it's still too slow after that.</p>\n\n<p>If it is, a good starting point is to focus on worst-case performance, i.e. to think about how a sneaky test case designed might make your code run as slowly as possible, and try to find ways to counter that.</p>\n\n<p>In particular, the worst case input for your algorithm (with or without the improvements I suggested above) is something like <code>NSNSNSNSNSNSNSNSNSNSNSNSNS...</code>, which forces the robot to move back and forth over an increasingly long stretch of visited cells, leading to an O(<em>n</em>²) execution time.</p>\n\n<p>One way to avoid that would be to store a dictionary of \"signposts\" recording, for each move we make, where we ended up on the grid after that move. That way, the next time the robot finds itself in the same square and moving in the same direction, it can skip all the cells in between. Also, since the movement rules are symmetric, we can also leave behind \"backwards\" signposts recording where the robot came from as it entered each cell, allowing us to skip the intervening cells in the opposite direction as well.</p>\n\n<p>A quick sketch of how to implement that might look something like this:</p>\n\n<pre><code># look-up table of (row_step, col_step, opposite_heading) for each compass heading\ndirections = {\n 'N': (-1, 0, 'S'),\n 'S': (+1, 0, 'N'),\n 'W': (0, -1, 'E'),\n 'E': (0, +1, 'W'),\n}\n\nrow = start_row\ncol = start_col\nvisited = {(row, col)} # loop below assumes current square is always marked as visited\nsignposts = {}\n\nfor compass_heading in instructions:\n last_row = row\n last_col = col\n row_step, col_step, opposite_heading = directions[compass_heading]\n\n while (row, col) in visited:\n if (row, col, compass_heading) in signposts:\n # we've been this way before!\n row, col = signposts[row, col, compass_heading]\n row += row_step\n col += col_step\n\n visited.add((row, col))\n\n signposts[last_row, last_col, compass_heading] = (row, col)\n signposts[row, col, opposite_heading] = (last_row, last_col)\n</code></pre>\n\n<p>Note that, as written, the <code>signposts</code> dictionary always grows linearly with the size of the input. You may obtain some additional speed and memory savings by removing old signposts as they become unnecessary.</p>\n\n<p>In particular, we can safely remove any signposts we encounter as soon as we've used them, since they will either become useless or get overwritten anyway. We can also safely remove any <em>backwards</em> signposts that we pass, since those also become useless. With those changes, the optimized inner loop would look something like this:</p>\n\n<pre><code> while (row, col) in visited:\n if (row, col, compass_heading) in signposts:\n # follow and remove signposts; any that are still valid will be restored below\n row, col = signposts.pop((row, col, compass_heading))\n del signposts[row, col, opposite_heading]\n row += row_step\n col += col_step\n</code></pre>\n\n<p>However, note that the set of visited cells will still grow linearly, and that meandering paths like, say, <code>NESWNESWNESWNESWNESW...</code> can still leave behind a linearly growing number of signposts, so the worst-case memory consumption is still linear even with this optimization.</p>\n\n<p>Ps. <a href=\"https://tio.run/##fVOxjuIwEO39FXNQhCy5CHTdniiuQNfRUGyxQshLzGKtE@dsA0JRvp2bSRwbWAlXzrPf@L03k/riDrr6db2OYWL0eWudqDPYaeV3uq61lU6ksNcGBN8d8LCsubVwELyQ1ScrpBE7J3VlYQENA1zJKnmFyc95BrMMknWSZj28Jnjq4VWA3whGiAjJMsBLDxMB7yDcMmYdN26LUvGxuf9Cud2XrKwzx6BltFqu30bwAvPZjLGeEuisJ4UC7CTJZ0EeKIkuhLQFGIPSuoYPobAA@j6WwsLuaIyoHNh/R24ESAtcnfnFQsnNFxbhFnw9ZuVnhRm6Lh00QDn6CLc@QpAV3Gp/7fwrbgejpDdAvXCSTNCzpoX6C4hNen94fMO6OrWRlZvsR381EZqHSy3sjS6hwdfajE5Vm@f5KO2554NUAmJq5Mfb763Qkvt4I3tMoKOEpCKJ1hhHT3XhVwUYUeqTiFd/I3oBd@AOqBHWSaXgxJUs4EzbD4EU67TBpnQtvCs96KFBGCrmta4nT5SmdxUKoSL1PbIeW7BhN2/CdBH6FnCSMV2ELgZ8aAzcpT9E72POeVFE0ak/jMKGWcrCCH0ztsEQYoUH/hNjRPteHhUMwv8YI0/0T7g7Bz/QwnBlGBZo/K69OYxjAU3YdwFcr/8B\" rel=\"noreferrer\" title=\"Python 3 – Try It Online\">Here's a simple online demo</a> of the signpost-optimized algorithm I describe above, with some debug print statements added. Feel free to play around with it to see how it works.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:18:03.617",
"Id": "428155",
"Score": "0",
"body": "I had tried using 2-d arrays, it saves time but takes a lot of memory. I liked the idea of using sets. I actually have never tried it before. Thanks a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T14:15:48.810",
"Id": "221345",
"ParentId": "221332",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "221345",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:29:25.053",
"Id": "221332",
"Score": "7",
"Tags": [
"python",
"algorithm",
"python-3.x",
"time-limit-exceeded"
],
"Title": "Google \"Wiggle walk\""
} | 221332 |
<p>So, I've got a game in the pipeline. </p>
<p><a href="https://i.stack.imgur.com/7iHOV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7iHOV.png" alt="Game environment screenshot"></a></p>
<p>There's a problem, tho. After a couple of weeks of lunch hours incrementally adding stuff, it's regularly using up 100% of my CPU and slowing down. I don't really know how to go about debugging what part of the application is using all those resources.</p>
<p>I've particularly noticed that if you restart the map, (by pressing r or falling in water) a few times, the resource issue gets much worse.</p>
<p><strong>Possible issues:</strong></p>
<p>It's loading quite a lot of assets in <code>/js/loader.js</code></p>
<p>The collision method on the platforms group (<code>interaction.landOnPlatform</code>) is being called many times a second. Although that steps over most functionality when 3 flags are false.</p>
<pre><code> landOnPlatform: function (player, platform) {
if (platform.breakable) {
interaction.breakPlatform(player, platform);
}
if (player.slamming) {
player.slamming = false;
action.shakeCamera();
}
if (player.jumping) {
if (player.body.onFloor()) {
audio.play_land();
player.jumping = false;
} else if (player.body.onCeiling()) {
audio.play_sfx('head_block')
}
}
},
</code></pre>
<p>There's also quite a lot of objects being created by <code>map.draw</code> (reading a file from <code>/maps/</code></p>
<p>Because of the repeated reloading exacerbating the issue, could it be that this block in map.draw is not removing all the objects and their interactions from memory?</p>
<pre><code> platforms.clear(true, true);
doors.clear(true, true);
water.clear(true, true);
keys.clear(true, true);
springs.clear(true, true);
sliders.clear(true, true);
slider_tracks.clear(true, true);
</code></pre>
<hr>
<p>The full code base is here:</p>
<p><a href="https://github.com/AJFaraday/night_and_day" rel="nofollow noreferrer">https://github.com/AJFaraday/night_and_day</a></p>
<p>I'm really looking for advice on how to find this issue, or more information on exactly what and where the issue is. </p>
<p>Please be kind, I'm a ruby developer playing in JavaScript, so this isn't my first language.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T12:01:28.770",
"Id": "427962",
"Score": "2",
"body": "Have you tried profiling it? You can [use Chrome dev tools](https://developers.google.com/web/tools/chrome-devtools/rendering-tools/) for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T12:33:06.740",
"Id": "427971",
"Score": "0",
"body": "@Pritilender I wasn’t aware of it, but sounds like it could be really helpful here. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:18:21.017",
"Id": "428096",
"Score": "0",
"body": "I haven't yet solved this problem, but I did find this discussion of Phaser 3 performance. Saving for future investigation: http://www.html5gamedevs.com/topic/38516-what-is-wrong-with-phaser3-performance/"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:47:41.210",
"Id": "221334",
"Score": "1",
"Tags": [
"javascript",
"phaser.io"
],
"Title": "Why is this Phaser 3 app munching resources?"
} | 221334 |
<p>currently i am working on javascript. Learning deep etc. So i decided to made my own tic tac toe game 4x4 without any tips. Then i stucked. If anyone can help me will be perfect. Game is playable right now. But i can't set the algorithm who win the game? What should i refer for winner? All winner positions to an array, or save the player moves and put it in the algorithm? </p>
<p>Game is on 4x4 table, 3 in a row(vertical, horizontal or diagonal) won the game.</p>
<p>I am adding jsfiddle right here. Thanks in advance. </p>
<p><a href="https://jsfiddle.net/vsmile/fbgq1429/3/" rel="nofollow noreferrer">https://jsfiddle.net/vsmile/fbgq1429/3/</a></p>
<pre><code>$(document).ready(function()
{
const PLAYER = "X";
const COMPUTER = "O";
let game_status = true;
var emptyCells = [];
var playerPos = [];
var computerPos = [];
$('.col').click(function() {
isGameOver(PLAYER);
//Do Not Click Filled Div
if ($(this).text().length !== 0) {
return;
}
//Save Player Moves
playerPos.push([Number($(this).attr("data-x")), Number($(this).attr("data-y"))]);
//Make Click
$(this).html(PLAYER);
//Clear Empty Cells To Fill Later!
emptyCells = [];
//Let Computer Move
computerMove();
});
function computerMove(){
isGameOver(COMPUTER);
//Save Computer Moves
computerPos.push([Number($(this).attr("data-x")),Number($(this).attr("data-y"))]);
//Add All Empty Cells To An Array
for(let x=1; x<=4; x++){
for (let y=1; y<=4; y++) {
if ($('.col[data-x='+x+'][data-y='+y+']').text().length == 0) {
emptyCells.push($('.col[data-x='+x+'][data-y='+y+']'));
}
}
}
//Click Random Empty Cell
if (emptyCells.length > 0) {
let computerChoice = emptyCells[Math.floor(Math.random() * emptyCells.length)];
computerChoice.text(COMPUTER);
}
}
function isGameOver($req) {
//THIS IS WHERE I STUCK!
//Vertical Check
//Horizontal Check
//Diagonal Check
}
});
</code></pre>
<p>This is the HTML codes: </p>
<pre><code> <div class="row">
<div class="col" data-x="1" data-y="1"></div>
<div class="col" data-x="1" data-y="2"></div>
<div class="col" data-x="1" data-y="3"></div>
<div class="col" data-x="1" data-y="4"></div>
</div>
<div class="row">
<div class="col" data-x="2" data-y="1"></div>
<div class="col" data-x="2" data-y="2"></div>
<div class="col" data-x="2" data-y="3"></div>
<div class="col" data-x="2" data-y="4"></div>
</div>
<div class="row">
<div class="col" data-x="3" data-y="1"></div>
<div class="col" data-x="3" data-y="2"></div>
<div class="col" data-x="3" data-y="3"></div>
<div class="col" data-x="3" data-y="4"></div>
</div>
<div class="row">
<div class="col" data-x="4" data-y="1"></div>
<div class="col" data-x="4" data-y="2"></div>
<div class="col" data-x="4" data-y="3"></div>
<div class="col" data-x="4" data-y="4"></div>
</div>
</code></pre>
<p>EDIT: </p>
<p>If i put all correct solutions, it works like charm. But i need dynamically improve my code. For example;</p>
<pre><code> const grid = [
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
];
const wonMoves = [
[[1,1], [2,2], [3,3]],
[[1,1], [1,2], [1,3]],
..
..
];
</code></pre>
<p>After a move. I can change <code>grid[i][j];</code> then i can check if it matches the correct solutions.But what if tictactoe game 10x10 board? Now what? This should be dynamic. Thats what i need, that code improvement would be great. Thanks. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T13:07:45.463",
"Id": "427982",
"Score": "0",
"body": "Welcom to code review. Unfortunately this post is off topic. On code review we only suggest improvements to working code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T14:25:08.630",
"Id": "427989",
"Score": "0",
"body": "Actually its working when i made all correct solutions. Like this, i am editing question right now."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T11:59:25.307",
"Id": "221335",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"jquery",
"tic-tac-toe"
],
"Title": "Tic Tac Toe finish the game function"
} | 221335 |
<p>This is the first time that I have add (I mean, I try) Ajax with Jquery to PHP and Mysql (pagination). This is a link to the test page: <a href="http://mantykora.cleoni.com:8080/2020_pagination_1/public/page=2" rel="nofollow noreferrer">testpage1</a></p>
<p>I think everything works, but is it done correctly?</p>
<p>Thank you in advance for good advice .</p>
<p><strong>1. Ajax(index.php)</strong></p>
<pre><code>$(window).on('load', function () { // makes sure that whole site is loaded
$('#status').fadeOut();
$('#preloader').delay(350).fadeOut('slow');
});
$(document).ready(function(){
var url_string = window.location.href;
var url_parts = url_string.split('/');
var piece = url_parts[url_parts.length -1]; //get last part of url (it should be page=n)
var page;
if(piece.substring(0, 5) === 'page=') {
page = parseInt(piece.substr(5));
} else { //if it's the first time you landed in the page you haven't page=n
page = 1;
}
load_data(page);
// load_data(1);
function load_data(page)
{
$('#load_data').html('<div id="status" style="" ></div>');
$.ajax({
url:"pagination2.php",
method:"POST",
data:{page:page},
success:function(data){
$('#load_data').html(data);
}
});
}
$(document).on('click', '.pagination_link', function(event)
{
event.preventDefault();
var page = $(this).attr("id");
load_data(page);
//Now push PAGE to URL
window.history.pushState({page}, `Selected: ${page}`, `${'page=' + page}`)
//window.history.pushState({page}, `Selected: ${page}`, `./selected=${page}`)
return event.preventDefault();
});
window.addEventListener('popstate', e => {
var page = $(this).attr("id");
load_data(e.state.page);
console.log('popstate error!');
});
});
</code></pre>
<p><strong>2. pagination2.php</strong></p>
<pre><code> <?php
//$page = '';
$rowperpage = 10;
//$page = $_POST['page'] ?? 1;
$page = 1;
if($_POST['page'] > 1)
{
$p = (($_POST['page'] - 1) * $rowperpage);
$page = $_POST['page'];
}
else
{
$p = 0;
}
?>
<?php
$visible = $visible ?? true;
$products_count = count_all_products(['visible' => $visible]);
$sql = "SELECT * FROM products ";
$sql .= "WHERE visible = true ";
$sql .= "ORDER BY position ASC ";
$sql .= "LIMIT ".$p.", ".$rowperpage."";
$product_set = find_by_sql($sql);
$product_count = mysqli_num_rows($product_set);
if($product_count == 0) {
echo "<h1>Nie ma produktow w tej kategorii</h1>";
}
while($run_product_set = mysqli_fetch_assoc($product_set)) { ?>
<div style="float: left; margin-left: 20px; margin-top: 10px; class="small">
<a href="<?php echo url_for('/show.php?id=' . h(u($run_product_set['id']))); ?>">
<img src="staff/images/<?php echo h($run_product_set['filename']); ?> " width="150">
</a>
<p><?php echo h($run_product_set['prod_name']); ?></p>
</div>
<?php }
mysqli_free_result($product_set);
?>
<section id="pagination">
<?php
$url = url_for('index_all.php');
if($_POST['page'] > 1)
{
$page_nb = $_POST['page'];
}
else
{
$page_nb = 1;
}
$check = $p + $rowperpage;
$prev_page = $page_nb - 1;
$limit = $products_count / $rowperpage;
//echo $limit;
//exit;
$limit = ceil($limit);
$current_page = $page_nb;
if($page_nb > 1) {
//echo "<a href='index_all.php?page=".$prev_page."'>Back</a>";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$prev_page."'>Back</span>";
}
if ( $products_count > $check ) {
for ( $i = max( 1, $page_nb - 5 ); $i <= min( $page_nb + 5, $limit ); $i++ ) {
if ( $current_page == $i ) {
echo "<span class=\"selected\">{$i}</span>";
} else {
//echo "<a href=\"{$url}?page=" . $i . "\">{$i}</a>";
//echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."' onclick='window.history.go(1); return false;'>".$i."</span>";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
//echo "<a class='pagination_link' href='' id='".$i."'>{$i}</a>";
}
}
}
if ($products_count > $check) {
$next_page = $page_nb + 1;
//echo "<a href='index_all.php?page=".$next_page."'>Next</a>";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$next_page."'>Next</span>";
}
?>
</code></pre>
<p><strong>3. htaccess</strong></p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T11:33:17.570",
"Id": "428124",
"Score": "0",
"body": "If your code is not working as intended, you do not have an on-topic question. Broken coding attempts are appropriately posted on Stackoverflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T11:39:30.183",
"Id": "428127",
"Score": "0",
"body": "The problem is that I have no experience with Ajax and Jquery and I do not know if it should work or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T11:40:55.697",
"Id": "428128",
"Score": "0",
"body": "Quote from your question: \"_One thing I can not solve - once the user clicks the link 5 and go to product detail, when he comes back, he back to 1 not 5. I do not know why._\" This is why you should post on SO instead of CodeReview. We don't fix broken code, we refine working code here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T11:49:04.497",
"Id": "428129",
"Score": "0",
"body": "And ... it comes out that there is no error in the code, but it should be added \"Jquery ajax to display product detail\" . Today I found out about it but I still do not know how to do it :)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T15:53:09.673",
"Id": "428172",
"Score": "0",
"body": "We also expect the author of the code to know what the code does and why. I'm sorry but your question is still off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T20:20:44.007",
"Id": "428207",
"Score": "0",
"body": "Ok, What you are about to do, do quickly."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T12:21:03.970",
"Id": "221336",
"Score": "1",
"Tags": [
"php",
"jquery",
"mysql",
"ajax",
"pagination"
],
"Title": "Make Pagination using Ajax with Jquery, PHP"
} | 221336 |
<p>This is a <a href="https://leetcode.com/problems/sliding-puzzle/" rel="nofollow noreferrer">Leetcode problem</a>:</p>
<blockquote>
<p><em>On a 2 x 3 <code>board</code>, there are 5 tiles represented by the integers <code>1</code>
through <code>5</code> and an empty square represented by <code>0</code>.</em></p>
<p><em>A move consists of choosing <code>0</code> and a 4-directionally adjacent number
and swapping it.</em></p>
<p><em>The state of the board is <span class="math-container">\$solved\$</span> if and only if the <code>board</code> is
<code>[[1,2,3],[4,5,0]]</code>.</em></p>
<p><em>Given a puzzle board, return the least number of moves required so
that the state of the board is solved. If it is impossible for the
state of the board to be solved, return <code>-1</code>.</em></p>
<p><strong><em>Note -</em></strong></p>
<ul>
<li><em><code>board</code> will be a 2 x 3 array as described above.</em></li>
<li><em><code>board[i][j]</code> will be a permutation of <code>[0, 1, 2, 3, 4, 5]</code>.</em></li>
</ul>
</blockquote>
<p>Here is my solution to this challenge:</p>
<pre><code>from collections import deque
class Solution:
def get_new_state(self, index1, index2, current_state):
if current_state[index1] == "0" or current_state[index2] == "0":
current_state = list(current_state)
current_state[index1], current_state[index2] = current_state[index2], current_state[index1]
return "".join(current_state)
return None
def sliding_puzzle(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
min_step = 1 << 31
# need to convert board to a string so that we can add it as a state in the set
# construct the graph based on the positions of the next place it can swap
graph = {0:[1, 3], 1:[0, 2, 4], 2:[1, 5], 3:[0, 4], 4:[1, 3, 5], 5:[2, 4]}
# convert init board to an initial state
init_state = [] + board[0] + board[1]
init_state = "".join(str(_) for _ in init_state)
visited = {init_state}
queue = deque([[init_state, 0]])
while queue:
top = queue.popleft()
current_state, step = top
# check results
if current_state == "123450":
min_step = min(min_step, step)
for index1 in graph:
for index2 in graph[index1]:
new_state = self.get_new_state(index1, index2, current_state)
if new_state is not None and new_state not in visited:
queue.append([new_state, step + 1])
visited.add(new_state)
if min_step == 1<< 31:
return -1
return min_step
</code></pre>
<p><strong>Explanation</strong></p>
<p>Convert the <code>board</code> to a list so that we can have a <code>visit</code> set to track which state is visited.</p>
<p>Construct an adjacency list to mark which position we can go to. For example, <code>[[1, 2, 3], [4, 5, 0]]</code>, as it is a <code>board</code> value, <code>1</code> can swap with <code>4</code> or <code>2</code>.
If we make it a string <code>"123450"</code>, that means position <code>0</code> (so-called index) can swap with index value <code>0</code> and index value <code>3</code> => <code>0:[1, 3]</code>, same for <code>1:[0, 2, 4]</code> for so on so forth.</p>
<p>Now that we have the graph, we just need to do a regular BFS.</p>
<p>Here are some example outputs:</p>
<pre><code>#print(sliding_puzzle([[1,2,3],[4,0,5]]))
>>> 1
#Explanation: Swap the 0 and the 5 in one move.
</code></pre>
<p></p>
<pre><code>#print(sliding_puzzle([[1,2,3],[5,4,0]]))
>>> -1
#Explanation: No number of moves will make the board solved.
</code></pre>
<p></p>
<pre><code>#print(sliding_puzzle([[4,1,2],[5,0,3]]))
>>> 5
#Explanation: 5 is the smallest number of moves that solves the board.
#An example path -
#After move 0: [[4,1,2],[5,0,3]]
#After move 1: [[4,1,2],[0,5,3]]
#After move 2: [[0,1,2],[4,5,3]]
#After move 3: [[1,0,2],[4,5,3]]
#After move 4: [[1,2,0],[4,5,3]]
#After move 5: [[1,2,3],[4,5,0]]
</code></pre>
<p></p>
<pre><code>#print(sliding_puzzle([[3,2,4],[1,5,0]]))
>>> 14
</code></pre>
<p>Here are the times taken for each output:</p>
<pre><code>%timeit output.sliding_puzzle([[1,2,3],[4,0,5]])
3.24 ms ± 629 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit output.sliding_puzzle([[1,2,3],[5,4,0]])
3.17 ms ± 633 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit output.sliding_puzzle([[4,1,2],[5,0,3]])
3.32 ms ± 719 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit output.sliding_puzzle([[3,2,4],[1,5,0]])
2.75 ms ± 131 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code></pre>
<p>Here is my Leetcode result (32 test cases):</p>
<p><a href="https://i.stack.imgur.com/E7jNh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E7jNh.png" alt="Leetcode result"></a></p>
<p>So, I would like to know whether I could make my program shorter and more efficient.</p>
| [] | [
{
"body": "<p>Many great ideas here:</p>\n\n<ul>\n<li>using a hashable data structure to be able to store it in a set</li>\n<li>using a dequeue to generate the various possible states</li>\n<li>storing the neighboors in a dictionnary</li>\n</ul>\n\n<p>However, various points can be improved.</p>\n\n<p><strong>Initialisation of the board</strong></p>\n\n<p>Having 2 consecutive assignments to <code>init_state</code> makes things more complicated than needed.</p>\n\n<p>Starting with \"[] + \" is not required.</p>\n\n<p>Using <code>_</code> as a variable name is pretty common but it usually corresponds to a value that is not going to be used. In your case, I'd use a more normal name.</p>\n\n<p>Thus, I'd recommend:</p>\n\n<pre><code>init_state = \"\".join(str(c) for c in board[0] + board[1])\n</code></pre>\n\n<p><strong>Stopping as soon as possible</strong></p>\n\n<p>Because of the way the queue is built, elements with be in increasing order regarding the <code>step</code> element. One of the implication is that once we've found a solution, there is no need to continue, no solution will ever be better. You can return at that point. That also removes the need for a special value corresponding to \"no solution found so far\".</p>\n\n<pre><code>def sliding_puzzle(board):\n \"\"\"\n :type board: List[List[int]]\n :rtype: int\n \"\"\"\n # need to convert board to a string so that we can add it as a state in the set\n # construct the graph based on the positions of the next place it can swap\n graph = {0:[1, 3], 1:[0, 2, 4], 2:[1, 5], 3:[0, 4], 4:[1, 3, 5], 5:[2, 4]}\n\n # convert init board to an initial state\n init_state = \"\".join(str(c) for c in board[0] + board[1])\n\n visited = {init_state}\n queue = deque([[init_state, 0]])\n while queue:\n top = queue.popleft()\n current_state, step = top\n\n # check results\n if current_state == \"123450\":\n return step\n\n for index1 in graph:\n for index2 in graph[index1]:\n new_state = get_new_state(index1, index2, current_state)\n if new_state is not None and new_state not in visited:\n queue.append([new_state, step + 1])\n visited.add(new_state)\n return -1\n\n</code></pre>\n\n<p>This makes the code way faster : twice faster on my machine on the test cases provided, more than twice on a more comprehensive test suite:</p>\n\n<pre><code>def find_new_tests():\n import random\n board = \"123450\"\n values_found = {}\n for i in range(1000):\n board_lst = list(board)\n random.shuffle(board_lst)\n ret = sliding_puzzle([board_lst[0:3], board_lst[3:]])\n if ret not in values_found:\n values_found[ret] = ''.join(board_lst)\n print(values_found)\n\nstart = time.time()\nfor i in range(10):\n # Provided in the question\n assert sliding_puzzle([[1,2,3],[4,0,5]]) == 1\n assert sliding_puzzle([[1,2,3],[5,4,0]]) == -1\n assert sliding_puzzle([[4,1,2],[5,0,3]]) == 5\n assert sliding_puzzle([[3,2,4],[1,5,0]]) == 14\n # Found randomly\n assert sliding_puzzle([[1,2,0],[4,5,3]]) == 1\n assert sliding_puzzle([[1,2,3],[0,4,5]]) == 2\n assert sliding_puzzle([[1,3,0],[4,2,5]]) == 3\n assert sliding_puzzle([[1,5,2],[0,4,3]]) == 4\n assert sliding_puzzle([[4,1,3],[2,0,5]]) == 5\n assert sliding_puzzle([[4,1,2],[5,3,0]]) == 6\n assert sliding_puzzle([[2,3,5],[1,0,4]]) == 7\n assert sliding_puzzle([[5,2,3],[1,4,0]]) == 8\n assert sliding_puzzle([[4,2,3],[5,0,1]]) == 9\n assert sliding_puzzle([[5,0,3],[1,2,4]]) == 10\n assert sliding_puzzle([[1,2,5],[3,0,4]]) == 11\n assert sliding_puzzle([[4,0,1],[3,2,5]]) == 12\n assert sliding_puzzle([[3,1,0],[4,5,2]]) == 13\n assert sliding_puzzle([[1,4,3],[5,2,0]]) == 14\n assert sliding_puzzle([[0,1,3],[2,5,4]]) == 15\n assert sliding_puzzle([[5,1,3],[0,4,2]]) == 16\n assert sliding_puzzle([[1,3,0],[5,4,2]]) == 17\n assert sliding_puzzle([[2,0,1],[3,5,4]]) == 18\n assert sliding_puzzle([[0,2,1],[3,5,4]]) == 19\n assert sliding_puzzle([[3,2,1],[0,5,4]]) == 20\n assert sliding_puzzle([[4,2,3],[0,1,5]]) == -1\nprint(time.time() - start)\n</code></pre>\n\n<p><strong>Finding the sliding pieces</strong></p>\n\n<p>At the moment, to generate new state, you try each cell and for each cell, each neighboor then eventually you check than one or the other is empty.</p>\n\n<p>You just need to find the empty cell and consider its neighboor.</p>\n\n<p>This makes the code almost 3 times faster (and 7 times faster than the original code) and more concise:</p>\n\n<pre><code>def get_new_state(index1, index2, current_state):\n current_state = list(current_state)\n current_state[index1], current_state[index2] = current_state[index2], current_state[index1]\n return \"\".join(current_state)\n\ndef sliding_puzzle(board):\n \"\"\"\n :type board: List[List[int]]\n :rtype: int\n \"\"\"\n # need to convert board to a string so that we can add it as a state in the set\n # construct the graph based on the positions of the next place it can swap\n graph = {0:[1, 3], 1:[0, 2, 4], 2:[1, 5], 3:[0, 4], 4:[1, 3, 5], 5:[2, 4]}\n\n # convert init board to an initial state\n init_state = \"\".join(str(c) for c in board[0] + board[1])\n\n visited = {init_state}\n queue = deque([[init_state, 0]])\n while queue:\n current_state, step = queue.popleft()\n\n # check results\n if current_state == \"123450\":\n return step\n\n empty = current_state.find(\"0\")\n for candidate in graph[empty]:\n new_state = get_new_state(empty, candidate, current_state)\n if new_state not in visited:\n queue.append([new_state, step + 1])\n visited.add(new_state)\n return -1\n</code></pre>\n\n<p><strong>Other optimisation ideas</strong></p>\n\n<p>When pieces on the left border are in place, there is no need to move them anymore.\n(On a 3x3 board, this would apply also to the top/bottom borders).\nThus, we can reduce the search space by not trying to move them in these cases. I did not find any noticeable improvement by doing so:</p>\n\n<pre><code> pieces_to_keep = set()\n if current_state[0] == \"1\" and current_state[3] == \"4\":\n pieces_to_keep.add(0)\n pieces_to_keep.add(3)\n\n empty = current_state.find(\"0\")\n for candidate in graph[empty]:\n if candidate not in pieces_to_keep:\n new_state = get_new_state(empty, candidate, current_state)\n if new_state not in visited:\n queue.append((new_state, step + 1))\n visited.add(new_state)\n\n</code></pre>\n\n<p><strong>Micro optimisation</strong></p>\n\n<p>We could try to save a bit of time by avoiding calling the <code>get_new_state</code> function and inlining the corresponding code.</p>\n\n<pre><code> for candidate in graph[empty]:\n tmp_state = list(current_state)\n tmp_state[empty], tmp_state[candidate] = tmp_state[candidate], \"0\"\n new_state = ''.join(tmp_state)\n if new_state not in visited:\n queue.append((new_state, step + 1))\n visited.add(new_state)\n\n</code></pre>\n\n<p>This leads to a significant improvement in performances.</p>\n\n<p><strong>More extreme caching</strong></p>\n\n<p>We can easily notice two interesting points:</p>\n\n<ul>\n<li><p>there are not so many reachable positions (360)</p></li>\n<li><p>when looking for a non reachable position, we have to generate all reachable position.</p></li>\n</ul>\n\n<p>This leads to an idea: we may as well compute all the positions and the number of steps required once and for all. This is an expensive initialisation step but as soon as we look for a single non reachable position, it is worth it. The more requests we perform, the more amortised the upfront operations are as each request takes a constant time.</p>\n\n<p>Corresponding code is:</p>\n\n<pre><code>\nfrom collections import deque\n\ndef generate_cache():\n graph = {0:[1, 3], 1:[0, 2, 4], 2:[1, 5], 3:[0, 4], 4:[1, 3, 5], 5:[2, 4]}\n init_state = '123450'\n results = {init_state: 0}\n queue = deque([[init_state, 0]])\n while queue:\n current_state, step = queue.popleft()\n empty = current_state.find(\"0\")\n for candidate in graph[empty]:\n tmp_state = list(current_state)\n tmp_state[empty], tmp_state[candidate] = tmp_state[candidate], \"0\"\n new_state = ''.join(tmp_state)\n if new_state not in results:\n queue.append((new_state, step + 1))\n results[new_state] = step + 1\n return results\n\ncache = generate_cache()\n\ndef sliding_puzzle(board):\n \"\"\"\n :type board: List[List[int]]\n :rtype: int\n \"\"\"\n init_state = \"\".join(str(c) for c in board[0] + board[1])\n return cache.get(init_state, -1)\n\n</code></pre>\n\n<p>This got me:</p>\n\n<pre><code>Runtime: 32 ms, faster than 100.00% of Python3 online submissions for Sliding Puzzle.\nMemory Usage: 13.3 MB, less than 15.86% of Python3 online submissions for Sliding Puzzle.\n</code></pre>\n\n<p><strong>Hardcoded cache</strong></p>\n\n<p>This would probably be a right place to stop but for some reason, after a few days, I got a bit curious of the performance gain we'd have by having the cache hardcoded:</p>\n\n<pre><code>Runtime: 32 ms, faster than 100.00% of Python3 online submissions for Sliding Puzzle.\nMemory Usage: 13.1 MB, less than 80.58% of Python3 online submissions for Sliding Puzzle.\n</code></pre>\n\n<p>I must confess that I am a bit disappointed.</p>\n\n<p>Additional note: at this level of details, resubmitting the same solution can lead to different performances.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T20:50:49.853",
"Id": "428048",
"Score": "1",
"body": "Upvoted! Amazing answer. Here is the Leetcode result for your code - `Runtime: 44 ms, faster than 97.46% of Python 3 online submissions for Sliding Puzzle.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T20:56:50.563",
"Id": "428049",
"Score": "1",
"body": "Thanks for the feedback. You got me eager to find how 2.54% did :) My answer will probably get update in the next minutes!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T20:59:10.883",
"Id": "428050",
"Score": "1",
"body": "@Justin You can see a new optimisation on the edited version of my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T21:06:59.407",
"Id": "428051",
"Score": "0",
"body": "Thanks a lot! Here's the Leetcode result (keeps changing actually, but it's the same as the previous one) - `Runtime: 44 ms, faster than 97.46% of Python3 online submissions for Sliding Puzzle`. But all in all, it is way faster than mine, which is all I needed. Accepted!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T21:57:30.617",
"Id": "428056",
"Score": "0",
"body": "Thanks. I've added a last suggestion anyway. Now I can go to bed :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:50:31.503",
"Id": "428163",
"Score": "1",
"body": "New status: \"Runtime: 32 ms, faster than 100.00% of Python3 online submissions for Sliding Puzzle.\nMemory Usage: 13.3 MB, less than 15.86% of Python3 online submissions for Sliding Puzzle.\""
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T20:36:06.427",
"Id": "221364",
"ParentId": "221339",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221364",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T13:26:59.700",
"Id": "221339",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"breadth-first-search",
"sliding-tile-puzzle"
],
"Title": "(Leetcode) Sliding puzzle in Python"
} | 221339 |
<p>I should estimate the effect of B fields on particle deflection using <span class="math-container">\$F=V \times B \times Force\$</span>.</p>
<p>I have a 2D mesh with <span class="math-container">\$n_x\$</span> and <span class="math-container">\$n_y\$</span> which show the number of points in each direction. <span class="math-container">\$B\$</span> is the magnetic field which is a 2D mesh arrays (with dimension <span class="math-container">\$n_x \times n_y= 1600 \times 900 = 1440000\$</span>) and <span class="math-container">\$V\$</span> is the velocity of particles and is a 1D array (with dimension 431605462). I also have two 1D arrays (with the same dimension as the <span class="math-container">\$V\$</span> array) which show the x and y coordinates of each particles. I called them <code>grid_pro_x</code> and <code>grid_pro_y</code>.</p>
<p>Since <span class="math-container">\$V\$</span> is a 1D array and <span class="math-container">\$B\$</span> is a 2D array I can not directly multiply <span class="math-container">\$V\$</span> with <span class="math-container">\$B\$</span>. To solve this issue I created a 2D zero array for the <span class="math-container">\$V\$</span> and using 2 <em>for</em>-loops I find particles which stand in each cell of the mesh. I consider the average velocity of all particles as a velocity component of each cell. Because of the large dimensionality of the mesh, if I keep the original dimension, the code needs several days to complete the <span class="math-container">\$V\$</span> array since it needs to be repeated 1440000 times. As a solution, I compressed <span class="math-container">\$V\$</span> with an optional variable called <code>divider</code>. If I use <code>divider = 10</code> I guess the code needs 2 days to be finished and if I use <code>divider = 100</code> the code will be finished in half an hour but now the precision of the results reduces significantly. </p>
<p>You can see the code in the following.</p>
<pre><code>nx,ny= 1600, 900
xmin = -30.0e-6
xmax = 50.0e-6
ymin = -45.0e-6
ymax = 45.0e-6
#### create a 2D velocity array
divider = 100
m_p= 1.6726219e-27 # (kg unit) proton mass
nx_new = nx/divider
ny_new = ny/divider
Vx = np.zeros((ny_new, nx_new))
Vy = np.zeros((ny_new, nx_new))
res_x = (xmax - xmin)/nx_new # resolution in x direction
res_y = (ymax - ymin)/ny_new # resolution in y direction
# Find corresponding indices
for i in range( 0,ny_new ):
for j in range( 0,nx_new):
xx = i*res_x
yy = j*res_y
##### all particles with different Px confined in a specific cell
Px_pro_lim = Px_pro[(grid_pro_x >= xx ) & (grid_pro_x < xx+res_x ) & (grid_pro_y >= yy ) & (grid_pro_y < yy+res_y ) ]
Vx[i,j] = np.mean(Px_pro_lim)/m_p
#print 'Vx[i,j]= ' ,Vx[i,j]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-03T23:34:16.727",
"Id": "437865",
"Score": "3",
"body": "I think an example or something would go a long way in explaining what your code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T18:31:23.667",
"Id": "447989",
"Score": "1",
"body": "As it sits, your code will throw `NameError`s against `Px_pro`, `grid_pro_x`, and `gird_pro_y`. Can you provide context into what these are?"
}
] | [
{
"body": "<p>If you are trying to make it fast, the last thing to do is drop into Python for-loops. Keep it all in numpy as much as possible. </p>\n\n<p>The code below maps the particles to the mesh and calculates the mean v for all the particles in each mesh square. With 400M particles having random x,y, and v on a 1600x900 size mesh, it runs in about 100 seconds on my laptop.</p>\n\n<pre><code>xi = np.digitize(x, np.linspace(xmin, xmax, nx, endpoint=False)) - 1\nyi = np.digitize(y, np.linspace(ymin, ymax, ny, endpoint=False)) - 1\n\nflat_index = nx*yi + xi\n\ncounts = np.bincount(flat_index)\n\nvsums = np.bincount(flat_index, weights=v)\n\nmeans = (vsums / counts).reshape(nx,ny)\n</code></pre>\n\n<p><code>np.digitize(x, bins)</code> maps values the values in the array x, to ints based on the values in bins. x < bin[0] maps to 0; bin[0] <= x < bin[1] maps to 1; and so on. The <code>endpoints=False</code> makes sure the indices go from 1 to 1440000 instead of 1 to 143999; and the <code>-1</code> shifts it to 0 to 1439999.</p>\n\n<p><code>np.linspace(start, end, nsteps)</code> divides the range [start, end) in to nstep even intervals. This is used to define the bins for <code>np.digitize()</code>.</p>\n\n<p><code>nx*yi + xi</code> basically converts the x and y indices to a 1D index from 0 to 1439999, because bincount only works on 1D arrays</p>\n\n<p><code>np.bincount(z, weights)</code> if weights is omitted, this counts the number of occurrences of each integer in z (like a histogram). If provided, weights is an array of the same dim as z, the values of the corresponding weights are summed instead of just counting the integers. So setting weights to v, sums the velocity of each particle in a mesh square.</p>\n\n<p><code>(sums / counts).reshape(nx,ny)</code> calculates the means and reshapes the result into the 1600x900 mesh. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T04:27:23.863",
"Id": "237271",
"ParentId": "221340",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T13:30:24.877",
"Id": "221340",
"Score": "9",
"Tags": [
"python",
"numpy"
],
"Title": "Find indices using for loop"
} | 221340 |
<p>I wanted to know if the useMemo function extracted like this is valid at all. This is a whole component (Sorry for the imports) that uses useMemo to get a data that is grabbed from the server using GraphQL and react-apollo-hooks.</p>
<p>I extracted the useMemo to prevent bloat in the actual component.</p>
<pre><code>/**
* The list of grades that the teacher needs to choose first.
*/
import React, { useMemo, memo } from 'react';
import {
Paper,
Table,
TableHead,
TableRow,
TableCell,
TableBody,
Button,
} from '@material-ui/core';
import { useQuery } from 'react-apollo-hooks';
import Container from '../../../components/Container';
import { GET_ALL_GRADES, Grades } from '../../../graphql/grades';
import { useAuth } from '../../../auth/index';
import { RouteComponentProps, NavigateFn } from '@reach/router';
function useGradesData(data: Grades[], navigate: NavigateFn) {
return useMemo(() => {
if (!data) {
return '';
}
return data.map(grade => {
return {
async listSubjectFromGrades() {
await navigate(`/list/${grade.gradeId}`);
},
...grade,
};
});
}, [data, navigate]);
}
function Grade(props: RouteComponentProps) {
const tenantId =
useAuth().tenantIds[0] || 'c96bcd70-70bc-4e66-b47d-88a066912a77';
const { data, loading } = useQuery(GET_ALL_GRADES, {
variables: {
tenantId,
},
}) as { data: Grades[]; loading: boolean };
const mappedData = useGradesData(data, props.navigate!);
if (loading) {
return <p>Loading</p>;
}
return (
<Container>
<Paper style={{ width: '100%' }}>
<Table style={{ width: '100%' }}>
<TableHead>
<TableRow>
<TableCell>#</TableCell>
<TableCell>Nombre del Grado</TableCell>
<TableCell>Acción</TableCell>
</TableRow>
</TableHead>
<TableBody>
{!!mappedData &&
mappedData.map((grade, index) => (
<TableRow key={grade.gradeId}>
<TableCell>{index + 1}</TableCell>
<TableCell>{grade.name}</TableCell>
<TableCell>
<Button onClick={grade.listSubjectFromGrades}>Ver</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
</Container>
);
}
export default memo(Grade);
</code></pre>
<p>In addition, you are more than welcome to spot any other improvements in the whole code. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T03:18:58.313",
"Id": "429801",
"Score": "0",
"body": "I *think* it should work. Does it work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T11:09:15.817",
"Id": "429838",
"Score": "0",
"body": "It does!! No issues so far."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-13T01:43:38.480",
"Id": "429927",
"Score": "1",
"body": "Yes, I think this extraction is completely valid, in similar extraction is also used authoritatively: https://usehooks.com"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-13T02:51:36.277",
"Id": "429931",
"Score": "1",
"body": "Awesome, thanks! I already extracted it and so far no es-lint issues or functionality break. I'm more concerned about the parameters that the function needs to be executed mroe than anything"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T14:04:43.577",
"Id": "221343",
"Score": "1",
"Tags": [
"javascript",
"react.js",
"typescript",
"memoization"
],
"Title": "Extract useMemo to its own custom hook"
} | 221343 |
<p>Today I had a simple task: I have products, quantities and a dummy, and I needed to know which percentage of the total quantities of that product the dummy represented. My DataFrame looked like this:</p>
<pre><code>Product Qty Dummy
A 10 0
B 15 0
B 5 1
C 5 0
D 5 0
D 20 1
</code></pre>
<p>And I needed to get there:</p>
<pre><code>Product Qty_pct
B 0.25
D 0.8
</code></pre>
<p>So, I only needed the percentage when the dummy takes value = 1</p>
<p>I managed to do it, like this:</p>
<pre><code>df2=df.pivot_table(columns='Dummy',index='Product',aggfunc='sum',values=['Qty']).reset_index()
df2['Qty_pct']=df2['Qty'][1]/(df4['Qty'][1]+df2['Qty'][0])
df2.columns=df2.columns.get_level_values(0)
</code></pre>
<p>To me it seems like a very indirect way to achieve my goal and I feel this can be done in a way more elegant way. What would you do?</p>
| [] | [
{
"body": "<p>I think the better way is to use <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html?highlight=groupby\" rel=\"nofollow noreferrer\">groupby</a>. It looks more logical and \"natural\":</p>\n\n<pre><code>df = pd.DataFrame({\n 'Product': ['A', 'B', 'B', 'C', 'D', 'D'],\n 'Qty': [10, 15, 5, 5, 5, 20],\n 'Dummy': [0, 0, 1, 0, 0, 1]\n})\n\n# Create new column = Dummy*Qty\ndf['DQty'] = df['Dummy'] * df['Qty']\n\n# Groupby df by 'Product' and summarize columns\ndf2 = df.groupby('Product').sum()\n\n# Create new column equal to percentage of the total quantities\ndf2['Q'] = df2['DQty'] / df2['Qty']\n\n# Drop unnecessary columns\ndf2 = df2.drop(columns=['Dummy', 'Qty', 'DQty'])\n\n# Drop rows equal to zero\ndf2 = df2.loc[df2['Q'] != 0]\ndf2\n</code></pre>\n\n<p>The result is:</p>\n\n<pre><code> Q\nProduct \nB 0.25\nD 0.80\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T16:37:36.383",
"Id": "221354",
"ParentId": "221348",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221354",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T15:41:51.737",
"Id": "221348",
"Score": "3",
"Tags": [
"python",
"pandas"
],
"Title": "Calculate percentage based on dummy variable in Pandas"
} | 221348 |
<p>I created a PHP program to generate random phone numbers. A valid phone number:</p>
<ul>
<li>must be exactly 11 digits in length, and</li>
<li>must start with any of the values mentioned in the <code>$a</code> array, and</li>
</ul>
<p>How can I improve it? Specifically, how can I improve</p>
<ul>
<li>its readability, and</li>
<li>its performance, assuming I want to generate millions of results.</li>
</ul>
<pre><code><?php
function rand_(){
$digits_needed=7;
$random_number=''; // set up a blank string
$count=0;
while ( $count < $digits_needed ) {
$random_digit = mt_rand(0, 8);
$random_number .= $random_digit;
$count++;
}
return $random_number;
}
$a=array('0812', '0813' ,'0814' ,'0815' ,'0816' ,'0817' ,'0818','0819','0909','0908');
$i=0;
while($i<21){
$website = $a[mt_rand(0, count($a) - 1)];
print $website . rand_().'<br>';
$i++;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:17:47.353",
"Id": "428154",
"Score": "0",
"body": "@mickmackusa How?It does do what it supposed to do and perfectly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:19:41.353",
"Id": "428156",
"Score": "0",
"body": "@mickmackusa I've edited my question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:53:44.073",
"Id": "428164",
"Score": "0",
"body": "Thank you for improving your question. I have removed my downvote."
}
] | [
{
"body": "<ol>\n<li>Use accurate and meaningful names for functions and variable to improve readability.</li>\n<li>Condense your numeric loop conditions into a <code>for</code> loop versus <code>while</code> loop.</li>\n<li>Avoid declaring single-use variables.</li>\n<li>Make functions versatile by passing output-altering arguments with the call.</li>\n<li>Write default argument values when possible/reasonable so that, in some cases, no arguments need to be passed for the most common scenario.</li>\n<li>Avoid counting a static array in a loop. If you <em>need</em> to count it, count it once before entering the loop and reference the count variable.</li>\n<li>If you prefer <code>mt_rand</code>'s randomness, use it in place of my <code>array_rand()</code> call below, but obey #6 about counting.</li>\n<li>Obey PSR Coding Standards. Spacing and tabbing don't improve performance, but they sure make your code easier to read.</li>\n</ol>\n\n<p>Some suggested applications of my generalized advice:</p>\n\n<p>Code: (<a href=\"https://3v4l.org/T49Ne\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>function randomNumberSequence($requiredLength = 7, $highestDigit = 8) {\n $sequence = '';\n for ($i = 0; $i < $requiredLength; ++$i) {\n $sequence .= mt_rand(0, $highestDigit);\n }\n return $sequence;\n}\n\n$numberPrefixes = ['0812', '0813', '0814', '0815', '0816', '0817', '0818', '0819', '0909', '0908'];\nfor ($i = 0; $i < 21; ++$i) {\n echo $numberPrefixes[array_rand($numberPrefixes)] , randomNumberSequence() , \"\\n\";\n}\n</code></pre>\n\n<p>Possible Output:</p>\n\n<pre><code>08161776623\n08157676208\n08188430651\n08187765326\n08176077144\n09087477073\n08127415352\n08191681262\n08168828747\n08195023836\n08198008111\n09096738254\n08162004285\n08166810731\n08130133373\n09093214002\n08154125422\n08160702315\n08143817877\n08194806336\n08133183466\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:52:13.960",
"Id": "221421",
"ParentId": "221352",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221421",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T16:19:25.827",
"Id": "221352",
"Score": "5",
"Tags": [
"php",
"random"
],
"Title": "PHP program to generate random phone number"
} | 221352 |
<p><strong>The task</strong></p>
<blockquote>
<p>Given a string and a pattern, find the starting indices of all
occurrences of the pattern in the string. For example, given the
string "abracadabra" and the pattern "abr", you should return [0, 7].</p>
</blockquote>
<p><strong>My solution</strong></p>
<pre><code>function findStartingIndex(T, pattern) {
let S = T;
const res = [];
while(true) {
const i = S.indexOf(pattern);
if (i === -1) { return res; }
S = S.substring(i + 1);
res.push(i ? i + 1 : i);
}
return res;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T01:32:23.277",
"Id": "428063",
"Score": "1",
"body": "a challenge like this is much more instructive if you don't use `indexOf`. See also: [Knuth-Morris-Pratt](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T01:35:55.077",
"Id": "428064",
"Score": "0",
"body": "@OhMyGoodness thanks, just skimmed through the article but it sounds interesting. Will reimplement the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T11:21:11.377",
"Id": "428121",
"Score": "0",
"body": "Your code does not work for many inputs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T11:35:26.170",
"Id": "428125",
"Score": "0",
"body": "@Blindman67 yes, I didn't test it thoroughly. Just pushed the code. :( I wish I could delete this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T12:43:41.760",
"Id": "428138",
"Score": "0",
"body": "@Blindman67 What is your opinion about this approach: https://codereview.stackexchange.com/questions/221409/find-the-starting-indices-of-all-occurrences-of-the-pattern-in-the-string-follo"
}
] | [
{
"body": "<p>Because I'm a fan of functional programming, I want to implement this without any <code>for</code> or <code>while</code> loops, which necessarily require mutating variables. </p>\n\n<p>The way I'd do this, is with a recursive function. </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function findIndexes(n, h, acc = [], currentIndex = 0) {\n const index = h.indexOf(n);\n\n if (index < 0) {\n return acc;\n } else {\n\n const newHaystack = h.slice(index + 1);\n return findIndexes(n, newHaystack, [...acc, index + currentIndex], currentIndex + index + 1);\n }\n}\n\nconsole.log(findIndexes(\"abr\", \"abracadabra\"));\nconsole.log(findIndexes(\"1\", \"1111\"));\nconsole.log(findIndexes(\"12\", \"121212\"));\nconsole.log(findIndexes(\"1212\", \"12121212\")); //This one is a tricky case, as the sub strings overlap. \nconsole.log(findIndexes(\"1221\", \"1221221221\"));\nconsole.log(findIndexes(\"111\", \"11111111111\"));\nconsole.log(findIndexes(\"a\", \"banana\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Now, whether you want to implement that <code>indexOf</code> function yourself is up to you, but in any case - this how I'd do the rest of it. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T00:28:06.360",
"Id": "428219",
"Score": "2",
"body": "Any reason why this is being downvoted?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T04:18:13.350",
"Id": "221379",
"ParentId": "221359",
"Score": "-1"
}
},
{
"body": "<p>Like @Roland Illig said, your code has bug with \"banana\" because of you mutable your string length each time you use your <code>substring</code> function. </p>\n\n<p>I think you better replace your pattern each time it matchs by string that has same length pattern but does not match your pattern</p>\n\n<pre><code>function findStartingIndex(T, pattern) {\n let S = T;\n const res = [];\n while(true) {\n const i = S.indexOf(pattern);\n if (i === -1) { return res; }\n const newPattern = pattern.replace(/./,'_');\n\n S = S.replace(pattern, newPattern);\n res.push(i);\n }\n return res;\n}\n\n</code></pre>\n\n<p>For string \"banana\" it will return [1,3,5]</p>\n\n<p>Or you can consider my solution:</p>\n\n<pre><code>findStartingIndex = (s) => {\n const result = [];\n while (s.match(/abr/)) {\n result.push(s.match(/abr/).index);\n s=s.replace('abr','___');\n }\n return result;\n}\n</code></pre>\n\n<p>Use regex here is not necessary but it is more flexible in case the pattern is dynamic.</p>\n\n<p>Down voter: please consider your vote!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T04:45:26.177",
"Id": "221382",
"ParentId": "221359",
"Score": "-1"
}
},
{
"body": "<p>Your code contains a bug.</p>\n\n<p>For <code>banana</code> and <code>a</code>, it should return <code>[1, 3, 5]</code>, but it doesn't.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T13:04:54.490",
"Id": "428142",
"Score": "0",
"body": "Have a look here: https://codereview.stackexchange.com/q/221409/54442"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T04:59:22.580",
"Id": "221383",
"ParentId": "221359",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221383",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T18:13:15.913",
"Id": "221359",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge"
],
"Title": "Find the starting indices of all occurrences of the pattern in the string"
} | 221359 |
<p>I'm a beginner developer, and it's my very first project: a simple math operations calculator in Python 3 using Tkinter for GUI.</p>
<p><strong>Obs: This code is an evolution of my previous code of the same project: <a href="https://codereview.stackexchange.com/questions/219124/calculator-in-python3-using-tkinter/">initial code</a>.</strong></p>
<p>This calculator, in despite of only process the four basic math operations (add, subtraction, multiplication an division), tries to behave like a classic calculator about the inputs treatment.</p>
<p><strong>Using examples as a classic calculator:</strong></p>
<ul>
<li><p>Press 2, so plus button, then 3, then equal. The result 5 will be shown. After this, keeping pressing equal will proceed the addition of 3 to the respective result.</p></li>
<li><p>When user press an operator key (+,-,* or /) after the first operand input, pressing a different operator will change the operator.</p></li>
<li><p>After the the operands input, pressing an operator key will lead to result and operator storage. (User press 2, press plus, press 3, then press minus. The result 5 will be shown and the minus operator will be stored).</p></li>
</ul>
<p><strong><em>I've followed the suggestions the best I could and refactored all the code.</em></strong></p>
<p><strong>The main problems that I tried to solve were:</strong></p>
<ul>
<li>Using <code>eval</code> to process calculation.</li>
</ul>
<p>It seemed so convenient using <code>eval</code> at the beggining. I didn´t have to create any rules or data treatment. Also, the calculator could process big expressions including things like parenthesis.</p>
<p>But I was warned about the vulnerability of using <code>eval</code>. Then I also realized that it is a pretty lazy solution.</p>
<p>So, I´ve managed to include methods for data treatment and processing the calculations. The application now behaves more like a conventional calculator and removed the capacity to calculate expressions at once.</p>
<ul>
<li>Too many modules:</li>
</ul>
<p>The fact of having too many modules lead me to have problems with circular imports and incorrect import calls, as I didn´t know much about importing. After some study about it and following the suggestions gave to me, I made the code lean by using only two modules and using imports correctly.</p>
<ul>
<li>Code repetition:</li>
</ul>
<p>The blocks for buttons creation and placement had too many lines. So I´ve followed some instructions to dinamically create and place them.</p>
<ul>
<li>Unecessary use of <code>self</code>:</li>
</ul>
<p>As a begginer at Python and OOP, I was using <code>self</code> at every variable inside the classes and was warned about <code>self</code> on variables to be used only for a variable that will be changed later in the class outside of the method it is generated in. So, the new code removed <code>self</code>s where wasn´t really necessary.</p>
<p>Finally, that´s the new code:</p>
<p><strong>Module: main.py</strong></p>
<pre><code>import tkinter
import application
class TkinterWindow(tkinter.Tk):
def __init__(self):
super().__init__()
self.geometry('640x480')
def main():
window = TkinterWindow()
app = application.Calculator(window)
app.pack(fill='both', expand=1, padx=10, pady=10)
app.mainloop()
if __name__ == '__main__':
main()
</code></pre>
<p><strong>Module: application.py</strong></p>
<pre><code>import tkinter
class Calculator(tkinter.Frame):
def __init__(self, parent):
super().__init__(parent)
self.rowconfigure(0, weight=1) # Row for display
self.rowconfigure(1, weight=1) # Row for buttons frame
self.columnconfigure(0, weight=1)
self.focus_set()
# Variables for calculations and process control
self.display_chars = tkinter.StringVar()
self.display_chars.set(0)
self.aggregator = []
self.operator = None
self.decimal_separator = False
self.total = 0
self.error = None
self.first_operator = 0
self.second_operator = 0
self.first_operator_status = False
self.new_entry = True
self.aggregator_status = 'Inactive'
self.place_frames()
self.bind("<Key>", self.key_handler)
self.bind("<Return>", self.return_key_handler)
self.bind("<BackSpace>", self.backspace_handler)
self.bind("<Escape>", self.esc_handler)
##self.debugger()
def place_frames(self):
display_frame = DisplayContainer(self
).grid(row=0, column=0, sticky='nsew')
buttons_frame = ButtonsContainer(self
).grid(row=1, column=0, sticky='nsew')
def debugger(self):
print(f'AGGREGATOR current content: {self.aggregator}')
print(f'AGGREGATOR current status: {self.aggregator_status}')
print(f'new_entry: {self.new_entry}')
print(f'decimal_separator: {self.decimal_separator}')
print(f'Current OPERATOR: {self.operator}')
print(f'first_operator value: {self.first_operator}')
print(f'second_operator value: {self.second_operator}')
print(f'first_operator_status: {self.first_operator_status}')
print(f'TOTAL: {self.total}')
print('--------------------------------------------------')
def key_handler(self, event):
'''Handles inputs comming from the keyboard.
This function only accepts four types of keyboard inputs:
(1) Numbers
(2) Basic math operators: +, -, *, /
(3) '=' key
(4) ',' or '.' for decimal separator
Obs: Other keys are ignored
Cases (1) and (4) make the respective value to be shown at
the calculator display.
Case (2) calls the operator handling, that either stores a
value or executes an operation.
Case (3) calls the resolving function.
'''
if event.char.isdigit():
numerical_char = event.char
self.put_char_on_display(numerical_char)
#self.debugger()
elif event.char in ('+', '-', '*', '/'):
operator_char = event.char
self.operators_handler(operator_char)
elif event.char == '=':
self.resolve_operation()
elif event.char == ',' or event.char == '.':
# There can be only one decimal separator at time.
#
# Also, self.new_entry checks if it´s the initial entry
# at first or second number. If so, considers its
# beggining as been a decimal of 0. That´s the case
# when user presses comma/dot at the beggining of the entry.
if self.decimal_separator == False:
if self.new_entry:
zeropoint_char = '0.'
self.put_char_on_display(zeropoint_char)
self.decimal_separator = True
#self.debugger()
else:
decimal_char = '.'
self.put_char_on_display(decimal_char)
self.decimal_separator = True
#self.debugger()
def buttons_handler(self, button):
'''Handles inputs comming from the calculator´s buttons.
As function key_handler does, it handles the following
inputs:
(1) Numbers, that are displayed or stored.
(2) Basic math operators, that stores a value and operator.
or process an operation, according to context.
(3) Resolves an operation with the values and operator stored.
(4) Sets an decimal separator
'''
if button in range(10):
numerical_char = str(button)
self.put_char_on_display(numerical_char)
#self.debugger()
elif button in ('+', '-', '*', '/'):
operator_char = str(button)
self.operators_handler(operator_char)
elif button == '=':
self.resolve_operation()
elif button == '.':
# There can be only one decimal separator at time.
#
# Also, self.new_entry checks if it´s the initial entry
# at first or second number. If so, clicking or typing the
# comma or dot makes the program consider the beggining as
# been a decimal of zero.
# That´s the case when user presses comma/dot at the
# beggining of the entry.
if self.decimal_separator == False:
if self.new_entry:
zeropoint_char = '0.'
self.put_char_on_display(zeropoint_char)
self.decimal_separator = True
#self.debugger()
else:
decimal_char = '.'
self.put_char_on_display(decimal_char)
self.decimal_separator = True
#self.debugger()
def return_key_handler(self, event):
self.resolve_operation()
def backspace_handler(self, event):
if self.aggregator:
del self.aggregator[-1]
self.display_chars.set(self.aggregator)
#self.debugger()
def esc_handler(self, event):
self.set_to_default()
def put_char_on_display(self, char):
'''Makes an numeric input from keyboard or button be displayed.
This function handles two situations:
- Checks if it is the beggining of the input, through the self.new_entry variable. If true, clears the inputs aggregator and displays the new value passed, allowing posterior values to be added.
- If chars input is process is already in course, keep adding the values passed through the params into the inputs aggregator.
The aggregator variable self.aggregator progressivly gets numbers or a decimal separator to form a value that will be stored when an operator or the equal sign is activated.
'''
if self.new_entry == True:
self.aggregator = []
self.aggregator.append(char)
self.display_chars.set(self.aggregator)
self.aggregator_status = 'Active'
self.new_entry = False
else:
self.aggregator.append(char)
self.display_chars.set(self.aggregator)
self.aggregator_status = 'Active'
def operators_handler(self, char):
'''Gets an operator char and handles as context.
Set an operator via button click or keyboard envolves three situations:
(1) If no value is stored yet, and inputs are already in course.
This case, makes the value in aggregator be stored as the first operand.
(2) First operand is already stored, no new values are been inserted. The program then changes the operator, if it´s different.
(3) If first operand is already stored, a new input is in course.
The program stores the value as the second operand and executes the operation according to the operator set.
'''
# Assingn the first operand
if self.first_operator_status == False:
self.first_operator = self.get_values_from_aggregator()
self.first_operator_status = True
self.operator = char
self.new_entry = True
self.decimal_separator = False
self.aggregator_status = 'Inactive'
#self.debugger()
else:
# Handles user changing the operators
if (self.first_operator_status == True and
self.aggregator_status == 'Inactive'):
if char != self.operator:
self.operator = char
#self.debugger()
else:
# If user press any operator after typing the second value
# the value on display will be assingned in second_operator
# variable and resolve_operation() will be called.
self.second_operator = self.get_values_from_aggregator()
self.operator = char
self.aggregator_status = 'Inactive'
self.resolve_operation()
def get_values_from_aggregator(self):
'''Converts the content of aggregator in a float number and
returns it.
If nothing is inserted into aggregator (and it´s empty), then it means that the value is zero.
'''
values = ''.join(self.aggregator)
if values:
return float(values)
else:
return 0
def resolve_operation(self):
'''Stores value as first or second operator, then executes
the corresponding operation. So, call the finish method
with its result as parameter.
'''
if self.first_operator_status == False:
self.first_operator = self.get_values_from_aggregator()
else:
self.second_operator = self.get_values_from_aggregator()
if self.operator == '+':
result = self.first_operator + self.second_operator
self.finish(result)
elif self.operator == '-':
result = self.first_operator - self.second_operator
self.finish(result)
elif self.operator == '*':
result = self.first_operator * self.second_operator
self.finish(result)
elif self.operator == '/':
try:
result = self.first_operator / self.second_operator
except ZeroDivisionError as error:
self.error = error
self.finish(0)
except:
self.error = error
self.finish(0)
else:
self.finish(result)
def finish(self, result):
# Displays the result and sets variables for new operations.
self.total = result
self.display_chars.set(f'{self.total}')
self.aggregator = [str(self.total)]
self.aggregator_status = 'Inactive'
self.new_entry = True
self.decimal_separator = False
self.first_operator_status = False
if self.error:
if isinstance(self.error, ZeroDivisionError):
self.set_to_default()
self.display_chars.set('ZeroDivisionError')
else:
set_to_default()
self.display_chars.set('Unknown Error')
#self.debugger()
def set_to_default(self):
'''Sets program to its default parameters..
This happens if an error is found or CLEAR is activated.
'''
self.display_chars.set(0)
self.aggregator = []
self.operator = None
self.decimal_separator = False
self.total = 0
self.error = None
self.first_operator = 0
self.second_operator = 0
self.first_operator_status = False
self.new_entry = True
self.aggregator_status = 'Inactive'
#self.debugger()
class DisplayContainer(tkinter.Frame):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
tkinter.Label(
self,
background='lightgrey',
relief='ridge',
border=5,
textvariable=self.parent.display_chars,
).pack(fill='both', expand=1)
class ButtonsContainer(tkinter.Frame):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
for x in range(0, 5):
self.rowconfigure(x, weight=1)
if x < 4:
self.columnconfigure(x, weight=1)
self.create_buttons()
def create_buttons(self):
pad = 15
row = 0
column = 0
for i in range(10):
if i == 0:
tkinter.Button(
self,
text=i,
padx=pad,
pady=pad,
command=lambda n=i: self.parent.buttons_handler(n)
).grid(row=3, column=1, sticky='nsew')
else:
tkinter.Button(
self,
text=i,
padx=pad,
pady=pad,
command=lambda n=i: self.parent.buttons_handler(n)
).grid(row=row, column=column, sticky='nsew')
if column == 2:
column = 0
row += 1
else:
column += 1
for i in [
['+', 0, 3], ["-", 1, 3],
['*', 2, 3], ['/', 3, 3],
['.', 3, 0], ['=', 3, 2],
['CLEAR', 4, 0]
]:
if i[0] == 'CLEAR':
tkinter.Button(
self,
text=i[0],
padx=pad,
pady=pad,
command=self.parent.set_to_default
).grid(row=i[1], column=i[2], columnspan=4, sticky='nsew')
elif i[0] == '=':
tkinter.Button(
self,
text=i[0],
padx=pad,
pady=pad,
command=self.parent.resolve_operation
).grid(row=i[1], column=i[2], sticky='nsew')
else:
tkinter.Button(
self,
text=i[0],
padx=pad,
pady=pad,
command=lambda n=i[0]: self.parent.buttons_handler(n)
).grid(row=i[1], column=i[2], sticky='nsew')
</code></pre>
<p><strong>Difficulties that still exist:</strong></p>
<p>The button layout code can be more efficient, but I did not understood 100% the suggestions of the old topic, and not feel confident to apply these changes.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T18:34:09.937",
"Id": "221361",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"calculator",
"tkinter"
],
"Title": "Python 3 Tkinter Calculator - follow-up"
} | 221361 |
<p>There is A LOT of information online stating that you should NEVER catch a NullPointerException. Generally I agree, but I am wondering about this one case.</p>
<p>I have inherited code that requires me to access data that I need in the following way</p>
<pre><code>context.getGrandParent().getParent().getChild().isRequired()
</code></pre>
<p>There is no guarantee that any of the objects in this hierarchy will not be null.
I have to enter a block if isRequired() returns true. First, and what I initially wrote, with null checks:</p>
<pre><code>if(context != null
&& context.getGrandParent() != null
&& context.getGrandParent().getParent() != null
&& context.getGrandParent().getParent().getChild() != null
&& context.getGrandParent().getParent().getChild().isRequired()
){
// continue with business logic
} else {
LOG.error("Unable to determine if processing is required.");
}
// continue with other inherited code
</code></pre>
<p>Setting aside that I could refactor this, perhaps for readability, wouldn't it make more sense to do the following?</p>
<pre><code>boolean isRequired = false;
try {
isRequired = context.getGrandParent().getParent().getChild().isRequired();
} catch (NullPointerException npe) {
LOG.error("Unable to determine if processing is required.");
}
if(isRequired){
// continue with business logic
}
// continue with other inherited code
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T21:40:41.860",
"Id": "428053",
"Score": "1",
"body": "some notes on null propagation: https://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T22:24:51.857",
"Id": "428058",
"Score": "0",
"body": "yes i like the version with an exception. You should not make a code where normal funtionality is that some variable is present or not. You sould not make if-else branches instead of exception cases ( like in AJNeufeld answer) in error log howewer you must determine what exactly place is absent)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T00:15:03.803",
"Id": "428061",
"Score": "0",
"body": "I agree, use the exception, guidelines are for the obedience of fools and the guidance of wise men. This is a case were clarity reigns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:35:43.497",
"Id": "428162",
"Score": "0",
"body": "@dfhwze: Thanks for the link. It gives a good overview of Optional that AJNeufeld recommends."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T14:16:09.180",
"Id": "440192",
"Score": "0",
"body": "`.getParent().getChild()` wait what? Doesn't that go back to where we came from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T14:17:45.873",
"Id": "440194",
"Score": "0",
"body": "The real solution here is not to catch a null-pointer or use an `Optional`, you should find a way to inject the value of `context.getGrandParent().getParent().getChild()` as a separate variable/field, or inject a `Predicate` where you inject `childYouAreLookingFor.isRequired()`. Your current code goes against the principle of \"Tell, don't ask\""
}
] | [
{
"body": "<p>The problem with catching <code>NullPointerException</code> is “which one did you catch?” A <code>null</code> can be returned from <code>getGrandParent()</code>, and using that return value without checking will cause the exception. <strong>OR</strong> a bug in <code>getGrandParent()</code> might cause an exception while trying to find the parent’s parent, and you are obscuring the bug by assuming the <code>NullPointerException</code> results from a properly returned <code>null</code> value.</p>\n\n<p>You can use <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Optional.html\" rel=\"noreferrer\"><code>Optional</code></a> to properly capture the <code>null</code> and not call subsequent function. </p>\n\n<pre><code>Optional<Boolean> isRequired = Optional.ofNullable(context)\n .map(Context::getGrandParent)\n .map(GrandParent::getParent)\n .map(Parent::getChild)\n .map(Child::isRequired);\n\nif (!isRequired.isPresent()) {\n LOG.error(\"Unable to determine if processing is required.\");\n} else if (isRequired.get()) {\n // continue with business logic\n}\n</code></pre>\n\n<p>The <code>Context::</code>, <code>GrandParent::</code>, <code>Parent::</code>, <code>Child::</code> class types are, of course, WAG's. You'll need to supply the corrent types based on the type returned by the previous stage.</p>\n\n<p>Alternately, you could use <code>.getOrElse(Boolean.FALSE)</code> at the end of the <code>.map()</code> chain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:06:11.760",
"Id": "428077",
"Score": "0",
"body": "This may be the only case where creating an Optional to avoid an explicit null check would be a good idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:24:47.637",
"Id": "428160",
"Score": "0",
"body": "Thank you for this. I think I will go this route. For academic reasons, would you have the same opinion if all of the getters are actually just getters with no logic? In that case there would be no bug (it would just return a reference to a member or null)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T15:20:14.580",
"Id": "428169",
"Score": "0",
"body": "@TCCV Absolutely. For what might be a getter with no logic today may become a computation or delegation method tomorrow."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T22:14:30.687",
"Id": "221372",
"ParentId": "221367",
"Score": "6"
}
},
{
"body": "<p>The solution of @AJNeufeld is elegant and solves your immediate problem. However, I want to make a case for doing things the verbose way: check for each bad condition individually, log an error if the value is null, and continue onward otherwise. This has two advantages.</p>\n\n<p>First, it allows custom error messages depending on which value is null. If a missing field is a serious error in your data, your error log should have tons of information about it! Simply giving up and logging a generic error does not help you fix the database.</p>\n\n<p>Second, it allows you to assign each object to a variable. Presumably, you need to use at least some of these objects inside of the business logic, so having variables bound to each will avoid extra calls to the getters later on.</p>\n\n<p>The resulting code would look something like this.</p>\n\n<pre><code>if (context == null) {\n LOG.error(\"Cannot process: context is null.\");\n return;\n}\n\nGrandParent grandParent = context.getGrandParent();\nif (grandParent == null) {\n LOG.error(String.format(\"Cannot process: context %s has null grandParent.\", context));\n return;\n}\n\nParent parent = grandParent.getParent();\nif (parent == null) {\n LOG.error(String.format(\"Cannot process: grandParent %s has null parent.\", grandParent));\n return;\n}\n\nChild child = parent.getChild();\nif (child == null) {\n LOG.error(String.format(\"Cannot process: parent %s has null child.\", parent));\n return;\n}\n\nif (child.isRequired()) {\n // business logic\n}\n</code></pre>\n\n<p>The code is admittedly quite verbose, but it is readable and clear. In production, useful error messages like these can be much more important than concise code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T15:27:38.393",
"Id": "428170",
"Score": "2",
"body": "It also avoids a possible concurrent execution logic problem in the second code block of the OP's post, where `context.getGrandParent() != null` evaluates to `true`, but by the time `&& context.getGrandParent().getParent() != null` is evaluated, `getGrandParent()` now returns a `null` and results in the `NullPointerException` anyway. Keeping each object, as it is retrieved, in a local variable prevents the item you just tested from changing just after you tested it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T15:07:53.897",
"Id": "221423",
"ParentId": "221367",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221372",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T21:22:26.823",
"Id": "221367",
"Score": "5",
"Tags": [
"java",
"null"
],
"Title": "Multiple null Checks or try/catch NullPointerException"
} | 221367 |
<p><strong>Background</strong></p>
<p>An API endpoint that returns phone numbers. I would appreciate some feedback on this very simple <a href="https://github.com/JwanKhalaf/ZetaTelecom/blob/3aa4a6606018f47b2e123f49b47efdd24a70bba4/ZetaTelecom.Services/Services/PhoneNumbersService.cs" rel="nofollow noreferrer">service class</a> that is part of the <a href="https://github.com/JwanKhalaf/ZetaTelecom/tree/310c4b52f98e175a66a4d4e14a6ad4aaed48f033" rel="nofollow noreferrer">overall solution</a>. Here is its <strong>Interface</strong>:</p>
<pre><code>public interface IPhoneNumbersService
{
Task<IList<PhoneNumberViewModel>> GetAllPhoneNumbersAsync();
Task<IList<CustomerPhoneNumberViewModel>> GetCustomerPhoneNumbersAsync(int customerId);
}
</code></pre>
<p>And here is its implementation:</p>
<pre><code>public class PhoneNumbersService : IPhoneNumbersService
{
private ZetaContext context;
private readonly ILogger logger;
public PhoneNumbersService(
ZetaContext context,
ILogger<PhoneNumbersService> logger)
{
this.context = context;
this.logger = logger;
}
public async Task<IList<PhoneNumberViewModel>> GetAllPhoneNumbersAsync()
{
List<PhoneNumberViewModel> phoneNumbers = await context
.PhoneNumbers
.AsNoTracking()
.Select(x => new PhoneNumberViewModel
{
Customer = $"{x.Customer.Title} {x.Customer.FirstName} {x.Customer.LastName}",
PhoneNumber = x.Value
})
.ToListAsync();
logger.LogTrace($"{phoneNumbers.Count} phone numbers were retrieved from the database.");
return phoneNumbers;
}
public async Task<IList<CustomerPhoneNumberViewModel>> GetCustomerPhoneNumbersAsync(int customerId)
{
Customer customer = await context
.Customers
.AsNoTracking()
.Include(x => x.PhoneNumbers)
.Where(x => x.Id == customerId)
.SingleOrDefaultAsync();
if (customer == null)
{
throw new CustomerNotFoundException(customerId);
}
List<CustomerPhoneNumberViewModel> customerPhoneNumbers = customer
.PhoneNumbers
.Select(x => new CustomerPhoneNumberViewModel
{
PhoneNumber = x.Value,
IsActive = x.IsActive,
CreatedAt = x.CreatedAt
})
.ToList();
return customerPhoneNumbers;
}
}
</code></pre>
<p>The <strong>Controller</strong> that calls the above service looks like this:</p>
<pre><code>[ApiController]
public class PhoneNumbersController : ControllerBase
{
private readonly IPhoneNumbersService phoneNumbersService;
private readonly ILogger logger;
public PhoneNumbersController(
IPhoneNumbersService phoneNumbersService,
ILogger<PhoneNumbersController> logger)
{
this.phoneNumbersService = phoneNumbersService;
this.logger = logger;
}
[Route("api/numbers/")]
public async Task<IActionResult> GetAllPhoneNumbersAsync()
{
IList<PhoneNumberViewModel> phoneNumbers = await phoneNumbersService.GetAllPhoneNumbersAsync();
return Ok(phoneNumbers);
}
[Route("api/customers/{customerId}/numbers")]
public async Task<IActionResult> GetCustomerPhoneNumbers(int? customerId)
{
if (!customerId.HasValue || customerId.Value == 0)
{
throw new ArgumentNullException(nameof(customerId));
}
try
{
IList<CustomerPhoneNumberViewModel> customerPhoneNumbers = await phoneNumbersService.GetCustomerPhoneNumbersAsync(customerId.Value);
return Ok(customerPhoneNumbers);
}
catch (CustomerNotFoundException exception)
{
logger.LogError($"The customer with Id: {exception.CustomerId} could not be found.");
return NotFound();
}
}
}
</code></pre>
<p>One thing I am not sure about: Where should one convert the Entity <code>PhoneNumber.cs</code> to its ViewModel <code>PhoneNumberViewModel.cs</code>. Should this happen in the Service class like it is now (see <code>.Select()</code>)? Or should this happen in the controller?</p>
<p>If in the controller, then that means my service method <code>GetAllPhoneNumbersAsync()</code> should return a list (or should it be IEnumerable or ICollection) of the entities to the controller. Is that bad? Some say that is leaking my entities into the controller, others say the service should be as re-usable as possible and shouldn't do any mapping.</p>
<p>For an Enterprise application, what more can you do to improve the above? Any tips and pointers would be greatly appreciated.</p>
| [] | [
{
"body": "<h2>Design</h2>\n\n<p>The API should preferrably consist of its own contracts (interfaces and <a href=\"https://en.wikipedia.org/wiki/Data_transfer_object\" rel=\"nofollow noreferrer\">DTO's</a>). The problem with your API is that it returns data that is too much flattened to be usable for consumers other than your intended application. </p>\n\n<p>Ask yourself this:</p>\n\n<ul>\n<li>What if someone wants a different string layout for <code>PhoneNumberViewModel.Customer</code>?</li>\n</ul>\n\n<blockquote>\n<pre><code> .Select(x => new PhoneNumberViewModel\n {\n // A specific string concatenation is bad practice for an API ->\n Customer = $\"{x.Customer.Title} {x.Customer.FirstName} {x.Customer.LastName}\",\n PhoneNumber = x.Value\n })\n\n public class PhoneNumberViewModel // <- make a DTO from this\n {\n public string PhoneNumber { get; set; }\n public string Customer { get; set; } // <- reference a Customer DTO here\n }\n</code></pre>\n</blockquote>\n\n<h3>Tips</h3>\n\n<ul>\n<li>Make your own DTO objects, keep OO-principles into account (don't flatten objects to <code>string</code>)</li>\n<li>Use dedicated mappers from/to your domain or <a href=\"https://en.wikipedia.org/wiki/Data_access_object\" rel=\"nofollow noreferrer\">DAO</a> and the DTO. You could use a <a href=\"https://automapper.org/\" rel=\"nofollow noreferrer\">framework</a> for this.</li>\n</ul>\n\n<h3>Argument Guards</h3>\n\n<p>Distinguish arguments that are not set from those that have an incorrect value. There is also a simpler way of checking a <code>Nullable<></code> against either <code>null</code> or a value.</p>\n\n<blockquote>\n<pre><code>if (!customerId.HasValue || customerId.Value == 0)\n{\n throw new ArgumentNullException(nameof(customerId));\n}\n</code></pre>\n</blockquote>\n\n<pre><code>if (customerId == null) // <- calls customerId.HasValue\n{\n throw new ArgumentNullException(nameof(customerId));\n}\nif (customerId == 0) // <- calls customerId.Value\n{\n throw new ArgumentException(\"The value cannot be 0.\", nameof(customerId));\n}\n</code></pre>\n\n<h2>Q&A</h2>\n\n<blockquote>\n <p>Where should one convert the Entity PhoneNumber.cs to its ViewModel \n PhoneNumberViewModel.cs?</p>\n</blockquote>\n\n<p>Convert data to view models on the client. <code>PhoneNumberViewModel</code> should not be a contract in your service at all. Instead, create a DTO and let your controller map from DAO to DTO. In enterprise code, however, you might want to use <a href=\"https://en.wikipedia.org/wiki/Multitier_architecture\" rel=\"nofollow noreferrer\">multiple layers</a> and refactor your server alltogether.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:30:12.973",
"Id": "428080",
"Score": "0",
"body": "Thank you very much @dfhwze. I would like something clarified please, by Data Access Object, do you mean my `Entity`? The thing defined as `DbSet<Entity>` in the `DbContext` class? If yes, then isn't that what people mean by \"leaking entities\" into the controller class? I mean sure, you are then mapping the Entity to a DTO and returning the DTO, but still, isn't that leaking the entities?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:37:26.567",
"Id": "428083",
"Score": "0",
"body": "@J86 The way I would handle it is (1) having a Data Layer that works with Entity/DAO classes (2) having a Domain Layer which works domain entities and maps from/to the Data Layer and (3) having a Service Layer that works with DTO entities and maps from/to the Domain Layer. Exceptions to these tiered layers can be made for CQRS, ODATA, and other querayble patterns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:38:39.917",
"Id": "428084",
"Score": "0",
"body": "So to answer your question, your controller would not know your Entities in a n-tiered application."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:43:38.883",
"Id": "428085",
"Score": "0",
"body": "Ok, thank you, so the service would actually return the `PhoneNumberDTO`. In a simple case such as this, do I need a Domain layer? I mean even if I did, would I gain anything? Because the `PhoneNumberEntity.cs` (assume I rename my entities to end with the word Entity) would be a direct map to `PhoneNumber.cs` in my `.Domain` project."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:44:54.827",
"Id": "428087",
"Score": "0",
"body": "@J86 You proably don't need a Domain Layer for this. Only when you're extending your API with CRUD operations I would consider adding in a Domain Layer. But without Domain Layer, your Service Layer is responsible for mapping entities to DTO's."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:12:21.297",
"Id": "221389",
"ParentId": "221371",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221389",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T22:02:14.277",
"Id": "221371",
"Score": "2",
"Tags": [
"c#",
"api",
"asp.net-core",
"dto"
],
"Title": "API endpoint that returns phone numbers"
} | 221371 |
<p>Currently, I am in the process of optimizing a program that takes a <em><strong>n x n</strong></em> matrix and multiplies it with its <strong>transpose</strong>. I am trying to optimize my matrix calculation algorithm so that it completes in as few clock cycles as possible.</p>
<p>Here is my pseudo code attempt at creating an optimised algorithm.</p>
<pre><code>
// Matrix Multiplicaiton B = A*A'
for(int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
temp = 0;
n_times_i = n * i;
for (int k = 0; k < (n*n); k+=n)
{
temp += A[j + k] * A[i + k];
}
B[j + n_times_i] = temp;
}
}
</code></pre>
<p>Can anyone see any way that I might be able to further improve upon my algorithm here?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-05T02:10:23.000",
"Id": "518426",
"Score": "1",
"body": "Throw all of this out and use BLAS instead? is there a reason you aren't calling into that or LAPACK?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-05T09:14:48.360",
"Id": "518437",
"Score": "1",
"body": "It's hard to review a small fragment out of context. Please show the full function, including any user-defined types you need. A great question would also include your test suite, so we can reproduce your results."
}
] | [
{
"body": "<p>Barring any compiler heroics, you are computing <code>n*n</code> a total of <span class=\"math-container\">\\$n^3\\$</span> times. You might want to cache that result.</p>\n\n<pre><code>const int nn = n*n;\n</code></pre>\n\n<hr>\n\n<p><code>B[j + n_times_i]</code> is a linearly increasing address location, given that <code>j</code> increases by 1 for each middle loop, and and <code>i</code> increases once for each outer loop, which is <code>n</code> increases of <code>j</code>. Taking advantage of that, you can skip the <code>j + n*i</code> calculation, and <code>B[ ]</code> indexing.</p>\n\n<pre><code>int *pB = &B;\n// ... loops & calculation of temp omitted for brevity.\n *pB++ = temp;\n</code></pre>\n\n<hr>\n\n<p>Result:</p>\n\n<pre><code>const int nn = n*n;\nint *pB = B;\n\nfor (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n temp = 0;\n for (int k = 0; k < nn; k += n) {\n temp += A[i+k] * A[j+k];\n }\n *pB++ = temp;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>You <em>may</em> find that you can get additional speed by using pointer arithmetic for <code>A[i+k]</code> and <code>A[j+k]</code>.</p>\n\n<pre><code>int *pAi = A + i;\nint *pAj = A + j;\nfor (k=0; k<n; k++) { // Note: n. The nn variable is no longer needed.\n temp += *pAi * *pAj;\n pAi += n;\n pAj += n;\n}\n</code></pre>\n\n<p>But, you’ll need to profile to find out. It depends on the number of free registers you have ... and the compiler/optimizers these days are pretty darn good.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T13:23:21.347",
"Id": "428145",
"Score": "1",
"body": "\"*compiler heroics*\" is quite a strong term for a very simple optimisation (even if we don't declare `n` as constant, all optimisers will spot it's unmodified and re-use the expression result)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:26:25.587",
"Id": "428161",
"Score": "4",
"body": "@TobySpeight Shh! They might hear you. They are subtle and quick to anger, and I appreciate all heroics efforts they make on my behalf, big and small, and dare not anger them in any way, for without them I would be forced to wrestle with the dreaded realm and the demons of assembly, ARM, Thumb, MIPS and the brethren of x86, and the pony ... he comes!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T06:06:19.950",
"Id": "428230",
"Score": "0",
"body": "@TobySpeight, thanks so much for your help on the solution above. Quick question for you - What might the pointer arithmetic for *pAi and *pAj look like in MIPS assembly?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T03:53:24.177",
"Id": "221377",
"ParentId": "221374",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221377",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T00:42:18.860",
"Id": "221374",
"Score": "5",
"Tags": [
"c",
"matrix"
],
"Title": "Multiplying a Matrix with its Transpose"
} | 221374 |
<p>Here is my bash script that I just wrote to count line of code for JavaScript project.</p>
<p>It will list number of:</p>
<ul>
<li>Comment lines</li>
<li>Blank lines</li>
<li>All lines</li>
</ul>
<p>Here is my script:</p>
<pre><code>#!/bin/bash
fileExt="*.js"
allFiles=$(find ./ -name "$fileExt")
commentLines=$((perl -ne 'print "$1\n" while /(^\s+\/\/\s*\w+)/sg' $allFiles;\
perl -0777 -ne 'print "$1\n" while /(\*\*.*?\*\/)/sg' $allFiles) | wc -l)
blankLines=$(grep '^[[:space:]]*//' -r --include $fileExt | wc -l)
allLines=$(echo $allFiles | xargs wc -l | tail -n 1 | cut -d " " -f 2)
echo -e "\nTotal comments line is: $commentLines.\n\
Total blank lines is: $blankLines.\n\
\nTotal all lines is: $allLines."
</code></pre>
<p>Let me explain it a little bit:</p>
<h3>First, we need to list all files that end with ".js" within the project:</h3>
<pre><code>allFiles=$(find ./ -name "$fileExt")
</code></pre>
<h3>Second, we count all comment lines:</h3>
<pre><code>commentLines=$((perl -ne 'print "$1\n" while /(^\s+\/\/\s*\w+)/sg' $allFiles;\
perl -0777 -ne 'print "$1\n" while /(\*\*.*?\*\/)/sg' $allFiles) | wc -l)
</code></pre>
<p>There are 2 types of comment lines in JavaScript:</p>
<ol>
<li><p>Line start with only space and <code>//</code> or only <code>//</code></p>
<p>Example:</p>
<pre><code>//this is a comment line
</code></pre>
<p>// this is a comment line
// this also is a comment line</p>
<p>All above are comment lines, and we got 3 lines total here. But the following is not comment lines:</p>
<pre><code>function foo(params 1) { // return void
}
</code></pre>
<p>The line contains <code>// return void</code> is not considered as a comment, so we do not need to count it.</p>
<p>And for the kind of comment line. I using the regex with <code>perl</code> to print all comment lines that match with regex:</p>
<pre><code>/(^\s+\/\/\s*\w+)/sg
</code></pre></li>
<li><p>Multi-line comment (<a href="https://en.wikipedia.org/wiki/JSDoc" rel="nofollow noreferrer">JSDOC</a>):</p>
<p>Example:</p>
<pre><code>/**
* return something
* @param {object} obj
* return void
*/
</code></pre>
<p>So we need to count all number of lines that start from the line with <code>/**</code> and end with <code>*/</code>, we have 5 lines here.</p>
<p>I use this regex to match:</p>
<pre><code>perl -0777 -ne 'print "$1\n" while /(\*\*.*?\*\/)/sg' $allFiles
</code></pre>
<p>So the total number of comment lines is the sum of two types comment lines above.</p></li>
</ol>
<h3>Third</h3>
<p>We need to count blank lines.</p>
<p>I use the following command to match:</p>
<pre><code>grep '^[[:space:]]*//' -r --include $fileExt | wc -l
</code></pre>
<h3>Finally</h3>
<p>We need to count all lines:</p>
<pre><code>echo $allFiles | xargs wc -l | tail -n 1 | cut -d " " -f 2
</code></pre>
<p>I wonder if my solution is good enough or not.</p>
| [] | [
{
"body": "<blockquote>\n <pre class=\"lang-bsh prettyprint-override\"><code>fileExt=\"*.js\"\nallFiles=$(find ./ -name $fileExt)\n</code></pre>\n</blockquote>\n\n<p>This is a bug. The wildcard in <code>$fileExt</code> will be expanded by the shell, and cause a syntax error when the current directory has more than one matching file in it:</p>\n\n<pre><code>$ touch a.js b.js\n$ fileExt=\"*.js\"\n$ find ./ -name $fileExt\nfind: paths must precede expression: `b.js'\nfind: possible unquoted pattern after predicate `-name'?\n</code></pre>\n\n<p>You need to quote the variable. Better yet, use the <code>globstar</code> option to populate an array and eliminate <code>find</code> altogether:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>fileExt=\"js\"\nshopt -s globstar\ndeclare -a allFiles=( **/*.$fileExt )\ngrep … \"${allFiles[@]}\" # to use the array\n</code></pre>\n\n<p>This regex does not match blank lines:</p>\n\n<blockquote>\n <pre class=\"lang-bsh prettyprint-override\"><code>grep '^[[:space:]]*//' \n</code></pre>\n</blockquote>\n\n<p>Just <code>/*</code> is enough to start a multi-line comment in JavaScript (not <code>/**</code>).</p>\n\n<p>The script reads every file four times. That is slow. Since you're using Perl already, just let it count everything. Then you don't need to capture the file names at all, since they are used only once:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>#!/bin/bash\nshopt -s globstar\nexec perl -nle '\n BEGIN { \n @ARGV=grep -f, @ARGV or die \"no matching files\\n\";\n $comment = $blank = 0;\n }\n if ( m{ ^\\s*/\\* }x .. m{ \\*/ }x or m{ ^\\s*// }x ) { $comment++ }\n elsif ( m{ ^\\s*$ }x ) { $blank++ }\n END { print \"$comment comment lines; $blank blank lines; $. total lines\" }\n' **/*.js\n</code></pre>\n\n<p>At this point we're barely using bash anymore, and the globbing can be moved inside the Perl script, using the File::Find module:</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>#!/usr/bin/perl -wnl\nBEGIN {\n use strict;\n use File::Find;\n my $ext=\"js\";\n my @dirs=( @ARGV ? @ARGV : '.' );\n @ARGV=();\n find(sub { -f and /\\.$ext$/o and push @ARGV, $File::Find::name }, @dirs );\n our ($comment, $blank) = (0, 0);\n}\n\nif ( m{ ^\\s*/\\* }x .. m{ \\*/ }x or m{ ^\\s*// }x ) { $comment++ }\nelsif ( m{ ^\\s*$ }x ) { $blank++ }\n\nEND {\n print \"$comment comment lines; $blank blank lines; $. total lines\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:58:30.230",
"Id": "428089",
"Score": "1",
"body": "Thank you a lot, this is a lot of stuffs that I did not know before, maybe this is the best answer at the moment"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:59:59.527",
"Id": "428091",
"Score": "0",
"body": "I understand this: grep '^[[:space:]]*//', this is my mistake!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:07:48.333",
"Id": "428150",
"Score": "2",
"body": "Pure Perl is a good approach; it does require Perl's File::Find module to do the recursion, and the clumsiness of that module is a peeve of mine. But sure, why not? Edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T04:36:13.960",
"Id": "428486",
"Score": "0",
"body": "The wildcard in $fileExt will be expanded by the shell, and cause a syntax error when the current directory has more than one matching file in it => you were right. I wasn't even aware that because of using zsh and I got no problem at all. I think next time better I will use pure bash.\n\nIn zsh, I even can use some command like: \nwc -l **/*.js\n\nThank you once again!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T05:52:17.567",
"Id": "221385",
"ParentId": "221378",
"Score": "7"
}
},
{
"body": "<h1>General</h1>\n\n<p>Run <code>shellcheck</code> on this script - almost all variable expansions are unquoted, but need to be quoted. That will also highlight the non-portable <code>echo -e</code> (prefer <code>printf</code> instead) and a dodgy use of <code>$((</code> where <code>$( (</code> would be safer.</p>\n\n<p>I recommend setting <code>-u</code> and <code>-e</code> shell options to help you catch more errors.</p>\n\n<h1>Flexibility</h1>\n\n<p>Instead of requiring users to change to the top directory of the project, we could allow them to specify one or more directories as command-line arguments, and use current directory as a fallback if no arguments are provided:</p>\n\n<pre><code>dirs=(\"${@:-.}\")\n</code></pre>\n\n<h1>Finding files</h1>\n\n<p><code>allFiles</code> will include directories and other non-regular files, if they happen to end in <code>.js</code>. We need to add a file type predicate:</p>\n\n<pre><code>allFiles=$(find \"${dirs[@]}\" -name \"$fileExt\" -type f)\n</code></pre>\n\n<p>Since we're using Bash, it makes sense to take advantage of array variables - though we'll still have problems for filenames containing whitespace. To fix that, we need to read answers to <a href=\"//stackoverflow.com/q/23356779\"><em>How can I store the “find” command results as an array in Bash?</em></a>:</p>\n\n<pre><code>allFiles=()\nwhile IFS= read -r -d ''; do\n allFiles+=(\"$REPLY\")\ndone < <(find ./ -name \"$fileExt\" -type f -print0)\n</code></pre>\n\n<p>It may almost be simpler to set <code>globstar</code> shell option and then remove non-regular files from the glob result.</p>\n\n<h1>Counting comment lines</h1>\n\n<p>I didn't follow your Perl code, but I have an alternative approach using <code>sed</code>:</p>\n\n<ul>\n<li>convert all lines from initial <code>/**</code> to final <code>*/</code> to begin with <code>//</code> instead,</li>\n<li>then keep only the lines beginning with optional whitespace then <code>//</code>:</li>\n</ul>\n\n\n\n<pre><code>sed -e '\\!^[[:blank:]]*/\\*\\*!,\\!\\*/!s/.*/\\\\\\\\/' \\\n -e '\\|^[[:blank:]]*//|!d'\n</code></pre>\n\n<p>(Actually, that's a lot less pretty than I'd hoped!)</p>\n\n<h1>Blank lines</h1>\n\n<p>Here, we've used the regular expression that matches comment lines. We want <code>'^[[:blank:]]*$'</code> instead, to match lines that contain <em>only</em> (optional) whitespace.</p>\n\n<h1>All lines</h1>\n\n<p>Again, over-complicated: just <code>cat</code> the files together and then use <code>wc -l</code>.</p>\n\n<h1>Printing</h1>\n\n<p>I find it easier to visualise output formatting if we simply use a here-document:</p>\n\n<pre><code>cat <<EOF\nTotal comments lines is: $commentLines.\nTotal blank lines is: $blankLines.\nTotal all lines is: $allLines.\nEOF\nexit\n</code></pre>\n\n<hr>\n\n<h1>Modified code</h1>\n\n<pre><code>#!/bin/bash\nset -eu\n\nfileExt='*.js'\ndirs=(\"${@:-/usr/lib/nodejs/lodash}\")\n\nallFiles=()\nwhile IFS= read -r -d ''; do\n allFiles+=(\"$REPLY\")\ndone < <(find \"${dirs[@]}\" -name \"$fileExt\" -type f -print0)\n\ncommentLines=$(sed -e '\\!^[[:blank:]]*/\\*\\*!,\\!\\*/!s/.*/\\\\\\\\/' \\\n -e '\\|^[[:blank:]]*//|!d' \\\n \"${allFiles[@]}\" | wc -l)\nblankLines=$(cat \"${allFiles[@]}\" | grep -c '^[[:blank:]]*$')\nallLines=$(cat \"${allFiles[@]}\" | wc -l)\n\ncat <<EOF\nTotal comment lines is: $commentLines.\nTotal blank lines is: $blankLines.\nTotal all lines is: $allLines.\nEOF\n</code></pre>\n\n<p>Although this makes three passes over the input files, that might be an acceptable trade-off against the complexity of a single-pass approach here (and is already the approach taken in the original code).</p>\n\n<hr>\n\n<h1>Single-pass version using <code>awk</code></h1>\n\n<p>A single-pass version doesn't require us to use an array to store the filenames; we can simply stream the file contents into a suitable counting function. We could implement that counting function in shell, but it's probably easier to write a short <code>awk</code> program. Note that with no arrays, we can make this a POSIX shell program:</p>\n\n<pre><code>#!/bin/sh\nset -eu\n\nfileExt='*.js'\n\nfind \"${@:-.}\" -name \"$fileExt\" -type f -print0 | xargs -0 cat |\n awk 'BEGIN { all = 0; blank = 0; comment = 0; incomment = 0; }\n\n { ++all\n if ($0 ~ \"/\\\\*\") { incomment = 1 }\n if (incomment) { ++comment; if ($0 ~ \"\\\\*/\") incomment = 0; }\n else { blank += ($0 ~ \"^[[:blank:]]*$\"); comment += ($0 ~ \"^[[:blank:]]*//\") } }\n\n END { print \"Total comment lines is:\", comment\n print \"Total blank lines is:\", blank\n print \"Total all lines is:\", all }'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T13:18:00.830",
"Id": "221413",
"ParentId": "221378",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "221385",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T04:11:20.847",
"Id": "221378",
"Score": "9",
"Tags": [
"regex",
"bash",
"shell",
"perl",
"sh"
],
"Title": "Count line of code for a JavaScript project"
} | 221378 |
<p>I wanted to make a <code>Sequence</code> that can do a pre-order traversal of Binary Tree. Doing so provides automatically unlocks wonderfully useful methods, like <code>prefix</code>, <code>map</code>, <code>filter</code>, etc. But doing so requires implementing an Iterator, which conforms to <code>IteratorProtocol</code>.</p>
<p>Implementing <code>next()</code> to vend elements means that the usual simple recursive solutions aren't possible (because Swift doesn't have continuations, you have no way of "suspending" your recursion until the next call to <code>next()</code>). This is my best attempt. It's working and gives the correct answers, but I would love some feedback.</p>
<p>Here's my primary Binary Tree data structure (note the absence of <code>parent</code> references):</p>
<pre><code>//=== BinaryTreeNode.swift
public final class BinaryTreeNode<T>: BinaryTreeNodeProtocol {
public let payload: T
public let left: BinaryTreeNode<T>?
public let right: BinaryTreeNode<T>?
init(
_ payload: T,
_ left: BinaryTreeNode<T>? = nil,
_ right: BinaryTreeNode<T>? = nil
) {
self.payload = payload
self.left = left
self.right = right
}
}
</code></pre>
<p>To allow this iterator to be used in more cases, I extracted out the binary-freeness into a protocol. For example, UIViews could be made to conform, without requiring people to reproduce portions of their view hierarchy into my <code>BinaryTreeNode</code> objects.</p>
<pre><code>//=== BinaryTreeNodeProtocol.swift
public protocol BinaryTreeNodeProtocol {
associatedtype Payload
var payload: Payload { get }
var left: Self? { get }
var right: Self? { get }
}
</code></pre>
<p>Here's the <code>Sequence</code>/<code>Iterator</code> implementation:</p>
<pre><code>//=== BinaryPreorderIterator.swift
public extension BinaryTreeNodeProtocol {
var preorderTraversal: BinaryTreePreorderSequence<Self> { return BinaryTreePreorderSequence(self) }
}
public struct BinaryTreePreorderSequence<Tree: BinaryTreeNodeProtocol>: Sequence {
private let tree: Tree
public init(_ tree: Tree) { self.tree = tree }
public func makeIterator() -> BinaryPreorderIterator<Tree> {
return BinaryPreorderIterator(tree: self.tree)
}
}
public struct BinaryPreorderIterator<Tree: BinaryTreeNodeProtocol>: IteratorProtocol {
private var backtrackStack: [(node: Tree, nextAction: NextAction)]
private enum NextAction { case visitRoot, visitLeft, visitRight, returnToParent }
public init(tree: Tree) {
backtrackStack = [(tree, .visitRoot)]
}
public mutating func next() -> Tree.Payload? {
// Using a non-constant boolean expression circumvent's the compilers warnings about the value always being false.
let debugPrinting = Bool("false")!
if debugPrinting { print("next()") }
while let popped = backtrackStack.last {
if debugPrinting {
print("\tloop - backtrackStack:")
for (node, nextAction) in backtrackStack.dropLast() {
print("\t\t| \(node.payload) \(nextAction)")
}
print("\t\t↳ \(popped.node.payload) \(popped.nextAction) <--- current state\n")
}
advanceState()
switch (popped.nextAction) {
case .visitRoot:
let returnValue = popped.node.payload
if debugPrinting { print("\treturning \(returnValue)\n") }
return returnValue
case .visitLeft:
// This block could be more nicely expressed as the following code,
// but that doesn't work, because the second method call is unconditional,
// unlike an if/else-if pair.
//
// tryMarkingLeftToVisitNext()
// tryMarkingRightToVisitNext()
if let leftChild = lastState().node.left {
self.visitNext(leftChild)
}
else if let rightChild = lastState().node.right {
self.visitNext(rightChild)
}
case .visitRight:
tryMarkingRightToVisitNext()
case .returnToParent:
break
}
}
return nil
}
private func assertLastStateExists() {
precondition(!backtrackStack.isEmpty, """
lastState() should only be called when there IS a last state, i.e. the backtrace stack isn't empty.
""")
}
private func lastState() -> (node: Tree, nextAction: NextAction) {
assertLastStateExists()
return backtrackStack.last!
}
private mutating func setNextActionOnLastNode(_ newNextAction: NextAction) {
assertLastStateExists()
backtrackStack[backtrackStack.count - 1].nextAction = newNextAction // gross, but Array.last is write-only
}
private mutating func advanceState() {
switch lastState().nextAction {
case .visitRoot: setNextActionOnLastNode(.visitLeft)
case .visitLeft: setNextActionOnLastNode(.visitRight)
case .visitRight: setNextActionOnLastNode(.returnToParent)
case .returnToParent: backtrackStack.removeLast()
}
}
private mutating func tryMarkingLeftToVisitNext() {
if let leftChild = lastState().node.left {
self.visitNext(leftChild)
}
}
private mutating func tryMarkingRightToVisitNext() {
if let rightChild = lastState().node.right {
self.visitNext(rightChild)
}
}
private mutating func visitNext(_ node: Tree) {
backtrackStack.append((node: node, nextAction: .visitRoot))
}
}
</code></pre>
<p>And here's a little demo:</p>
<pre><code>func sampleTree() -> BinaryTreeNode<Int> {
typealias B = BinaryTreeNode
// 4
// / \
// 2 6
// / \ / \
// 1 3 5 7
return B(4, B(2, B(1), B(3)), B(6, B(5), B(7)))
}
print(Array(sampleTree().preorderTraversal))
</code></pre>
<p>Questions:</p>
<ol>
<li>Is there a way to extract the <code>if</code>/<code>else if</code> pair into calls to <code>tryMarkingLeftToVisitNext()</code>/<code>tryMarkingRightToVisitNext()</code>? Obviously they could be wrapped in the same <code>if</code>/<code>else if</code> pair, but that doesn't really tidy anything.</li>
<li><p>I have a strong suspition that one of the <code>NextAction</code> states can be removed entirely.</p>
<p>For example, if elements' payloads were returned upon visiting them, they could be added to the backtrace with a next state of <code>visitLeft</code>, omitting the need for <code>visitRoot</code> (merely existing in the backtrace implies <code>visitRoot</code> was already done).</p>
<p>I was close to getting this going, but faced issues with how to visit the root (since my backtrace is initialized to <code>[(tree, .visitRoot)]</code>, to kick things off on the first call to <code>next()</code>). I could only achieve it if I added a separate <code>root</code> instance variable to my iterator, and a special case in <code>next()</code> branch to handle the root.</p></li>
</ol>
<p>All other feedback and suggestions are greatly appreciated!</p>
| [] | [
{
"body": "<p>Let's start with a bug: If a node has a right but no left child then the right subtree is traversed twice. As an example, the tree</p>\n\n<pre><code>// 1\n// \\\n// 2\n// / \\\n// 3 4\nreturn B(1, nil, B(2, B(3), B(4)))\n</code></pre>\n\n<p>produces the output</p>\n\n<pre><code>[1, 2, 3, 4, 2, 3, 4]\n</code></pre>\n\n<p>The reason is that for the (empty) left child of node ①, the right child node ② is added twice to the stack, in <code>func advanceState()</code> at</p>\n\n<pre><code>case .visitLeft: setNextActionOnLastNode(.visitRight)\n</code></pre>\n\n<p>and in the “main loop” at</p>\n\n<pre><code>else if let rightChild = lastState().node.right {\n self.visitNext(rightChild)\n}\n</code></pre>\n\n<p>The solution is simple: Remove that else case in <code>case .visitLeft:</code>. Which means that you call just <code>tryMarkingLeftToVisitNext()</code>, as intended:</p>\n\n<pre><code> case .visitLeft:\n tryMarkingLeftToVisitNext()\n\n case .visitRight:\n tryMarkingRightToVisitNext()\n</code></pre>\n\n<p>or inline those two functions, since each of them is called only once.</p>\n\n<hr>\n\n<p>What I don't like is how the stack is treated in the main loop:</p>\n\n<pre><code>while let popped = backtrackStack.last {\n advanceState()\n switch (popped.nextAction) {\n // ...\n }\n}\n</code></pre>\n\n<p>The variable name <code>popped</code> suggests that the element is <em>removed</em> from the stack, but it isn't: It remains on the stack and is mutated or removed in <code>func advanceState()</code>.</p>\n\n<p>I would also suggest to have a single place where the current state is acted upon, not two places (which can cause subtle bugs, as we saw above).</p>\n\n<p>The main loop then would look like this</p>\n\n<pre><code>while let popped = backtrackStack.popLast() {\n switch (popped.nextAction) {\n // ...\n }\n}\n</code></pre>\n\n<p>where the switch handles the different cases, and appends new states to the stack where necessary. This </p>\n\n<ul>\n<li>simplifies the code and the logic,</li>\n<li>makes various utility functions obsolete,</li>\n<li>makes the <code>.removeToParent</code> case obsolete,</li>\n<li>makes the forced unwrapping in <code>last!</code> and the checks for a non-empty stack obsolete at various places.</li>\n</ul>\n\n<p>This leads to the following implementation of <code>struct BinaryPreorderIterator</code>:</p>\n\n<pre><code>public struct BinaryPreorderIterator<Tree: BinaryTreeNodeProtocol>: IteratorProtocol {\n private var backtrackStack: [(node: Tree, nextAction: NextAction)]\n private enum NextAction { case visitRoot, visitLeft, visitRight }\n\n public init(tree: Tree) {\n backtrackStack = [(tree, .visitRoot)]\n }\n\n public mutating func next() -> Tree.Payload? {\n while let popped = backtrackStack.popLast() {\n switch (popped.nextAction) {\n case .visitRoot:\n backtrackStack.append((popped.node, .visitLeft))\n return popped.node.payload\n\n case .visitLeft:\n backtrackStack.append((popped.node, .visitRight))\n if let leftChild = popped.node.left {\n backtrackStack.append((leftChild, .visitRoot))\n }\n\n case .visitRight:\n if let rightChild = popped.node.right {\n backtrackStack.append((rightChild, .visitRoot))\n }\n }\n }\n\n return nil\n }\n}\n</code></pre>\n\n<hr>\n\n<p>And now we see that the stack actually just identifies the nodes which have to be visited later. If we push left and right child nodes onto the stack immediately when a node is encountered then the <code>enum NextAction</code> and the while-loop are not needed anymore:</p>\n\n<pre><code>public struct BinaryPreorderIterator<Tree: BinaryTreeNodeProtocol>: IteratorProtocol {\n private var backtrackStack: [Tree]\n\n public init(tree: Tree) {\n backtrackStack = [tree]\n }\n\n public mutating func next() -> Tree.Payload? {\n guard let node = backtrackStack.popLast() else {\n return nil // Stack is empty.\n }\n if let rightChild = node.right {\n backtrackStack.append(rightChild)\n }\n if let leftChild = node.left {\n backtrackStack.append(leftChild)\n }\n return node.payload\n }\n}\n</code></pre>\n\n<p>Note that we have reduced the implementation of <code>struct BinaryPreorderIterator</code> from 75 lines to 20 lines (not counting the debug output) and simplified it considerably. It also takes less memory and is more efficient.</p>\n\n<p><em>Remark:</em> <code>func next()</code>could be more compactly written using <code>Optional.map</code>:</p>\n\n<pre><code> public mutating func next() -> Tree.Payload? {\n guard let node = backtrackStack.popLast() else {\n return nil\n }\n node.left.map { backtrackStack.append($0) }\n node.right.map { backtrackStack.append($0) }\n return node.payload\n }\n</code></pre>\n\n<p>or even</p>\n\n<pre><code> public mutating func next() -> Tree.Payload? {\n return backtrackStack.popLast().map { node in\n node.left.map { backtrackStack.append($0) }\n node.right.map { backtrackStack.append($0) }\n return node.payload\n }\n }\n</code></pre>\n\n<p>but that does not make it better readable or understandable.</p>\n\n<hr>\n\n<p>Some further suggestions:</p>\n\n<p>It suffices to implement the <code>IteratorProtocol</code> protocol and to <em>declare</em> the <code>Sequence</code> conformance, making <code>struct BinaryTreePreorderSequence</code> obsolete:</p>\n\n<pre><code>public extension BinaryTreeNodeProtocol {\n var preorderTraversal: BinaryPreorderIterator<Self> {\n return BinaryPreorderIterator(tree: self) }\n}\n\npublic struct BinaryPreorderIterator<Tree: BinaryTreeNodeProtocol>: IteratorProtocol, Sequence {\n private var backtrackStack: [Tree]\n\n public init(tree: Tree) {\n backtrackStack = [tree]\n }\n\n public mutating func next() -> Tree.Payload? {\n guard let node = backtrackStack.popLast() else {\n return nil\n }\n if let rightChild = node.right {\n backtrackStack.append(rightChild)\n }\n if let leftChild = node.left {\n backtrackStack.append(leftChild)\n }\n return node.payload\n }\n}\n</code></pre>\n\n<p>This works because there is a default implementation of <code>func makeIterator()</code> for <code>IteratorProtocol</code>.</p>\n\n<p>Finally, I would <em>not</em> use empty argument labels in the init method of <code>class BinaryTreeNode</code>:</p>\n\n<pre><code>public final class BinaryTreeNode<T>: BinaryTreeNodeProtocol {\n // ...\n\n init(\n _ payload: T,\n left: BinaryTreeNode<T>? = nil,\n right: BinaryTreeNode<T>? = nil\n ) {\n // ...\n }\n}\n</code></pre>\n\n<p>This requires more typing, but may be easier to read, and allows to create nodes with a right subtree only, without having to use a <code>nil</code> argument for the left subtree:</p>\n\n<pre><code>B(1, right: B(2, left: B(3), right: B(4)))\n// versus\nB(1, nil, B(2, B(3), B(4)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:04:00.923",
"Id": "428149",
"Score": "0",
"body": "Wow, this is *much* more improved than I was expecting! I wasn't thrilled about the `while let popped = backtrackStack.last` part either, but I found myself re-appending the elements I just popped off, so I changed to this \"peek\" approach instead but forgot to rename the `popped` variable. (Boy I wish we just had a simple stack with nice `peek()`/`push()`/`pop()` operations)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:08:49.880",
"Id": "428151",
"Score": "0",
"body": "I understand the removal of `if let rightChild = popped.node.right` under the `.visitLeft` case (since its absence just caused another loop around, this time reaching the `.visitRight` state because of the `advance()` call from the previous loop). I'm a little confused about how you were able to remove the need for the loop, but part of the problem there was that I don't remember the problem that the loop initially solved lol. I'll think on it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:13:12.047",
"Id": "428152",
"Score": "0",
"body": "I have mixed feelings about conforming to both `IteratorProtocol` and `Sequence`. I knew it was possible, but I thought you would need to add a `makeIterator()` implementation that just does `return self`. Didn't know that the standard library adds that by default, so that serves as a kind of \"endorsement\". But I still don't like the idea of making one-shot sequences where it's not strictly necessary, even if making a separate `Sequence` requires this extra boilerplate"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:20:47.487",
"Id": "428158",
"Score": "0",
"body": "Think you so much for your time Martin, I appreciate it. I'll work over this and let you know if I have any follow up questions :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T16:11:40.573",
"Id": "428561",
"Score": "0",
"body": "Suppose the binary tree nodes had parent references, it wouldn't be possible to do any better, space-wise, right? Intuitively that makes sense to me, but maybe I'm missing something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T20:53:11.443",
"Id": "428611",
"Score": "0",
"body": "@Alexander: I think you would still need a stack to remember in which direction to move from a parent node: to the next parent or to the right child."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T21:39:57.407",
"Id": "428620",
"Score": "0",
"body": "Yeah, that was my thinking too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T02:09:19.180",
"Id": "428632",
"Score": "0",
"body": "@Alexander: Thinking about it again: My last comment is probably wrong, because every node has a *unique* successor in the traversal. When you return from a node to its parent node then you can compare this node to the parent's left and right child, and decide where to continue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T02:55:11.720",
"Id": "428634",
"Score": "0",
"body": "@Alexander: But this would not save *memory* because you had a parent pointer in each node. The stack becomes only as large as the tree's height."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T09:11:04.303",
"Id": "221399",
"ParentId": "221380",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221399",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T04:31:47.693",
"Id": "221380",
"Score": "1",
"Tags": [
"algorithm",
"tree",
"swift",
"iterator"
],
"Title": "Sequence for Pre-order traversal of Binary Trees"
} | 221380 |
<p>I have a need to convert wire encoding (big-endian) to little-endian in Python.</p>
<p>The conversion needs to happen as a separate function; I am not allowed to change the function that reads the byte stream because it will break a lot of other functions.</p>
<p>The best I can think of is this:</p>
<pre><code>def be_to_le(value: int) -> int:
assert isinstance(value, int)
numbytes = len(f"0{value:x}") >> 1
if numbytes == 1:
return value
rslt = 0
for b in value.to_bytes(numbytes, byteorder="little"):
rslt <<= 8
rslt |= b
return rslt
</code></pre>
<p>Is there a better way?</p>
| [] | [
{
"body": "<p>To calculate number of bytes, better use:</p>\n\n<pre><code>numbytes = math.ceil(value.bit_length() / 8)\n</code></pre>\n\n<p>And then you can just:</p>\n\n<pre><code>def be_to_le(value: int) -> int:\n numbytes = math.ceil(value.bit_length() / 8)\n return int.from_bytes(value.to_bytes(numbytes, byteorder=\"little\"), byteorder=\"big\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T17:50:43.207",
"Id": "430185",
"Score": "0",
"body": "Ooohhh... so `int` has a `bit_length()` method? That's news to me... Thanks for telling me that! I'll probably not use `math.ceil` though. `(n + 7) >> 3` might be better since it keeps everything in `int` land. Anyways, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T16:26:47.717",
"Id": "221433",
"ParentId": "221381",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221433",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T04:37:15.177",
"Id": "221381",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"integer",
"bitwise",
"serialization"
],
"Title": "Indeterminate-length big-endian to little-endian conversion in Python"
} | 221381 |
<p>I have re-write a new version of Javascript Simple Calculator. Any thoughts in regards to this new design and how can it be improved further? One of my thoughts are to create a Javascript object for "Calculator" and move all the relevant property into it.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict";
var lastNumberString, isFirstZero, lastInputIsOperator;
// 12. lastNumberString is 12.
// 12+3. lastNumberString is 3.
// lastNumberString will be reset to empty each time operator is pressed.
// This is one reason of having lastInputIsOperator flag.
// lastNumberString is to:
// - block more than one decimal.
// - set the first zero.
// isFirstZero is flags to detect if lastNumberString has the first zero.
// true: has first zero.
// If first zero exists, and key pressed is zero or number,
// replace (remove char and insert) will be performed.
var expStr = document.getElementById('lblExpressionString');
// Any changes in outputArray will be synced to expStr
// for display. This is the UI layer.
var result = document.getElementById('lblResult');
// Each time a equation key in pressed, result will be shown after math evaluation.
// This is the UI layer.
// For single line calculation design, this element shall be removed.
// expStr will overwrite will final result
var outputArray = [];
// Each time a key is pressed, a char will pushed into this array
// If replace operation is needed, last pushed char will be popped
// This implements stack FIFO for 0(1) performance.
// outputArray data has to be synced to expStr but hidden.
// For easier debugging, this is can displayed.
const init = () => {
lastNumberString = '';
outputArray = [];
expStr.innerText = '';
result.innerText = '0';
lastInputIsOperator = true;
isFirstZero = false; // False means first zero does not exist in lastNumberString yet.
}
const appendExp = s => {
lastNumberString += s;
outputArray.push(s);
}
const replaceLastChar = s => {
// Does not required to update lastNumberString because
// subsequent checking is based on isFirstZero flag.
// Replace only happen in two condition.
// 0 -> 1
// + -> -
outputArray.pop();
outputArray.push(s);
}
const displayExpressionString = () => {
expStr.innerText = outputArray.join('');
}
init();
$('#ac').click(function () {
init();
})
$('#back').click(function () {
if (outputArray.length === 0) {
return;
}
// 10 -> 1
outputArray.pop();
displayExpressionString();
if (outputArray.length === 0) {
init();
return;
}
// Peek last char
const lastChar = outputArray[outputArray.length - 1];
// 1
console.log(lastChar);
// If last char after pop is a number or decimal
// Add more condition if there are more key like %
if (Number.isInteger(parseInt(lastChar)) || lastChar === '.')
lastInputIsOperator = false;
else
lastInputIsOperator = true;
})
$('#decimal').click(function (item) {
if (lastNumberString.includes('.')) {
return;
}
if (lastNumberString === '') {
// '' -> 0.
appendExp('0.');
} else {
// 1 -> 1.
appendExp(item.target.textContent);
}
displayExpressionString();
lastInputIsOperator = false;
isFirstZero = false;
})
$('.number').click(function (item) {
debugger
if (lastNumberString === '') {
// '' -> 1
appendExp(item.target.textContent);
// '' -> 0
if (item.target.textContent === '0')
isFirstZero = true;
} else if (isFirstZero) {
if (item.target.textContent !== '0') {
// 0 -> 1
debugger
replaceLastChar(item.target.textContent);
isFirstZero = false;
}
} else {
// 1 -> 10
appendExp(item.target.textContent);
}
displayExpressionString();
lastInputIsOperator = false;
})
$('.operator').click(function (item) {
if (outputArray.length === 0) {
return;
}
if (lastInputIsOperator) {
// 1+ -> 1-
replaceLastChar(item.target.textContent);
} else {
// 1 -> 1+
appendExp(item.target.textContent);
}
lastInputIsOperator = true;
displayExpressionString();
// Reset to allow first zero again.
lastNumberString = '';
isFirstZero = false;
})
const evaluateExp = () => {
// Result is stored in the textbox
// The expression is stored in the textbox. Expression ie 1+2
if (lastInputIsOperator && outputArray.length > 0) {
outputArray.pop();
displayExpressionString();
} else if (outputArray.length > 0) {
expStr.innerText = expStr.innerText.replace('x', '*').replace('÷', '/');
result.innerText = eval(expStr.innerText);
const tempResult = result.innerText;
// Reset. Similar as init()
expStr.innerText = '';
outputArray = [];
lastNumberString = '';
lastInputIsOperator = false;
isFirstZero = true;
// Result become last number string.
lastNumberString = tempResult;
for (const item of tempResult)
outputArray.push(item);
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.containerCal {
display: grid;
justify-content: center;
grid-template-columns: 80px 80px 80px 80px;
grid-template-rows: 40px 80px;
grid-template-areas: "header header header header" "header header header header" "main main main main" "main main main main" "main main main main" "main main main main" "main main main main";
border: 1px solid black;
max-width: 320px;
margin: 0 auto;
background-color: black;
padding: 0px;
}
.item-header1 {
grid-area: header;
grid-row-start: 1;
grid-row-end: 1;
background-color: black;
color: silver;
text-align: right;
font-size: 2em;
padding: 10px;
}
.item-header2 {
grid-area: header;
grid-row-start: 2;
grid-row-end: 2;
background-color: black;
color: white;
text-align: right;
font-size: 4em;
padding: 10px;
}
.zero {
grid-column-start: 1;
grid-row-start: 7;
grid-column: span 2;
}
.equal {
grid-column-start: 4;
grid-row-start: 6;
grid-row-end: span 2;
}
/* Some hover effects */
.btn:hover {
background-color: yellow;
cursor: pointer;
color: black;
/*box-shadow: 0px 4px silver;*/
}
.btn {
font-size: 150%;
background-color: whitesmoke;
border: none;
color: black;
padding: 20px;
text-align: center;
margin: 1px;
border-radius: 1%;
font-weight: bold;
}
.orange {
background-color: orange;
}
.btnC {
color: red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="containerCal">
<div class="item item-header1" id='lblExpressionString'></div>
<div class="item item-header2" id='lblResult'></div>
<button type="button" id='ac' class='btn btnC'>C</button>
<button type="button" value="" id='back' class='btn key'><<</button>
<button type="button" value="x" class='operator btn key'>x</button>
<button type="button" value="÷" class='operator btn key'>÷</button>
<button type="button" value="9" class='number btn key'>9</button>
<button type="button" value="8" class='number btn key'>8</button>
<button type="button" value="7" class='number btn key'>7</button>
<button type="button" value="-" class='operator btn key'>-</button>
<button type="button" value="6" class='number btn key'>6</button>
<button type="button" value="5" class='number btn key'>5</button>
<button type="button" value="4" class='number btn key'>4</button>
<button type="button" value="+" class='operator btn key'>+</button>
<button type="button" value="3" class='number btn key'>3</button>
<button type="button" value="2" class='number btn key'>2</button>
<button type="button" value="1" class='number btn key'>1</button>
<button type="button" onClick="evaluateExp()" class="btn orange equal">=</button>
<button type="button" value="0" class='number zero btn key'>0</button>
<button type="button" value="." id='decimal' class='btn key'>.</button>
</div></code></pre>
</div>
</div>
</p>
<p>The source is extracted from my github repo - <a href="https://github.com/ngaisteve1/CalculatorJS" rel="nofollow noreferrer">https://github.com/ngaisteve1/CalculatorJS</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T06:01:11.063",
"Id": "221386",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Javascript Calculator which implement Stack"
} | 221386 |
<p>This chatbot will take the input from csv file and give the output to the user's question...here problem I am facing is when user asks any question, it gives tkenize output of user's text</p>
<pre><code>#Block 1
""" In this block we will import all the required libraries """
import pandas as pd # importing pandas to read the csv file
import nltk
import re
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from sklearn.feature_extraction.text import TfidfVectorizer
import random
import string
from sklearn.metrics.pairwise import cosine_similarity
#Block 2
""" This block will import csv file and save it to a variable """
db_main = pd.read_csv(r'D:\Python\QnA_using_NLTK\qa_database.csv', sep = ',',
names=["Question", "Answer", "user_response"])
# Block 3
""" Data Cleaning and preprocessing """
#nltk.download('stopwords')
corpus = [] # corpus list is created to append output of initial cleaning of data
wordnet=WordNetLemmatizer()
for i in range(0, len(db_main)):
review = re.sub('[^a-zA-Z0-9]', ' ', db_main['Question'][i])
review = review.lower()
review = review.split()
review = [wordnet.lemmatize(word) for word in review if not word in stopwords.words('english')]
review = ' '.join(review)
corpus.append(review)
#sent_tokens = nltk.sent_tokenize(db_main.Question)# converts to list of sentences
#word_tokens = nltk.word_tokenize(db_main.Question)# converts to list of words
#Block 4
""" This block will create tfidf vector and will create bag of words """
# Creating the Bag of Words model
cv = TfidfVectorizer()
X = cv.fit_transform(corpus).toarray()
#Block 5
""" This block will define 2 functions"""
lemmer = WordNetLemmatizer()
def LemTokens(tokens):
return [lemmer.lemmatize(token) for token in tokens]
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
def LemNormalize(text):
return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))
#Block 6
""" this block will listdown user inputs and probable outputs """
GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey",)
GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"]
</code></pre>
<p>#Block 7 </p>
<pre><code>"""Checking for greetings """
def greeting(sentence):
"""If user's input is a greeting, return a greeting response"""
for word in sentence.split():
if word.lower() in GREETING_INPUTS:
return random.choice(GREETING_RESPONSES)
# Block 8
""" Generating response """
def response(user_response):
robo_response=''
corpus.append(user_response)
TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
tfidf = TfidfVec.fit_transform(corpus)
vals = cosine_similarity(tfidf[-1], tfidf)
idx=vals.argsort()[0][-2]
flat = vals.flatten()
flat.sort()
req_tfidf = flat[-2]
if(req_tfidf==0):
robo_response=robo_response+"I am sorry! I don't understand you"
return robo_response
else:
robo_response = robo_response+corpus[idx]
return robo_response
flag=True
print("ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!")
while(flag==True):
user_response = input()
user_response=user_response.lower()
if(user_response!='bye'):
if(user_response=='thanks' or user_response=='thank you' ):
flag=False
print("ROBO: You are welcome..")
else:
if(greeting(user_response)!=None):
print("ROBO: "+greeting(user_response))
else:
print("ROBO: ",end="")
print(response(user_response))
corpus.remove(user_response)
else:
flag=False
print("ROBO: Bye! take care..")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:23:28.920",
"Id": "428079",
"Score": "1",
"body": "Please only provide working code, which your require to get reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T17:41:29.100",
"Id": "428191",
"Score": "0",
"body": "Welcome to Code Review! Unfortunately this post is off-topic for this site. Please read [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) - note that it states \"_If you are looking for feedback on a specific **working** piece of code...then you are in the right place!_\" Also, when posting your question, there should have been text on the side that read \"_Your question **must contain code that is already working correctly**_...\" When you have fixed the code, please [edit] your post to include the working code and it can be reviewed.\""
}
] | [
{
"body": "<p>okay... \njust have some advice for you\nFirst of all - read PEP8 (<a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a>)\nIt's a really important document for writing clear code in Python\nTry to make a clear structure of your code - check all imports and def's\nYou do not really need to import all module for using only one function of it - like pandas\nAlso, check all spaces and brackets in your code\nSo, you better should not use \"magic strings\" - try to use some variables for filename and columns in it, and then you will be able to move them away from code\nAnd use a construction like\n if <strong>name</strong> == \"<strong>main</strong>\": </p>\n\n<p>try to refactor your code and then someone will help you with review</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T17:42:24.873",
"Id": "428192",
"Score": "0",
"body": "Welcome to Code Review! Please note, questions involving code that's not working as intended, are off-topic on this site. If OP edits their post to address the problem and make their post on-topic, they make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T09:41:56.677",
"Id": "221400",
"ParentId": "221387",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T06:30:29.800",
"Id": "221387",
"Score": "-2",
"Tags": [
"python"
],
"Title": "Can anyone check this SImple chatbot application and suggest me the corrective measures?"
} | 221387 |
<p>I want as an exercise to create an e-commerce application from bottom up. My main goal here is to gain a lot of knowledge. I have experience in web development, but never have been there from the start of the project. The database schema was always already in place and also the server infrastructure (Azure) had been setup and configured. Those 2 things are my main goals for doing this exercise.</p>
<p>I've chosen to create quite a complex application (as far as I think) to make sure I encounter lots of questions so that I can learn a lot from this exercise.</p>
<p>My application would be some sort of e-commerce app where both users and companies can register. Companies have the possibility to add products. Products belong to a category and have attributes, discounts, quantities with specific prices. Users can then buy these products from the companies, but the companies can also buy from other companies.</p>
<p>Companies and Users (or company to company) would interact through a private messaging system (1 to 1) where users can request a quote and companies can answer with an offer. Companies also have the possibility to add employees who have the possibility to interact on behalf of the company. So every employee of the company should have access to all messages of the company.</p>
<p>When the party (user or company) buys a product(s) an order is created containing the specific details of the product(s) at that time. After payment the order is then shipped to the provided address of the party.</p>
<p>I would also like to get as many statistics as possible from the interactions occurring on the site. For example: total orders per company, the reaction time of a company to a message, the number of orders handled by employee x of company y...</p>
<p>I have tried to create my own db schema, but there are a lot of flaws in it I think. I have used existing questions to get to the schema I have now. I hope someone can help me in further designing my schema by giving me tips and hints or examples. </p>
<p>This is my db schema:</p>
<p><a href="https://i.stack.imgur.com/TYMuG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TYMuG.jpg" alt="enter image description here"></a></p>
<p>As requested I've only put a subset of code to be reviewed. This is the part with Parties (Users and Companies) and Messages.</p>
<p>This is the sql code:</p>
<pre><code>-- ************************************** [dbo].[PartyType]
CREATE TABLE [dbo].[PartyType]
(
[PartyTypeCode] nvarchar(5) NOT NULL ,
[Description] nvarchar(50) NOT NULL ,
[Name] nvarchar(50) NOT NULL ,
CONSTRAINT [PK_PartyType] PRIMARY KEY CLUSTERED ([PartyTypeCode] ASC)
);
GO
-- ************************************** [dbo].[Party]
CREATE TABLE [dbo].[Party]
(
[PartyId] uniqueidentifier NOT NULL ,
[PartyTypeCode] nvarchar(5) NOT NULL ,
CONSTRAINT [PK_Party] PRIMARY KEY CLUSTERED ([PartyId] ASC),
CONSTRAINT [PartyToPartyType_FK] FOREIGN KEY ([PartyTypeCode]) REFERENCES [dbo].[PartyType]([PartyTypeCode])
);
GO
CREATE NONCLUSTERED INDEX [fkIdx_30] ON [dbo].[Party]
(
[PartyTypeCode] ASC
)
GO
EXEC sp_addextendedproperty @name = N'MS_Description', @value = N'classifies', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Party', @level2type=N'CONSTRAINT', @level2name=N'PartyToPartyType_FK';
GO
-- ************************************** [dbo].[User]
CREATE TABLE [dbo].[User]
(
[UserId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_User] PRIMARY KEY NONCLUSTERED ([UserId] ASC),
CONSTRAINT [FK_18] FOREIGN KEY ([UserId]) REFERENCES [dbo].[Party]([PartyId])
);
GO
CREATE NONCLUSTERED INDEX [fkIdx_18] ON [dbo].[User]
(
[UserId] ASC
)
GO
-- ************************************** [dbo].[Company]
CREATE TABLE [dbo].[Company]
(
[CompanyId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_Company] PRIMARY KEY CLUSTERED ([CompanyId] ASC),
CONSTRAINT [FK_21] FOREIGN KEY ([CompanyId]) REFERENCES [dbo].[Party]([PartyId])
);
GO
CREATE NONCLUSTERED INDEX [FK] ON [dbo].[Company]
GO
CREATE NONCLUSTERED INDEX [fkIdx_21] ON [dbo].[Company]
(
[CompanyId] ASC
)
GO
-- ************************************** [dbo].[Contact]
CREATE TABLE [dbo].[Contact]
(
[ContactId] uniqueidentifier NOT NULL ,
[CompanyId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_Contact] PRIMARY KEY CLUSTERED ([ContactId] ASC),
CONSTRAINT [FK_229] FOREIGN KEY ([CompanyId]) REFERENCES [dbo].[Company]([CompanyId])
);
GO
CREATE NONCLUSTERED INDEX [fkIdx_229] ON [dbo].[Contact]
(
[CompanyId] ASC
)
GO
-- ************************************** [dbo].[Thread]
CREATE TABLE [dbo].[Thread]
(
[ThreadId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_Thread] PRIMARY KEY CLUSTERED ([ThreadId] ASC)
);
GO
-- ************************************** [dbo].[ThreadParticipator]
CREATE TABLE [dbo].[ThreadParticipator]
(
[ThreadId] uniqueidentifier NOT NULL ,
[PartyId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_ThreadParticipator] PRIMARY KEY CLUSTERED ([PartyId] ASC, [ThreadId] ASC),
CONSTRAINT [FK_100] FOREIGN KEY ([PartyId]) REFERENCES [dbo].[Party]([PartyId]),
CONSTRAINT [FK_97] FOREIGN KEY ([ThreadId]) REFERENCES [dbo].[Thread]([ThreadId])
);
GO
CREATE NONCLUSTERED INDEX [fkIdx_100] ON [dbo].[ThreadParticipator]
(
[PartyId] ASC
)
GO
CREATE NONCLUSTERED INDEX [fkIdx_97] ON [dbo].[ThreadParticipator]
(
[ThreadId] ASC
)
GO
-- ************************************** [dbo].[Message]
CREATE TABLE [dbo].[Message]
(
[MessageId] uniqueidentifier NOT NULL ,
[ThreadId] uniqueidentifier NOT NULL ,
[AuthorId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_Message] PRIMARY KEY CLUSTERED ([MessageId] ASC),
CONSTRAINT [FK_211] FOREIGN KEY ([ThreadId]) REFERENCES [dbo].[Thread]([ThreadId]),
CONSTRAINT [FK_214] FOREIGN KEY ([AuthorId]) REFERENCES [dbo].[Party]([PartyId])
);
GO
CREATE NONCLUSTERED INDEX [fkIdx_211] ON [dbo].[Message]
(
[ThreadId] ASC
)
GO
CREATE NONCLUSTERED INDEX [fkIdx_214] ON [dbo].[Message]
(
[AuthorId] ASC
)
GO
-- ************************************** [dbo].[MessageReadState]
CREATE TABLE [dbo].[MessageReadState]
(
[MessageId] uniqueidentifier NOT NULL ,
[PartyId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_MessageReadState] PRIMARY KEY CLUSTERED ([MessageId] ASC, [PartyId] ASC),
CONSTRAINT [FK_88] FOREIGN KEY ([MessageId]) REFERENCES [dbo].[Message]([MessageId]),
CONSTRAINT [FK_91] FOREIGN KEY ([PartyId]) REFERENCES [dbo].[Party]([PartyId])
);
GO
CREATE NONCLUSTERED INDEX [fkIdx_88] ON [dbo].[MessageReadState]
(
[MessageId] ASC
)
GO
CREATE NONCLUSTERED INDEX [fkIdx_91] ON [dbo].[MessageReadState]
(
[PartyId] ASC
)
GO
-- ************************************** [dbo].[Address]
CREATE TABLE [dbo].[Address]
(
[AddressId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_Address] PRIMARY KEY CLUSTERED ([AddressId] ASC)
);
GO
-- ************************************** [dbo].[PartyAddress]
CREATE TABLE [dbo].[PartyAddress]
(
[PartyId] uniqueidentifier NOT NULL ,
[AddressId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_PartyAddress] PRIMARY KEY CLUSTERED ([AddressId] ASC, [PartyId] ASC),
CONSTRAINT [FK_55] FOREIGN KEY ([PartyId]) REFERENCES [dbo].[Party]([PartyId]),
CONSTRAINT [FK_58] FOREIGN KEY ([AddressId]) REFERENCES [dbo].[Address]([AddressId])
);
GO
CREATE NONCLUSTERED INDEX [fkIdx_55] ON [dbo].[PartyAddress]
(
[PartyId] ASC
)
GO
CREATE NONCLUSTERED INDEX [fkIdx_58] ON [dbo].[PartyAddress]
(
[AddressId] ASC
)
GO
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:43:48.060",
"Id": "428086",
"Score": "0",
"body": "That is quite the model to review. Perhaps you could ask for a subset of it to get reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:57:43.093",
"Id": "428088",
"Score": "0",
"body": "@dfhwze I've modified the sql code. I've left the entire schema there, but I've only left the sql code containing users, companies and messages. Is that better?\nDo I ask in another question about the rest? Or do I modify my question here after I got an answer on my first subset?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:59:17.330",
"Id": "428090",
"Score": "2",
"body": "I think it's a good idea to wait for the review of this question before asking a followup question :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T10:14:13.490",
"Id": "429187",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T10:15:16.420",
"Id": "429188",
"Score": "0",
"body": "A follow-up question is posted as a separate (new) question, linking back to the old (this) question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T10:38:30.687",
"Id": "429190",
"Score": "0",
"body": "@Mast Are my questions relevant for this site? Or is more for the dba site then? My question was closed there as too broad.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T10:50:32.780",
"Id": "429191",
"Score": "0",
"body": "Your code is a bit on the light side. It's mainly creating tables and 1 stored procedure. If your questions are about functions your database already does, it could be ok. If it's about functions you're not sure your database does, you should find out before posting them. When in doubt, there's the [help/on-topic]. Or find us in [chat](https://chat.stackexchange.com/rooms/8595/the-2nd-monitor)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T10:52:56.330",
"Id": "429193",
"Score": "0",
"body": "But honestly, we mainly deal with code. A database can be reviewed as part of the product, but we don't do pure database reviews."
}
] | [
{
"body": "<p>You really need to focus on the various \"who\" s in your model. </p>\n\n<ul>\n<li>Company </li>\n<li>Contact </li>\n<li>User </li>\n<li>Buyer</li>\n<li>Seller</li>\n<li>Party</li>\n<li>Participator</li>\n</ul>\n\n<p>Try to separate the who from the role. The role is the relationship between the who and the event.</p>\n\n<p>As a modelling example:</p>\n\n<ul>\n<li>a user is the entity that performs some action.</li>\n<li>a user must belong to one organization (or many, see broker below)</li>\n<li>An organization contains 0 to many users and can be residential or commercial. (An organization without\nusers can't do anything)</li>\n<li>A customer is an organization that buys product (transacted by the user\nwithin the organization).</li>\n<li>A vendor is an organization that sells product (transacted by a user\nwithin that organization).</li>\n<li>A user that buys and sells products is still a single user, belonging\nto a single organization.</li>\n<li>A broker that buys or sells on behalf of multiple organizations is\n(<em>design decision</em>) [a unique user for each organization it represents \n| associated to each organization it represents but is still a single\nuser]</li>\n</ul>\n\n<p>That first bullet is very important. Every action should be associated to a real physical entity. If there is ever a question of who bought/sold something, you should be able to tie it back to the real entity that performed the action. Eventually fraud will occur and you don't want to be the system that dead-ends the investigation because you only associated the order to a generic company record. Make sure you build accountability into your system, even if the company may circumvent it by using shared credentials, etc.</p>\n\n<p>I'm not a big fan of uniqueidentifiers (16 bytes). I'd switch to int (4 bytes) instead. If you expect a very high volume, use bigint (8 bytes) . This also helps provide a human consumable (order, product, etc) id. In my opinion, GUIDs just take up more space and run a bit slower without providing a tangible benefit. Even Amazon uses big integers for their order numbers.</p>\n\n<p>Non-clustered indexes are for performance tuning and are not considered part of the data model. In your question, they just add clutter.</p>\n\n<p>One of the best ways to refine your model is to ask questions of it before you write any code. Go back to your requirements and see if you can generate some questions your model is intended to fulfill.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T06:41:48.293",
"Id": "428982",
"Score": "0",
"body": "Wes, in your modelling example you mention that a company has 0 or more users. This is in fact not correct. I rechecked my schema and saw that I had an error. There should be a relationship between company and user, where a company always has 1 owner and that owner is a user.\nI think that by adding that relationship the accountability issue is somehow solved?\nAlso, it's not required for a user to belong to an organisation. A user can be a single entity being simply a customer.\nA company always has a user as owner and can act as customer (buyer) or as company (seller)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T10:51:36.053",
"Id": "429192",
"Score": "1",
"body": "I have accepted this as answer as it pointed me out to some issues in my db design and helped me to raise some other questions which I have asked in [this question](https://codereview.stackexchange.com/questions/221851/parties-and-messages-in-sql-e-commerce-db-design).\n\nWith regards to the identifiers, I'll keep that in mind. Thx!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T13:54:34.980",
"Id": "429216",
"Score": "0",
"body": "As a seller, a company still requires a user to list the product for sale and may not be the owner. There is no reason to eliminate that relationship. Its more work to allow transactions with a user (buyer) and a company (seller). Better to keep it at the user level, and have the company relationship be through the users involved in the transaction. It also reflects reality better. How will you handle the company business being handled by an employee other than the owner when the company grows or the owner is seriously ill?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T07:27:24.577",
"Id": "429327",
"Score": "0",
"body": "So the only reason I have company table is to keep track of the products it has? Messaging and Order handling should happen via the users linked to the company."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T18:27:30.530",
"Id": "221735",
"ParentId": "221391",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221735",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T07:33:07.177",
"Id": "221391",
"Score": "4",
"Tags": [
"sql",
"sql-server",
"database",
"t-sql"
],
"Title": "SQL e-commerce database design"
} | 221391 |
<p>I would like to ask a code review for the class below.</p>
<p>I am asking this because VS showed a quite low <em>Maintainability Index</em> of 54 and I am wondering if it is <strong>good code</strong>.</p>
<p>I know I could have extracted some parts of the long method to smaller private methods (or local methods but that would not help a lot I think), but I think <strong>in case of extension method classes</strong> it is better to stick with the one method - one extension concept.</p>
<p>What do you think? (Any feedback is highly appreciated!)</p>
<pre><code>using System;
namespace GridPathFinder.Utilities
{
public static class StringExtensions
{
/// <summary>
/// Converts the string to a 2 dimensional char array (<see cref="char[,]"/>),
/// finding new lines based on the <see cref="Environment.NewLine"/> value.
/// </summary>
/// <param name="input">The input string to convert.</param>
/// <returns>
/// A <see cref="char[,]"/> where dimension 0 indicates rows, dimension 1 indicates columns.
/// </returns>
public static char[,] To2DCharArray(
this string input,
StringSplitOptions stringSplitOptions = StringSplitOptions.RemoveEmptyEntries)
{
return To2DCharArray(input, new string[] { Environment.NewLine }, stringSplitOptions);
}
/// <summary>
/// Converts the string to a 2 dimensional char array (<see cref="char[,]"/>),
/// finding new lines based on the <paramref name="separators"/> given.
/// </summary>
/// <param name="input">The input string to convert.</param>
/// <param name="separators">Array of separator strings</param>
/// <returns>
/// A <see cref="char[,]"/> where dimension 0 indicates rows, dimension 1 indicates columns.
/// </returns>
public static char[,] To2DCharArray(
this string input,
string[] separators,
StringSplitOptions stringSplitOptions = StringSplitOptions.RemoveEmptyEntries)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (input == string.Empty)
throw new ArgumentException($"{nameof(input)} cannot be empty.");
if (separators == null)
throw new ArgumentNullException(nameof(separators));
if (separators.Length == 0)
throw new ArgumentException($"{nameof(separators)} array has to contain at least one separator string.");
string[] inputLines = input.Split(separators, stringSplitOptions);
int widthOfFirstLine = inputLines[0].Length;
char[,] array = new char[inputLines.Length, widthOfFirstLine];
for (int row = 0; row < inputLines.Length; row++)
{
if (inputLines[row].Length != widthOfFirstLine)
{
throw new ArgumentException($"{nameof(input)}'s all rows has to be equal in width," +
$"but the width of row with index {row} differs from the width of first row.");
}
for (int col = 0; col < inputLines[row].Length; col++)
{
array[row, col] = inputLines[row][col];
}
}
return array;
}
}
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:24:25.913",
"Id": "428099",
"Score": "0",
"body": "Does it need to be a multiimensional array [,] or can it also be a jagged array [][]?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:26:08.343",
"Id": "428101",
"Score": "0",
"body": "@dfhwze Good finding, in my application it is more convenient to work with a 2D array instead. (However jagged arrays offer a tiny performance improvement over multidimensional arrays)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:29:29.480",
"Id": "428103",
"Score": "0",
"body": "Perhaps you could use the flow described at https://stackoverflow.com/questions/26291609/converting-jagged-array-to-2d-array-c-sharp to convert 'inputLines' to 'array'."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:10:29.593",
"Id": "221395",
"Score": "1",
"Tags": [
"c#",
"strings",
".net",
"extension-methods"
],
"Title": "string.To2DCharArray extension method implementation"
} | 221395 |
<p>I currently use the following code to asynchronously <strong>create a cimsession</strong> to a remote host, <strong>query the remote host</strong>, <strong>return multiple values</strong> and finally <strong>updated some textboxes</strong> on my WPF window. Just wanting to know if anyone can see any glaring issues (I'm new to all things async and c# :) ) or a better was of doing it:</p>
<pre><code>using System.Threading;
using System.Threading.Tasks;
using Microsoft.Management.Infrastructure;
//creating cimsession to remote host
CimSession session = await Task.Run(() =>
{
return CimSession.Create(computerHostName);
});
//getting username, bootupstate, manufacturer and model
var GI1 = await Task.Run(() =>
{
var results = new List<string>();
IEnumerable<CimInstance> queryResults = session.QueryInstances(nameSpace, WQL, "SELECT Username, BootUpState, Manufacturer, Model FROM Win32_ComputerSystem");
foreach(CimInstance i in queryResults)
{
results.Add(i.CimInstanceProperties["Username"].Value.ToString());
results.Add(i.CimInstanceProperties["BootUpState"].Value.ToString());
results.Add(i.CimInstanceProperties["Manufacturer"].Value.ToString());
results.Add(i.CimInstanceProperties["Model"].Value.ToString());
}
//returning all the variables
return results;
});
//adding username, bootupstate, manufacturer and model to their textboxes
GIUS.Text = GI1[0];
GIBS.Text = GI1[1];
GIMF.Text = GI1[2];
GIMD.Text = GI1[3];
</code></pre>
<p>Any suggestions or help is appreciated :) </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:34:42.470",
"Id": "428104",
"Score": "0",
"body": "Which library comes CimSession from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:37:58.230",
"Id": "428105",
"Score": "0",
"body": "@dfhwze Apologies, I've updated the question :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T12:24:07.130",
"Id": "428132",
"Score": "0",
"body": "This is a snippet which is missing important context. We can't give you a proper review unless you provide the full methods (or ideally the full class) and whatever XAML is necessary to show how they're called. (Eg. are we dealing with async event handlers?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T12:31:20.920",
"Id": "428134",
"Score": "0",
"body": "Hi @PeterTaylor, I'm not really able to share any more code. I just wanted some assistance with the particular snippet. I really appreciate everyone's help and have marked dfhwze's response as the answer as it was the most helpful"
}
] | [
{
"body": "<h2>Conventions</h2>\n<ul>\n<li>Use meaningful and camel-cased names <code>var GI1</code> <code>GIUS</code> ..</li>\n<li>Use <code>var</code> when the instance type is the same as the declaring type <code>CimSession session =</code></li>\n</ul>\n<h2>Design</h2>\n<p>I suggest to create a class to store the info you require from the cim interface.</p>\n<pre><code> class CimInfo\n {\n public CimInfo(CimInstance cim)\n {\n UserName = GetProperty(cim, "UserName");\n BootUpState = GetProperty(cim, "BootUpState");\n Manufacturer = GetProperty(cim, "Manufacturer");\n Model = GetProperty(cim, "Model");\n }\n\n private static string GetProperty(CimInstance cim, string name)\n {\n if (cim == null) throw new ArgumentNullException(nameof(cim));\n return cim.CimInstanceProperties[name].Value.ToString();\n }\n\n public string UserName { get; }\n public string BootUpState { get; }\n public string Manufacturer { get; }\n public string Model { get; }\n }\n</code></pre>\n<p>The async operations can be merged and rewritten using the new class. Since you only have need of one cim instance, we could also avoid looping all queried results.</p>\n<p>Notes:</p>\n<ul>\n<li>Perhaps there is an alternative available for <code>QueryInstances</code> that only returns the first result.</li>\n<li>If <code>CimSession</code> implements <code>IDisposable</code>, use a <code>using</code> block for it.</li>\n</ul>\n<p>snippet</p>\n<pre><code>var cimInfo = await Task.Run(() =>\n {\n var session = CimSession.Create(computerHostName);\n var queryResults = session.QueryInstances(nameSpace, WQL, \n "SELECT Username, BootUpState, Manufacturer, Model FROM Win32_ComputerSystem");\n return new CimInfo(queryResults.FirstOrDefault());\n });\n</code></pre>\n<p>And the output could be</p>\n<pre><code>TextBoxUserName.Text = cimInfo.UserName;\nTextBoxBootUpState.Text = cimInfo.BootUpState;\nTextBoxManufacturer.Text = cimInfo.Manufacturer;\nTextBoxModel.Text = cimInfo.Model;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T09:25:22.987",
"Id": "428113",
"Score": "0",
"body": "Thank you for your quick reply :) I actually have multiple tasks that get information from WMI and other sources so I think creating a class for each one would just create unnecessary code. I like the idea though :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T09:05:22.663",
"Id": "221398",
"ParentId": "221396",
"Score": "2"
}
},
{
"body": "<blockquote>\n<pre><code>//creating cimsession to remote host\nCimSession session = await Task.Run(() =>\n{\n return CimSession.Create(computerHostName);\n});\n</code></pre>\n</blockquote>\n\n<p><code>Task.Run</code> is a red flag. This should be</p>\n\n<pre><code>CimSession session = await CimSession.CreateAsync(computerHostName);\n</code></pre>\n\n<p>Similarly for every method you call on <code>session</code> which has a <code>...Async</code> version, you should use the <code>...Async</code> version.</p>\n\n<hr>\n\n<p>It seems that you're calling this from a GUI thread. That means you need to be careful about where your continuations are executed. I would suggest pulling the async calls out into a method and using <code>.ConfigureAwait(false)</code> on all of them, and then calling that method from the GUI thread with <code>ContinueWith(...)</code> to update the GUI, but since you refuse to provide more context I can't be more specific.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T14:13:08.373",
"Id": "428265",
"Score": "0",
"body": "I'm not sure I understand that last part: using `ConfigureAwait(false)` in the pulled-out method makes sense, but why use `ContinueWith` (which will need to be directed to the UI thread) rather than `await` for the GUI update after calling such a method? Has something horrifying about `async` been discovered that I've not yet come across?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T14:42:13.633",
"Id": "428266",
"Score": "0",
"body": "@VisualMelon, the GUI update has to be directed to the UI thread somehow, and exceptions also want to be reflected in the UI from the UI thread."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T15:42:01.403",
"Id": "221426",
"ParentId": "221396",
"Score": "3"
}
},
{
"body": "<p>Please note that you have a memory leak. You have to dispose of the CimSession and the CimInstances that are created. You can confirm this with something like dotMemory as I have tested and confirmed. You either need to use a using statement or dispose. You can dispose of the CimInstances after you process them in the foreach loop. Also Microsoft.Management.Infrastructure already implements asynchronous methods they just don't conform to the normal TPL and use the observer pattern which makes it not as obvious on how to use(As I have discovered trying to migrate a library from System.Management). If you are doing this for multiple remote computers using Task.Run is going to use the thread pool for each task and block while it performs that synchronous code which remote CimSessions can take awhile and could lead to thread pool exhaustion. Its hard to see with example how you are actually using code and if that could be an issue. If using Reactive extensions is an option you can use it to make it easier like so.</p>\n<pre><code> var tuple = await CimSession\n .CreateAsync(null)\n .SelectMany(_ => Observable.Using(() => _, session => session.QueryInstancesAsync(@"root\\cimv2", "WQL", "SELECT Username, BootUpState, Manufacturer, Model FROM Win32_ComputerSystem")), (session, cimInstance) =>\n {\n using (cimInstance)\n {\n return Tuple\n .Create(cimInstance.CimInstanceProperties["Username"]\n ?.Value?.ToString() ?? string.Empty\n , cimInstance.CimInstanceProperties["BootUpState"]\n ?.Value?.ToString() ?? string.Empty\n , cimInstance.CimInstanceProperties["Manufacturer"]\n ?.Value?.ToString() ?? string.Empty\n , cimInstance.CimInstanceProperties["Model"]\n ?.Value?.ToString() ?? string.Empty);\n }\n })\n .FirstAsync();\n</code></pre>\n<p>You also could have an exception if the value is null and then call ToString() as you can see below I account for that as well. I am assuming that wql query will only ever return one result otherwise you could remove the .FirstAsync() and put .ToList(). It is returning a tuple value where you can just access every item in tuple but as @dfhwze said probably better to use a class to store your values. Also since using wpf probably better to implement the MVVM pattern and use a view model and bind to those values from the class. If doing that ensure to implement the INotifyPropertyChanged interface on the class to ensure no wpf binding leaks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T20:25:11.327",
"Id": "252617",
"ParentId": "221396",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221398",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T08:31:04.063",
"Id": "221396",
"Score": "0",
"Tags": [
"c#",
"asynchronous"
],
"Title": "C# Tasks for Asynchronous Operations"
} | 221396 |
<p><strong>The task</strong></p>
<p>is taken from <a href="https://leetcode.com/problems/number-of-islands/" rel="nofollow noreferrer">leetcode</a></p>
<blockquote>
<p>Given a 2d grid map of '1's (land) and '0's (water), count the number
of islands. An island is surrounded by water and is formed by
connecting adjacent lands horizontally or vertically. You may assume
all four edges of the grid are all surrounded by water.</p>
<p><strong>Example 1:</strong></p>
<p>Input:</p>
<pre><code>11110
11010
11000
00000
</code></pre>
<p>Output: 1</p>
<p><strong>Example 2:</strong></p>
<p>Input:</p>
<pre><code>11000
11000
00100
00011
</code></pre>
<p>Output: 3</p>
</blockquote>
<p><strong>My solution</strong></p>
<pre><code>/**
* @param {character[][]} grid
* @return {number}
*/
function numIslands(grid) {
if (grid === null || grid === void 0 || !grid.length || !grid[0].length) { return 0; }
const NR = grid.length;
const NC = grid[0].length;
const check = (r,c) => {
if (r < 0 || c < 0 || r >= NR || c >= NC || grid[r][c] === "0" ) { return; }
grid[r][c] = "0";
check(r + 1, c);
check(r - 1, c);
check(r, c + 1);
check(r, c - 1);
}
let res = 0;
for (let r = 0; r < NR; r++) {
for (let c = 0; c < NC; c++) {
if (grid[r][c] === "1") {
res++;
check(r,c);
}
}
}
return res;
};
</code></pre>
| [] | [
{
"body": "<p>I think your algorithm is good. Not much can be done there.</p>\n\n<p>Readability is the last thing people care about when solving puzzles like this, but here on Core Review we do care. So, here's my answer, and it may not be what you expect. </p>\n\n<p>Just remember that readability is good for you. It makes it easier to understand and debug your own code. In the end it will safe you time, especially when the puzzles get a lot harder.</p>\n\n<p>First of all; Variable names need to tell us what they contain, so <code>rowNo</code> instead of <code>r</code>, <code>colNo</code> instead of <code>c</code>. When you've got 10 one-letter variables you <em>will</em> loose track of their meaning.</p>\n\n<p>Too many <code>||</code> conditions in an <code>if ()</code> don't improve readability either. Why not use functions like this:</p>\n\n<pre><code>function insideGrid(rowNo, colNo) {\n let insideRow = rowNo >= 0 && rowNo < gridWidth,\n insideCol = colNo >= 0 && colNo < gridHeight;\n return insideRow && insideCol;\n}\n\nfunction onLand(rowNo, colNo) {\n return insideGrid(rowNo, colNo) && grid[rowNo][colNo];\n}\n</code></pre>\n\n<p>Then you can do:</p>\n\n<pre><code>function eraseIsland(rowNo, colNo) {\n if (onLand(rowNo, colNo)) {\n eraseIsland(rowNo - 1, colNo);\n eraseIsland(rowNo + 1, colNo);\n eraseIsland(rowNo, colNo + 1);\n eraseIsland(rowNo, colNo - 1);\n }\n}\n</code></pre>\n\n<p>There is <a href=\"https://www.freecodecamp.org/news/constant-confusion-why-i-still-use-javascript-function-statements-984ece0b72fd/\" rel=\"nofollow noreferrer\">no good reason to use arrow functions</a>, but you can use them for correctly named tiny functions (this is a bit controversial, I know).</p>\n\n<p>An alternative way to walk over the grid is:</p>\n\n<pre><code>let islandCount = 0;\ngrid.forEach((row, rowNo) => {\n row.foreach((island, colNo) => {\n if (island) {\n islandCount++;\n eraseIsland(rowNo, colNo);\n }\n });\n});\n</code></pre>\n\n<p>Ah, see, I did use arrow functions afteral!</p>\n\n<p>Don't think that shorter code is always better code, it isn't. You could minify your code to one line, like this:</p>\n\n<pre><code>function numIslands(a){if(null===a||void 0===a||!a.length||!a[0].length)return 0;const b=a.length,d=a[0].length,e=(f,g)=>{0>f||0>g||f>=b||g>=d||\"0\"===a[f][g]||(a[f][g]=\"0\",e(f+1,g),e(f-1,g),e(f,g+1),e(f,g-1))};let f=0;for(let g=0;g<b;g++)for(let b=0;b<d;b++)\"1\"===a[g][b]&&(f++,e(g,b));return f}\n</code></pre>\n\n<p>But is that better? I don't think so. As a programmer you're not only writing code for the computer to understand, but also for normal human beings, including yourself. </p>\n\n<p><strong>In summary:</strong> Your solution is fine, but the coding could be improved.</p>\n\n<p><em>(all code published here is untested!)</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T15:58:07.560",
"Id": "428173",
"Score": "0",
"body": "+1 for mentioning \"readability\" and picking up on details. Lately I have been pushing code out for the sake of pushing out code. But some of them are buggy or - as you mentioned - not very readable. However I don't really agree on your statement `There is no good reason to use arrow functions`. I think if you use them as an anonymous function or as a \"class\" function, then they are absolutely fine."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T13:57:24.880",
"Id": "221416",
"ParentId": "221403",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221416",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T10:53:59.500",
"Id": "221403",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"ecmascript-6"
],
"Title": "Number of Islands"
} | 221403 |
<p>I have implemented an AVL tree using shared_ptr. I know that there is an overhead regarding using shared_ptr and instead a unique_ptr could be used. But the thing is that my node contains also a parent pointer, it turns out so each node can be pointed by two/three other nodes at the same time, one pointer from its parent and the second/third from his child nodes and I can't replace shared_ptr with unique_ptr. Any thoughts about this?
The code is shown below:</p>
<pre><code>#include <algorithm>
#include <memory>
#include <vector>
class Node {
public:
int data;
std::shared_ptr<Node> left;
std::shared_ptr<Node> right;
std::shared_ptr<Node> parent;
public:
Node() : data(0) {}
explicit Node(int d) : data(d) {}
};
class Avl {
private:
size_t current_size;
std::shared_ptr<Node> root;
private:
int height(std::shared_ptr<Node> node);
std::shared_ptr<Node> get_min(std::shared_ptr<Node> node);
std::shared_ptr<Node> inorder_successor(std::shared_ptr<Node> node);
void add_helper(std::shared_ptr<Node> parent, std::shared_ptr<Node> node);
std::shared_ptr<Node> find_helper(std::shared_ptr<Node> parent_node, std::shared_ptr<Node> node);
std::shared_ptr<Node> find_helper(std::shared_ptr<Node> parent_node, int data);
void destroy_helper(std::shared_ptr<Node>& node);
void transplant(std::shared_ptr<Node> node, std::shared_ptr<Node> second_node);
std::shared_ptr<Node> left_rotate(std::shared_ptr<Node> node);
std::shared_ptr<Node> right_rotate(std::shared_ptr<Node> node);
std::shared_ptr<Node> left_right_rotate(std::shared_ptr<Node> node);
std::shared_ptr<Node> right_left_rotate(std::shared_ptr<Node> node);
void check_balance(std::shared_ptr<Node> node);
std::shared_ptr<Node> rebalance(std::shared_ptr<Node> node);
void traverse_inorder_helper(std::shared_ptr<Node> node, std::vector<int>& out);
void traverse_preorder_helper(std::shared_ptr<Node> node, std::vector<int>& out);
void traverse_postorder_helper(std::shared_ptr<Node> node, std::vector<int>& out);
public:
Avl() : current_size(0) {}
void add(std::shared_ptr<Node> node);
void add(int data);
std::shared_ptr<Node> find(std::shared_ptr<Node> node);
std::shared_ptr<Node> find(int data);
void remove(std::shared_ptr<Node> node);
void remove(int data);
void destroy();
void traverse_inorder(std::vector<int>& out);
void traverse_preorder(std::vector<int>& out);
void traverse_postorder(std::vector<int>& out);
inline size_t size() const {
return current_size;
}
inline bool empty() const {
return !(static_cast<bool>(current_size));
}
};
int Avl::height(std::shared_ptr<Node> node) {
if(!node) {
return 0;
}
return std::max(height(node->left), height(node->right)) + 1;
}
std::shared_ptr<Node> Avl::get_min(std::shared_ptr<Node> node) {
std::shared_ptr<Node> temp = node->right;
while(temp->left) {
temp = temp->left;
}
return temp;
}
void Avl::remove(std::shared_ptr<Node> node) {
if(!node->left) {
transplant(node, node->right);
check_balance(node);
} else if(!node->right) {
transplant(node, node->left);
check_balance(node);
} else {
std::shared_ptr<Node> successor = inorder_successor(node);
if(successor->parent != node) {
transplant(successor, successor->right);
check_balance(successor->parent);
successor->right = node->right;
if(successor->right) {
successor->right->parent = successor;
}
}
transplant(node, successor);
successor->left = node->left;
if(successor->left) {
successor->left->parent = successor;
}
successor->parent = node->parent;
check_balance(successor);
}
}
void Avl::remove(int data) {
std::shared_ptr<Node> node = find(data);
std::shared_ptr<Node> successor = 0;
if(!node) {
return;
}
if(!node->left) {
transplant(node, node->right);
check_balance(node);
} else if(!node->right) {
transplant(node, node->left);
check_balance(node);
} else {
successor = inorder_successor(node);
if(successor->parent != node) {
transplant(successor, successor->right);
check_balance(successor->parent);
successor->right = node->right;
if(successor->right) {
successor->right->parent = successor;
}
}
transplant(node, successor);
successor->left = node->left;
if(successor->left) {
successor->left->parent = successor;
}
successor->parent = node->parent;
check_balance(successor);
}
}
std::shared_ptr<Node> Avl::find_helper(std::shared_ptr<Node> parent_node, std::shared_ptr<Node> node) {
if(!parent_node || parent_node->data == node->data) {
return parent_node;
}
if(node->data > parent_node->data) {
return find_helper(parent_node->right, node);
} else if(node->data < parent_node->data) {
return find_helper(parent_node->left, node);
}
return 0;
}
std::shared_ptr<Node> Avl::find_helper(std::shared_ptr<Node> parent_node, int data) {
if(!parent_node || data == parent_node->data) {
return parent_node;
}
if(data > parent_node->data) {
return find_helper(parent_node->right, data);
} else if(data < parent_node->data) {
return find_helper(parent_node->left, data);
}
return 0;
}
std::shared_ptr<Node> Avl::find(std::shared_ptr<Node> node) {
std::shared_ptr<Node> temp = root;
return find_helper(temp, node);
}
std::shared_ptr<Node> Avl::find(int data) {
std::shared_ptr<Node> temp = root;
return find_helper(temp, data);
}
void Avl::destroy() {
root.reset();
}
void Avl::destroy_helper(std::shared_ptr<Node>& node) {
}
void Avl::transplant(std::shared_ptr<Node> node, std::shared_ptr<Node> second_node)
{
if(!node->parent) {
root = second_node;
}
if(node->parent && node->parent->right == node) {
node->parent->right = second_node;
} else if(node->parent && node->parent->left == node) {
node->parent->left = second_node;
}
if(node->parent && second_node) {
second_node->parent = node->parent;
}
}
std::shared_ptr<Node> Avl::inorder_successor(std::shared_ptr<Node> node) {
std::shared_ptr<Node> temp = node;
if(temp->right) {
return get_min(temp);
}
std::shared_ptr<Node> parent = temp->parent;
while(parent && temp == parent->right) {
temp = parent;
parent = parent->parent;
}
return parent;
}
std::shared_ptr<Node> Avl::left_rotate(std::shared_ptr<Node> node) {
std::shared_ptr<Node> temp = node->right;
node->right = temp->left;
temp->left = node;
if(node->right) {
node->right->parent = node;
}
temp->parent = node->parent;
if(node->parent) {
if(node == node->parent->left) {
node->parent->left = temp;
} else if(node == node->parent->right) {
node->parent->right = temp;
}
}
node->parent = temp;
return temp;
}
std::shared_ptr<Node> Avl::right_rotate(std::shared_ptr<Node> node) {
std::shared_ptr<Node> temp = node->left;
node->left = temp->right;
temp->right = node;
if(node->left) {
node->left->parent = node;
}
temp->parent = node->parent;
if(node->parent) {
if(node == node->parent->left) {
node->parent->left = temp;
} else if(node == node->parent->right) {
node->parent->right = temp;
}
}
node->parent = temp;
return temp;
}
std::shared_ptr<Node> Avl::left_right_rotate(std::shared_ptr<Node> node) {
node->left = left_rotate(node->left);
return right_rotate(node);
}
std::shared_ptr<Node> Avl::right_left_rotate(std::shared_ptr<Node> node) {
node->right = right_rotate(node->right);
return left_rotate(node);
}
void Avl::add_helper(std::shared_ptr<Node> parent, std::shared_ptr<Node> node) {
if(node->data > parent->data) {
if(!parent->right) {
parent->right = node;
node->parent = parent;
++current_size;
} else {
add_helper(parent->right, node);
}
} else if(node->data < parent->data) {
if(!parent->left) {
parent->left = node;
node->parent = parent;
++current_size;
} else {
add_helper(parent->left, node);
}
} else {
return;
}
check_balance(node);
return;
}
void Avl::add(std::shared_ptr<Node> node) {
if(!root) {
root = node;
return;
}
add_helper(root, node);
}
void Avl::add(int data) {
if(!root) {
root = std::make_shared<Node>(data);
return;
}
std::shared_ptr<Node> node = std::make_shared<Node>(data);
add_helper(root, node);
}
void Avl::check_balance(std::shared_ptr<Node> node) {
if(height(node->left) - height(node->right) > 1 || height(node->left) - height(node->right) < -1) {
node = rebalance(node);
}
if(!node->parent) {
return;
}
check_balance(node->parent);
}
//void Avl::rebalance(std::shared_ptr<Node> node) {
std::shared_ptr<Node> Avl::rebalance(std::shared_ptr<Node> node) {
if(height(node->left) - height(node->right) > 1) {
if(height(node->left->left) >= height(node->left->right)) {
node = right_rotate(node);
} else {
node = left_right_rotate(node);
}
}
if(height(node->left) - height(node->right) < -1) {
if(height(node->right->right) >= height(node->right->left)) {
node = left_rotate(node);
} else {
node = right_left_rotate(node);
}
}
if(!node->parent) {
root = node;
}
return node;
}
void Avl::traverse_inorder(std::vector<int>& out) {
std::shared_ptr<Node> node = root;
traverse_inorder_helper(node, out);
}
void Avl::traverse_preorder(std::vector<int>& out) {
std::shared_ptr<Node> node = root;
traverse_preorder_helper(node, out);
}
void Avl::traverse_postorder(std::vector<int>& out) {
std::shared_ptr<Node> node = root;
traverse_postorder_helper(node, out);
}
void Avl::traverse_inorder_helper(std::shared_ptr<Node> node, std::vector<int>& out) {
if(!node) {
return;
}
traverse_inorder_helper(node->left, out);
out.push_back(node->data);
traverse_inorder_helper(node->right, out);
}
void Avl::traverse_preorder_helper(std::shared_ptr<Node> node, std::vector<int>& out) {
if(!node) {
return;
}
out.push_back(node->data);
traverse_preorder_helper(node->left, out);
traverse_preorder_helper(node->right, out);
}
void Avl::traverse_postorder_helper(std::shared_ptr<Node> node, std::vector<int>& out) {
if(!node) {
return;
}
traverse_postorder_helper(node->left, out);
traverse_postorder_helper(node->right, out);
out.push_back(node->data);
}
</code></pre>
| [] | [
{
"body": "<h1><a href=\"https://coliru.stacked-crooked.com/a/73214a1a89ce7f41\" rel=\"nofollow noreferrer\">Memory Leak</a></h1>\n<p><code>std::shared_ptr</code>s free their target when the last reference to that target disappears. Since you have <code>Node</code>s that point at each other (<code>node->right->parent == node</code>) that never happens. <code>std::weak_ptr</code> is made to solve this problem.</p>\n<h2>Ownership vs Pointing</h2>\n<p>You are not forced to use <code>std::shared_ptr</code> just because you want to point at it from multiple spots. <code>std::shared_ptr</code> means "I co-own that data and as long as I live that data will live". Looking at <code>Node</code> that really isn't what you meant. One way to model this is that <code>Node</code>s own their children, but the children only point to the parent, they don't own their parent. That would leave you with</p>\n<pre><code>std::unique_ptr<Node> left;\nstd::unique_ptr<Node> right;\nNode* parent;\n</code></pre>\n<p>Alternatively you can look into <code>std::weak_ptr</code> which is made to avoid cyclic references.</p>\n<h1>Don't Expose Your Privates</h1>\n<p><code>Node</code> is <code>private</code> to <code>Avl</code>. Outside users should not be concerned with how to wire up <code>Node</code>s. Right now I can do <code>avl.find(x)->data = x + 1; //update value</code> which breaks your tree. Since changing the value breaks the tree you cannot give the user a non-<code>const</code> reference to the data. You could make the <code>Node</code> members <code>private</code>, add <code>Avl</code> as a <code>friend</code> and add a <code>Avl::set_value(const std::shared_ptr<Node> &)</code> function that handles the rebalancing correctly. Maybe add a <code>public</code> getter for <code>data</code>, but definitely no constructor.</p>\n<h1>Unnecessary Copies</h1>\n<p><code>int height(std::shared_ptr<Node> node);</code> for example makes a copy of its argument which means an increment and decrement of the atomic reference counter which means thread synchronization. Taking a <code>const &</code> would avoid that.</p>\n<h1>Naming</h1>\n<p><code>destroy</code> is more commonly named <code>clear</code>.<br />\nI would argue that functions returning a <code>bool</code> should be phrased as a question. <code>empty</code> should be <code>is_empty</code> to avoid <code>tree.empty(); //does not actually empty the tree</code>. But the STL also does this wrong and keeping it STL-compatible instead of logical is also a reasonable design decision. Maybe use both.</p>\n<h1>Dead Code</h1>\n<p><code>destroy_helper</code> seems to be useless.</p>\n<h1>Interface</h1>\n<h2>Const Correctness</h2>\n<p>If I get a <code>const Avl &tree</code> I can barely do anything with it. I can check the <code>size</code> and if it's <code>empty</code>. I cannot <code>travers_*</code> it or <code>find</code> anything in it. Those functions should be <code>const</code> too.</p>\n<h2>Out Parameters</h2>\n<p><code>void traverse_inorder(std::vector<int>& out);</code> is ugly to use and usually inefficient. <code>std::vector<int> traverse_inorder() const;</code> is much nicer to work with. If you keep the old version as a minor performance improvement call <code>.reserve</code> or <code>.resize</code> on the vector since you know exactly how big it will end up.</p>\n<h2>Noise</h2>\n<pre><code>inline size_t size() const {\n return current_size;\n}\n</code></pre>\n<p>is already implicitly <code>inline</code>, so just remove the redundant keyword.</p>\n<h2>Unnecessary Privacy</h2>\n<p>You already have <code>get_min</code>, but it's <code>private</code>. Since you already have it may as well expose it to the user (probably without the parameter or making it optional) instead of having them reimplement it.</p>\n<h1>Logic</h1>\n<p>I only looked at this briefly, so this is nowhere near complete.<br />\n<code>void Avl::add(std::shared_ptr<Node> node)</code> adds a <code>Node</code> without any unlinking. It keeps its parent and <code>left</code> and <code>right</code>, possibly going into another tree.<br />\n<code>Avl tree_copy = tree;</code> compiles, but doesn't make a copy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T14:01:55.877",
"Id": "428148",
"Score": "0",
"body": "Thank you for review, I will try to implement a model where the children pointers are unique and the parent is a raw pointer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T13:09:45.830",
"Id": "221412",
"ParentId": "221407",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221412",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T12:11:54.107",
"Id": "221407",
"Score": "1",
"Tags": [
"c++",
"tree",
"c++14",
"pointers"
],
"Title": "AVL tree implementation using shared_ptr/unique_ptr"
} | 221407 |
<p>I wrote the script below as my first python program that will be running in a production environment. Essentially this program looks at a source location and moves all the files to a destination location if the file is older than 14 days old and does not exists in the destination. I had a user on stack overflow suggest some variable name changes and I am in the process of doing that. I would love if someone could review this code and let me know if anyone sees any potential bugs or errors that I might run into. </p>
<pre><code>import os
import shutil
import time
import errno
import time
import sys
import logging
import logging.config
source = r'C:\Users\Desktop\BetaSource'
dest = r'C:\Users\Desktop\BetaDest'
#Gets the current time from the time module
now = time.time()
#Timer of when to purge files
cutoff = now - (14 * 86400)
source_list = []
all_sources = []
all_dest_dirty = []
logging.basicConfig(level = logging.INFO, filename = time.strftime("main-%Y-%m-%d.log"))
def main():
dest_files()
purge_files()
#I used the dess_files function to get all of the destination files
def dest_files():
for dest_root, dest_subdirs, dest_files in os.walk(dest):
for f in dest_files:
global All_dest_dirty
all_dest_dirty.append(f)
def purge_files():
logging.info('invoke purge_files method')
#I removed all duplicates from dest because cleaning up duplicates in dest is out of the scope
all_dest_clean = list(dict.fromkeys(all_dest_dirty))
#os.walk used to get all files in the source location
for source_root, source_subdirs, source_files in os.walk(source):
#looped through every file in source_files
for f in source_files:
#appending all_sources to get the application name from the file path
all_sources.append(os.path.abspath(f).split('\\')[-1])
#looping through each element of all_source
for i in all_sources:
#logical check to see if file in the source folder exists in the destination folder
if i not in all_dest_clean:
#src is used to get the path of the source file this will be needed to move the file in shutil.move
src = os.path.abspath(os.path.join(source_root, i))
#the two variables used below are to get the creation time of the files
t = os.stat(src)
c = t.st_ctime
#logical check to see if the file is older than the cutoff
if c<cutoff:
logging.info(f'File has been succesfully moved: {i}')
print(f'File has been succesfully moved: {i}')
shutil.move(src,dest)
#removing the allready checked source files for the list this is also used in other spots within the loop
all_sources.remove(i)
else:
logging.info(f'File is not older than 14 days: {i}')
print(f'File is not older than 14 days: {i}')
all_sources.remove(i)
else:
all_sources.remove(i)
logging.info(f'File: {i} allready exists in the destination')
print(f'File: {i} allready exists in the destination')
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p>This is just a brain dump of some things about your code that I hope you find useful.</p>\n\n<h1>Automated tools</h1>\n\n<p>Automated tools can help you maintain your code more easily.</p>\n\n<p>The first ones I install whenever I start a new Python project, are:</p>\n\n<ul>\n<li><a href=\"https://github.com/python/black\" rel=\"nofollow noreferrer\">black</a> — The uncompromising Python code formatter</li>\n<li><a href=\"https://github.com/timothycrosley/isort\" rel=\"nofollow noreferrer\">isort</a> — A Python utility to sort imports</li>\n<li><a href=\"https://github.com/pycqa/flake8\" rel=\"nofollow noreferrer\">flake8</a> — A tool to enforce PEP 8 compliance (among other things)</li>\n</ul>\n\n<p>I ran them on your code with the following options:</p>\n\n<ul>\n<li><code>pipenv run black clean_old_files.py</code></li>\n<li><code>pipenv run flake8 --max-line-length 88 clean_old_files.py</code></li>\n<li><code>pipenv run isort clean_old_files.py -m=3 -tc -l=88</code></li>\n</ul>\n\n<p>(An aside, I'm using <a href=\"https://github.com/pypa/pipenv\" rel=\"nofollow noreferrer\">Pipenv</a> to manage my <a href=\"https://stackoverflow.com/q/41972261\">virtual environments</a>. They're unmissable once you start getting into larger projects with external dependencies, and other contributors.)</p>\n\n<h1>Noisy comments</h1>\n\n<p>You have several comments that explain <em>what</em> the code does, rather than <em>why</em>.</p>\n\n<p>For instance this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Gets the current time from the time module\nnow = time.time()\n# Timer of when to purge files\ncutoff = now - (14 * 86400)\n</code></pre>\n\n<p>which could be rewritten as:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Timer of when to purge files\ncutoff = time.time() - (14 * 86400)\n</code></pre>\n\n<p>which removes one \"what\" comment, and inlines a temporary variable.</p>\n\n<p>My advice would be to go over all the comments in your script, and see which are \"what\" comments, and which are \"why\" comments.</p>\n\n<h1>Code structure</h1>\n\n<p>A minor thing to start off, I'd move the <code>main</code> function to the bottom of the script, right before <code>if __name__ == \"__main__\"</code>, which, conceptually makes most sense to me.</p>\n\n<p>You are mutating global variables from functions, which makes it harder to follow your program structure as-is.</p>\n\n<p>On a related note, you also have <code>global All_dest_dirty</code>, which is a typo.</p>\n\n<h1>Globals</h1>\n\n<p>Instead of, for instance:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>all_dest_dirty = []\n\ndef dest_files():\n for dest_root, dest_subdirs, dest_files in os.walk(dest):\n for f in dest_files:\n global all_dest_dirty\n all_dest_dirty.append(f)\n</code></pre>\n\n<p>prefer:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def dest_files():\n dirty_files = []\n for dest_root, dest_subdirs, dest_files in os.walk(dest):\n for f in dest_files:\n dirty_files.append(f)\n\n return dirty_files\n\nall_dest_dirty = dest_files()\n</code></pre>\n\n<h1>Closing remarks</h1>\n\n<p>Correct me if I'm wrong, but from</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>all_dest_clean = list(dict.fromkeys(all_dest_dirty))\n</code></pre>\n\n<p>I think that you're trying to remove duplicates from a list?</p>\n\n<p>You can write that as</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>all_dest_clean = set(all_dest_dirty)\n</code></pre>\n\n<p>which uses the <a href=\"https://docs.python.org/3.7/library/stdtypes.html#set\" rel=\"nofollow noreferrer\"><code>set</code></a> data type, which prevents any duplicates. Plus, it's less typing, and also clearer. :-)</p>\n\n<hr>\n\n<p>I hope you found my mini review helpful. You're doing great for a <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged 'beginner'\" rel=\"tag\">beginner</a>! Keep it up. Also, let me know if anything is unclear.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-02T18:35:14.427",
"Id": "428429",
"Score": "0",
"body": "That was a great answer! I love your feedback. I’ll definitely go through and create those functions to return values rather than manipulating global variables. Also id I turned all_dest_clean into a set would I still be able to check if I is not in all_dest_clean? Im not super familiar what the difference between using a list compared to a set."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-02T20:20:33.683",
"Id": "428439",
"Score": "1",
"body": "@TheMuellTrain Thank you! Re: `would I still be able to check if I is not in all_dest_clean` Yup! That's still possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T15:24:39.043",
"Id": "428556",
"Score": "0",
"body": "I have modified the `dest_files()` function to `return dirty_files`. My question now is what is the best practice for defining `all_dest_dirty = dest_files()` I can not define it at the top of my program with the rest of the variables. Is it common to just define this right after the function?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T21:22:04.753",
"Id": "221506",
"ParentId": "221408",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221506",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T12:32:57.297",
"Id": "221408",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"file-system"
],
"Title": "Python script to clean out old files from a repository"
} | 221408 |
<p><strong>The task</strong> </p>
<p>was initially solved <a href="https://codereview.stackexchange.com/questions/221359/find-the-starting-indices-of-all-occurrences-of-the-pattern-in-the-string">here</a>, but was too buggy:</p>
<blockquote>
<p>Given a string and a pattern, find the starting indices of all
occurrences of the pattern in the string. For example, given the
string "abracadabra" and the pattern "abr", you should return [0, 7].</p>
</blockquote>
<p><strong>My solution</strong></p>
<p>Tried to solve it using <a href="https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm" rel="nofollow noreferrer">KMP-algorithm</a>:</p>
<pre><code>function findStartingIndex(T, pattern) {
if (pattern.length > T.length) { return []; }
let next = 0;
const res = [];
const check = i => {
for (let j = 1; j < pattern.length; j++) {
if (next <= i && T[i + j] === pattern[0]) { next = i + j - 1; }
if (T[i + j] !== pattern[j]) { return false; }
}
if (next <= i) { next = i + pattern.length - 1; }
return true;
};
for (let i = 0; i < T.length; i++) {
if (i + pattern.length > T.length) { return res; }
if (T[i] === pattern[0] && check(i)) { res.push(i); }
i = next;
}
return res;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T22:32:05.937",
"Id": "428217",
"Score": "0",
"body": "Did you write automated tests? Which are your test cases? As you saw in the previous question, a single test case is not enough. If you only had this single test case, the expression `(() => [0, 7])` would satisfy all test cases, even though it is clearly wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T22:39:08.677",
"Id": "428218",
"Score": "0",
"body": "@RolandIllig Nope, I didn't write automated tests. But maybe I should in the future. I only tested some cases that I thought were critical: `abracadabra | abr`, `banana | a`, `12121212 | 1212`, `1111 | 1`"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T12:42:52.270",
"Id": "221409",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"ecmascript-6"
],
"Title": "Find the starting indices of all occurrences of the pattern in the string - KMP algorithm follow-up"
} | 221409 |
<p>This function returns the number of pairs of the same elements in the array</p>
<p>It takes, array length and the array as the parameter</p>
<blockquote>
<blockquote>
<p>n: Length of array</p>
<p>ar: Array of integers for example</p>
<p>4 6 7 8 7 6 6 7 6 4</p>
</blockquote>
<p>returns 4</p>
</blockquote>
<pre><code>fun getNumberOfPairs(n: Int, ar: Array<Int>): Int {
val enteries = HashSet<Int>()
var pairs = 0
for (i in 0 until n) {
if (!enteries.contains(ar[i])) {
enteries.add(ar[i])
} else {
pairs++
enteries.remove(ar[i])
}
}
println(pairs)
return pairs
}
</code></pre>
<p>How can we write this code in a better way for readability/performance?</p>
| [] | [
{
"body": "<p>Overall it's very readable and fast already. Good job.</p>\n\n<p>I have some suggestions for possible improvements:</p>\n\n<ul>\n<li>As <code>n</code> must be equal to <code>ar.size</code>, you could drop that parameter from the method and use <code>ar.size</code> in place of <code>n</code> within the method body.</li>\n<li>This method is a pure function except for the side effect of printing the result. Being a \"pure function\" is often a good thing so you can move the printing of the result to outside the method. Printing something is also quite time-consuming.</li>\n<li>Your method could easily support more than <code>Int</code>, it doesn't have to be restricted by a specific type. You could check for duplicates of any type so we can make this method generic.</li>\n<li>As you are iterating over elements you could use <code>for (e in ar)</code> instead of iterating over the indexes with <code>for (i in 0 until n)</code>. This would make it more efficient for data structures that doesn't have a <span class=\"math-container\">\\$O(1)\\$</span> lookup-time, for example <code>LinkedList</code>.</li>\n<li>The method <code>HashSet.add</code> returns <code>false</code> if the value already exists, so you don't need the call to <code>.contains</code>.</li>\n<li>There is a typo in the name <code>enteries</code>, it should be called <code>entries</code>.</li>\n<li><code>ar</code> could be called <code>input</code> to make it more readable.</li>\n</ul>\n\n<p>After applying all of the above, this is what you would end up with:</p>\n\n<pre><code>fun <T> getNumberOfPairs(input: Array<T>): Int {\n val entries = HashSet<T>()\n var pairs = 0\n\n for (e in input) {\n if (!entries.add(e)) {\n pairs++\n entries.remove(e)\n }\n }\n return pairs\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T13:22:27.187",
"Id": "221415",
"ParentId": "221411",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221415",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T12:50:06.250",
"Id": "221411",
"Score": "4",
"Tags": [
"array",
"kotlin"
],
"Title": "Finding the number of pairs in an integer Array"
} | 221411 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.