text stringlengths 1 2.12k | source dict |
|---|---|
javascript, performance, html, dom
//loop over other rows and do the same process if a cell is in add to a cell class none (in css .none{display: none;})
for (let i = 0; i < trs.length; i++) {
const element = trs[i];
let tds = [...element.querySelectorAll("td")];
for (let j = 0; j < tds.length; j++) {
if (array_index.includes(j)) {
tds[j].classList.add("none");
}
}
}
table {
border-collapse: collapse;
border: 1px solid;
}
tr,
th,
td {
border: 1px solid;
text-align: center;
}
.none {
display: none;
}
<table class="table_pp">
<thead>
<tr>
<th>column_1</th>
<th>column_2</th>
<th>column_3</th>
<th>column_4</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>0</td>
<td>5</td>
<td>0</td>
</tr>
<tr>
<td>3</td>
<td>0</td>
<td>6</td>
<td>0</td>
</tr>
<tr>
<td>8</td>
<td>0</td>
<td>2</td>
<td>0</td>
</tr>
</tbody>
</table>
Is it the right way of doing it?
Answer: Aside from the ambiguity in the question, you are definitely taking a circuitous route to identify the columns. CSS's nth-child would vastly simplify querying the DOM.
// determine column count from th cells in thead
document.querySelectorAll('thead th').forEach((_, i) => {
// only interested in the nth-child for each column in the tbody
const cols = [...document.querySelectorAll(`tbody tr td:nth-child(${i+1})`)]
// get the sum (or whatever determines why to hide
const total = cols.reduce((acc, col) => acc + parseInt(col.textContent), 0)
if (total === 0) {
// add the css class to each tbody column
cols.forEach(col => {
col.classList.add('none')
}) | {
"domain": "codereview.stackexchange",
"id": 43445,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, performance, html, dom",
"url": null
} |
javascript, performance, html, dom
// also hide the header th
const headerCol = document.querySelector(`thead th:nth-child(${i+1})`)
if (headerCol) headerCol.classList.add('none')
}
})
table {
border-collapse: collapse;
border: 1px solid;
}
tr,
th,
td {
border: 1px solid;
text-align: center;
}
.none {
display: none;
}
<table class="table_pp">
<thead>
<tr>
<th>column_1</th>
<th>column_2</th>
<th>column_3</th>
<th>column_4</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>0</td>
<td>5</td>
<td>0</td>
</tr>
<tr>
<td>3</td>
<td>0</td>
<td>6</td>
<td>0</td>
</tr>
<tr>
<td>8</td>
<td>0</td>
<td>2</td>
<td>0</td>
</tr>
</tbody>
</table> | {
"domain": "codereview.stackexchange",
"id": 43445,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, performance, html, dom",
"url": null
} |
java, algorithm
Title: Figure out initial balance for bank accounts to avoid them going into negative balance after transfer transactions
Question: I had to solve this problem yesterday on Codility as part of a job interview. At the end, even though my code passes the initial 3 tests, it failed most of the other tests (which are hidden) and it also failed most of the performance tests. And now I'm puzzled as to why and I was hoping somebody would shine a light on the glaring issues with my code.
Problem description:
Write a method that takes in 2 parameters:
A string containing either "A" or "B" indicating the recipient of a bank transfer.
An integer array containing the amount for each of those transfers.
So for instance, if the String is BA and the array is [1,2], it means A transfers 1 to B, then B transfers 2 to A.
This method should return what the initial balance for each bank account A and B need to be so that they never go into negative balance.
In the example above, it should return [1, 1].
Initial balance [1, 1].
A transfers 1 to B [0, 2].
B transfers 2 to A [2, 0].
Final balance [2, 0].
Important points:
The input String and the input Array will always have the same length.
The input String will only contain "A" and/or "B".
I can't remember if the numbers on the array had to be positive, though I have not tested for negative numbers, so that might be a reason for the failure.
Other test scenarios:
"BAABA" - [2,4,1,1,2] - answer should be [2,4].
Initial Balance [2, 4].
A transfers 2 to B [0, 6].
B transfers 4 to A [4, 2].
B transfers 1 to A [5, 1].
A transfers 1 to B [4, 2].
B transfers 2 to A [6, 0].
"ABAB" - [10, 5, 10, 15] answer should be [0, 15].
"B" - [100] - answer should be [100,0].
"AB" - [3, 3] - answer should be [0,3].
My code
public class Bank {
public int[] solution(String R, int[] V) {
int aInitial = 0;
int bInitial = 0;
int aBalance = 0;
int bBalance = 0; | {
"domain": "codereview.stackexchange",
"id": 43446,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm",
"url": null
} |
java, algorithm
int aBalance = 0;
int bBalance = 0;
for (int i = 0; i < R.length(); i++) {
char destination = R.charAt(i);
int amount = V[i];
if (destination == 'A') {
int remaining = bBalance - amount;
if (remaining < 0) {
bInitial += Math.abs(remaining);
bBalance = 0;
}
aBalance += amount;
} else if (destination == 'B') {
int remaining = aBalance - amount;
if (remaining < 0) {
aInitial += Math.abs(remaining);
aBalance = 0;
}
bBalance += amount;
}
}
return new int[] {aInitial, bInitial};
}
}
```
Answer: The problem with your solution appears to be that B's balance doesn't change when B makes a transfer out of their account and B had a high enough starting balance to do so. And vice versa for A.
You can simplify by simulating all the transfers starting from a zero balance, and keep track of the lowest (most negative) balance that was reached. Then negate it to get the starting balance that would have given a zero balance at that point instead.
public int[] solution(String recipients, int[] amounts) {
int minA = 0;
int minB = 0;
int balA = 0;
int balB = 0;
for (int i = 0; i < recipients.length(); i++) {
if (recipients.charAt(i) == 'A') {
balA += amounts[i];
balB -= amounts[i];
if (balB < minB) {
minB = balB;
}
} else if (recipients.charAt(i) == 'B') {
balB += amounts[i];
balA -= amounts[i];
if (balA < minA) {
minA = balA;
}
}
}
return new int[] { -minA, -minB };
} | {
"domain": "codereview.stackexchange",
"id": 43446,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm",
"url": null
} |
python, python-3.x, comparative-review
Title: Calculate the number of people occupied at each time interval
Question: The following scripts calculate a list with the number of people occupied at each time interval.
The intervals are defined by the timestamps of two consecutive events that come from the sorted list events_timeline.
Also, start_ts and end_ts are taking into account for intervals calculation and for each event, one person is occupied.
input data to be used in the following scripts:
MINIMUM_EVENT_INTERVAL = 1
start_ts = 1598939760.0
end_ts = 1598939792.0
events_timeline = [(1598939761.0, 's'), (1598939771.0, 's'), (1598939781.0, 'e'),
(1598939791.0, 'e')] # 's' and 'e' denote start and end event respectively
1st approach:
people_occupied = []
start_events = 0
end_events = 0
num_events_timeline = len(events_timeline)
if events_timeline[0][0] - start_ts >= MINIMUM_EVENT_INTERVAL:
people_occupied.append(0)
for index, (ts, event) in enumerate(events_timeline):
if event == 's':
start_events += 1
else:
end_events += 1
if index != num_events_timeline - 1 and ts == events_timeline[index + 1][0]:
continue
if index == num_events_timeline - 1 and end_ts - ts < MINIMUM_EVENT_INTERVAL:
break
people_occupied.append(start_events - end_events)
print(f'1st approach: {people_occupied}')
2nd approach:
currently_occupied = 0
people_occupied = []
if events_timeline[0][0] - start_ts >= MINIMUM_EVENT_INTERVAL:
people_occupied.append(0)
for (start_time, event_type), (end_time, _) in zip(events_timeline[:-1], events_timeline[1:]):
if event_type == 's':
currently_occupied += 1
else:
currently_occupied -= 1
if end_time > start_time:
people_occupied.append(currently_occupied)
if end_ts - events_timeline[-1][0] >= MINIMUM_EVENT_INTERVAL:
people_occupied.append(0)
print(f'2nd approach: {people_occupied}')
Both approaches do the job, but which one of them should be preferred and why? | {
"domain": "codereview.stackexchange",
"id": 43447,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, comparative-review",
"url": null
} |
python, python-3.x, comparative-review
Both approaches do the job, but which one of them should be preferred and why?
Answer: Generally, at the edge of your program you shouldn't be entering datetimes as timestamp numeric literals, but as human-legible datetimes. On the inside of your program, you also shouldn't be processing datetimes as numeric timestamps, but instead as well-typed datetime.datetime instances.
The interior of your loop ignores MINIMUM_EVENT_INTERVAL and only pays attention to that at the bounds of your event sequence. This seems unlikely to be a good idea. Ideally, you would pay attention to that minimum for every event, and treat your bounds start_ts and end_ts the same way that you treat everything in your main timeline.
Generally I think your second approach using zip is preferable, but it isn't enough. You should write well-typed functions. Iterator functions are a convenient way to capture your logic.
Suggested
This (intentionally) isn't exactly equivalent in terms of logic, but since all of your timestamps already meet the interval minimum, the output is the same.
from datetime import datetime, timedelta
from typing import Iterable, Iterator, Literal, Sequence
MINIMUM_EVENT_INTERVAL = timedelta(seconds=1)
Event = tuple[
datetime,
# 's' and 'e' denote start and end event respectively
Literal['s', 'e'],
]
def get_events_with_endpoints(
start_ts: datetime,
end_ts: datetime,
events: Iterable[Event],
) -> Iterator[Event]:
yield start_ts, 's'
yield from events
yield end_ts, 'e'
def get_occupied(events: Sequence[Event]) -> Iterator[int]:
currently_occupied = 0
for (start_time, _), (end_time, event_type) in zip(events[:-1], events[1:]):
if end_time - start_time >= MINIMUM_EVENT_INTERVAL:
yield currently_occupied
if event_type == 's':
currently_occupied += 1
else:
currently_occupied -= 1 | {
"domain": "codereview.stackexchange",
"id": 43447,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, comparative-review",
"url": null
} |
python, python-3.x, comparative-review
def main() -> None:
timeline = (
(datetime(2020, 9, 1, 3, 26, 1), 's'),
(datetime(2020, 9, 1, 3, 26, 11), 's'),
(datetime(2020, 9, 1, 3, 26, 21), 'e'),
(datetime(2020, 9, 1, 3, 26, 31), 'e'),
)
events = get_events_with_endpoints(
start_ts=datetime(2020, 9, 1, 3, 26, 0),
end_ts =datetime(2020, 9, 1, 3, 26, 32),
events=timeline,
)
print(tuple(get_occupied(tuple(events))))
if __name__ == '__main__':
main()
Output
(0, 1, 2, 1, 0) | {
"domain": "codereview.stackexchange",
"id": 43447,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, comparative-review",
"url": null
} |
python, python-2.x
Title: Function to add a new key pair value to my JSON file
Question: As you can see I am using a counter variable to iterate through my JSON file and it's a dictionary that has a list of dictionaries. Once I find the key normalHours I divide it and add it to my dictionary hours_per_week. Then I update the dictionary it is associated with. Is it better to use for i in range instead of the counter? Anything else I can do to clean up or speed up the code?
Here is my json file, I deleted most of the key pairs for easier readability.
{
"employeeData": [
{
"normalHours": 80,
"givenName": "ROBERTO",
},
{
"normalHours": 80,
"givenName": "HEATHER",
},
{
"normalHours": 80,
"givenName": "PAUL",
}
] }
def add_hours_per_week(json_file):
"""
Add new dictionary value hoursPerWeek to our JSON data
"""
# Create new dictionary hours_per_week.
hours_per_week = {}
hours_divide_by_2 = 0
normal_hours_counter = 0
try:
for key, values in json_file.items():
if str(key) == "employeeData":
# JSON is in a list of dictionaries
for item in values:
# If normalHours field is Null, "", or 0 add an empty field
if not item["normalHours"] or item["normalHours"] == 0:
hours_per_week["hoursPerWeek"] = ""
else:
# Divide normalHours by 2 rounded to 2 decimals.
hours_divide_by_2 = round(float(item["normalHours"]) / 2, 2)
hours_per_week["hoursPerWeek"] = hours_divide_by_2
json_file['employeeData'][normal_hours_counter].update(hours_per_week)
normal_hours_counter += 1
print("%d employee updated with hoursPerWeek" % normal_hours_counter if normal_hours_counter <= 1 else
"%d employees updated with hoursPerWeek" % normal_hours_counter)
return json_file | {
"domain": "codereview.stackexchange",
"id": 43448,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-2.x",
"url": null
} |
python, python-2.x
except Exception as e:
print("Exception in add_hours_per_week: ", e)
Answer: This code exhibits a collection of anti-patterns typically seen in Python that together are making your life more difficult:
Dictionary lasagna, having non-structured data used directly from the result of a JSON parse
In-place mutation
Exception swallowing
Infectious nullity
I don't see any value in your employees updated print. At the absolute least, this should be converted to a proper logging call, but I would sooner drop it entirely.
This code needs to be significantly re-thought, along with any code you haven't shown that depends on such patterns. Consider instead:
Define a simple dataclass or NamedTuple representing each Employee
Write a simple property method for hours_per_week
Do not round() in your business logic, only upon presentation
Explicit casting to a float should not be needed
Suggested
from typing import Any, Iterable, Iterator, NamedTuple, Optional
class Employee(NamedTuple):
given_name: str
normal_hours: Optional[float]
@classmethod
def from_dict(cls, data: Iterable[dict[str, Any]]) -> Iterator['Employee']:
for employee in data:
yield cls(
given_name=employee['givenName'],
normal_hours=employee.get('normalHours'),
)
@property
def hours_per_week(self) -> Optional[float]:
return self.normal_hours and self.normal_hours / 2
def __str__(self) -> str:
if self.normal_hours:
return (
f'{self.given_name}:'
f' {self.normal_hours} hours,'
f' {self.hours_per_week:.2f} hours per week'
)
return self.given_name | {
"domain": "codereview.stackexchange",
"id": 43448,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-2.x",
"url": null
} |
python, python-2.x
def main() -> None:
json_content = {
'employeeData': [
{'normalHours': 80, 'givenName': 'ROBERTO'},
{'normalHours': 80, 'givenName': 'HEATHER'},
{'normalHours': 80, 'givenName': 'PAUL'},
{'normalHours': None, 'givenName': 'JULIO'}
]
}
employees = Employee.from_dict(json_content['employeeData'])
for employee in employees:
print(employee)
if __name__ == '__main__':
main()
Output
ROBERTO: 80 hours, 40.00 hours per week
HEATHER: 80 hours, 40.00 hours per week
PAUL: 80 hours, 40.00 hours per week
JULIO
Python 2
Similar, just worse.
class Employee:
def __init__(self, given_name, normal_hours):
self.given_name = given_name
self.normal_hours = normal_hours
@classmethod
def from_dict(cls, data):
for employee in data:
yield cls(
given_name=employee['givenName'],
normal_hours=employee.get('normalHours'),
)
@property
def hours_per_week(self):
return self.normal_hours and self.normal_hours / 2
def __str__(self):
if self.normal_hours:
return '%s: %f hours, %.2f hours per week' % (
self.given_name,
self.normal_hours,
self.hours_per_week,
)
return self.given_name
def main():
json_content = {
'employeeData': [
{'normalHours': 80, 'givenName': 'ROBERTO'},
{'normalHours': 80, 'givenName': 'HEATHER'},
{'normalHours': 80, 'givenName': 'PAUL'},
{'normalHours': None, 'givenName': 'JULIO'}
]
}
employees = Employee.from_dict(json_content['employeeData'])
for employee in employees:
print(employee)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43448,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-2.x",
"url": null
} |
c++, strings
Title: String formatting in C++
Question: To develop my understanding of C++, I've written an overload function that allows users to use & to insert strings within other strings (denoted by a $ character). So far, it only works with one replacement in a string. For example:
"Hello $" & "World" -> "Hello World"
I want to receive feedback, because I'm sure there's a much better way than using three for loops. And I'd like a better foundation before moving forward with multiple replacements in a single string.
#include <string>
#include <iostream>
std::string operator&(const std::string& str, const char* cstr) {
if (str.empty()) {
return std::string(cstr);
}
if (str.find("$") == std::string::npos) {
return str + std::string(cstr);
}
int string_length = str.length();
int cstr_length = 0;
while (cstr[cstr_length] != '\0') {
cstr_length++;
}
int length = string_length + cstr_length;
std::string result = "";
int i;
for (i = 0; i < str.find("$"); i++) {
result += str[i];
}
i++; // Skips past the '$'
for (int j = 0; j < cstr_length; j++) {
result += cstr[j];
}
for (; i < string_length; i++) {
result += str[i];
}
return result;
}
int main(int argc, char** argv) {
std::string string = "Hello $, My name is Ben!";
char* cstr = (char*)"World";
std::string result = string & cstr;
std::cout << result << std::endl;
return 0;
}
Answer:
Keep your includes ordered. Thus, you won't lose track of them, even if there are more of them.
Common modern order goes from local to universal, to ensure headers are self-contained. Exceptions are fixed or at least annotated. All groups are sorted and separated by an empty line for emphasis:
precompiled header if applicable, for obvious technical reasons
the corresponding header, to ensure it is self-contained
own headers
external libraries headers
system headers
standard headers | {
"domain": "codereview.stackexchange",
"id": 43449,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings",
"url": null
} |
c++, strings
Any of the last three might be amalgamated.
#include <iostream>
#include <string>
#include <string_view>
Don't bolt your own operators on someone else's type. It just invites confusion. Use a properly named free function instead.
Using C++17 std::string_view leads to a more efficient and convenient interface, and simplifies your implementation.
Avoid special cases. They mean more code (which can be wrong), and slow down the common case.
std::string replace_placeholder(std::string_view format, std::string_view a) {
auto pos = format.find('$');
auto rest = pos + 1;
std::string r;
r.reserve(format.size() + a.size() - (pos != std::string_view::npos));
if (pos == std::string_view::npos)
rest = pos = format.size();
r.append(format.begin(), format.begin() + pos);
r += a;
r.append(format.begin() + rest, format.end());
return r;
}
Don't name arguments you won't use. Thus, you avoid confusing future readers (like yourself) nor cause spurious warnings.
In the case of main(), you might just leave the arguments out completely.
Eliminate dead code and dead variables. They will just confuse, and if you want to restore them, there is source control. Let the compiler warn you about them as it can.
Don't muzzle the compiler just because it has the audacity to warn you. Figure out what you did wrong instead, and fix that. Yes, sometimes you have to override it, but you have to be judicious and careful there, using the least dangerous tool to get the job done.
In the specific case, instead of casting away const, fix the pointer type. const_cast would have been less dangerous than an unrestricted C-style cast, if it had been appropriate.
Embrace auto. Almost Always Auto is a good idea to avoid mismatches and unintended conversions, especially if the exact type doesn't matter to you. | {
"domain": "codereview.stackexchange",
"id": 43449,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings",
"url": null
} |
c++, strings
Only use std::endl when you need to flush the stream. Actually, belay that, be explicit and use std::flush.
Also, when the program ends the standard streams are flushed.
See "What is the C++ iostream endl fiasco?".
return 0; is implicit for main().
int main() {
std::string string = "Hello $, My name is Ben!";
auto cstr = "World";
auto result = replace_placeholder(string, cstr);
std::cout << result << "\n";
} | {
"domain": "codereview.stackexchange",
"id": 43449,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings",
"url": null
} |
python, performance, numpy, pandas
Title: Generate new column based on two columns of dataframe
Question: I need to generate column a_b based on column a and column b of df, if both a and b are greater than 0, a_b is assigned a value of 1, if both a and b are less than 0, a_b is assigned a value of -1, I am using double np.where .
My code is as follows, where generate_data generates demo data and get_result is used for production, where get_result needs to be run 4 million times:
import numpy as np
import pandas as pd
rand = np.random.default_rng(seed=0)
pd.set_option('display.max_columns', None)
def generate_data() -> pd.DataFrame:
_df = pd.DataFrame(rand.uniform(-1, 1, 70).reshape(10, 7), columns=['a', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6'])
return _df
def get_result(_df: pd.DataFrame) -> pd.DataFrame:
a = _df.a.to_numpy()
for col in ['b1', 'b2', 'b3', 'b4', 'b5', 'b6']:
b = _df[col].to_numpy()
_df[f'a_{col}'] = np.where(
(a > 0) & (b > 0), 1., np.where(
(a < 0) & (b < 0), -1., 0.)
)
return _df
def main():
df = generate_data()
print(df)
df = get_result(df)
print(df)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43450,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, pandas",
"url": null
} |
python, performance, numpy, pandas
if __name__ == '__main__':
main()
Data generated by generate_data:
a b1 b2 b3 b4 b5 b6
0 0.273923 -0.460427 -0.918053 -0.966945 0.626540 0.825511 0.213272
1 0.458993 0.087250 0.870145 0.631707 -0.994523 0.714809 -0.932829
2 0.459311 -0.648689 0.726358 0.082922 -0.400576 -0.154626 -0.943361
3 -0.751433 0.341249 0.294379 0.230770 -0.232645 0.994420 0.961671
4 0.371084 0.300919 0.376893 -0.222157 -0.729807 0.442977 0.050709
5 -0.379516 -0.028329 0.778976 0.868087 -0.284410 0.143060 -0.356261
6 0.188600 -0.324178 -0.216762 0.780549 -0.545685 0.246374 -0.831969
7 0.665288 0.574197 -0.521261 0.752968 -0.882864 -0.327766 -0.699441
8 -0.099321 0.592649 -0.538716 -0.895957 -0.190896 -0.602974 -0.818494
9 0.160665 -0.402608 0.343990 -0.600969 0.884226 -0.269780 -0.789009
My desired result:
a b1 b2 b3 b4 b5 b6 a_b1 \
0 0.273923 -0.460427 -0.918053 -0.966945 0.626540 0.825511 0.213272 0.0
1 0.458993 0.087250 0.870145 0.631707 -0.994523 0.714809 -0.932829 1.0
2 0.459311 -0.648689 0.726358 0.082922 -0.400576 -0.154626 -0.943361 0.0
3 -0.751433 0.341249 0.294379 0.230770 -0.232645 0.994420 0.961671 0.0
4 0.371084 0.300919 0.376893 -0.222157 -0.729807 0.442977 0.050709 1.0
5 -0.379516 -0.028329 0.778976 0.868087 -0.284410 0.143060 -0.356261 -1.0
6 0.188600 -0.324178 -0.216762 0.780549 -0.545685 0.246374 -0.831969 0.0
7 0.665288 0.574197 -0.521261 0.752968 -0.882864 -0.327766 -0.699441 1.0
8 -0.099321 0.592649 -0.538716 -0.895957 -0.190896 -0.602974 -0.818494 0.0
9 0.160665 -0.402608 0.343990 -0.600969 0.884226 -0.269780 -0.789009 0.0 | {
"domain": "codereview.stackexchange",
"id": 43450,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, pandas",
"url": null
} |
python, performance, numpy, pandas
a_b2 a_b3 a_b4 a_b5 a_b6
0 0.0 0.0 1.0 1.0 1.0
1 1.0 1.0 0.0 1.0 0.0
2 1.0 1.0 0.0 0.0 0.0
3 0.0 0.0 -1.0 0.0 0.0
4 1.0 0.0 0.0 1.0 1.0
5 0.0 0.0 -1.0 0.0 -1.0
6 0.0 1.0 0.0 1.0 0.0
7 0.0 1.0 0.0 0.0 0.0
8 -1.0 -1.0 -1.0 -1.0 -1.0
9 1.0 0.0 1.0 0.0 0.0
Performance evaluation:
%timeit get_result(df)
1.56 ms ± 54.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
How can it be faster?
Answer: I don't see any value in Pandas here. Use Numpy broadcasting directly between an a 10x1 array and a b 10x6 array, producing a new 10x6 array. Your inner where() does work with these arrays unmodified, but there are faster methods that do not use where and instead call np.sign or np.ceil.
from collections import defaultdict
from statistics import mean
from timeit import timeit
import numpy as np
rand = np.random.default_rng(seed=0)
a = rand.uniform(low=-1, high=1, size=(10, 1))
b = rand.uniform(low=-1, high=1, size=(10, 6))
# if both a and b are greater than 0, a_b is assigned a value of 1,
# if both a and b are less than 0, a_b is assigned a value of -1
def op():
return np.where(
(a > 0) & (b > 0),
1,
np.where(
(a < 0) & (b < 0), -1, 0,
)
)
def ceils():
return np.ceil(a)*np.ceil(b) - np.floor(a)*np.floor(b)
def signs():
sa = np.sign(a)
return sa * (sa == np.sign(b))
METHODS = (op, ceils, signs)
results = [method() for method in METHODS]
for result in results[1:]:
assert np.allclose(results[0], result)
N = 10_000
times = defaultdict(list)
for _ in range(10):
for method in METHODS:
t = timeit(method, number=N)
times[method.__name__].append(t)
for method, method_time in times.items():
print(f'{method:>6}: {mean(method_time)/N*1e6:6.1f} us')
Output
op: 24.3 us
ceils: 10.0 us
signs: 8.0 us | {
"domain": "codereview.stackexchange",
"id": 43450,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, pandas",
"url": null
} |
python, performance, python-3.x, strings, file
Title: Adding string to a text file without duplicates
Question: I have a function below, store_in_matchid_file, and it adds certain strings to a .txt file as long as that string doesn't already exist in the file. However that file is getting to be millions of lines long and the process of checking is becoming too long.
I was hoping someone would be able to indicate a way I could speed up the process, by changing how I've coded the process.
def store_in_matchid_file(distinct_matchids_func):
# Ids stored in the text file
with open('MatchIds.txt') as f:
current_id_list = f.read().splitlines()
# Ids recently collected (Previously a set, converted to list to iterate over)
distinct_matchids_list = list(distinct_matchids_func)
# Adding Ids that don't exist in the file
with open('MatchIds.txt', 'a') as file:
for match in distinct_matchids_list:
if match not in current_id_list:
file.write(match + '\n')
Answer: You could make some improvements:
Open the file just once in read+update mode.
Instead of current_id_list, use a set, which can test whether an item is one of the existing items quickly, regardless of how many existing items there are.
Iterating over the file handle f will give you entries a line at a time; you don't need to read the entire file at once and call .splitlines() on it.
You don't need to explicitly convert distinct_matchids_func into a list; you can just iterate over it.
Some other remarks:
distinct_matchids_func is a weird name — is it a function or an iterable?
We're assuming that the distinct_matchids_func are indeed distinct, and don't contain duplicates.
You should write a docstring for the function rather than a comment. | {
"domain": "codereview.stackexchange",
"id": 43451,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, strings, file",
"url": null
} |
python, performance, python-3.x, strings, file
def store_in_matchid_file(distinct_matchids_func):
"""
Append items from distinct_matchids_func as lines to MatchIds.txt that
are not already present in the file.
"""
with open('MatchIds.txt', 'r+') as f:
current_ids = set(f)
for match in distinct_matchids_func:
match += '\n'
if match not in current_ids:
f.write(match)
But as @Reinderien suggests in a comment, storing these entries in a database such as sqlite could be a better option. It's going to perform better (since it uses data structures to facilitate quick searches), and it will be less prone to corruption (for example, if multiple processes try to manipulate the file at the same time). | {
"domain": "codereview.stackexchange",
"id": 43451,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, strings, file",
"url": null
} |
java, beginner, minesweeper
Title: Text Based Minesweeper in Java
Question: I have been working on a text based minesweeper game in Java and I am looking for some ways to improve it. I worked through this project through JetBrains academy. I will attach the instructions of the final part of the project
Objectives In this final stage, your program should contain the
following additional functionality:
Print the current state of the minefield starting with all unexplored
cells at the beginning, ask the player for their next move with the
message Set/unset mine marks or claim a cell as free:, treat the
player's move according to the rules, and print the new minefield
state. Ask for the player's next move until the player wins or steps
on a mine. The player's input contains a pair of cell coordinates and
a command: mine to mark or unmark a cell, free to explore a cell.
If the player explores a mine, print the field in its current state,
with mines shown as X symbols. After that, output the message You
stepped on a mine and failed!.
Generate mines like in the original game: the first cell explored with
the free command cannot be a mine; it should always be empty. You can
achieve this in many ways – it's up to you.
Use the following symbols to represent each cell's state:
. as unexplored cells
/ as explored free cells without mines around it
Numbers from 1 to 8 as explored free cells with 1 to 8 mines around
them, respectively
X as mines
* as unexplored marked cells
Here is part of an example they gave
The greater-than symbol followed by a space (> ) represents the user input. Note that it's > not part of the input.
Example 1: the user loses after exploring a cell that contains a mine
|123456789|
-|---------|
1|.........|
2|.........|
3|.........|
4|.........|
5|.........|
6|.........|
7|.........|
8|.........|
9|.........|
-|---------|
Set/unset mines marks or claim a cell as free: > 3 2 free | {
"domain": "codereview.stackexchange",
"id": 43452,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, minesweeper",
"url": null
} |
java, beginner, minesweeper
|123456789|
-|---------|
1|.1///1...|
2|.1//12...|
3|11//1....|
4|////1....|
5|11111....|
6|.........|
7|.........|
8|.........|
9|.........|
-|---------|
Set/unset mines marks or claim a cell as free: > 1 1 free
|123456789|
-|---------|
1|11///1...|
2|.1//12...|
3|11//1....|
4|////1....|
5|11111....|
6|.........|
7|.........|
8|.........|
9|.........|
-|---------|
Set/unset mines marks or claim a cell as free: > 1 2 mine
|123456789|
-|---------|
1|11///1...|
2|*1//12...|
3|11//1....|
4|////1....|
5|11111....|
6|.........|
7|.........|
8|.........|
9|.........|
-|---------|
I will attach the code below. Any advice would be greatly appreciated but here are some of my overarching questions I have about my code
I wasn't sure how much code I should write in my main method. Does the game logic belong in the class or in the main method? One major debate I had with myself was whether to put the scanner in the main method or in the class itself (as you can see, I went with the latter). What would you have done?
I had to duplicate my code whenever I was doing operations with neigboring cells. For example, I use for (int i = Math.max(0, row - 1); i <= Math.min(8, row + 1) ; i++) and for (int j = Math.max(0, initialCol - 1); j <= Math.min(8, initialCol + 1); j++) whenever I need to iterate through a cells neighbors. Is there any way I could improve how I go about doing this?
Jetbrains academy introduced enums before completing this project but I didn't know how I would use them. Would they have made my code any better?
You may notice the lack of comments in my code. I don't use them too often (I know it's a bad habit to get into). Is the code self explanatory or does it need more comments?
And here is my code:
package minesweeper;
import java.util.Objects;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here | {
"domain": "codereview.stackexchange",
"id": 43452,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, minesweeper",
"url": null
} |
java, beginner, minesweeper
public class Main {
public static void main(String[] args) {
// write your code here
Minefield game = new Minefield();
while (!game.hasLost || !game.hasWon) {
game.nextTurn();
}
}
}
class Minefield {
int[][] board = new int[9][9];
boolean[][] mineLocations = new boolean[9][9];
boolean[][] marked = new boolean[9][9];
boolean[][] explored = new boolean[9][9];
boolean hasWon;
boolean hasLost;
boolean boardSet;
static Scanner scanner = new Scanner(System.in);
private int mines;
public Minefield(){
System.out.print("How many mines do you want on the field? ");
this.mines = scanner.nextInt();
this.showMinefield();
}
public void nextTurn() {
System.out.print("Set/unset mines marks or claim a cell as free: ");
int col = scanner.nextInt() - 1;
int row = scanner.nextInt() - 1;
String command = scanner.next();
if (this.isExplored(row, col)) {
System.out.println("This cell is already explored!");
} else {
executeTurn(row, col, command);
}
}
private void executeTurn(int row, int col, String command) {
switch (command) {
case "free":
if (!boardSet) {
boardSet = true;
this.newBoard(row, col);
explore(row, col);
}
if (this.hasMineAt(row, col)) {
this.revealMinefield();
System.out.println("You stepped on a mine and failed!");
this.hasLost = true;
} else {
explore(row, col);
}
break;
case "mine":
this.marked[row][col] = !this.marked[row][col];
}
this.checkWin();
this.showMinefield();
} | {
"domain": "codereview.stackexchange",
"id": 43452,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, minesweeper",
"url": null
} |
java, beginner, minesweeper
private void newBoard(int initialRow, int initialCol){
//ensures the first move doesn't have any mines
for (int i = Math.max(0, initialRow - 1); i <= Math.min(8, initialRow + 1); i++) {
for (int j = Math.max(0, initialCol - 1); j <= Math.min(8, initialCol + 1); j++) {
this.board[i][j] = -1;
}
}
Random random = new Random();
for (int i = 0; i < this.mines; i++) {
int mineRow , mineCol;
do {
mineRow = random.nextInt(9);
mineCol = random.nextInt(9);
} while (this.board[mineRow][mineCol] == -1);
this.board[mineRow][mineCol] = -1;
this.mineLocations[mineRow][mineCol] = true;
}
for (int i = Math.max(0, initialRow - 1); i <= Math.min(8, initialRow + 1); i++) {
for (int j = Math.max(0, initialCol - 1); j <= Math.min(8, initialCol + 1); j++) {
this.board[i][j] = 0;
}
}
for (int i = 0; i < this.board.length; i++) {
for (int j = 0; j < this.board[0].length; j++) {
if (this.hasMineAt(i,j)) {
for (int k = Math.max(0, i - 1); k <= Math.min(8, i + 1) ; k++) {
for (int l = Math.max(0, j - 1); l <= Math.min(8, j + 1); l++) {
if (!(k == i && l == j)) {
this.board[k][l]++;
}
}
}
}
}
}
if (board[initialRow][initialCol] != 0) {
System.out.println("Error with mine spawning");
}
} | {
"domain": "codereview.stackexchange",
"id": 43452,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, minesweeper",
"url": null
} |
java, beginner, minesweeper
private void showMinefield() {
System.out.println(" |123456789|");
System.out.println("-|---------|");
for (int i = 0; i < this.board.length; i++) {
System.out.print((i + 1) + "|");
for (int j = 0; j < this.board[0].length; j++) {
if (this.isMarked(i, j)) {
System.out.print("*");
} else if (this.board[i][j] == 0 && this.isExplored(i, j)) {
System.out.print("/");
} else if (this.isExplored(i, j)){
System.out.print(this.board[i][j]);
} else {
System.out.print(".");
}
}
System.out.print("|");
System.out.println();
}
System.out.println("-|---------|");
}
private void revealMinefield() {
System.out.println(" |123456789|");
System.out.println("-|---------|");
for (int i = 0; i < this.board.length; i++) {
System.out.print((i + 1) + "|");
for (int j = 0; j < this.board[0].length; j++) {
if (this.hasMineAt(i, j)) {
System.out.print("X");
} else if (this.board[i][j] == 0 && this.isExplored(i, j)) {
System.out.print("/");
} else if (this.isExplored(i, j)){
System.out.print(this.board[i][j]);
} else {
System.out.print(".");
}
}
System.out.print("|");
System.out.println();
}
System.out.println("-|---------|");
}
private boolean hasMineAt(int row, int col) {
return this.mineLocations[row][col];
}
private boolean isMarked(int row, int col) {
return this.marked[row][col];
}
private boolean isExplored(int row, int col) {
return this.explored[row][col];
}
private void explore(int row, int col) { | {
"domain": "codereview.stackexchange",
"id": 43452,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, minesweeper",
"url": null
} |
java, beginner, minesweeper
private void explore(int row, int col) {
this.explored[row][col] = true;
this.marked[row][col] = false;
if (this.board[row][col] == 0) {
for (int i = Math.max(0, row - 1); i <= Math.min(8, row + 1) ; i++) {
for (int j = Math.max(0, col - 1); j <= Math.min(8, col + 1) ; j++) {
if (!this.isExplored(i, j)) {
this.explore(i, j);
}
}
}
}
}
private void checkWin(){
if (this.marked == this.mineLocations) {
this.hasWon = true;
return;
}
for (int i = 0; i < this.board.length; i++) {
for (int j = 0; j < this.board[0].length; j++) {
if (this.hasMineAt(i, j) && !this.isMarked(i,j)) {
return;
}
}
}
this.hasWon = true;
}
} | {
"domain": "codereview.stackexchange",
"id": 43452,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, minesweeper",
"url": null
} |
java, beginner, minesweeper
}
Answer: In my opinion, the main method should be used to set up and start the game. It should not be responsible for running it, so the loop would be in an incorrect place. The reason is that main method is just an entry point for a standalone applications. If your game should be a part of a larger application later, then you can no longer use the main method to run the game.
Setting up the scanner should be in the main method, but there are limitations to that. In a fully modular approach that follows single responsibility principle and separation of concerns, the game engine itself should not be dependant on a specific input method. You would have a separate IO-component that handles input from a scanner and converts it to game commands. I.e. it reads data from the scanner, parses them and passes them as method calls to the game engine and then outputs the game state in a way that is suitable to the player. When made this way, there could be different IO-components for console and GUI and they could both use the same game engine.
The IO-component can further be split into a view and a controller, but that may be something for later learning.
Enums could be used to represent the CellState of each cell in the 2d array: UNDISTURBED, REVEALED, FLAGGED. The data structures you have in the Minesweeper class don't lend themselves too well for this. Instead of having multiple arrays each containing a certain property of the locations in the field, you should have a single array containing objects that represent everything related to a single location. So create a class named Cell, put the boolean containsMine and CellState state in there and replace the four arrays with Cell[][] mineField = new Cell[9][9].
You have two fields called hasWon and hasLost. These should be replaced with a GameState enum that has the values ONGOING, WON, LOST. This way you safeguard yourself from accidentally endinf up in an invalid state where both hasWon and hasLost are true. | {
"domain": "codereview.stackexchange",
"id": 43452,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, minesweeper",
"url": null
} |
python, web-scraping, pandas
Title: web scraping with pandas and apscheduler
Question: Below is a script to scrape data from the National Severe Storms Laboratory Probsevere dataset. Their data is available at a 2 minute interval and is only available for 24 hours before moving to the archives. The data is GeoJSON which I convert to a MultiIndex DataFrame and save as a parquet. The script runs once an hour to collect the previous hours data at a 10 min interval.
The script is running on a raspberry pi and writing the parquet to an external HHD. I am collecting the data for a machine learning project. Eventually I will serve the data from the pi to my local network. I use shapely to convert the geometry into geometric shapes.
from datetime import datetime
from typing import Mapping
import pandas as pd
import numpy as np
import requests
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.interval import IntervalTrigger
NCEP_DATA = "https://mrms.ncep.noaa.gov/data"
scheduler = BlockingScheduler()
def name_to_datetime(names: pd.Series) -> pd.DatetimeIndex:
return pd.DatetimeIndex(names.str.replace("_", "T").str.extract(r"(\d*T\d*).json")[0]).rename("validTime")
def read_mrms(*args: str) -> pd.DataFrame:
url = "/".join([NCEP_DATA, *args]) + "/?C=M;O=D"
return pd.read_html(url)[0].dropna()
def read_probsevere() -> pd.DataFrame:
df = read_mrms("ProbSevere", "PROBSEVERE")
df.index = name_to_datetime(df.Name)
return (NCEP_DATA + "/ProbSevere/PROBSEVERE/" + df["Name"]).rename("url")
def get_last_hours_data():
s = read_probsevere()
last_hour = datetime.utcnow() - pd.to_timedelta(1, unit="h")
is_last_hour = (s.index.day == last_hour.day) & (s.index.hour == last_hour.hour)
is_10_min_interval = (s.index.minute % 10) == 0
return s[is_last_hour & is_10_min_interval] | {
"domain": "codereview.stackexchange",
"id": 43453,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, web-scraping, pandas",
"url": null
} |
python, web-scraping, pandas
def to_dataframe(mrms_files: Mapping[pd.Timestamp, str]) -> pd.DataFrame:
def generate():
for vt, url in mrms_files.items():
features = requests.get(url).json()["features"]
print(f"data collected for {vt}")
for feat in features:
props = feat["properties"]
props["validTime"] = vt
props["geometry"] = feat["geometry"]
yield props
ps = pd.DataFrame(generate()).set_index(["validTime", "ID"])
ps["AVG_BEAM_HGT"] = ps["AVG_BEAM_HGT"].str.replace(r"[A-Za-z]", "", regex=True).apply(pd.eval)
ps[["MAXRC_EMISS", "MAXRC_ICECF"]] = (
ps[["MAXRC_EMISS", "MAXRC_ICECF"]]
.stack()
.str.extract(r"(?:\()([a-z]*)(?:\))")
.replace({"weak": 1, "moderate": 2, "strong": 3})
.fillna(0)
.unstack(-1)
.droplevel(0, axis=1)
)
ps.loc[:, ps.columns != "geometry"] = ps.loc[:, ps.columns != "geometry"].astype(np.float32)
return ps
@scheduler.scheduled_job(IntervalTrigger(hours=1))
def on_hour():
template = "/media/external/data/{0}.parquet"
last = get_last_hours_data()
df = to_dataframe(last)
file_name = template.format(datetime.now().strftime("%Y-%m-%d.HR%H"))
df.to_parquet(file_name)
print(f"file saved as {file_name}")
if __name__ == "__main__":
on_hour()
scheduler.start() | {
"domain": "codereview.stackexchange",
"id": 43453,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, web-scraping, pandas",
"url": null
} |
python, web-scraping, pandas
if __name__ == "__main__":
on_hour()
scheduler.start()
Answer: In terms of scheduling and process persistence, it sounds like you "just run it" and hope that it stays running. This seems risky and is more effort than it's worth. Delete apscheduler and run the process once an hour using cron. The process will start, do its business and save its file, then quit.
name_to_datetime is unnecessarily complex. You don't need to do string operations on this series: instead, issue one call to to_datetime with exact=False so that you don't need to worry about the surrounding text. This will return another series and not an index, but Pandas is smart enough to make an index upon assignment.
Your url creation is also more complex than it needs to be. You already make a URL that you pass to read_html - why not re-use that?
I don't think it's a great idea to directly compare the day and hour components of your index. Instead, you can simply subtract the index from now, and compare to your timedelta.
Rather than modulating your minute to choose a row once every ten minutes, this is what resample has been written for. Use a frequency string of 10T.
I think you have misinterpreted AVG_BEAM_HGT. When it says
'15.65 kft / 4.77 km' | {
"domain": "codereview.stackexchange",
"id": 43453,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, web-scraping, pandas",
"url": null
} |
python, web-scraping, pandas
it does NOT mean "please divide 15.65 kilofeet by 4.77 kilometres", and you should NOT use eval (especially for untrusted data that have come fresh off the internet!) Instead it means "the average beam height is 15.65 kilofeet, otherwise known as 4.77 kilometres for people who prefer units that are not an affront to all things holy". Drop everything except the 4.77 quantity.
Your MAXRC processing needs some love. Why are you paying attention to the "weak"/"moderate"/"strong" descriptors when it gives you the numeric equivalent as well? You should ignore those descriptors and only use the numeric equivalent. After all, the site itself has generated those descriptors based on very simple threshold rules from the data. Don't stack/unstack, don't droplevel, and just do a replace on that sub-frame.
In your filename formatting, you don't need to call strftime: you can pass that format definition directly in the format field of an f-string.
I must say that you're getting the hang of indices - you've chosen them well for these data (your validTime and ID).
Your URL suffix:
"/?C=M;O=D"
is deeply suspicious. If those are separate URL query parameters, I would expect & rather than ;, which can be done for you by passing those letters into the params kwarg of get.
In your call to read_html, you should be telling it to skip rows 1 and 2 as those contain a separator and a parent directory, respectively.
Something weird is going on in the mrms_files argument to to_dataframe. That's not a mapping: that's already a DataFrame, and you should not be calling .items(), but rather .iterrows().
Suggested
I temporarily switched from parquet to CSV output so that I can inspect the results.
import re
from datetime import datetime
import pandas as pd
from requests import Session
NCEP_DATA = 'https://mrms.ncep.noaa.gov/data'
def name_to_datetime(names: pd.Series) -> pd.Series:
times = pd.to_datetime(names, format='%Y%m%d_%H%M%S', exact=False)
return times.rename('validTime') | {
"domain": "codereview.stackexchange",
"id": 43453,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, web-scraping, pandas",
"url": null
} |
python, web-scraping, pandas
def read_mrms(session: Session, *args: str) -> pd.DataFrame:
url = '/'.join((NCEP_DATA, *args))
with session.get(
url=url,
params={'C': 'M', 'O': 'D'},
headers={'Accept': 'text/html'},
) as response:
response.raise_for_status()
df, = pd.read_html(
io=response.text,
skiprows=[1, 2], # separator, parent dir
parse_dates=['Last modified'],
)
df = df.dropna()
df.index = name_to_datetime(df.Name)
df['url'] = (url + '/') + df.Name
return df
def read_probsevere(session: Session) -> pd.DataFrame:
return read_mrms(session, 'ProbSevere', 'PROBSEVERE')
def get_last_hours_data(session: Session) -> pd.DataFrame:
s = read_probsevere(session)
one_hour = pd.to_timedelta(1, unit='H')
is_last_hour = (datetime.utcnow() - s.index) <= one_hour
s = s[is_last_hour].resample('10T').first()
return s
def to_dataframe(session: Session, mrms_files: pd.DataFrame) -> pd.DataFrame:
def generate():
for valid_time, row in mrms_files.iterrows():
with session.get(
url=row.url,
headers={'Accept': 'application/json'},
) as response:
response.raise_for_status()
features = response.json()['features']
print(f'data collected for {valid_time}')
for feat in features:
props = feat['properties']
props['validTime'] = valid_time
props['geometry'] = feat['geometry']
yield props
ps = pd.DataFrame(generate()).set_index(['validTime', 'ID']) | {
"domain": "codereview.stackexchange",
"id": 43453,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, web-scraping, pandas",
"url": null
} |
python, web-scraping, pandas
ps = pd.DataFrame(generate()).set_index(['validTime', 'ID'])
# e.g. 3.97 kft / 1.21 km
ps['AVG_BEAM_HGT'] = ps.AVG_BEAM_HGT.str.extract(
re.compile(
r'''(?x) # verbose
( # capturing group
[\d.]+ # float characters, at least one
)
\s*km # consume whitespace, literal 'km'
'''
), expand=False,
).astype(float)
maxrc = ['MAXRC_EMISS', 'MAXRC_ICECF']
ps[maxrc] = (
ps[maxrc]
.replace(
to_replace=re.compile(
# e.g. 4.4%/min
r'''(?x) # verbose
^.*? # start, lazy consume everything
( # capturing group
[\d.]+ # float chars, at least one, greedy
)
%? # optional literal percent
/min # literal "per minute"
.*$ # consume everything, end
'''
), value=r'\1', regex=True,
)
.replace('N/A', 0)
.astype(float)
)
return ps
def on_hour() -> None:
with Session() as session:
last = get_last_hours_data(session)
df = to_dataframe(session, last)
# /media/external/data/...parquet actually
file_name = f'data_{datetime.now():%Y-%m-%d.HR%H}.csv'
df.to_csv(file_name)
print(f'file saved as {file_name}')
if __name__ == '__main__':
on_hour()
Output
data collected for 2022-06-11 09:40:00
data collected for 2022-06-11 09:50:00
data collected for 2022-06-11 10:00:00
data collected for 2022-06-11 10:10:00
data collected for 2022-06-11 10:20:00
data collected for 2022-06-11 10:30:00
data collected for 2022-06-11 10:40:00
file saved as data_2022-06-11.HR08.csv | {
"domain": "codereview.stackexchange",
"id": 43453,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, web-scraping, pandas",
"url": null
} |
beginner, programming-challenge, converting, powershell
Title: PowerShell script to convert .reg files to PowerShell commands
Question: This is a PowerShell script I wrote a while ago that converts Windows Registry files to PowerShell commands(New-Item, Remove-Item, Set-ItemProperty and Remove-ItemProperty), it supports conversion of all six registry value types (REG_SZ, REG_DWORD, REG_QWORD, REG_BINARY, REG_EXPAND_SZ and REG_MULTI_SZ), and you got it right, I figured out how to correctly convert binary types.
You can view my original script here:https://superuser.com/a/1615077/1250181
Today I improved it, and this is the final version of my script, I used reg add to add REG_BINARY values because Set-ItemProperty can't add them, I used commas instead of "\0" because that's the correct way to add them with Set-ItemProperty, and Registry PSProvider does only provide 2 PSDrives by default: HKCU: and HKLM:, so if the registry files modifies other hives I added the lines to create them.
Please review my code(Tested on PowerShell 7, lower versions may not work):
Function reg2ps1 {
[CmdLetBinding()]
Param(
[Parameter(ValueFromPipeline=$true, Mandatory=$true)]
[Alias("FullName")]
[string]$path,
$Encoding = "utf8"
) | {
"domain": "codereview.stackexchange",
"id": 43454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, converting, powershell",
"url": null
} |
beginner, programming-challenge, converting, powershell
Begin {
$hive = @{
"HKEY_CLASSES_ROOT" = "HKCR:"
"HKEY_CURRENT_CONFIG" = "HKCC:"
"HKEY_CURRENT_USER" = "HKCU:"
"HKEY_LOCAL_MACHINE" = "HKLM:"
"HKEY_USERS" = "HKU:"
}
[system.boolean]$isfolder=$false
$addedpath=@()
}
Process {
switch (test-path $path -pathtype container)
{
$true {$files=(get-childitem -path $path -recurse -force -file -filter "*.reg").fullname;$isfolder=$true}
$false {if($path.endswith(".reg")){$files=$path}}
}
foreach($File in $Files) {
$Commands = @()
if ($(Get-Content -Path $File -Raw) -match "HKEY_CLASSES_ROOT") {$commands+="New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT | Out-Null"}
elseif ($(Get-Content -Path $File -Raw) -match "HKEY_CURRENT_CONFIG") {$commands+="New-PSDrive -Name HKCC -PSProvider Registry -Root HKEY_CURRENT_CONFIG | Out-Null"}
elseif ($(Get-Content -Path $File -Raw) -match "HKEY_USERS") {$commands+="New-PSDrive -Name HKU -PSProvider Registry -Root HKEY_USERS | Out-Null"}
[string]$text=$nul
$FileContent = Get-Content $File | Where-Object {![string]::IsNullOrWhiteSpace($_)} | ForEach-Object { $_.Trim() }
$joinedlines = @()
for ($i=0;$i -lt $FileContent.count;$i++){
if ($FileContent[$i].EndsWith("\")) {
$text=$text+($FileContent[$i] -replace "\\").trim()
} else {
$joinedlines+=$text+$FileContent[$i]
[string]$text=$nul
}
} | {
"domain": "codereview.stackexchange",
"id": 43454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, converting, powershell",
"url": null
} |
beginner, programming-challenge, converting, powershell
foreach ($joinedline in $joinedlines) {
if ($joinedline -match '\[' -and $joinedline -match '\]' -and $joinedline -match 'HKEY') {
$key=$joinedline -replace '\[|\]'
switch ($key.StartsWith("-HKEY"))
{
$true {
$key=$key.substring(1,$key.length-1)
$hivename = $key.split('\')[0]
$key = "`"" + ($key -replace $hivename,$hive.$hivename) + "`""
$Commands += 'Remove-Item -Path {0} -Force -Recurse' -f $key
}
$false {
$hivename = $key.split('\')[0]
$key = "`"" + ($key -replace $hivename,$hive.$hivename) + "`""
if ($addedpath -notcontains $key) {
$Commands += 'New-Item -Path {0} -ErrorAction SilentlyContinue | Out-Null'-f $key
$addedpath+=$key
}
}
}
}
elseif ($joinedline -match "`"([^`"=]+)`"=") {
[System.Boolean]$delete=$false
[System.Boolean]$binary=$false
$name=($joinedline | select-string -pattern "`"([^`"=]+)`"").matches.value | select-object -first 1
switch ($joinedline)
{
{$joinedline -match "=-"} {$commands+=$Commands += 'Remove-ItemProperty -Path {0} -Name {1} -Force' -f $key, $Name;$delete=$true}
{$joinedline -match '"="'} {
$type="String"
$value=$joinedline -replace "`"([^`"=]+)`"="
}
{$joinedline -match "dword"} {
$type="Dword" | {
"domain": "codereview.stackexchange",
"id": 43454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, converting, powershell",
"url": null
} |
beginner, programming-challenge, converting, powershell
{$joinedline -match "dword"} {
$type="Dword"
$value=$joinedline -replace "`"([^`"=]+)`"=dword:"
$value="0x"+$value
}
{$joinedline -match "qword"} {
$type="Qword"
$value=$joinedline -replace "`"([^`"=]+)`"=qword:"
$value="0x"+$value
}
{$joinedline -match "hex(\([2,7,b]\))?:"} {
$value=($joinedline -replace "`"[^`"=]+`"=hex(\([2,7,b]\))?:").split(",")
$hextype=($joinedline | select-string -pattern "hex(\([2,7,b]\))?").matches.value
switch ($hextype)
{
{$hextype -match 'hex(\([2,7])\)'} {
$ValueEx='$value=for ($i=0;$i -lt $value.count;$i+=2) {if ($value[$i] -ne "00") {[string][char][int]("0x"+$value[$i])}'
switch ($hextype)
{
'hex(2)' {$type="ExpandString"; invoke-expression $($ValueEx+'}')}
'hex(7)' {$type="MultiString"; invoke-expression $($ValueEx+' else {","}}'); $value=0..$($value.count-3) | %{$value[$_]}}
}
$value=$value -join ""
if ($type -eq "ExpandString") {$value='"'+$value+'"'}
}
'hex(b)' {
$type="Qword"
$value=for ($i=$value.count-1;$i -ge 0;$i--) {$value[$i]}
$value='0x'+($value -join "").trimstart('0')
} | {
"domain": "codereview.stackexchange",
"id": 43454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, converting, powershell",
"url": null
} |
beginner, programming-challenge, converting, powershell
}
'hex' {
$type="REG_BINARY"
$value=$value -join ""
$binary=$true
}
}
}
}
if ($delete -eq $false) {
switch ($binary)
{
$false {$line='Set-ItemProperty -Path {0} -Name {1} -Type {2} -Value {3}'}
$true {$line='Reg Add {0} /v {1} /t {2} /d {3} /f';$key=$key.replace(":\","\")}
}
$commands+=$line -f $key, $name, $type, $value
}
}
elseif ($joinedline -match "@=") {
$name='"(Default)"';$type='string';$value=$joinedline -replace '@='
$commands+='Set-ItemProperty -Path {0} -Name {1} -Type {2} -Value {3}' -f $key, $name, $type, $value
}
}
$parent=split-path $file -parent
$filename=[System.IO.Path]::GetFileNameWithoutExtension($file)
$Commands | out-file -path "${parent}\${filename}_reg.ps1" -encoding $encoding
}
if ($isfolder -eq $true) {
$allcommands=(get-childitem -path $path -recurse -force -file -filter "*_reg.ps1").fullname | where-object {$_ -notmatch "allcommands_reg"} | foreach-object {get-content $_}
$allcommands | out-file -path "${path}\allcommands_reg.ps1" -encoding $encoding
}
}
}
$path = $args[0]
reg2ps1 $path | {
"domain": "codereview.stackexchange",
"id": 43454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, converting, powershell",
"url": null
} |
beginner, programming-challenge, converting, powershell
Usage example: .\reg2ps1.ps1 "path\to\reg.reg"
Sample Input:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DPS]
"DelayedAutoStart"=dword:00000000
"Description"="@%systemroot%\\system32\\dps.dll,-501"
"DisplayName"="Diagnostic Policy Service"
"ErrorControl"=dword:00000001
"FailureActions"=hex:80,51,01,00,00,00,00,00,00,00,00,00,03,00,00,00,14,00,00,\
00,01,00,00,00,c0,d4,01,00,01,00,00,00,e0,93,04,00,00,00,00,00,00,00,00,00
"ImagePath"=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,\
74,00,25,00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,73,\
00,76,00,63,00,68,00,6f,00,73,00,74,00,2e,00,65,00,78,00,65,00,20,00,2d,00,\
6b,00,20,00,4c,00,6f,00,63,00,61,00,6c,00,53,00,65,00,72,00,76,00,69,00,63,\
00,65,00,4e,00,6f,00,4e,00,65,00,74,00,77,00,6f,00,72,00,6b,00,20,00,2d,00,\
70,00,00,00
"ObjectName"="NT AUTHORITY\\LocalService"
"RequiredPrivileges"=hex(7):53,00,65,00,43,00,68,00,61,00,6e,00,67,00,65,00,4e,\
00,6f,00,74,00,69,00,66,00,79,00,50,00,72,00,69,00,76,00,69,00,6c,00,65,00,\
67,00,65,00,00,00,53,00,65,00,43,00,72,00,65,00,61,00,74,00,65,00,47,00,6c,\
00,6f,00,62,00,61,00,6c,00,50,00,72,00,69,00,76,00,69,00,6c,00,65,00,67,00,\
65,00,00,00,53,00,65,00,41,00,73,00,73,00,69,00,67,00,6e,00,50,00,72,00,69,\
00,6d,00,61,00,72,00,79,00,54,00,6f,00,6b,00,65,00,6e,00,50,00,72,00,69,00,\
76,00,69,00,6c,00,65,00,67,00,65,00,00,00,53,00,65,00,49,00,6d,00,70,00,65,\
00,72,00,73,00,6f,00,6e,00,61,00,74,00,65,00,50,00,72,00,69,00,76,00,69,00,\
6c,00,65,00,67,00,65,00,00,00,00,00
"ServiceSidType"=dword:00000003
"Start"=dword:00000003
"Type"=dword:00000020 | {
"domain": "codereview.stackexchange",
"id": 43454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, converting, powershell",
"url": null
} |
beginner, programming-challenge, converting, powershell
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DPS\Parameters]
"ServiceDll"=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,\
00,74,00,25,00,5c,00,73,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,\
64,00,70,00,73,00,2e,00,64,00,6c,00,6c,00,00,00
"ServiceDllUnloadOnStop"=dword:00000001
"ServiceMain"="ServiceMain"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DPS\Security]
"Security"=hex:01,00,14,80,8c,00,00,00,98,00,00,00,14,00,00,00,30,00,00,00,02,\
00,1c,00,01,00,00,00,02,80,14,00,ff,01,0f,00,01,01,00,00,00,00,00,01,00,00,\
00,00,02,00,5c,00,04,00,00,00,00,00,14,00,ff,01,0f,00,01,01,00,00,00,00,00,\
05,12,00,00,00,00,00,18,00,ff,01,02,00,01,02,00,00,00,00,00,05,20,00,00,00,\
20,02,00,00,00,00,14,00,8d,01,02,00,01,01,00,00,00,00,00,05,04,00,00,00,00,\
00,14,00,8d,01,02,00,01,01,00,00,00,00,00,05,06,00,00,00,01,01,00,00,00,00,\
00,05,12,00,00,00,01,01,00,00,00,00,00,05,12,00,00,00 | {
"domain": "codereview.stackexchange",
"id": 43454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, converting, powershell",
"url": null
} |
beginner, programming-challenge, converting, powershell
Sample Output:
New-Item -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS" -ErrorAction SilentlyContinue | Out-Null
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS" -Name "DelayedAutoStart" -Type Dword -Value 0x00000000
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS" -Name "Description" -Type String -Value "@%systemroot%\\system32\\dps.dll,-501"
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS" -Name "DisplayName" -Type String -Value "Diagnostic Policy Service"
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS" -Name "ErrorControl" -Type Dword -Value 0x00000001
Reg Add "HKLM\SYSTEM\CurrentControlSet\Services\DPS" /v "FailureActions" /t REG_BINARY /d 805101000000000000000000030000001400000001000000c0d4010001000000e09304000000000000000000 /f
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS" -Name "ImagePath" -Type ExpandString -Value "%SystemRoot%\System32\svchost.exe -k LocalServiceNoNetwork -p"
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS" -Name "ObjectName" -Type String -Value "NT AUTHORITY\\LocalService"
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS" -Name "RequiredPrivileges" -Type MultiString -Value SeChangeNotifyPrivilege,SeCreateGlobalPrivilege,SeAssignPrimaryTokenPrivilege,SeImpersonatePrivilege
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS" -Name "ServiceSidType" -Type Dword -Value 0x00000003
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS" -Name "Start" -Type Dword -Value 0x00000003
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS" -Name "Type" -Type Dword -Value 0x00000020
New-Item -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS\Parameters" -ErrorAction SilentlyContinue | Out-Null
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS\Parameters" -Name "ServiceDll" -Type ExpandString -Value "%SystemRoot%\system32\dps.dll" | {
"domain": "codereview.stackexchange",
"id": 43454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, converting, powershell",
"url": null
} |
beginner, programming-challenge, converting, powershell
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS\Parameters" -Name "ServiceDllUnloadOnStop" -Type Dword -Value 0x00000001
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS\Parameters" -Name "ServiceMain" -Type String -Value "ServiceMain"
New-Item -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DPS\Security" -ErrorAction SilentlyContinue | Out-Null
Reg Add "HKLM\SYSTEM\CurrentControlSet\Services\DPS\Security" /v "Security" /t REG_BINARY /d 010014808c00000098000000140000003000000002001c000100000002801400ff010f0001010000000000010000000002005c000400000000001400ff010f0001010000000000051200000000001800ff01020001020000000000052000000020020000000014008d010200010100000000000504000000000014008d010200010100000000000506000000010100000000000512000000010100000000000512000000 /f | {
"domain": "codereview.stackexchange",
"id": 43454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, converting, powershell",
"url": null
} |
beginner, programming-challenge, converting, powershell
Registry Editor View:
Answer: I don't use Windows much and have very little experience with the registry, so I have a hard time judging the functional parts. So most of my comments are about the code style.
While PowerShell is not very sensitive when it comes to case, convention matters, and so does readability.
If a variable has multiple words in it, don't make it all lowercase with no separator. $joinedLines is conventional, but both $joined_lines and ${joined-lines} are at least nicer than $joinedlines
Method names, property names and cmdlet flag names generally start with an uppercase letter. Select-String -pattern "...".matches.value works, but Select-String -Pattern "...".Matches.Value is more conventional.
But above all else, be consistent in terms of how you refer to each variable. $Commands and $commands are the same, sure, but if you pick one and and stick to it it gets easier to read.
You can get rid of some duplication by re-using the same code for all three New-PSDrive command additions thanks to your $hive variable (if you remove the colons):
foreach ($root in $hive) {
if ((Get-Content -Path $file -Raw) -match $root) {
if ((Get-PSDrive).Name -notcontains $hive[$root]) {
$commands += "New-PSDrive -Name $($hive[$root]) -PSProvider Registry -Root $root"
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, converting, powershell",
"url": null
} |
beginner, programming-challenge, converting, powershell
Though if you do that, you'd have to replace $hive.$hiveName with something more like "$($hive[$hiveName]):" later on.
You have a few switch statements where the only cases are $true and $false. It'd probably be clearer to just make those into if statements.
You have a couple if ($someVariable -eq $true) and if ($someVariable -eq $false) -- you can just replace those with if ($someVariable) and if ( ! $someVariable)
At one point, you go $command+=$Command+="...", which might be intentional, but doesn't look like it. If it is, you should probably add a comment specifying that, and possibly spell the line out like $command = $command + $command + "...".
If you have multiple statements on a single line separated by ;, consider splitting it into multiple lines instead (for loop headers not included)
Code tends to look a lot more pleasant when statements and operators get some space to breathe. for ($i=0;$i -lt $FileContent.count;$i++){ works exactly the same as for ($i = 0; $i -lt $FileContent.count; $i++) {, but the second is less of a hassle to read.
As a Cmdlet, your reg2psi function should probably follow the Verb-Noun naming convention, with a name like ConvertFrom-RegistryFile perhaps?
I'm not sure creating the allcommands_reg.ps1 is your script's responsibility, and I'm also not sure it's well-behaved if you're working on a folder that contains a file called allcommands.reg. Might be best to just have your cmdlet create the individual *_reg.ps1 files and making a separate script for combining them.
The line joining removes all backslashes from lines that end with a backslash, which could be dangerous unless you know that a backslash will never appear in another position. Maybe that's the case (I don't know much about the Windows registry), but being explicit and replacing \\$ instead is probably best.
Also, when doing the line joining, you can just iterate over the lines directly rather than keeping track of an index: | {
"domain": "codereview.stackexchange",
"id": 43454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, converting, powershell",
"url": null
} |
beginner, programming-challenge, converting, powershell
foreach ($line in $fileContent) {
if ($line.EndsWith("\")) {
# stuff
} else {
# stuff
}
}
Once the lines are joined...
I think that first series of matches can be reduced to just one like $joinedLine -match '^\[-?HKEY[^\]]*\]$'. But again, I don't have much registry experience, I might be missing something.
If instead of treating the key as starting with - you treat the line as starting with [- you might be able to get rid of some duplication:
$key = $joinedLine -replace '^\[-?|\]$'
$hiveName = $key.Split('\')[0]
$key = '"' + ($key -replace $hiveName, "$($hive[$hiveName]):") + '"'
if ($joinedLine -StartsWith '[-') {
# Add a Remove-Item command
} else {
# Maybe add a New-Item command
} | {
"domain": "codereview.stackexchange",
"id": 43454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, converting, powershell",
"url": null
} |
c#, .net, hash-map
Title: Sorting Dictionary in a lexicographical order and applying MD5 encryption
Question: I'm sorting a Dictionary in a lexicographical order and applying MD5 encryption. I would like to wrap the sorting somewhere inside the encryption method or so.
Official Java example - here
Docs
private static string GenerateSign(Dictionary<string, object> query, string apiSecret)
{
var sb = new StringBuilder();
var queryParameterString = string.Join("&",
query.Where(kvp => !string.IsNullOrWhiteSpace(kvp.Value.ToString()))
.Select(kvp => $"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value.ToString())}"));
sb.Append(queryParameterString);
if (sb.Length > 0)
{
sb.Append('&');
}
sb.Append("api_secret=").Append(apiSecret);
return sb.ToString();
}
private static string Sign(string source)
{
using var md5 = MD5.Create();
var sourceBytes = Encoding.UTF8.GetBytes(source);
var hash = md5.ComputeHash(sourceBytes);
return BitConverter.ToString(hash).Replace("-", string.Empty).ToLowerInvariant();
}
public ValueTask SubscribeToPrivateAsync()
{
var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var @params = new Dictionary<string, object>
{
{ "api_key", _apiKey },
{ "req_time", now },
{ "op", "sub.personal" }
};
var javaSorted = @params.OrderBy(item => item.Key, StringComparer.Ordinal)
.ToDictionary(i => i.Key, i => i.Value);
var signature = Sign(GenerateSign(javaSorted, _apiSecret));
var request = new PersonalRequest("sub.personal", _apiKey, signature, now);
return SendAsync(request);
}
private ValueTask SendAsync<TRequest>(TRequest request)
where TRequest : SocketRequest
{
var json = JsonSerializer.Serialize(request);
var message = new Message(Encoding.UTF8.GetBytes(json));
return _websocketClient.SendAsync(message);
}
``` | {
"domain": "codereview.stackexchange",
"id": 43455,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map",
"url": null
} |
c#, .net, hash-map
Answer: For the MD5 hashing, I would suggest making it an extension method, if it's going to be used outside this scope, however, if it's only used in this class, you can keep it as is, and if it's only going to be used only for this payload, then you can put it inside the GenerateSign method. Also, you can use Convert.ToHexString instead of BitConverter.ToString.
this part :
var @params = new Dictionary<string, object>
{
{ "api_key", _apiKey },
{ "req_time", now },
{ "op", "sub.personal" }
};
var javaSorted = @params.OrderBy(item => item.Key, StringComparer.Ordinal)
.ToDictionary(i => i.Key, i => i.Value);
can be simplified by using SortedDictionary<string, object>, so it would be something like this :
var @params = new SortedDictionary<string, object>(StringComparer.Ordinal)
{
{ "api_key", _apiKey },
{ "req_time", now },
{ "op", "sub.personal" }
};
// the dictionary is sorted, and ready to use
in GenerateSign, Join, LINQ, and StringBuilder are mixed, it's fine, but we can add more readability to it and also add some micro-improvements, by simply use foreach and a StringBuilder. something like this :
private static string GenerateSign(IDictionary<string, object> items, string apiSecret)
{
if (items?.Count == 0) return null;
if (string.IsNullOrWhiteSpace(apiSecret)) return null;
var builder = new StringBuilder();
foreach(var item in items)
{
var key = item.Key;
var value = item.Value?.ToString();
if (!string.IsNullOrWhiteSpace(value))
{
if (builder.Length > 0)
{
builder.Append('&');
}
builder.Append($"{key}={HttpUtility.UrlEncode(value)}");
}
}
builder.Append("&api_secret=").Append(apiSecret); | {
"domain": "codereview.stackexchange",
"id": 43455,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map",
"url": null
} |
c#, .net, hash-map
builder.Append("&api_secret=").Append(apiSecret);
// hash the payload
using var md5 = MD5.Create();
var sourceBytes = Encoding.UTF8.GetBytes(builder.ToString());
var hash = md5.ComputeHash(sourceBytes);
return Convert.ToHexString(hash).ToLowerInvariant();
}
There is another option here, which I found it feasable, since the payload (from the documentation) is small, and fixed length.
this is the request payload example:
{
"op":"sub.personal",
"api_key": "api_key",
"sign": "b8d2ff6432798ef858782d7fd109ab41",
"req_time": "1561433613583"
}
if this is going to have the same object length and order, then how about implementing a class model for it, instead of dictionary ? and use JsonProperty attribute to set the key name and order.
Example with Json.NET :
public class MexcSubPersonalPayload
{
private readonly string _apiSecret;
[JsonProperty("op", Order = 1)]
public string Operation => "sub.personal";
[JsonProperty("api_key", Order = 2)]
public string ApiKey { get; private set; }
[JsonProperty("sign", Order = 3)]
public string Signature => Sign(this.ToString());
[JsonProperty("req_time", Order = 4)]
public long RequestTime => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
private string Sign(string str)
{
if (string.IsNullOrWhiteSpace(str)) return null;
using var md5 = MD5.Create();
var sourceBytes = Encoding.UTF8.GetBytes(str);
var hash = md5.ComputeHash(sourceBytes);
return Convert.ToHexString(hash).ToLowerInvariant();
}
public MexcSubPersonalPayload(string apiKey, string apiSecret)
{
ApiKey = apiKey;
_apiSecret = apiSecret;
}
public override string ToString()
{
return $"api_key={ApiKey}&req_time={RequestTime}&op={Operation}&api_secret={_apiSecret}";
}
}
Example with System.Text.Json:
public class MexcSubPersonalPayload
{
private readonly string _apiSecret; | {
"domain": "codereview.stackexchange",
"id": 43455,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map",
"url": null
} |
c#, .net, hash-map
[JsonPropertyName("op")]
[JsonPropertyOrder(1)]
public string Operation => "sub.personal";
[JsonPropertyName("api_key")]
[JsonPropertyOrder(2)]
public string ApiKey { get; private set; }
[JsonPropertyName("sign")]
[JsonPropertyOrder(3)]
public string Signature => Sign(this.ToString());
[JsonPropertyName("req_time")]
[JsonPropertyOrder(4)]
public long RequestTime => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
private string Sign(string str)
{
if (string.IsNullOrWhiteSpace(str)) return null;
using var md5 = MD5.Create();
var sourceBytes = Encoding.UTF8.GetBytes(str);
var hash = md5.ComputeHash(sourceBytes);
return Convert.ToHexString(hash).ToLowerInvariant();
}
public MexcSubPersonalPayload(string apiKey, string apiSecret)
{
ApiKey = apiKey;
_apiSecret = apiSecret;
}
public override string ToString()
{
return $"api_key={ApiKey}&req_time={RequestTime}&op={Operation}&api_secret={_apiSecret}";
}
}
I don't see a need for using UrlEncode in this model, as the values will be always valid, except for api_key and _apiSecret, if they have invalid characters, then you might use UrlEncode in them, but I don't know if is it going to invalidate the keys (public and private keys) or the service provider would handle the escaped characters (in this case it won't invalidate them).
anyhow, using the above model, you would only need to pass the public and private keys, and then convert it to JSON.
usage with Json.NET
var json = JsonConvert.SerializeObject(new MexcSubPersonalPayload("api_key", "api_secret"));
usage with System.Text.Json
var json = JsonSerializer.Serialize(new MexcSubPersonalPayload("api_key", "api_secret"));
UPDATE FROM THE COMMENTS
Combine javaSorted with GenerateSign
private static string GenerateSign(IDictionary<string, object> items, string apiSecret)
{
if (items?.Count == 0) return null; | {
"domain": "codereview.stackexchange",
"id": 43455,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map",
"url": null
} |
c#, .net, hash-map
if (string.IsNullOrWhiteSpace(apiSecret)) return null;
var builder = new StringBuilder();
foreach (var item in items.Where(x => !string.IsNullOrWhiteSpace(x.Value?.ToString())).OrderBy(x => x.Key, StringComparer.Ordinal))
{
var key = item.Key;
var value = item.Value.ToString();
if (builder.Length > 0)
{
builder.Append('&');
}
builder.Append($"{key}={HttpUtility.UrlEncode(value)}");
}
builder.Append("&api_secret=").Append(apiSecret);
//hash the payload
using var md5 = MD5.Create();
var sourceBytes = Encoding.UTF8.GetBytes(builder.ToString());
var hash = md5.ComputeHash(sourceBytes);
return Convert.ToHexString(hash).ToLowerInvariant();
} | {
"domain": "codereview.stackexchange",
"id": 43455,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map",
"url": null
} |
beginner, c, array, snake-game
Title: Simple snake game with C and raylib
Question: Made a simple snake game using C and raylib for graphics, Would like to be critiqued on the clearity and efficiency of the code.
#include <raylib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define DIRECTION_UP (Vec2i){0, -1}
#define DIRECTION_DOWN (Vec2i){0, 1}
#define DIRECTION_LEFT (Vec2i){1, 0}
#define DIRECTION_RIGHT (Vec2i){-1, 0}
enum GameState
{
GAME_START,
GAME_RUNNING,
GAME_OVER
};
enum CellState
{
CELL_EMPTY,
CELL_SNAKE,
CELL_APPLE
};
typedef unsigned uint;
typedef struct
{
int x, y;
} Vec2i;
typedef struct
{
uint *cells;
uint height, width;
} Board;
typedef struct
{
bool collided;
uint tailLength;
Vec2i headPosition;
Vec2i headDirection;
Vec2i *tail;
} Snake;
static uint gameState = GAME_START;
static uint gameScore = 0;
static Board board;
static Snake snake;
static Vec2i applePosition;
void board_set(Vec2i v, uint c)
{
#ifdef DEBUG
if (v.x > board.width || v.y > board.height)
{
fprintf(stderr, "Can not get board at (%d,%d).\n", v.x, v.y);
exit(1);
}
#endif
*(board.cells + v.x * board.width + v.y) = c;
}
uint board_get(Vec2i v)
{
#ifdef DEBUG
if (v.x > board.width || v.y > board.height)
{
fprintf(stderr, "Can not set board at (%d,%d).\n", v.x, v.y);
exit(1);
}
#endif
return *(board.cells + v.x * board.width + v.y);
}
void apple_spawn()
{
while (true)
{
//Spawn within bounds of the board
int x = (rand() % (board.width - 2)) + 1;
int y = (rand() % (board.height - 2)) + 1;
//Do not spawn on snake cells
if (board_get((Vec2i){x, y}) != CELL_SNAKE)
{
applePosition.x = x;
applePosition.y = y;
break;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43456,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, snake-game",
"url": null
} |
beginner, c, array, snake-game
break;
}
}
}
void snake_tail_grow()
{
snake.tailLength++;
if (snake.tailLength == 1)
{
snake.tail[snake.tailLength].x = snake.headPosition.x ;
snake.tail[snake.tailLength].y = snake.headPosition.y ;
return;
}
//Previous tail
snake.tail[snake.tailLength] = snake.tail[snake.tailLength - 1];
}
bool apple_eaten()
{
//Check if snake head is on the same cell as the apple
if (snake.headPosition.x == applePosition.x && snake.headPosition.y == applePosition.y)
return true;
return false;
}
void game_create(uint w, uint h)
{
board.cells = calloc(h * w, sizeof *(board.cells));
snake.tail = calloc(h * w, sizeof (Vec2i));//Allocate for longest tail length possible on the board
if (board.cells == NULL || snake.tail == NULL)
{
fprintf(stderr, "Failed to allocate memory.\n");
exit(1);
}
board.width = w;
board.height = h;
snake.tailLength = 0;
snake.headDirection.x = 0;
snake.headDirection.y = 0;
//Spawn snake at the center of the board
uint centerX = board.width / 2;
uint centerY = board.height / 2;
snake.headPosition.x = centerX;
snake.headPosition.y = centerY;
}
void game_destroy()
{
free(snake.tail);
free(board.cells);
}
void game_update()
{
//Clear board
memset(board.cells, CELL_EMPTY, board.height * board.width * sizeof *(board.cells));
//Update cells to be on the new positions
board_set(snake.headPosition, CELL_SNAKE);
board_set(applePosition, CELL_APPLE);
for (uint i = 0; i < snake.tailLength; i++)
board_set(snake.tail[i], CELL_SNAKE);
//Snake collision with board boundary
if (snake.headPosition.x >= board.width || snake.headPosition.x <= 0)
snake.collided = true;
if (snake.headPosition.y >= board.height || snake.headPosition.y <= 0)
snake.collided = true; | {
"domain": "codereview.stackexchange",
"id": 43456,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, snake-game",
"url": null
} |
beginner, c, array, snake-game
//Shift to last to make space for new tail
memmove(snake.tail + 1, snake.tail, snake.tailLength * sizeof *(snake.tail));
snake.tail[0] = snake.headPosition;
//Move snake in the direction
snake.headPosition.x += snake.headDirection.x;
snake.headPosition.y += snake.headDirection.y;
if (apple_eaten())
{
gameScore++;
snake_tail_grow();
apple_spawn();
}
if (snake.collided)
gameState = GAME_OVER;
}
void game_input()
{
if (IsKeyDown(KEY_W))
snake.headDirection = DIRECTION_UP;
if (IsKeyDown(KEY_S))
snake.headDirection = DIRECTION_DOWN;
if (IsKeyDown(KEY_D))
snake.headDirection = DIRECTION_LEFT;
if (IsKeyDown(KEY_A))
snake.headDirection = DIRECTION_RIGHT;
}
void game_draw()
{
uint widthRatio = GetScreenWidth() / board.width;
uint heightRatio = GetScreenHeight() / board.height;
for (uint x = 0; x < board.width; x++)
for (uint y = 0; y < board.height; y++)
{
switch (board_get((Vec2i){x, y}))
{
case CELL_SNAKE :
DrawRectangle(x * widthRatio, y * heightRatio, widthRatio, heightRatio, GREEN);
break;
case CELL_APPLE :
DrawRectangle(x * widthRatio, y * heightRatio, widthRatio, heightRatio, RED);
break;
}
}
//Draw score
DrawText(TextFormat("Score : %u", gameScore), 0, 0, 20, WHITE);
}
int main()
{
InitWindow(640, 640, "Snake");
SetTargetFPS(10);
game_create(20, 20);
apple_spawn();
while (!WindowShouldClose())
{
BeginDrawing();
ClearBackground(BLACK);
switch (gameState)
{
case GAME_START : | {
"domain": "codereview.stackexchange",
"id": 43456,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, snake-game",
"url": null
} |
beginner, c, array, snake-game
DrawText("Press space to start.", 0, 0, 40, WHITE);
DrawText("W,A,S,D keys for movement.", 0, 40, 25, WHITE);
if (IsKeyPressed(KEY_SPACE))
gameState = GAME_RUNNING;
break;
case GAME_RUNNING :
game_input();
game_update();
game_draw();
break;
case GAME_OVER :
DrawText("Game Over :(", 0, 0, 40, RED);
DrawText(TextFormat("Score : %u", gameScore), 0, 40, 40, WHITE);
DrawText("Press escape to exit.", 0, 80, 40, WHITE);
}
EndDrawing();
}
game_destroy();
CloseWindow();
return 0;
}
How did I do?
Answer: Since there's only one translation unit here, mark your functions static similar to what you've already done with your global variables.
I don't see a lot of value in typedef unsigned uint; - I'd delete that.
You follow what I consider to be a reasonable pattern for struct declaration - no tags, all typedefs. You do not do the same with your enum but for consistency's sake you should.
Your code is non-reentrant due to the reliance on global state. This isn't the end of the world, but a proper refactor would involve moving all of those variables to a game state structure and operating only on instances of that structure instead of globals. You ask:
should the game state structure be static as well?, also would you mind elaborating the global state part a bit more?
No, your game state data should not be made static: once it's removed from the global namespace, it will be passed around in parameters and return values. For an example of what this could look like:
typedef struct {
unsigned score;
// ...
} GameState;
static void game_update(GameState *game) {
// ...
if (apple_eaten())
{
game->score++;
} | {
"domain": "codereview.stackexchange",
"id": 43456,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, snake-game",
"url": null
} |
beginner, c, array, snake-game
You need more const arguments, particularly for struct arguments.
Why should your if (v.x > board.width || v.y > board.height) check be surrounded in an #ifdef DEBUG? This is surely not performance-impactful so should be left in release builds.
*(board.cells + v.x * board.width + v.y) is slightly awkward. You can instead use an index-indirection like
board.cells[v.x * board.width + v.y] = c;
This while(true):
while (true)
{
//Spawn within bounds of the board
int x = (rand() % (board.width - 2)) + 1;
int y = (rand() % (board.height - 2)) + 1;
//Do not spawn on snake cells
if (board_get((Vec2i){x, y}) != CELL_SNAKE)
{
applePosition.x = x;
applePosition.y = y;
break;
}
}
can more legibly capture the termination condition as
int x, y;
do {
// Spawn within bounds of the board
x = (rand() % (board.width - 2)) + 1;
y = (rand() % (board.height - 2)) + 1;
// Do not spawn on snake cells
} while (board_get((Vec2i){x, y}) == CELL_SNAKE);
applePosition.x = x;
applePosition.y = y;
I consider the early-return in snake_tail_grow to be more legibly replaced by an else:
static void snake_tail_grow()
{
snake.tailLength++;
if (snake.tailLength == 1)
{
snake.tail[snake.tailLength].x = snake.headPosition.x;
snake.tail[snake.tailLength].y = snake.headPosition.y;
}
else
{
//Previous tail
snake.tail[snake.tailLength] = snake.tail[snake.tailLength - 1];
}
}
The boolean expression in apple_eaten should be returned directly rather than returning literals conditionally:
return snake.headPosition.x == applePosition.x && snake.headPosition.y == applePosition.y;
Since the results of the conditionals in game_input are mutually exclusive, you should use else on all but the first if.
Why are your widthRatio and heightRatio uint? Why should they not be promoted to floats? | {
"domain": "codereview.stackexchange",
"id": 43456,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, snake-game",
"url": null
} |
python, python-3.x, search, binary-search
Title: Implementation and Testing of Exponential Search for scenario where we search the same array/list many times
Question: Exponential Search is an optimization over binary search.
Conceptually, when searching for a number target in a list of numbers nums, exponential search first finds into which power-of-two sized bucket nums[2**p: 2**(p+1)] the target falls into. E.g., if nums has a size of 30, then the buckets are nums[0:1], nums[1:2], nums[2:4], nums[4:8], nums[8:16], and nums[16:30]. After finding an appropriate bucket, say nums[lo:hi], then we do a standard binary search for target, but we limit our scope of search to just nums[lo:hi].
Here's my implementation of Exponential Search for a scenario where we want to search multiple/many targets within the same list of numbers:
from bisect import bisect_left, bisect_right
INF = float('inf')
class ExpSearch:
def __init__(self, nums, max_target=None):
self.N = len(nums)
self.nums = nums
self.max_target = INF if max_target is None else max_target
self.pows = []
self.part = []
i = 1
while i < self.N and nums[i] <= self.max_target:
self.pows.append(i)
self.part.append(nums[i])
i <<= 1
# (i == 1 and self.N <= 1 or nums[1] > self.max_target) or
# (i//2 < self.N and self.part[-1] == nums[i//2] <= self.max_target)
# i >= self.N or nums[i] > self.max_target
if i < self.N:
self.pows.append(i)
self.part.append(nums[i])
self.P = len(self.part) # == len(self.pows)
self.pows.append(self.N) # Force self.pows(self.P) == self.N
self.pows.append(0) # Force self.pows[-1] == 0
# (i >= self.N and self.part[-1] == nums[1 << (self.P - 1)] <= self.max_target) or
# (i < self.N and self.part[-1] == nums[1 << (self.P - 1)] > self.max_target) | {
"domain": "codereview.stackexchange",
"id": 43457,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, search, binary-search",
"url": null
} |
python, python-3.x, search, binary-search
def find_left(self, target, lo=0, hi=None):
assert target <= self.max_target
hi = self.N if hi is None else hi
p = bisect_left(self.part, target)
# self.part[:p] < target
# self.part[p:] >= target
# p == 0 or self.part[p-1] == self.nums[1 << (p-1)] < target
# p == self.P or self.part[p] == self.nums[1 << p] >= target
# lo = max(lo, 1 << (p-1) if p > 0 else 0)
# hi = min(hi, 1 << p if p < self.P else self.N)
lo = max(lo, self.pows[p-1])
hi = min(hi, self.pows[p])
return bisect_left(self.nums, target, lo, hi)
def find_right(self, target, lo=0, hi=None):
assert target <= self.max_target
hi = self.N if hi is None else hi
p = bisect_right(self.part, target)
# self.part[:p] <= target
# self.part[:p] > target
# p == 0 or self.part[p-1] == self.nums[1 << (p-1)] <= target
# p == self.P or self.part[p] == self.nums[1 << p] > target
# lo = max(lo, 1 << (p-1) if p > 0 else 0)
# hi = min(hi, 1 << p if p < self.P else self.N)
lo = max(lo, self.pows[p-1])
hi = min(hi, self.pows[p])
return bisect_right(self.nums, target, lo, hi)
Here's the code with fewer comments:
from bisect import bisect_left, bisect_right
INF = float('inf') | {
"domain": "codereview.stackexchange",
"id": 43457,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, search, binary-search",
"url": null
} |
python, python-3.x, search, binary-search
INF = float('inf')
class ExpSearch:
def __init__(self, nums, max_target=None):
self.N = len(nums)
self.nums = nums
self.max_target = INF if max_target is None else max_target
self.pows = []
self.part = []
i = 1
while i < self.N and nums[i] <= self.max_target:
self.pows.append(i)
self.part.append(nums[i])
i <<= 1
if i < self.N:
self.pows.append(i)
self.part.append(nums[i])
self.P = len(self.part) # == len(self.pows)
self.pows.append(self.N) # Force self.pows(self.P) == self.N
self.pows.append(0) # Force self.pows[-1] == 0
def find_left(self, target, lo=0, hi=None):
assert target <= self.max_target
hi = self.N if hi is None else hi
p = bisect_left(self.part, target)
lo = max(lo, self.pows[p-1])
hi = min(hi, self.pows[p])
return bisect_left(self.nums, target, lo, hi)
def find_right(self, target, lo=0, hi=None):
assert target <= self.max_target
hi = self.N if hi is None else hi
p = bisect_right(self.part, target)
lo = max(lo, self.pows[p-1])
hi = min(hi, self.pows[p])
return bisect_right(self.nums, target, lo, hi)
Any suggestions/improvements are welcome!
Can you think of a better name for self.part?
I use self.pows == [1 << p for p in range(self.P)] so that instead of doing 1 << p, I can just do self.pows[p]. Actually, self.pows == [1 << p for p in range(self.P)] + [self.N, 0]. The [self.N, 0] tail simplifies the lo = max(lo, ...) and hi = min(hi, ...) code.
A lot of the code is invariants (conditions that hold at that point of execution) as comments. Is there a better way to convey these invariants/conditions? | {
"domain": "codereview.stackexchange",
"id": 43457,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, search, binary-search",
"url": null
} |
python, python-3.x, search, binary-search
I also wrote some test code. My main priority is to get a code review on the implementation, but I would be glad to hear suggestions/comments about the test code as well.
from random import randint
from .expsearch import ExpSearch
N = 1_000 # 100_000
MIN = -10_000
MAX = 10_000
T = 100
def gen_nums(N, min_, max_):
return [randint(min_, max_) for _ in range(N)]
def test():
nums = gen_nums(N, MIN, MAX)
nums.sort()
ES = ExpSearch(nums)
for _ in range(T):
target = randint(MIN-0.1*abs(MIN), MAX+0.1*abs(MAX))
l = ES.find_left(target)
# assert all(num < target for num in nums[:l])
# assert all(num >= target for num in nums[l:])
assert l == 0 or nums[l-1] < target
assert l == N or nums[l] >= target
r = ES.find_right(target)
# assert all(num <= target for num in nums[:r])
# assert all(num > target for num in nums[r:])
assert r == 0 or nums[r-1] <= target
assert r == N or nums[r] > target
print(f"Passed with target = {target}")
The test code generates a sorted list of size N whose values lie within [MIN, MAX] == [-10_000, 10_000] inclusive. Then it runs T = 100 tests. In each test, a random target is generated. The random target is:
within [MIN, MAX] with chance greater than 80%,
below MIN with a >8% chance, and
above MAX with a >8% chance.
Then the test tries to find target within nums using both ExpSearch.find_left and ExpSearch.find_right. In each case, the test checks that the returned index is correct.
I ran the tests with two N's.
N = 1_000 produces a sparse nums since N == 1_000 << MAX - MIN == 20_000. It is unlikely that the generated nums has a lot of duplicates.
N = 100_000 produces a dense nums since N == 100_000 >> MAX - MIN == 20_000. It is guaranteed that the generated nums has duplicates (in fact, it has at least 80_000 duplicates).
All tests pass. | {
"domain": "codereview.stackexchange",
"id": 43457,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, search, binary-search",
"url": null
} |
python, python-3.x, search, binary-search
All tests pass.
Answer: (Exponential Search is an improvement over binary search
where the target can be expected to be close to some starting point.)
class ExpSearch does not have a documented purpose and scope of application.
Same applies to find_left() and find_right()
using binary search on the pre-determined "partition values" it does not implement exponential search:
The probing sequence is much different.
It should be conventional using part.index(target), instead - if lo was 0:
if lo != 0, the values in part aren't helpful in finding bounds for binary search
I think the "invariant comments" great.
The test doesn't exercise setting no and hi
Minor:
• P isn't really used
• using __init__(self, nums, max_target=INF) allows self.max_target = max_target
It would be great if the test compared measures of effort for binary & exponential search for uniform, binomial and exponential distribution. | {
"domain": "codereview.stackexchange",
"id": 43457,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, search, binary-search",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
Title: Design Shopping Cart System Interview Problem [Python 3]
Question: Just practicing some objected oriented design questions. Please let me know what can be improved to be more OOD and extensible. Thank you.
Functional Requirements
Cart can hold multiple products
A product has a name and price. Name is unique.
Should show the total price
Should show itemized price
Should be able to add/remove products
Follow up
Checkout
Inventory
Add/remove/apply promotions
Misc
def floor_to_nearest_two(number):
return int(number * 100) / 100
class NotEnoughCartItem(Exception):
def __init__(self):
super().__init__('Not enough items in the cart')
class NotEnoughInventoryItem(Exception):
def __init__(self):
super().__init__('Not enough items in the inventory')
class InvalidInput(Exception):
def __init__(self, msg):
super().__init__(msg)
Product
class Product:
def __init__(self, product_id, name, price):
self.product_id = product_id
self.name = name
self.price = price
def __str__(self):
return f'Product: {self.name}, Price: ${self.price}'
InventoryItem
class InventoryItem:
def __init__(self, product):
self.product = product
self.count = 0
def update_item_count(self, count):
if count == 0:
return
if count < 0 and self.count < count:
raise NotEnoughInventoryItem()
self.count += count
def __str__(self):
return f'{self.product}, Count: {self.count}'
CartItem
class CartItem:
def __init__(self, product):
self.product = product
self.count = 0
self.total_price = 0
def update_item_count(self, count):
self.count += count
price_delta = self.product.price * count
self.total_price += price_delta
return price_delta | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
return price_delta
# If the price of a product gets changed after the product is added to the cart,
# the cart should reflect it.
def recalculate_total_price(self):
self.total_price = self.product.price * self.count
def __str__(self):
return f'Product: {self.product.name}, Count: {self.count}, ' \
f'Total: ${floor_to_nearest_two(number=self.total_price)}'
Cart
class Cart:
def __init__(self):
self.items: dict[int, CartItem] = dict()
self.total_price = 0
def add_item(self, product, count=1):
if count <= 0:
raise InvalidInput('Count must be a positive integer.')
item = self.items.setdefault(product.product_id, CartItem(product))
price_delta = item.update_item_count(count=count)
self.total_price += price_delta
def remove_item(self, product, count=1):
if count <= 0:
raise InvalidInput('Count must be a positive integer.')
item = self.items.get(product.product_id, None)
if not item or item.count < count:
raise NotEnoughCartItem()
price_delta = item.update_item_count(count=-count)
self.total_price += price_delta
if item.count == 0:
del self.items[product.product_id]
def delete_item(self, product):
item = self.items.get(product.product_id, None)
if not item:
return
self.remove_item(product=product, count=item.count)
def empty_cart(self):
self.items.clear()
self.total_price = 0
def recalculate_total_prices(self):
self.total_price = 0
for item in self.items.values():
item.recalculate_total_price()
self.total_price += item.total_price
def __str__(self):
result = 'Cart\n'
for item in self.items.values():
result += f'{str(item)}\n' | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
result += f'Total Price: ${floor_to_nearest_two(number=self.total_price)}'
return result
Inventory
class Inventory:
def __init__(self):
self.items: dict[int, InventoryItem] = dict()
def add_item(self, product, count=1):
if count <= 0:
raise InvalidInput('Count must be a positive integer.')
item = self.items.setdefault(product.product_id, InventoryItem(product))
item.update_item_count(count=count)
def remove_item(self, product, count=1):
if count <= 0:
raise InvalidInput('Count must be a positive integer.')
item = self.items.get(product.product_id, None)
if not item or item.count < count:
raise NotEnoughInventoryItem()
item.update_item_count(count=-count)
def check_stock(self, product, count):
item = self.items.get(product.product_id, None)
if not item or item.count < count:
return False
return True
def __str__(self):
result = 'Inventory\n'
for item in self.items.values():
result += f'{item}\n'
return result
Promotions
class BasePromotion:
def __init__(self, name):
self.name = name
def apply_promotion(self, count, product_price):
raise NotImplementedError()
class DiscountPromotion(BasePromotion):
def __init__(self, name, discount_percentage):
super().__init__(name=name)
self.multiplier = 1 - discount_percentage / 100
def apply_promotion(self, count, product_price):
return count * product_price * self.multiplier
class BuyOneGetXPromotion(BasePromotion):
def __init__(self, name, x):
if x <= 0:
raise InvalidInput('x must be a positive integer')
super().__init__(name=name)
self.x = x
def apply_promotion(self, count, product_price):
divider = self.x + 1
return (count // divider + (0 if count % divider == 0 else 1)) * product_price | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
ReceiptItem
class ReceiptItem:
def __init__(self, product_name, price, count, original_total, final_total):
self.product_name = product_name
self.price = price
self.count = count
self.original_total = original_total
self.final_total = final_total
def __str__(self):
return f'{self.product_name}: ${self.price} * {self.count}.' \
f' Original: ${floor_to_nearest_two(number=self.original_total)}' \
f' => Final: ${floor_to_nearest_two(number=self.final_total)}'
Receipt
class Receipt:
def __init__(self):
self.items: list[ReceiptItem] = list()
self.original_total = 0
self.final_total = 0
def add_item(self, item: ReceiptItem):
self.items.append(item)
def __str__(self):
result = 'Receipt\n'
for item in self.items:
result += f'{str(item)}\n'
result += f'Original Total: ${floor_to_nearest_two(number=self.original_total)}\n'
result += f'Final Total: ${floor_to_nearest_two(number=self.final_total)}\n'
return result
CheckoutManager
class CheckoutManager:
def __init__(self, inventory: Inventory):
self.inventory = inventory
self.promotions: dict[int, BasePromotion] = dict()
def add_promo(self, product_id, promo: BasePromotion):
# Product does not need to exist in the inventory since the user may add the promo first.
# Latest promo overrides any existing ones.
self.promotions[product_id] = promo
def remove_promo(self, product_id):
if product_id not in self.promotions:
return
del self.promotions[product_id]
def checkout(self, cart: Cart):
if not cart.items:
raise NotEnoughCartItem() | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
def checkout(self, cart: Cart):
if not cart.items:
raise NotEnoughCartItem()
for cart_item in cart.items.values():
inventory_item = self.inventory.items.get(cart_item.product.product_id, None)
if not inventory_item or inventory_item.count < cart_item.count:
raise NotEnoughInventoryItem()
receipt = Receipt()
original_total_price = 0
final_total_price = 0
for cart_item in cart.items.values():
product = cart_item.product
self.inventory.remove_item(product=product, count=cart_item.count)
total_price = cart_item.total_price
original_total_price += total_price
receipt_item = ReceiptItem(
product_name=product.name, price=product.price, count=cart_item.count,
original_total=total_price, final_total=total_price)
receipt.add_item(item=receipt_item)
promo = self.promotions.get(product.product_id, None)
if promo:
total_price = promo.apply_promotion(count=cart_item.count, product_price=product.price)
receipt_item.final_total = total_price
final_total_price += total_price
receipt.original_total = original_total_price
receipt.final_total = final_total_price
cart.empty_cart()
print(f'Checkout Successful!\n{receipt}')
Test Code
def test():
fuji_apple = Product(product_id=1, name='Fuji Apple', price=2.5)
gala_apple = Product(product_id=2, name='Gala Apple', price=3)
milk = Product(product_id=3, name='Milk', price=4.99)
coke = Product(product_id=4, name='Coke', price=2) | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
inventory = Inventory()
inventory.add_item(product=fuji_apple, count=10)
inventory.add_item(product=gala_apple, count=100)
inventory.add_item(product=milk, count=50)
inventory.add_item(product=coke)
inventory.add_item(product=coke)
inventory.add_item(product=coke)
print(f'{inventory}\n')
fuji_discount_promo = DiscountPromotion(name='Fuji 30% Discount!', discount_percentage=30)
gala_discount_promo = DiscountPromotion(name='Gala 50% Discount!', discount_percentage=50)
milk_buy_one_get_3_promo = BuyOneGetXPromotion(name='Buy One Milk and Get Three!', x=3)
checkout_manager = CheckoutManager(inventory=inventory)
checkout_manager.add_promo(product_id=fuji_apple.product_id, promo=fuji_discount_promo)
checkout_manager.add_promo(product_id=gala_apple.product_id, promo=gala_discount_promo)
checkout_manager.add_promo(product_id=milk.product_id, promo=milk_buy_one_get_3_promo)
cart = Cart()
cart.add_item(product=fuji_apple)
cart.add_item(product=fuji_apple, count=3)
cart.add_item(product=gala_apple, count=5)
cart.add_item(product=milk, count=10)
cart.add_item(product=coke)
cart.add_item(product=coke)
cart.add_item(product=coke)
print(f'{cart}\n')
cart.remove_item(product=coke)
print(f'{cart}\n')
cart.remove_item(product=coke, count=2)
print(f'{cart}\n')
gala_apple.price = 1
print(f'{cart}\n')
cart.recalculate_total_prices()
print(f'{cart}\n')
cart.delete_item(product=milk)
print(f'{cart}\n')
cart.add_item(product=milk, count=9)
checkout_manager.checkout(cart=cart)
print(f'{cart}\n')
print(f'{inventory}\n') | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
Answer: Broadly speaking this does a lot of things right: self-written exceptions, (the start of) type hinting, overridden __str__, etc.
floor_to_nearest_two is dubious. There are better ways to round down - floor-division // probably suiting you - but you should you be rounding at all? And if you do, can you wait until the output stage? If you can wait (which is ideal), just use .2f in a format string or better yet call currency() which includes rounding and a currency symbol.
You need more type hints. You need to hint every method parameter and return value; if there's no return mark it -> None.
You can delete the __init__ from InvalidInput and assume the constructor of the parent; just write pass.
if count < 0 and self.count < count is odd. I guess you're passing a negative count if you're removing from inventory; but in a case like that, shouldn't it be
if count + self.count < 0
?
Your mutation model is problematic, and with it the update and recalculate methods. It's understandable for some of your classes to need to mutate, e.g. Cart; but at this scale re-calculating price subtotals and totals is so cheap that you should just have a one-pass total calculation function, no persisted totals or subtotals, and no price updating. Currently the recalculation strategy is fragile, vulnerable to bugs (even if there aren't any currently).
Prefer paren-wrapping () instead of escaping \ for multi-line string expressions.
dict() and list() are equivalent to literals {} and [].
Rather than loops like this:
for item in self.items.values():
result += f'{str(item)}\n'
prefer '\n'.join().
This:
def apply_promotion(self, count, product_price):
divider = self.x + 1
return (count // divider + (0 if count % divider == 0 else 1)) * product_price | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
is a little nasty. If I understand correctly, a more legible way of expressing this "buy one get X" is
divider = self.x + 1 # e.g. buy one get 3 -> divider = 4
groups = count // divider # number of item groups
if count % divider: # if purchase count is not an even multiple
groups += 1 # pay for the last group
return groups + product_price # pay once per group
Rather than remove_promo early-returning, invert the condition.
.get(x, None) is just .get(x).
You should convert your test method to actual tests - don't print; add asserts.
Suggested
Covering some of the above,
from locale import currency, LC_ALL, setlocale
setlocale(LC_ALL, '')
class NotEnoughCartItem(Exception):
def __init__(self):
super().__init__('Not enough items in the cart')
class NotEnoughInventoryItem(Exception):
def __init__(self):
super().__init__('Not enough items in the inventory')
class InvalidInput(Exception):
pass
class Product:
def __init__(self, product_id: int, name: str, price: float) -> None:
self.product_id = product_id
self.name = name
self.price = price
def __str__(self) -> str:
return f'Product: {self.name}, Price: {currency(self.price)}'
class InventoryItem:
def __init__(self, product: Product) -> None:
self.product = product
self.count = 0
def update_item_count(self, count: int) -> None:
if count == 0:
return
if count < 0 and self.count < count:
raise NotEnoughInventoryItem()
self.count += count
def __str__(self) -> str:
return f'{self.product}, Count: {self.count}'
class CartItem:
def __init__(self, product: Product) -> None:
self.product = product
self.count = 0
self.total_price = 0
def update_item_count(self, count: int) -> float:
self.count += count
price_delta = self.product.price * count
self.total_price += price_delta | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
price_delta = self.product.price * count
self.total_price += price_delta
return price_delta
def recalculate_total_price(self) -> None:
"""
If the price of a product gets changed after the product is added to the cart,
the cart should reflect it.
"""
self.total_price = self.product.price * self.count
def __str__(self) -> str:
return (
f'Product: {self.product.name}, Count: {self.count}, '
f'Total: {currency(self.total_price)}'
)
class Cart:
def __init__(self) -> None:
self.items: dict[int, CartItem] = {}
self.total_price = 0
def add_item(self, product: Product, count: int = 1) -> None:
if count <= 0:
raise InvalidInput('Count must be a positive integer.')
item = self.items.setdefault(product.product_id, CartItem(product))
price_delta = item.update_item_count(count=count)
self.total_price += price_delta
def remove_item(self, product: Product, count: int = 1) -> None:
if count <= 0:
raise InvalidInput('Count must be a positive integer.')
item = self.items.get(product.product_id)
if not item or item.count < count:
raise NotEnoughCartItem()
price_delta = item.update_item_count(count=-count)
self.total_price += price_delta
if item.count == 0:
del self.items[product.product_id]
def delete_item(self, product: Product) -> None:
item = self.items.get(product.product_id, None)
if item:
self.remove_item(product=product, count=item.count)
def empty_cart(self):
self.items.clear()
self.total_price = 0
def recalculate_total_prices(self) -> None:
self.total_price = 0
for item in self.items.values():
item.recalculate_total_price()
self.total_price += item.total_price | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
def __str__(self) -> str:
result = (
'Cart\n'
+ '\n'.join(str(item) for item in self.items.values())
+ f'Total Price: {currency(self.total_price)}'
)
return result
class Inventory:
def __init__(self) -> None:
self.items: dict[int, InventoryItem] = dict()
def add_item(self, product: Product, count: int = 1) -> None:
if count <= 0:
raise InvalidInput('Count must be a positive integer.')
item = self.items.setdefault(product.product_id, InventoryItem(product))
item.update_item_count(count=count)
def remove_item(self, product: Product, count: int = 1) -> None:
if count <= 0:
raise InvalidInput('Count must be a positive integer.')
item = self.items.get(product.product_id)
if not item or item.count < count:
raise NotEnoughInventoryItem()
item.update_item_count(count=-count)
def check_stock(self, product: Product, count: int) -> bool:
item = self.items.get(product.product_id, None)
if not item or item.count < count:
return False
return True
def __str__(self) -> str:
result = 'Inventory\n' + '\n'.join(str(v) for v in self.items.values())
return result
class BasePromotion:
def __init__(self, name: str) -> None:
self.name = name
def apply_promotion(self, count: int, product_price: float) -> float:
raise NotImplementedError()
class DiscountPromotion(BasePromotion):
def __init__(self, name: str, discount_percentage: float) -> None:
super().__init__(name=name)
self.multiplier = 1 - discount_percentage / 100
def apply_promotion(self, count: int, product_price: float) -> float:
return count * product_price * self.multiplier | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
class BuyOneGetXPromotion(BasePromotion):
def __init__(self, name: str, x: int) -> None:
if x <= 0:
raise InvalidInput('x must be a positive integer')
super().__init__(name=name)
self.x = x
def apply_promotion(self, count: int, product_price: float) -> float:
divider = self.x + 1
return (count // divider + (0 if count % divider == 0 else 1)) * product_price
class ReceiptItem:
def __init__(
self,
product_name: str,
price: float,
count: int,
original_total: float,
final_total: float,
) -> None:
self.product_name = product_name
self.price = price
self.count = count
self.original_total = original_total
self.final_total = final_total
def __str__(self) -> str:
return (
f'{self.product_name}: {currency(self.price)} * {self.count}.'
f' Original: {currency(self.original_total)}'
f' => Final: {currency(self.final_total)}'
)
class Receipt:
def __init__(self) -> None:
self.items: list[ReceiptItem] = []
self.original_total = 0
self.final_total = 0
def add_item(self, item: ReceiptItem):
self.items.append(item)
def __str__(self) -> str:
result = (
'Receipt\n'
+ '\n'.join(str(item) for item in self.items)
+ f'Original Total: {currency(self.original_total)}\n'
+ f'Final Total: {currency(self.final_total)}\n'
)
return result
class CheckoutManager:
def __init__(self, inventory: Inventory) -> None:
self.inventory = inventory
self.promotions: dict[int, BasePromotion] = dict()
def add_promo(self, product_id: int, promo: BasePromotion) -> None:
# Product does not need to exist in the inventory since the user may add the promo first.
# Latest promo overrides any existing ones.
self.promotions[product_id] = promo | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
def remove_promo(self, product_id: int) -> None:
if product_id not in self.promotions:
return
del self.promotions[product_id]
def checkout(self, cart: Cart) -> None:
if not cart.items:
raise NotEnoughCartItem()
for cart_item in cart.items.values():
inventory_item = self.inventory.items.get(cart_item.product.product_id)
if not inventory_item or inventory_item.count < cart_item.count:
raise NotEnoughInventoryItem()
receipt = Receipt()
original_total_price = 0
final_total_price = 0
for cart_item in cart.items.values():
product = cart_item.product
self.inventory.remove_item(product=product, count=cart_item.count)
total_price = cart_item.total_price
original_total_price += total_price
receipt_item = ReceiptItem(
product_name=product.name, price=product.price, count=cart_item.count,
original_total=total_price, final_total=total_price)
receipt.add_item(item=receipt_item)
promo = self.promotions.get(product.product_id, None)
if promo:
total_price = promo.apply_promotion(count=cart_item.count, product_price=product.price)
receipt_item.final_total = total_price
final_total_price += total_price
receipt.original_total = original_total_price
receipt.final_total = final_total_price
cart.empty_cart()
print(f'Checkout Successful!\n{receipt}')
def test() -> None:
fuji_apple = Product(product_id=1, name='Fuji Apple', price=2.5)
gala_apple = Product(product_id=2, name='Gala Apple', price=3)
milk = Product(product_id=3, name='Milk', price=4.99)
coke = Product(product_id=4, name='Coke', price=2) | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
inventory = Inventory()
inventory.add_item(product=fuji_apple, count=10)
inventory.add_item(product=gala_apple, count=100)
inventory.add_item(product=milk, count=50)
inventory.add_item(product=coke)
inventory.add_item(product=coke)
inventory.add_item(product=coke)
print(f'{inventory}\n')
fuji_discount_promo = DiscountPromotion(name='Fuji 30% Discount!', discount_percentage=30)
gala_discount_promo = DiscountPromotion(name='Gala 50% Discount!', discount_percentage=50)
milk_buy_one_get_3_promo = BuyOneGetXPromotion(name='Buy One Milk and Get Three!', x=3)
checkout_manager = CheckoutManager(inventory=inventory)
checkout_manager.add_promo(product_id=fuji_apple.product_id, promo=fuji_discount_promo)
checkout_manager.add_promo(product_id=gala_apple.product_id, promo=gala_discount_promo)
checkout_manager.add_promo(product_id=milk.product_id, promo=milk_buy_one_get_3_promo)
cart = Cart()
cart.add_item(product=fuji_apple)
cart.add_item(product=fuji_apple, count=3)
cart.add_item(product=gala_apple, count=5)
cart.add_item(product=milk, count=10)
cart.add_item(product=coke)
cart.add_item(product=coke)
cart.add_item(product=coke)
print(f'{cart}\n')
cart.remove_item(product=coke)
print(f'{cart}\n')
cart.remove_item(product=coke, count=2)
print(f'{cart}\n')
gala_apple.price = 1
print(f'{cart}\n')
cart.recalculate_total_prices()
print(f'{cart}\n')
cart.delete_item(product=milk)
print(f'{cart}\n')
cart.add_item(product=milk, count=9)
checkout_manager.checkout(cart=cart)
print(f'{cart}\n')
print(f'{inventory}\n')
if __name__ == '__main__':
test()
Output
Inventory
Product: Fuji Apple, Price: $2.50, Count: 10
Product: Gala Apple, Price: $3.00, Count: 100
Product: Milk, Price: $4.99, Count: 50
Product: Coke, Price: $2.00, Count: 3 | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, e-commerce
Cart
Product: Fuji Apple, Count: 4, Total: $10.00
Product: Gala Apple, Count: 5, Total: $15.00
Product: Milk, Count: 10, Total: $49.90
Product: Coke, Count: 3, Total: $6.00Total Price: $80.90
Cart
Product: Fuji Apple, Count: 4, Total: $10.00
Product: Gala Apple, Count: 5, Total: $15.00
Product: Milk, Count: 10, Total: $49.90
Product: Coke, Count: 2, Total: $4.00Total Price: $78.90
Cart
Product: Fuji Apple, Count: 4, Total: $10.00
Product: Gala Apple, Count: 5, Total: $15.00
Product: Milk, Count: 10, Total: $49.90Total Price: $74.90
Cart
Product: Fuji Apple, Count: 4, Total: $10.00
Product: Gala Apple, Count: 5, Total: $15.00
Product: Milk, Count: 10, Total: $49.90Total Price: $74.90
Cart
Product: Fuji Apple, Count: 4, Total: $10.00
Product: Gala Apple, Count: 5, Total: $5.00
Product: Milk, Count: 10, Total: $49.90Total Price: $64.90
Cart
Product: Fuji Apple, Count: 4, Total: $10.00
Product: Gala Apple, Count: 5, Total: $5.00Total Price: $15.00
Checkout Successful!
Receipt
Fuji Apple: $2.50 * 4. Original: $10.00 => Final: $7.00
Gala Apple: $1.00 * 5. Original: $5.00 => Final: $2.50
Milk: $4.99 * 9. Original: $44.91 => Final: $14.97Original Total: $59.91
Final Total: $24.47
Cart
Total Price: $0.00
Inventory
Product: Fuji Apple, Price: $2.50, Count: 6
Product: Gala Apple, Price: $1.00, Count: 95
Product: Milk, Price: $4.99, Count: 41
Product: Coke, Price: $2.00, Count: 3 | {
"domain": "codereview.stackexchange",
"id": 43458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, e-commerce",
"url": null
} |
python, programming-challenge
Title: Determine if Hill or Valley
Question: This is my accepted submission for LeetCode. The problem is
You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j].
Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index.
Return the number of hills and valleys in nums. | {
"domain": "codereview.stackexchange",
"id": 43459,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
(from LeetCode website)
It seemed to make the most sense to break this out by cases basically using if/elif. Due to rules, it also made sense to me at the time to reverse the list and go backwards in order to find whether still in a hill or valley. Do you see any improvements I could make?
class Solution(object):
def countHillValley(self, nums):
hills = 0
valley = 0
for index, item in enumerate(nums):
lastIndex = len(nums)-1
prevItem = nums[index-1]
nextItem = 0
if index != lastIndex:
nextItem = nums[index+1]
# no left neighbor
if index == 0:
hills += 0
valley += 0
# last index, no right neighbor
elif index == lastIndex:
# at last index there is no non-equal
# neighbor on the right
# so index is neither a hill or a valley
hills += 0
valley += 0
elif item > prevItem and item > nextItem:
hills += 1
elif item < prevItem and item == nextItem:
# enumerate over remainder of list
# start at next index
# This creates a list slice
# until find next non-equal neighbor
for interiorIndex, interiorItem in enumerate(nums[index:]):
if interiorItem != item:
if item < interiorItem:
valley += 1
break
if item > interiorItem:
hills += 0
break
elif item < prevItem and item < nextItem:
valley += 1
elif item < prevItem and item > nextItem:
valley += 0
elif item > prevItem and item < nextItem:
valley += 0
elif item == prevItem and item > nextItem:
reversedList = reversed(list(enumerate(nums[:index])))
for prevIndex, prevItem in reversedList:
if prevItem != item: | {
"domain": "codereview.stackexchange",
"id": 43459,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
for prevIndex, prevItem in reversedList:
if prevItem != item:
if item < prevItem:
hills += 0
valley += 0
break
if item > prevItem:
hills += 0
break
elif item > prevItem and item == nextItem:
for interiorIndex, interiorItem in enumerate(nums[index:]):
if interiorItem != item:
if item > interiorItem:
hills += 1
break
else:
valley += 0
break
return hills+valley | {
"domain": "codereview.stackexchange",
"id": 43459,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
Answer: The primary problem with your current implementation is its logical
complexity. Your code looks generally reasonable and LeetCode says it works,
so that's great -- congratulations in achieving the most important goal.
However, I must admit that I lacked the patience to give it in-depth study.
There's just a lot going on: several variables to mutate to keep track of
things; several if-else branches to handle the different possibilities; and,
worst of all, inner loops to look-ahead or look-behind to deal with the pesky
problem of adjacent equal values. Rather than spend too much effort reviewing
your specific code in great detail, I'll offer a different implementation
that illustrates a few useful techniques that apply to many
other types of problems.
Technique 1a: grouping equal values. As noted, the worst part of your
current implementation is handling adjacent equal values. But those values
don't affect the final result at all. So let's just get rid of them before
doing anything else. Python's
groupby
function can do many useful things and is worth learning about, but its
simplest behavior is to group equal values. The function emits (KEY, GROUP)
tuples where the "key" is the value and the "group" is an iterable of those
values. More commonly, one uses the function so that groups of related values
can be processed in batches together, but in our case, we can ignore the groups
and retain only the keys. This will give us a sequence with no pesky duplicates
sitting side-by-side.
Technique 1b: pre-processing the data. More broadly, sometimes
the best thing you can do to simplify a problem is to refuse to
accept the provided data as given. When solving a problem on LeetCode,
during a job interview, or when working on a project, don't be afraid
to think a bit outside the box: rather than puzzling over how to solve
the problem with the data at hand, try to imagine whether a different
organization of the data (or a subset of it) would make life easier. | {
"domain": "codereview.stackexchange",
"id": 43459,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
organization of the data (or a subset of it) would make life easier.
Which leads us to the next technique.
Technique 2: zipping to look-behind or look-ahead in sequences. Many
programming problems ask us to process a sequence of values while also knowing
things about nearby values in the sequence. That's annoying because one has to
worry about out-of-bounds problems. The resulting code tends to become
logically complex as we keep track of prior values or attempt to peek ahead
toward future values. A nice alternative is to zip the sequence together with a
shifted version of itself, which allows us to process each value with full
knowledge of its neighbors.
Technique 3: remembering that bool is a subclass of int. Specifically,
true and false can function as one and zero in a numeric context. This
means our function can just return a sum of logical evaluations.
Putting the techniques together. The code below illustrates one way to
solve the problem. Although LeetCode was happy with it, it is not optimized for
raw speed. Rather, its focus is code simplicity and intuitiveness: no if-else
logic; no mutation of status values; just just two steps involving data
reorganization and a final stage to sum over some boolean checks.
from itertools import groupby | {
"domain": "codereview.stackexchange",
"id": 43459,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
class Solution(object):
def countHillValley(self, nums):
# Get rid of adjacent equal values.
nums = [n for n, g in groupby(nums)]
# Zip the sequence to itself so we can evaluate each number
# alongside its neighbors to the left and right.
z = zip(nums[:-2], nums[1:-1], nums[2:])
# Count the hills and valleys.
return sum(
lft > n < rgt or lft < n > rgt
for lft, n, rgt in z
) | {
"domain": "codereview.stackexchange",
"id": 43459,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
go
Title: The levers puzzle
Question: I started playing Pathfinder: Kingmaker, and very soon ended up in a room with 6 levers, and a task to open a secret door by manipulating the levers. I assumed that the correct position for all the levers is up. But when you flip a single lever, one or two other levers also flip. For example, if you flip lever one, then levers two and four also flip, when you flip lever two, lever one also flips, etc.
But you know what, programming is more fun than playing games, so let's figure out what levers we need to pull in what sequence to get all of them up!
Feedback sought: I'm novice in golang, anything goes!
package main
import (
"fmt"
"strings"
)
type node struct {
state int // a bitmask for every possible levers' configuration, lever one is the least significant bit, 1 is up, 0 is down
neighbours []int // all configurations (states, above) that are reachable by flipping a single lever
levers map[int]int // lookup that given a neighbour state gives what lever is pulled to reach this state
}
// given levers configuration, print it out in human-readable format
func formatState(state int, width int) string {
var sb strings.Builder
for i := 0; i < width; i++ {
var desc string
if state&1 == 0 {
desc = "down"
} else {
desc = "up"
}
state >>= 1
sb.WriteString(fmt.Sprintf("%d - %s; ", i+1, desc))
}
result := sb.String()
if len(result) > 2 { // remove final "; "
result = result[:len(result)-2]
}
return result
} | {
"domain": "codereview.stackexchange",
"id": 43460,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go",
"url": null
} |
go
func printSolution(graph []node, prev map[int]int, start, end, width int) {
path := []int{end}
for z := end; z != start; z = prev[z] {
path = append(path, prev[z])
}
for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
path[i], path[j] = path[j], path[i]
}
for i := 1; i < len(path); i++ {
fmt.Printf("Pull lever %d:\n", graph[path[i-1]].levers[path[i]]+1)
fmt.Println(formatState(path[i], width))
}
}
// Simplified Dijkstra's algorithm
// https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode
func search(graph []node, start, end int) map[int]int {
q := []int{start}
prev := map[int]int{}
dist := map[int]int{}
for len(q) > 0 {
u := q[0]
q = q[1:]
if u == end {
return prev
}
for _, v := range graph[u].neighbours {
alt := dist[u] + 1
if i, ok := dist[v]; !ok || alt < i {
prev[v] = u
dist[v] = alt
q = append(q, v)
}
}
}
return nil
}
func initGraph(levers []int) []node {
var graph = make([]node, 1<<len(levers))
for i := 0; i < len(graph); i++ {
graph[i].state = i
graph[i].levers = make(map[int]int)
for j := 0; j < len(levers); j++ {
n := i ^ levers[j]
graph[i].neighbours = append(graph[i].neighbours, n)
graph[i].levers[n] = j
}
}
return graph
} | {
"domain": "codereview.stackexchange",
"id": 43460,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go",
"url": null
} |
go
func main() {
// This can come from an external input, but let's not overcomplicate:
var levers = []int{
0b001011, // lever one flips levers one, two and four
0b000011, // lever two flips levers one, and two
0b100100, // lever three flips levers three, two and six
0b011001, // lever four flips levers one, four and five
0b111000, // lever five flips levers four, five and six
0b110100, // lever six flips levers three, five and six
}
width := len(levers)
graph := initGraph(levers)
start := 0b011111
end := 0b111111
fmt.Printf("Starting poisition:\n%s\n", formatState(start, width))
fmt.Printf("Goal poisition:\n%s\n", formatState(end, width))
prev := search(graph, start, end)
if prev != nil {
printSolution(graph, prev, start, end, width)
} else {
fmt.Println("Solution not found")
}
}
Program output:
Starting poisition:
1 - up; 2 - up; 3 - up; 4 - up; 5 - up; 6 - down
Goal poisition:
1 - up; 2 - up; 3 - up; 4 - up; 5 - up; 6 - up
Pull lever 1:
1 - down; 2 - down; 3 - up; 4 - down; 5 - up; 6 - down
Pull lever 2:
1 - up; 2 - up; 3 - up; 4 - down; 5 - up; 6 - down
Pull lever 3:
1 - up; 2 - up; 3 - down; 4 - down; 5 - up; 6 - up
Pull lever 5:
1 - up; 2 - up; 3 - down; 4 - up; 5 - down; 6 - down
Pull lever 6:
1 - up; 2 - up; 3 - up; 4 - up; 5 - up; 6 - up
Answer:
You don't need to explicitly initialize the graph. It is waste of time and space. The graph has a very regular and predictable structure, so the neighbors could be computed on the fly during traversal.
map is a heavyweight structure, and looks like an overkill (again, the graph is very regular). A simple [] int, indexed by state seems to suffice both for prev and dist.
A single-letter identifiers (i, u, v in search) are kind of hard to follow. ok and alt are not of a great help either. | {
"domain": "codereview.stackexchange",
"id": 43460,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go",
"url": null
} |
go
States in the output table are misaligned. Consider changing the description to " up" (or something else of the same length as "down". | {
"domain": "codereview.stackexchange",
"id": 43460,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go",
"url": null
} |
c#, multithreading, .net, networking, udp
Title: NTP client displaying reference, originate, receive and transmit timestamps periodically with graceful shutdown in C#
Question: based on this stackoverflow topic: https://stackoverflow.com/a/12150289/15270760 I have decided to create a simple NTP client displaying difference between NTP server response and DateTime.Now called right after receiving NTP response. I was just curious of the result. I have read both RFC's 2030 and 1305 and it appered to me that there are four different timestamps, not as I expected, one. I have decided to cover all four of them. I was just curious of the result, again. I humbly ask for a code review based on this snippet of code. At the beggining I would like to emphasise that this is a simple console application so please don't be too harsh on me for keeping the Main() method name.
public sealed class NTP
{
public static void Main()
{
// Source: https://stackoverflow.com/a/12150289/15270760
const string ntpServer = "time.windows.com";
var address = Dns.GetHostEntry(ntpServer).AddressList.FirstOrDefault();
if (address is null) throw new Exception("No ntp server found");
var udpClient = new UdpClient();
var ntpServerEndpoint = new IPEndPoint(address, 123);
udpClient.Connect(ntpServerEndpoint);
udpClient.Client.ReceiveTimeout = 3000;
var tokenSource = new CancellationTokenSource();
Task.WaitAny(new Task[]
{
Task.Run(() => DisplayNtpServerResponsePeriodically(udpClient, ntpServerEndpoint, tokenSource)),
Task.Run(() => ReadUserInput(tokenSource)),
});
udpClient.Close();
} | {
"domain": "codereview.stackexchange",
"id": 43461,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, multithreading, .net, networking, udp",
"url": null
} |
c#, multithreading, .net, networking, udp
private static void ReadUserInput(CancellationTokenSource tokenSource)
{
var userInput = Console.ReadLine();
while (userInput != "q" && userInput != "Q")
{
userInput = Console.ReadLine();
}
Console.WriteLine("Closing application...");
tokenSource.Cancel();
}
private static async Task DisplayNtpServerResponsePeriodically(UdpClient udpClient,
IPEndPoint ntpServerEndpoint, CancellationTokenSource tokenSource)
{
while (!tokenSource.Token.IsCancellationRequested)
{
var bytesBuffer = new byte[48];
// Based on RFC 2030:
// Leap Indicator: First two bits - warning of an impending leap second to be inserted/deleted
// Version Number: Middle three bits - indicating version number, 011 equal to IPv4 only
// Mode values: Last three bits - indicating the mode, 011 equal to client mode
bytesBuffer[0] = 0b00011011;
udpClient.Send(bytesBuffer);
bytesBuffer = udpClient.Receive(ref ntpServerEndpoint);
var serverResponseReceivedDateTime = DateTime.Now;
var ntpServerTimestamps = GetNtpTimeStamps(bytesBuffer);
Console.WriteLine($"{ntpServerTimestamps.ToString(serverResponseReceivedDateTime)}");
await Task.Delay(5000);
}
}
private static NtpServerTimestamps GetNtpTimeStamps(byte[] bytesBuffer)
{
var fieldsIndexes = new int[] { 16, 24, 32, 40 }; | {
"domain": "codereview.stackexchange",
"id": 43461,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, multithreading, .net, networking, udp",
"url": null
} |
c#, multithreading, .net, networking, udp
var timestampsArray = new DateTime[4];
for (var i = 0; i < fieldsIndexes.Length; i++)
{
ulong seconds = BitConverter.ToUInt32(bytesBuffer, fieldsIndexes[i]);
ulong secondsFraction = BitConverter.ToUInt32(bytesBuffer, fieldsIndexes[i] + 4);
seconds = ConvertToLittleEndianUnsignedLong(seconds);
secondsFraction = ConvertToLittleEndianUnsignedLong(secondsFraction);
var milliseconds = (seconds * 1000) + ((secondsFraction * 1000) / 0x100000000L);
var dateTime =
(new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
timestampsArray[i] = dateTime;
}
return new NtpServerTimestamps(timestampsArray);
}
// Source: stackoverflow.com/a/3294698/162671
static uint ConvertToLittleEndianUnsignedLong(ulong x)
{
return (uint) (((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
private sealed class NtpServerTimestamps
{
private DateTime _referenceTimestamp { get; }
private DateTime _originateTimestamp { get; }
private DateTime _receiveTimestamp { get; }
private DateTime _transmitTimestamp { get; }
public NtpServerTimestamps(DateTime[] datetimeArray)
{
_referenceTimestamp = datetimeArray[0].ToLocalTime();
_originateTimestamp = datetimeArray[1].ToLocalTime();
_receiveTimestamp = datetimeArray[2].ToLocalTime();
_transmitTimestamp = datetimeArray[3].ToLocalTime();
} | {
"domain": "codereview.stackexchange",
"id": 43461,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, multithreading, .net, networking, udp",
"url": null
} |
c#, multithreading, .net, networking, udp
public string ToString(DateTime serverResponseReceivedDateTime)
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine($"-------------------NTP Server Response-------------------");
stringBuilder.AppendLine($"Reference: {_referenceTimestamp}:{_referenceTimestamp.Millisecond}");
stringBuilder.AppendLine($"Originate: {_originateTimestamp}:{_originateTimestamp.Millisecond}");
stringBuilder.AppendLine($"Receive: {_receiveTimestamp}:{_receiveTimestamp.Millisecond}");
stringBuilder.AppendLine($"Transmit: {_transmitTimestamp}:{_transmitTimestamp.Millisecond}");
stringBuilder.AppendLine($"Now: {serverResponseReceivedDateTime}:{serverResponseReceivedDateTime.Millisecond}");
stringBuilder.AppendLine("");
stringBuilder.AppendLine($"Reference-Now difference: {(serverResponseReceivedDateTime - _referenceTimestamp).TotalMilliseconds}");
stringBuilder.AppendLine($"Originate-Now difference: {(serverResponseReceivedDateTime - _originateTimestamp).TotalMilliseconds}");
stringBuilder.AppendLine($"Receive-Now difference: {(serverResponseReceivedDateTime - _receiveTimestamp).TotalMilliseconds}");
stringBuilder.AppendLine($"Transmit-Now difference: {(serverResponseReceivedDateTime - _transmitTimestamp).TotalMilliseconds}");
return stringBuilder.ToString();
}
}
}
Answer: Here are my observations
DisplayNtpServerResponsePeriodically
0b00011011: I would suggest to move such magic number into a const/static readonly
I would also recommend to do not reuse outgoing buffer as an incoming buffer
Last but not least Task.Delay should also receive the CancellationToken to avoid waiting "unnecessary" 5 seconds | {
"domain": "codereview.stackexchange",
"id": 43461,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, multithreading, .net, networking, udp",
"url": null
} |
c#, multithreading, .net, networking, udp
// Based on RFC 2030:
// Leap Indicator: First two bits - warning of an impending leap second to be inserted/deleted
// Version Number: Middle three bits - indicating version number, 011 equal to IPv4 only
// Mode values: Last three bits - indicating the mode, 011 equal to client mode
private static readonly byte[] Request_Bytes = new byte[] { 0b00011011 };
private static async Task DisplayNtpServerResponsePeriodically(UdpClient udpClient,
IPEndPoint ntpServerEndpoint, CancellationTokenSource tokenSource)
{
while (!tokenSource.Token.IsCancellationRequested)
{
udpClient.Send(Request_Bytes);
var bytesBuffer = udpClient.Receive(ref ntpServerEndpoint);
var serverResponseReceivedDateTime = DateTime.Now;
var ntpServerTimestamps = GetNtpTimeStamps(bytesBuffer);
Console.WriteLine($"{ntpServerTimestamps.ToString(serverResponseReceivedDateTime)}");
await Task.Delay(5000, tokenSource.Token);
}
}
BTW: ntpServerTimestamps.ToString(serverResponseReceivedDateTime): here the ToString name feels really unnatural
Most of the time ToString can receive a formatter parameter
So, I would suggest to find some different name here
GetNtpTimeStamps
Yet again move the magic numbers into const/static readonly fields
Please find some better naming here, I've just extracted them from the method
private static readonly DateTime baseTime = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static readonly int[] fieldsIndexes = new int[] { 16, 24, 32, 40 };
private const int MilliSecondMultiplier = 1_000;
private const long MilliSecondDivider = 0x100_000_000;
I would also suggest to use a List for timestamps rather than an array
It is much easier to use (.Add instead of [i])
It allows you to use foreach instead of for
You don't need to use brackets because of the operator precedence | {
"domain": "codereview.stackexchange",
"id": 43461,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, multithreading, .net, networking, udp",
"url": null
} |
c#, multithreading, .net, networking, udp
You don't need to use brackets because of the operator precedence
private static NtpServerTimestamps GetNtpTimeStamps(byte[] bytesBuffer)
{
var timestamps = new List<DateTime>(fieldsIndexes.Length);
foreach (var index in fieldsIndexes)
{
ulong seconds = BitConverter.ToUInt32(bytesBuffer, index);
ulong secondsFraction = BitConverter.ToUInt32(bytesBuffer, index + 4);
seconds = ConvertToLittleEndianUnsignedLong(seconds);
secondsFraction = ConvertToLittleEndianUnsignedLong(secondsFraction);
var milliseconds = seconds * MilliSecondMultiplier + secondsFraction * MilliSecondMultiplier / MilliSecondDivider;
timestamps.Add(baseTime.AddMilliseconds((long)milliseconds));
}
return new NtpServerTimestamps(timestamps.ToArray());
}
NtpServerTimestamps's ctor
It feels a bit clumsy to receive an array and then use it to retrieve items based on their positions
Maybe passing all four parameters separately is more explicit and less fragile
NtpServerTimestamps's ToString
If you introduce the following two helper methods
private string FormatDateTimeToDisplay(string prefix, DateTime timestamp)
=> $"{prefix}: {timestamp}:{timestamp.Millisecond}";
private string FormatDateTimesToDisplay(string prefix, DateTime received, DateTime timestamp)
=> $"{prefix}-Now difference: {(received - timestamp).TotalMilliseconds}";
And you are replacing the StringBuilder to a simple string.Join(Environment.NewLine, then your code would become much more readable | {
"domain": "codereview.stackexchange",
"id": 43461,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, multithreading, .net, networking, udp",
"url": null
} |
c#, multithreading, .net, networking, udp
public string ToString(DateTime serverResponseReceivedDateTime)
=> string.Join(Environment.NewLine, new[] {
"-------------------NTP Server Response-------------------",
FormatDateTimeToDisplay("Reference", _referenceTimestamp),
FormatDateTimeToDisplay("Originate", _originateTimestamp),
FormatDateTimeToDisplay("Receive", _receiveTimestamp),
FormatDateTimeToDisplay("Transmit", _transmitTimestamp),
FormatDateTimeToDisplay("Now", serverResponseReceivedDateTime),
"",
FormatDateTimesToDisplay("Reference", serverResponseReceivedDateTime, _referenceTimestamp),
FormatDateTimesToDisplay("Originate", serverResponseReceivedDateTime, _originateTimestamp),
FormatDateTimesToDisplay("Receive", serverResponseReceivedDateTime, _receiveTimestamp),
FormatDateTimesToDisplay("Transmit", serverResponseReceivedDateTime, _transmitTimestamp)
});
Yet again the ToString name feels a bit weird here | {
"domain": "codereview.stackexchange",
"id": 43461,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, multithreading, .net, networking, udp",
"url": null
} |
c, array
Title: Type safe generic array in c
Question: Here is my type safe dynamic array. I'm eventually going to make a hash table in C. I'm just wondering if anything seems wrong or out of place. Thanks.
#ifndef DARRAY_HEADER_INCLUDED
#define DARRAY_HEADER_INCLUDED
#include <stdlib.h>
#include <assert.h>
#include <string.h> | {
"domain": "codereview.stackexchange",
"id": 43462,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, array",
"url": null
} |
c, array
#define darray_deff(name, type)\
struct name {\
size_t capacity;\
size_t size;\
type *data;\
};\
void name##_grow(struct name *const _array, size_t const _capacity);\
void name##_reserve(struct name *const _array, size_t const _capacity);\
void name##_destroy(struct name *const _array);\
void name##_push(struct name *const _array, type const _value);\
void name##_push_unintialized(struct name *const _array, size_t const _amount);\
void name##_pop(struct name *const _array);\
type *name##_begin(struct name *const _array);\
type *name##_end(struct name *const _array);\
void name##_clear(struct name *const _array);\
int name##_empty(struct name *const _array);\
void name##_zero(struct name *const _array);\
\
void name##_grow(struct name *const _array, size_t const _capacity) {\
type *data = realloc(_array->data, _capacity * sizeof(type));\
assert(data);\
_array->data = data;\
_array->capacity = _capacity;\
}\
void name##_reserve(struct name *const _array, size_t const _capacity) {\
if(_capacity > _array->capacity) {\
name##_grow(_array, _capacity);\
}\
}\
void name##_destroy(struct name *const _array) {\
free(_array->data);\
_array->capacity = 0;\
_array->size = 0;\
}\
void name##_push(struct name *const _array, type const _value) {\
if(_array->size == _array->capacity) {\
size_t const capacity = (_array->capacity ? _array->capacity : 1);\
name##_grow(_array, capacity * 2);\
}\
_array->data[_array->size] = _value;\
++_array->size;\
}\
void name##_push_unintialized(struct name *const _array, size_t const _amount) {\
if(_array->size + _amount > _array->capacity) {\
size_t const new_capacity = _array->size + _amount;\
name##_grow(_array, new_capacity);\
}\
_array->size = _array->size + _amount;\
}\
inline void name##_pop(struct name *const _array) {\
--_array->size;\
}\
inline type *name##_begin(struct name *const _array) {\
return _array->data;\
}\ | {
"domain": "codereview.stackexchange",
"id": 43462,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, array",
"url": null
} |
c, array
}\
inline type *name##_begin(struct name *const _array) {\
return _array->data;\
}\
inline type *name##_end(struct name *const _array) {\
return _array->data + _array->size;\
}\
inline void name##_clear(struct name *const _array) {\
_array->size = 0;\
}\
inline int name##_empty(struct name *const _array) {\
return _array->size == 0;\
}\
void name##_zero(struct name *const _array) {\
memset(_array->data, 0, sizeof(type) * _array->size);\
}\ | {
"domain": "codereview.stackexchange",
"id": 43462,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, array",
"url": null
} |
c, array
#endif // DARRAY_HEADER_INCLUDED
```
Answer: Reduce clutter
const of an object serves little purpose in declarations other than to clutter code. This is the interface users often reference to understand the code. Make it easier for them.
// void name##_grow(struct name *const _array, size_t const _capacity);
void name##_grow(struct name * _array, size_t _capacity);
Add const to enquiry functions
// int name##_empty(struct name *const _array);
int name##_empty(const struct name *const _array);
// ^^^^^
Use bool for logical results
#include <stdbool.h>
// int name##_empty(struct name *const _array);
bool name##_empty(struct name *const _array);
Aside: personally I like isempty() vs. empty().
Tolerate a NULL on destroy
As free(NULL) is OK, allow name##_destroy(NULL) to simplify clean-up.
Guard against popping an empty table in name##_pop()
Missing name##_shrink()
It differs from name##_grow() in that shrinking to 0 and a result of NULL is OK.
I'd expect a good hash table function set to shrink selectively as well as grow.
Useful to add name##_apply()
int apply(array, state, func) applies function func(state, &element) to each element of the array.
Apply to each element as long as return value is 0. With a non-zero return, stop applying to the rest and return that value.
Very useful for printing each element and iterating the array.
pop() misnamed
I'd except a pop to return a value.
// void name##_pop(struct name *const _array)
type name##_pop(struct name *const _array)
Deeper
There are advantages for having a hash table size that is a prime - better hashing. To that end, for .capacity, I'd use an index into a look-up table of select primes - typical primes just smaller than powers-of-2. | {
"domain": "codereview.stackexchange",
"id": 43462,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, array",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, tic-tac-toe
Title: Design Tic Tac Toe Interview Problem [Python 3]
Question: Practicing objected oriented design. This time, it's designing the TicTacToe game. One difference between the real TicTacToe game is that I've made my TicTacToe game to have variable sized board.
Please review in terms of OOD and I've also left some comments in my code where I want feedback in particular. Thank you very much in advance.
Misc
from enum import Enum
from typing import Union, Optional, Callable
class InvalidInput(Exception):
pass
class SpotTaken(Exception):
def __init__(self, pos_x: int, pos_y: int) -> None:
super().__init__(f'({pos_x}, {pos_y}) is already taken!')
class GameNotRunning(Exception):
def __init__(self) -> None:
super().__init__('Game is currently not running.')
class InvalidBoardSize(Exception):
def __iter__(self) -> None:
super().__init__('Board size must be a positive integer.')
TicTacToe
class TicTacToe:
DEFAULT_BOARD_SIZE = 3
# Should this be inside the TicTacToe class or outside?
class Turn(str, Enum):
X = 'X'
O = 'O'
def __str__(self) -> str:
return self.value
# Should this be inside the TicTacToe class or outside?
class State(Enum):
RUNNING = 0
TURN_WON = 1
TIE = 2
def __init__(self, board_size: Optional[int] = None) -> None:
if board_size is not None and board_size <= 0:
raise InvalidBoardSize()
self.board_size = board_size or self.DEFAULT_BOARD_SIZE
self.board: list[list[Union[None, str]]] = [[None] * self.board_size for _ in range(self.board_size)]
self.turn = self.Turn.X
self.state = self.State.RUNNING
self.spots_left = self.board_size * self.board_size
def do_turn(self, pos_x: int, pos_y: int) -> None:
if self.state != self.State.RUNNING:
raise GameNotRunning() | {
"domain": "codereview.stackexchange",
"id": 43463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, tic-tac-toe",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, tic-tac-toe
if pos_x < 0 or pos_x >= self.board_size or pos_y < 0 or pos_y >= self.board_size:
raise InvalidInput('pos_x or pos_y is out of bounds!')
if self.board[pos_x][pos_y]:
raise SpotTaken(pos_x=pos_x, pos_y=pos_y)
self.board[pos_x][pos_y] = self.turn
self.spots_left -= 1
self._check_state()
if self.state == self.State.RUNNING:
self._change_turn()
# Optimally, I don't have to check all 8 possible ways.
# Technically, I only need to check the vertical of the column pos_y, the horizontal of the row pos_x,
# and the diagonals if the (pos_x, pos_y) overlaps with any of the points on the diagonal path.
# However, just to have a simpler code, just do the check on all 8 ways always.
# Since, these are such simple operations, it should not affect the performance really, anyway.
def _check_state(self) -> None:
# vertical check
for row in range(self.board_size):
winning_line_found = True
for col in range(self.board_size):
if self.board[row][col] != self.turn:
winning_line_found = False
break
if winning_line_found:
self.state = self.State.TURN_WON
return
# horizontal check
for col in range(self.board_size):
winning_line_found = True
for row in range(self.board_size):
if self.board[row][col] != self.turn:
winning_line_found = False
break
if winning_line_found:
self.state = self.State.TURN_WON
return | {
"domain": "codereview.stackexchange",
"id": 43463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, tic-tac-toe",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, tic-tac-toe
# top left to bottom right diagonal check
winning_line_found = True
for i in range(self.board_size):
if self.board[i][i] != self.turn:
winning_line_found = False
if winning_line_found:
self.state = self.State.TURN_WON
return
# top right to bottom left diagonal check
winning_line_found = True
for i in range(self.board_size):
if self.board[i][self.board_size - i - 1] != self.turn:
winning_line_found = False
if winning_line_found:
self.state = self.State.TURN_WON
return
if self.spots_left == 0:
self.state = self.State.TIE
def _change_turn(self) -> None:
self.turn = self.Turn.X if self.turn == self.Turn.O else self.Turn.O
def _get_status_msg(self) -> str:
if self.state == self.State.RUNNING:
msg = f'{self.turn}\'s turn.'
elif self.state == self.State.TURN_WON:
msg = f'{self.turn} WON!'
else:
msg = 'It\'s a TIE'
return msg
def _get_board_display(self) -> str:
return '\n'.join(str([str(val) if val else ' ' for val in row]) for row in self.board)
def __str__(self) -> str:
return (f'{self._get_board_display()}\n'
f'{self._get_status_msg()}')
TicTacToe CLI Manager
class TicTacToeCLIManager:
class State(Enum):
DETERMINE_BOARD_SIZE = 0
RUN_GAME = 1
ASK_RESTART = 2
QUIT = 3
def __init__(self) -> None:
self.tic_tac_toe: Union[TicTacToe, None] = None
self.state = self.State.DETERMINE_BOARD_SIZE
def run(self) -> None:
while self.state != self.State.QUIT:
self.STATE_TO_HANDLER[self.state](self) | {
"domain": "codereview.stackexchange",
"id": 43463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, tic-tac-toe",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, tic-tac-toe
def _handle_determine_board_size_state(self) -> None:
print('Determine the size of the board')
board_size = None
while board_size is None:
user_input = input()
try:
board_size = int(user_input)
except ValueError:
print('The size of the board must be an integer')
try:
self.tic_tac_toe = TicTacToe(board_size=board_size)
except InvalidBoardSize:
print('The size of the board has to be a positive integer')
return
print(self.tic_tac_toe)
self.state = self.State.RUN_GAME
def _handle_run_game_state(self) -> None:
user_input = input()
user_input_split = user_input.split(' ')
try:
pos_x, pos_y = int(user_input_split[0]), int(user_input_split[1])
except (ValueError, IndexError):
print('Inputs must have at least two integers separated by a space')
print(self.tic_tac_toe)
return
try:
self.tic_tac_toe.do_turn(pos_x=pos_x, pos_y=pos_y)
except (InvalidInput, SpotTaken):
print('Pick the position correctly, please')
print(self.tic_tac_toe)
if self.tic_tac_toe.state != self.tic_tac_toe.State.RUNNING:
self.state = self.State.ASK_RESTART
def _handle_ask_restart_state(self) -> None:
print('Do you want to replay? If so, type y')
user_input = input()
if user_input == 'y':
self.state = self.State.DETERMINE_BOARD_SIZE
else:
self.state = self.State.QUIT | {
"domain": "codereview.stackexchange",
"id": 43463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, tic-tac-toe",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, tic-tac-toe
# I want to put this constant STATE_TO_HANDLER at the top of the class. I don't like constants being at the bottom.
# However, if I put this above these methods, it cannot find the references to the methods.
# What's the best practice regarding this?
#
# I wanted to put typing on the Callable's parameter and return types. Eg. Callable[[TicTacToeCLIManager], None]
# However, the parameter type would be TicTacToeCLIManager and it cannot find the reference here
# since the TicTacToeCLIManager definition is not finished.
# What's the best practice regarding this, too?
STATE_TO_HANDLER: dict[State, Callable] = {
State.DETERMINE_BOARD_SIZE: _handle_determine_board_size_state,
State.RUN_GAME: _handle_run_game_state,
State.ASK_RESTART: _handle_ask_restart_state,
}
runner
def test():
TicTacToeCLIManager().run()
Answer: This is an incomplete review up to the function TicTacToe.turn
Re: if pos_x < 0 or pos_x >= self.board_size or pos_y < 0 or pos_y >= self.board_size:
An alternative to if x < min_x or x > max_x is if not min_x <= x <= max_x. I think the latter is more readable, but that's up to opinion. In this case, if you wanted to make the change, you'd change if pos_x < 0 or pos_x >= self.board_size to if not 0 <= pos_x < self.board_size and likewise for pos_y.
Suggest you rename self._check_state() to self._update_state() or something that indicates that the function might modify state.
# Optimally, I don't have to check all 8 possible ways.
This comment is only valid for a board size of 3. In general, an N x N board would have 2N + 2 possible "ways", so it might be beneficial to implement the optimization you mentioned. I.e. this optimization:
# Technically, I only need to check the vertical of the column pos_y, the horizontal of the row pos_x,
# and the diagonals if the (pos_x, pos_y) overlaps with any of the points on the diagonal path. | {
"domain": "codereview.stackexchange",
"id": 43463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, tic-tac-toe",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, tic-tac-toe
Horizontal check
# vertical check
for row in range(self.board_size):
winning_line_found = True
for col in range(self.board_size):
if self.board[row][col] != self.turn:
winning_line_found = False
break
If you consider rows to be horizontal and columns to be vertical, then this is actually a # horizontal check
Second, the code can be simplified to
horiz_winning_line_found = any(row == [self.turn] * self.board_size for row in self.board)
or, better yet, if y_pos is passed into self._check_state as an argument, you can just do
horiz_winning_line_found = self.board[y_pos] == [self.turn] * self.board_size
If you decide to go with this, it would make sense to make [self.Turn.X] * self.board_size and [self.Turn.O] * self.board_size into class variables of the TicTocToe class.
This not the most OOP thing to do, but if you consider a different representation of X and O on the board where X is marked by -1 and O is marked by +1, then the check state code could be simplified further. For example,
horiz_winning_line_found = self.board[y_pos] == [self.turn] * self.board_size
would become
horiz_winning_line_found = abs(sum(self.board[y_pos])) == self.board_size
also self._change_turn would simplify to
def _change_turn(self) -> None:
self.turn *= -1
Vertical check
If you pass x_pos into self._check_state, then you can simplify the vertical winning line check to just
vert_winning_line_found = all(self.board[r][x_pos] == self.turn for r in range(self.board_size))
or
vert_winning_line_found = ''.join(self.board[r][x_pos] for r in range(self.board_size) == [self.turn] * self.board_size
You are mixing terms like (rows, columns) with (x_pos, y_pos). I would suggest you rename (x_pos, y_pos) to (c, r), (col, row), (colNum, rowNum) or something to that effect so that everything is in terms of rows and columns. | {
"domain": "codereview.stackexchange",
"id": 43463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, tic-tac-toe",
"url": null
} |
python, python-3.x, object-oriented, interview-questions, tic-tac-toe
If you do end up passing x_pos and y_pos to self._check_state, here's a quick way to check whether x_pos, y_pos lie on the diagonal
# NW to SE diagonal
check_main_diag = x_pos == y_pos
# SW to NE diagonal
check_minor_diag = x_pos == self.board_size - 1 - y_pos
then you can just do
main_diag_winning_line = check_main_diag * all(self.board[i][i] == self.turn for i in range(self.board_size))
and something similar for minor_diag_winning_line | {
"domain": "codereview.stackexchange",
"id": 43463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented, interview-questions, tic-tac-toe",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.