instruction stringlengths 71 71.9k |
|---|
I am working on a project where I need to consume lot of records and then I am sending these records to some other system which uses zeromq.
Here is the flow:
Store all the incoming records in a CHM from multiple threads. Records will come at a very high speed.
From a background thread which runs every 30 seconds, sen... |
I just built my first scraper and I'd like to get your thoughts on the structure and the way I went about it. The basic premise of the script:
Get a random movie from IMDb's Top 250
Ask the user whether they've seen it before. If yes, print another random movie. If no, tell them to enjoy the movie and the script ends.... |
I wrote this code for Pascal's Triangle using recursion. Can someone please help me to review it for better performance?
# argument count is number of rows which is entered from terminal.
def pascal_t(count,input_list=0):
if not count: exit() # if count is 0 program will exit.
if not input_list: # to print fi... |
I am attempting the matched brackets problem. I have written a Python program which seems to do the job but is very slow and thus exceeds the time limit. Please help me making this code more efficient. I have explained my code in the comments.
length = int(input())
inp = input().split(' ')
inp = [ int(x) for x in inp ]... |
I currently have something like this:
Price price = new Price();
ActualValue actualValue = new ActualValue();
actualValue.setValue(price.getPreviousPrice().getRegion().getValue());
I want to make sure when calling getRegion() and getValue(), no NPE is thrown, trying to make it write in one line so I thought about usin... |
I'm still new to python, but my history is in the C/C++ world with plenty of Makefiles, though I've rarely written from scratch such elaborate ones as this. The Hitchhiker's Guide to Python gave me permission to use a Makefile to organize my Python project, so that's what I did.
I'm looking for suggestions on how to m... |
I don't know much about the design of cryptographic hash functions but despite that I made an attempt for the sake of learning. This is what I got:
#include <stdio.h>
void hash(int* bits, int bitsLen, int* out, int outLen){
const int tt[9] = {1,2,0,0,0,1,1,2,2};
int st[128], i, k, j, y, a, b, o = 0;
for (i=0; i<... |
This is a pseudo-follow up to Kotlin Data Class Wildcard: taking in advice from that question I came upon a better but quite different solution to the same problem.
The problem: fuzzy matching AST nodes. All regular properties should be checked for equality normally (via ==), but allowing any absent value to match a re... |
I'm relatively new to Python, coming from a deep C++ background. I'm mostly looking for feedback on how to make my code more idiomatic/pythonic, but I would welcome and appreciate any and all other feedback as well.
This code uses the Python library PyEphem, which builds upon XEphem, an X (UNIX GUI) program that's an ... |
I created this simple responsive layout for my web apps and website projects. I'd like to ask if you see any flaws or bad practices in this code? A working demo can be seen here http://codepen.io/anon/pen/QdavpZ/ Thank you in advance, for any efforts.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
... |
I am writing a custom form validation script compatible with IE8+. I just wanted to make sure I am not messing anything up. I have tested on IE8 its works. However, I want to make sure I am doing it the right way.
var wrapper = document.querySelector('.wrapper');
var btn = document.querySelector('button');
var in... |
The Collatz Sequence is an iterative sequence that is defined for all positive integers as such:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
If 13 were to be entered into this sequence, the result would be as follows:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
And the total number of terms in the chain would be 10. The s... |
I have in this class bellow, a method that gets the date from a file according to the name of the client. For each client, the method to extract the date is different. I want to use heritage or any other way to have a generic class without conditions, by putting all the specific code in somewhere else. I tried to creat... |
As part of a programming challenge, we are tasked with creating a function with an undetermined number of successive calls. As an example, let's say the function returns simply the sum of the provided arguments, it should work as follows :
sum(4)() // 4
sum(4)(5)() // 9
sum(4)(5)(9)() // 18
sum(4)(5)(9)(1)() // 19
// e... |
I wrote a function that returns a dictionary with statistics (memory usage, time, speed) based on another function that copies files/folders. I want to check if this is a good method or if you have any other suggestions or methods to improve it.
def get_copy_stats(funct, args):
stats = {}
mem_usg_bef = get_proc... |
In an ASP.NET MVC application (C#) have a factory-like class that generates settings objects of ISettingType for my application. However, some settings are very simple and a standard built-in such as a string or number type value can also suffice. I think that the way that I'm doing this is very much a code smell tho... |
I have began taking the CS50 course on EDX the past couple of days, and one of the tasks to accomplish was to write a credit card validator in C. I wrote it in C, and then I thought that I could go about the same thing in Python, and wrote the same program in Python. For those of you unfamiliar with the problem, here i... |
Can anyone give me recommendations on how to improve my code?
using System;
namespace mybinsearch2
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int key = int.Parse(Console.ReadLine());
int[] arr = new int[n]; int ... |
The following is a class for curl wrapper.
This class will be called like:
class curlWrapper {
private:
CURLcode curlCode;
CURL* curlHandle;
struct curl_slist *header = NULL;
MemoryStructA response;
static std::atomic<int> numberOfCurlProcess;
static std::atomic<bool> isGlobalInitCalled;... |
What should I call a variable that is used for indentation?
private string _indentString = "\t"; // can be set to " " or "\t\t", etc.
Is the purpose of the variable clear from the name?
|
I've written a pretty minimal parser for terminfo files which works as intended. It compiles fine and I've actually setup some tests over here which pass successfully too. Now I would like to get it reviewed. There are docs too.
Please skip over long list of enum members (which I've shortened quite a bit for reviewing)... |
I was playing with TCP/IP, and came across this 16 bit checksum function:
unsigned short csum(unsigned short *ptr,int nbytes)
{
register long sum;
unsigned short oddbyte;
register short answer;
sum=0;
while(nbytes>1) {
sum+=*ptr++;
nbytes-=2;
}
if(nbytes==1) {
oddby... |
This is my first time I tried to implement a custom STL vector with iterator. I have some questions:
What are better ways to write an iterator?
I know that there is a const iterator so in my case I need to create a second class for iterator? Is there any approachable way to not repeat yourself with second (and others)... |
I created a simple module, that is used to work as Enumeration. It can store all values with binary keys, so you can find them using binary pattern. It's called grouping.
Groups have the same structure as all values in enum, but their ids(binary keys) are composed from keys of values, that they contains.
Example of enu... |
Given a numbered table of contents with headers and the content of each section, I wanted to sort them correctly according to only the numeric value.
The first challenge: section numbers can be tricky to sort (i.e. sorted(["1.1.1", "1.1.2", "1.1.10"]) results in: ["1.1.1", "1.1.10", "1.1.2"] which is alphabetically cor... |
I am working on a tax calculator for a school assignment and was hoping to get some feedback on my current progress. I kind of feel like I over-complicated the code.
NOTE: I am required to do all of this in one single .java file otherwise I would have broken it up into separate files.
import java.util.Scanner;
class ... |
I coded a little implementation to encrypt and decrypt bytes with AES256 (ECB) in C#. I wanted to know if I can optimize/cleanup my code a bit more, or if it i fine like this:
using System;
using System.Security.Cryptography;
using System.Text;
namespace AES256
{
class Program
{
private static string ... |
When tossing a dice many many time all numbers tend to appear the same number of times, but if the number of throws is small then some numbers may appear more or less often than others, even considerably if the sample size is small enough.
This program shows a updating in real time graph of SIDES bars (6 in default), e... |
I have a program that is working, but it takes way too long to get the answer. With input like
15 100000000
111010111001100
The program checks for 15 numbers, and checks if two number beside the numbers in the second row adds up to exactly 1. If it adds up to 1, then the number would stay/change to 1, otherwise it cha... |
This is my implementation of a recursive binary search in C++. I'm still a newbie at C++ so:
Have I used any bad practices?
How could the code be improved upon in terms of efficiency?
Could recursion cause a stack overflow error, and if so how can I avoid this?
Criticism is welcome and appreciated!
#include<iostream... |
The algorithm needs to reduce an RDD[GPSRecord] based on the distance between several points, e.g. "give me only GPS records when the distance between them exceeds 15m".
Right now the algorithm is not interpolating points. It collects a point if it detects that the next value has a distance between it and the last poin... |
I am looking to replicate in Swift what the FFT function does in Matlab. Essentially, it takes an arbitrary length signal (not necessarily a multiple of \$2^n\$) and gives real and complex DFT coefficients.
Since the FFT described in Accelerate can only handle sample sizes that are multiples of \$2^n\$, I wrote a brute... |
pathmunge is an often-seen function in shell initialization files, used to add entries to the PATH environment variable without duplication. Examples:
Fedora /etc/profile's pathmunge.
How can I cleanly add to $PATH? - Unix & Linux
Unix shell function for adding directories to PATH
I wrote this pathmunge variation in ... |
I have code where I validate deviceId and clientId basis on what ProcessType is coming:
public static boolean isValid(ProcessType processType, Record record) {
String deviceId = DataUtils.extract(record, "deviceId");
String clientId =DataUtils.extract(record, "clientId");
if(processType == ProcessType.AB... |
Problem statement
A queen is standing on an \$n\$x\$n\$ chessboard. The chessboard's rows are numbered from \$1\$ to \$n\$, going from bottom to top; its columns are numbered from \$1\$ to \$n\$, going from left to right. Each square on the board is denoted by a tuple, \$(r,c)\$, describing the row, \$r\$, and column, ... |
Here is my code to serialize and deserialize binary tree, which may have a lot of empty nodes. I am written in Python 2.7. Any advice on performance improvement in terms of algorithm time complexity, bugs or code style advice is appreciated.
My major idea is, serialize only non-empty nodes, with node ID information, wh... |
From past year ,i have been mainly working on Js, and so have started implementing Algo Questions in js .can it be implemented in a better way.
/**
* Implementaion to find if a number can be expressed as x^y
* x is assumed to be >=0
*/
var canBeExpressedAsXraisedToY = function (n) {
if (n == 0 && n == 1) {
consol... |
I am implementing a DP-based range minimum query data structure and algorithm in Python 2.7. Any advice on algorithm time complexity improvements, code bugs or code style issues are appreciated.
More information about range minimum query.
from collections import defaultdict
import random
def build_rmq(numbers):
rmq... |
Problem statement
There are a total of \$n\$ courses you have to take, labeled from
\$0\$ to \$n - 1\$.
Some courses may have prerequisites, for example to take course \$0\$
you have to first take course \$1\$, which is expressed as a pair:
\$[0,1]\$
Given the total number of courses and a list of prerequisite
... |
I have a bunch of functions that return promises and need to chain them together. However, it's currently difficult to read and I would expect it to be even harder to maintain.
I have a function that performs the following actions:
Logs off any inactive users.
Verifies a user's credentials.
Creates a session and logs ... |
Here is my implementation of a doubly linked list. Basic functionality seems to be working fine. Please let me know your comments on the coding style and algo.
DoublyLinkedListNode.java
public class DoublyLinkedListNode<T>
{
private T DataItem;
private DoublyLinkedListNode<T> nextNode;
private DoublyLinkedL... |
I've written a heapsort implementation. It's generic: generic comparators and sequences with elements of a generic type.
The implementation (follows closely chapter 6 from Introduction to Algorithms 3rd Edition and) consists of
heapify: establishes the heap property for an element:
template<typename BiDirIterator, typ... |
The problem will take more than 2 minutes, so if you don't have much time I wouldn't recommend you to deal with the problem.
I found this paper on how to program "a new efficient ellipse detection method", so I thought why not just try it. I programmed it in Python but my implementation is - in contrast to the title ... |
I use the following function in a PowerShell script to check and - depending on the value of the $Action - either add or remove an Active Directory User Object from a Security Group.
Function Update-Group-Membership ($Action, $ADUser_Properties, $GroupName, $LogPathFileName) {
$CurrentGroupMembers = Get-ADGroupMem... |
I often need to perform LinQ queries to get distinct items from a IEnumerable based on one of its properties. I would like to know if this is a good way to wrap this operation:
<Extension()> Function DistinctOn(Of T)(iet As IEnumerable(Of T),
identity_property As Func(Of T, Objec... |
This code is built in flask, it allows a user to edit a title and a description of a div.
I have used the X-editable library which allows a user to edit text and use ajax requests.
I also process the value of the edited text and using python insert it into a mysql database.
The code works fine it is editing and saving ... |
Background
(these are the bits technically not for review, but feel free to point out any minor points)
An Entity class can be identified by a name and at least one alias:
public final class Entity {
private final String name;
private final Set<String> aliases;
public Entity(String name) {
this(na... |
I have written the following function to preprocess some text data as input to machine learning algorithm. It lowercase, tokenises, removes stop words and lemmatizes, returning a string of space-separated tokens. However, this code runs extremely slowly. What can I do to optimise it?
import os
import re
import csv
impo... |
My existing code has a scheduler that we init when a DataStore constructor is called.
private void initSchedulers() {
int initialDelay = applicationStartupConfig.getSchedulerInitialDelay();
int refreshPeriod = applicationStartupConfig.getSchedulerRefreshPeriod();
// above are fetched using config.yml(dropwi... |
This is a PHP script I wrote it back in 2015 and have been updating it since.
It is a MySQLI wrapper called SqlObject (class) that was originally created to be used by multiple different calling functions so the same SQL connection would be used, unlike some other wrappers (or code) that opens a connection for each que... |
I'm working on an implementation of a Wagner-Fischer-Algorithm for an online programming challenge site, but I can't seem to push the time down to where it needs to be. The assignment is to, for a number of different 'misspelled' words \$w_1, w_2, \dots , w_n\$ and a dictionary \$D\$ compute the editing distances betwe... |
I am trying to improve some code I did not write, mostly to make it easier for other people to understand (I found it to be really weirdly written). I attempted to rewrite it, and it does basically the same thing, using roughly the same processes.
However, the old one takes about 2 minutes to run with some data I recor... |
This is my first python/pygame program. Instead of using images I tried drawing with pygame.draw.line() and pygame.draw.arc() with time.sleep() for animation, but this adds delay.
I have commented that code before the while loop in main method.
Problem is, it still takes time to render as I have added pygame.time.Cloc... |
I'm working with a file format which stores data as a tree. Each node in the tree is known as a Tag, and every tag has a name and a value. The order of tags is not guaranteed, but the general structure is. For example, in the diagram below, the CompoundTag "John Smith" and "Albert Einstein" have the same structure even... |
I had never programmed in a functional programming language before. I think that this function has large nesting. Is there way to rewrite it better? I am most worried about the use of "flatten". Is there way to get rid of it? Also, is the indentation correct and does the function name correspond to Clojure naming style... |
I just wanted to share my newly created JavaScript code. This code is responsible for passing back only the unique elements for a given array. This one is quite useful when you have a huge array and you store objects with huge arrays.
Use case: you want to sort out all unique object to do provide a filtering mechanism ... |
Two lists of dictionaries. Dicts in A and B can be matched by a particular dict key that may be identical or similar. The result should be a list of the source key from A, the matching key from B, and an additional key from B.
Both lists are constructed using screen-scraping, so you normally don't get to see them (unle... |
I have written a piece of code that calculates how to cut pipes based on an order and fixed raw pipe length (in this case 288 feet), but I am not 100% happy with my current code as it counts the pipe pieces that have been created for each length in column C (see comment in code) and clears column C at the end. Is there... |
I have this in place for an RSA Key generation class. I force the user to swipe on the screen randomly and use that as a entropy pool.
class TouchRandom extends SecureRandom {
private final Stack<Byte> pool = new Stack<>();
@Override
public synchronized void nextBytes(byte[] bytes) {
for (int i = ... |
I have just written my first program in C#. Please explain:
Have I used any bad practices?
How could the code be improved?
I would appreciate if provide the changed code so and some comments so that I could see what was wrong and do some further reading to correct my mistakes. The program works fine.
using System;
us... |
I'm trying to brute force a Vigenere Cipher knowing only that the key length is 5+ characters and that the decrypted text has the word Hello, Andi. So I wrote this small Java program that tries to brute-force the key through a given numbers of threads and nested while loops.
Run.java (main class)
package vignere;
impo... |
Realized I have never implemented heap sort.
So here is my first attempt:
#include <iterator>
#include <tuple>
/*
0 => 1 2
1 => 3 4
2 => 5 6
3 => 7 8
4 => 9 10
5 => 11 12
6 => 13 14
P => P*2 + 1, P*2 + 2
C => (C-1)/2
*/
template<typename I>
class HeapSorter
{
I getParent(I root, I child)
{ ... |
I am creating a class with a constructor and instead of double handling, I thought I would use a one line conditional and if the class property is not set correctly then console.log out a message.
I want to know if there is a cleaner implementation for the following height property as at the moment I don't think readab... |
I have written a Python one-liner that permutes a given string. I wrote this just for fun using list comprehensions and I would like to get feedback from the community.
def permute(c, s=""):
return [s] if len(s) == len(c) else [x for y in [permute(c, e) for e in [s[0:i]+c[len(s)]+s[i:] for i in xrange(len(s)+1)]] f... |
I'm very new to python, however not new to programming as I've been doing C for some time.
So here is my practice of a merge sort, I looked at other questions however they were many more lines compared to mine. Which leaves me to believe I'm doing something wrong.
I come here to look for best practices in python, and I... |
I wrote the following functions to merge sort an array of Comparables. It seems to work well (I am testing the output to make sure it is sorted). It takes about 2.5 sec for 10 million randomly generated strings. However, when I use the system sort by calling Arrays.sort(), it takes about 18 seconds. Why this huge discr... |
I am provided a bunch of dates in the format (YYYYMMDD) such as:
date='20170503'
My goal is to convert that date into the number of days in the given year. For example, it would convert:
20170130 to 30
20170201 to 32
20151231 to 365
Here is my solution:
import pandas as pd
my_date = pd.to_datetime(date, format='%Y%m... |
I'm a student learning to code in C. I had to make a program for class to reverse lines of input from the keyboard (not character wise, but reverse the order of the lines input).
The program is working to the requirements of the assignment already, but feel free to have a look at my code and help me understand where I ... |
This is my solution to the Algorithmic Crush problem from HackerRank. Can I get any comments regarding where I can improve the code to be more efficient?
You are given a list of size \$N\$, initialized with zeroes. You have
to perform \$M\$ operations on the list and output the maximum of
final values of all the \... |
Trying to implement Heap Sort in Scala
class HeapSort
{
private def swap(array: Array[Int], lhs: Int, rhs: Int) =
{
val tmp = array(lhs);
array(lhs) = array(rhs);
array(rhs) = tmp;
}
private def getParent(child: Int): Int = (child - 1) / 2;
private def getChildren(parent: Int... |
I just wonder whether it is a common approach to hit the third-party API and fetch values within the initialize method?
Ex.
class BalanceTransaction::Update
include Service
attr_reader :offset, :transactions
def initialize(offset)
@offset = offset
@transactions = fetch_transactio... |
I have the latest version of ReSharper installed and I am trying to write a Unit Test for my MVC controller. I need the Unit Test to:
Ensure the ViewModel passed to the View is of the correct type.
So here is what I have at the moment:
public void Create_HasCorrectViewModelType()
{
// arrange
var controller =... |
I have to write a Dog Creator class. I initially wrote this code:
<?php
class Dog
{
private $id, $name, $size, $age;
public function setId($id){
$this->id = $id
}
public function setName($name){
$this->name = $name;
}
public function setSize($size){
$this->size = $size;
}
public function se... |
Today I have coded a simple function that will get a room model, if its already been loaded in to the dictionary then it will just return it, if its not in the dictionary if will try its best to load it from the database. I just wondered is this the best way I can do ths? or is there a better way...
public bool TryGetM... |
I have coded a quick room model system, let me run you should how it exactly works
X = 1 square
0 = block square
1 = 1 level higher
2 = 2 levels higher
and so on...
Example, a simple room model structure would be like below:
XXXXXXXXXX0XX
XXXXXXXXXX0XX
XXXXXXXXXX0XX
XXXXXXXXXX0XX
XXXXXXXXXX0XX
XXXXXXXXXX0XX
XXXXXXXX... |
I have the following password policy:
At least 8 characters in length
At least one digit
At least one special* character
*I consider any character that is not a letter, digit or space to be a special character.
I've come up with the following regex for enforcing this policy, and it seems to be working.
^(?=.*?[0-9... |
I want to check the memory usage of a process before and after I copy a large file or folder, and also, I want to get the maximum memory usage during file operation. Is this a good method?
def copy_folder(s,d):
if os.path.isdir(d):
shutil.rmtree(d)
shutil.copytree(s, d)
return get_folder_size(s)
de... |
Could someone tell me how I can improve this please? It's similar to my other question just another version of it.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sahara.Base.Game.Rooms
{
internal class Active... |
I'm currently taking an introductory course to Bash at my university, and was hoping to get some peer-review from whoever might have some time.
Full disclosure: the quality of the code isn't considered when the professor gives a grade as assignments only yield a PASS!
I've had very limited exposure to bash before taki... |
I noticed this old class of mine:
class SvgDrawing:
def __init__(self, print_layout):
self.print_layout = print_layout
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'svg_start.txt'), mode='r') as f:
self.svg_start = f.read()
with open(os.path.join(os.path.... |
I calculate the lowest quarter-hour using the following code:
public Date getQuarter() {
Calendar calendar = Calendar.getInstance();
int mins = calendar.get(Calendar.MINUTE);
if (mins < 15) {
mins = 0;
} else if (mins < 30) {
mins = 15;
} else if (mins < 45) {
mins = 30;
... |
Intro
This simple script will allow me to check for a specific opened port on a list of domains that I own. Instead of manually doing this check, I found Python a pretty good idea for such a task.
After profiling my code, I found out that def check_for_open_ports(): is really slow. It takes about 0:01:16.799242 seconds... |
I've created a little program that basically does the same thing as psexec. It will connect to a host via computer name, or IP address, run the given command, and log the output into a file (little extra for myself). I would like some critique on what I've done, what can I do better, what did I do well, etc.. Some key ... |
I'm having an issue defining a base class and child classes, which handle initialization differently. I want it to work in ES6 but allow babel to transpile to ES5, and currently babel does not have a backwards compatible translation for new.target so I'm looking for something "close enough".
class Complex {
construct... |
I am currently creating a system that allows a user to claim a coupon, after the coupon is claimed the receive currency on their account.
I recently ran into an issue in which if 2 requests with the same coupon code were fired at almost the exact same time my web service call would accept both (probably because of the ... |
I have coded a prize system in where I add a prize in the database and it calls the CheckPrizes(player) every time a player logs in to the application. I won't go in to detail of how they log in but thats the basics of it.
PrizeManager.cs:
using System;
using System.Collections.Concurrent;
using System.Collections.Gene... |
I am trying to write a small python code,where
I am reading a text file-which contains both Multiwords (MWEs)
and singular words (NMWEs).
I am trying to tag each one, as follows.
I have a dictionary of entries, containing the MWE and tagged MWE.
I am tagging them as replace, and whichever I could not tag as MWE
-the N... |
This was part of an exercise from exercism.io. If you fancy, view the repo here.
Given problem statement:
Write a program which produces the lyrics to that beloved classic, that field-trip favorite: 99 Bottles of Beer on the Wall.
Remove as much duplication as you possibly can.
Optimize for readability, even if it m... |
I've been writing a frequency shifter in C++ for an Audio Unit plugin. The best way for me to do this while keeping a large amount of other algorithms working in the same plugin was by writing a separate header file with a full class definition that could handle all things related to the frequency shift. After a few pr... |
I have wrote a program which prints sequence of numbers. But if number is divisible by 4 it prints x if divisible by 7 it prints y, if divisible by both 4 & 7 it prints xy otherwise it prints number.
var sequence_function = function () {
var result_array = [],
start = 1,
limit = 10;
for(i = sta... |
Here is a simple app that i am trying to implement in java.
my goal is to write a program that can convert ASCII to Binary and back.
Questions:
Am i violating any OOP Rule.
Is my code readable ?
How can i make it more efficient ?
Anything that want to suggest.
Code:
public class FXMLDocumentController implements I... |
I have made some improvement to Rabin Karp algorithm when the source and pattern only contain the characters from A to Z. The improvement is, I use base 26 for hashing (as there are total 26 characters). In this case, when the hashes match, there is no need to compare the actual string contents (since there are no hash... |
I'm returning to C++ after more than 10 years. The code I wrote for a simple quadtree style class has a ton of new elements I haven't used. I'm looking for comments on the design and not necessarily the quadtree implementation.
The code in its current state will work for my needs, with the exception of error catching... |
The code below is a Sudoku solver using backtracking. There is a fast mode which doesn't display the permutations in the Tk widget in real time; only the solved grid.
This is the second version of a sudoku solver using class inheritance and Tkinter. The first version was a one class version which was much faster (15 ti... |
Thee million men write down their name and the person to their left and the person on the far left throws out his paper. Reconstruct the list.
A List takes a while. Don't try 3 million unless you have some time.
Up front we do NOT know the remaining man on left is 0. That is what we are looking for. The remaining her... |
I've used Decorator to create a Dataset class used to build a Dataset Basic Empty (ConcreteComponent) and Iris class (ConcreteDecorated) used to populate it.
Decorator allows a user to add new functionality to an existing object
without altering its structure
For example, Iris has a its own way to load and store th... |
I am developing a plugin for QGIS (a Geographic Information Systems) software which uses Python. I have calculated four areas of interest, it does this by identifying each feature on the map (called map_layer) which falls into certain categories determined by an expression.
For example, Area 1 consists of three categor... |
I wrote code to creating structure with files on hard disc. I used here Composite pattern. Please make code review to this.
using System.Collections.Generic;
using System.Text;
namespace Common.FileSystem
{
public abstract class FileSystemItem
{
public FileSystemItem(string rootPath, string name)
... |
I have a method poker defined as below:
def poker(hands):
'''Returns the best hand from a list of hands.
Parameters:
hands: list
Example:
poker(hands) => hands
'''
return max(hands, key=hand_rank)
As mentioned in the docstrings, this function returns the best hand from a list of hands.
T... |
It's a long time since I've written a Sieve of Eratosthenes (about 3 decades, I think, in ZX Basic). So I decided to revisit in the light of experience.
Rather than allocating a vector of unknown size to sieve values, I keep an ordered set of upcoming composite values which are updated as they are reached.
#include <m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.