instruction stringlengths 71 71.9k |
|---|
itertools.cycle is cool, but it has an internal "storage" that uses up memory. And I wanted to practice "tampering" with built-in methods of classes, which is a new field for me. I tried to implement a class which mostly behaves like a list, but when we try to iterate over it (with for loop, for example), it would jump... |
Left rotate array (a), k times, n is size of array.
I know, we can calculate n, but prototype is mentioned in respective question.
#include <vector>
#include <iostream>
using namespace std;
vector<int> array_left_rotation(vector<int> a, int n, int k) {
vector<int> a1(n);
int np = -1;
for(int i = 0 ;i<... |
I have this view class for constant time rotations of a std::vector:
#include <iostream>
#include <string>
#include <vector>
template<typename T>
class vector_view {
public:
vector_view(std::vector<T>& vec) : vec{&vec}, offset{0} {}
const T& operator[](int index) const {
return (*vec)[(index + offset)... |
I am learning design patterns and I have implemented the abstract factory using generics C#.NET. Is this implementation correct or not? Or is there any SOLID principle violation?
using System;
namespace GenericAbstractFactory
{
public enum vehicles { car, bicycle, truck }
interface IFourWheeler
{
v... |
I have this piece of code, which raises an exception if there are no numbers from 3 services. I really don't like how it looks at the moment.
no_numbers = False
if use_verizon_sms:
if not Api.check_avalible_credits():
no_numbers = True
elif use_verizon:
if not buy_verizon_number():
no_numbers = True
else:
... |
Everyday I manually check that that my systems were backed up. I use the windows file system through the Explorer gui and check that the backup files were modified on the previous day or later.
This script walks the file system backup directory and compares the files modified since the start of the previous day to a li... |
I'm writing simple jQuery script for updating one field on another field's change. It's working, but I'm trying to write good code and use best practices. Can you please tell me what my mistakes and 'bad' things in this code?
Maybe I should use getTotalUserScore() in updateTotalUserScore(), not in $('.js-question-scor... |
Is there a better way to do this?
This function takes, as an argument, a natural number, n, which is between 1 and 52 inclusive and returns a list containing the point value associated with that number as an integer. The aces are the numbers 1,14,27,40 in the respective suits and they worth either 1 or 11 points. The r... |
I am currently implementing a virtual machine that runs a programming language similar to assembly. The difference is that an instruction in this language can have any number of operands. and the machine should not give an error. whatever the operand is inside the memory, the machine should make sense out of it. If the... |
Here is a recursive implementation of the Subset sum problem:
using System;
namespace Exercise
{
class SubsetSum
{
static void Main(string[] args)
{
set = new int[] { 2, 3, 1, -1};
PrintSet(set, "Initial Set.");
sum = 4;
Console.WriteLine("Wanted sum = {0}", sum);... |
I made a very simple Minesweeper using C# and WPF. My method for checking the adjacent mines for buttons is pretty long and could use some improvements, so how would I make it shorter and more "reasonable" so that it would not take so many code lines?
MiniMine.cs
namespace boardgame
{
class MiniMine : boardGame
... |
Normally, in order to have a polymorphic collection, we store pointers to a base class:
std::vector<base*> v; // or std::vector<std::unique_ptr<base>>
v.push_back(new derived{}); // problem: value is stored in a galaxy far far away
There are a couple of issues with this approach:
The std::vector<T> instan... |
This is a student module marks calculator that I was asked to write for a uni revision session in year 2.
Is this a good example of modern C++ code? Is there anything I can improve on or need to change to become a better programmer?
#include <iostream>
#include <cstdlib>
float student_results[5][2];
unsigned int inpu... |
I'm creating a virtual mapping software that essentially breaks coordinates into Areas. An Area is comprised of a defined list of boundary coordinates (coordinates that make the outer rim of the area, which connect to one another).
With this software, I need to randomly select points in EACH area that reside INSIDE of ... |
According to Rosetta Code:
The Chaos Game is a method of generating the attractor of an iterated
function system (IFS). One of the best-known and simplest examples
creates a fractal, using a polygon and an initial point selected at
random.
Task
Play the Chaos Game using the corners of an equilateral triangle
as the re... |
Let's say the model for a razor view has the following name:
Model.Receipt
and there are a couple of places where you do
@Model.Receipt.ID
@Model.Receipt.BillToCustomer
etc.
but you decide to shorten it by declaring the following code block:
@{ var receipt = Model.Receipt;} and now you use this receipt variable instead... |
SUNCE MEH BEEN WRUTEN CODEZ IN MUNY DIFFRNT PROGRAMMING LANGUAGES, MEH THOUGHTZ THAT ME TRY TO WRITE CODEZ IN AN ESOTERIC LANGUAGE. MEH CODEZ CALCULUTS A FAWCTORIAL OF UH USR INPUTTED NUMBAH IN LOLCODE, LOL.
SOME OF MEH QUSTIONS:
IZ MEH CODEZS A IDMITIC LOLCAT PROGUM?
IZ THERE A GOODER WAY OF WRUTING MEH factorial FUN... |
I am a total novice to Python and have been testing my skills recently. I found this particular challenge and wanted to give it a shot. I made this code and it functions well, but very slowly. I was looking for feedback on how to optimize in Python, as well as general Python best practices!
Main.py
from PIL import Imag... |
I've done a small one page project with slider (owlcarousel) & CSS3 animations .
Could you please look at HTML, CSS & JS and check for possible improvements? Thanks in advance.
Here's a page
$(document).ready(function() {
$('.menu-link,.btn-slider').smoothScroll({
speed: 1000,
of... |
I have the following code:
public abstract class BaseViewModel<PrimaryKey, ModelType>
{
//Some base fields
public static List<T> Convert<T>(IEnumerable<ModelType> collection)
where T : BaseViewModel<PrimaryKey, ModelType>, new()
{
var list = new List<T>();
if (collection != null)
... |
It's my implementation. Can I get some opinions on it?
import random
import os
import time
class Game:
def __init__(self, turns, w, h):
self.board = []
for x in range(0, h):
self.board.append([])
for y in range(0, w):
self.board[x].append(random.random())
self.turns = turns... |
Here is the simplest iterative implementation of Subset sum problem that I could come up with1, as a follow up to this recursive implementation of the same problem:
using System;
using System.Linq;
namespace Exercise
{
class SubsetSumBinaryNumber
{
static void Main(string[] args)
{
int[] arr = { 2, 3, ... |
I have a WinForms project that uses the Passive View MVP pattern. In the Presenter of one of my Views I have a function that gets questions and from its Model. But I want to make sure these collections are not empty so that I can inform the user when they are. Right now my code seems very ugly and I wonder if anyone ha... |
(Originally posted on Stack Overflow)
I need to run through a number of bespoke files (I'm unsure if they are unicode / ascii or binary so have attached a snapshot through notepad++). I'd like to count the number of instances of a simple string.
I've managed to get this working using the CreateObject("ADODB.Stream") m... |
Is there a way to refactor the following Python code so that the number of lines in generation of the dictionary can be reduced?
data = frame['data'].split(';')
cat_data = {
'xbee_address': '\x00' + frame['source_addr'],
'state': data[0],
'flow_rate': data[1],
'operating_hours': data[2],
'operati... |
I have written a function in python with three loops which is time consuming. Is it possible to do the same operation in less time with some other way.
Here are my code and sample data you can run at your end
#Expand files to minute-level
def expand_b34(data):
final_list = []
df_columns = list(data.columns.toli... |
I have a workbook that some very non-technical people will be entering data into. In the past, I've had them type over formulas and otherwise screw up the data, so I've locked everything except where they're supposed to enter data, then I've password protected the workbook and worksheet. Unfortunately, Microsoft, in th... |
I've written a backend for a chat app but I'm not sure, if I'm following all the SOLID principles and if my code is clean enough.
IModel interface for my db entities:
interface IModel
{
/**
* get a specific field from the model.
* @param string $fieldName name of the field to return
* @return mixed;
... |
I recently got rejected from interview after I send them this site. They said it is too contrived, and I used Redux which was unnecessary. I really would like to know what is it specifically.
I tried to follow best practices pattern and create dumb components + 1 main layout that manage all functions and state from sto... |
There is a matrix of \$m\$ rows and \$n\$ columns where each row is filled gradually. Given the first row of the matrix we can generate the elements in the subsequent rows using the formula:
$$\begin{align}
a_{i,j} =&\ a_{i-1,j} \oplus a_{i-1,j+1}\quad\forall j:0\le j\le n-2 \\
a_{i,n-1} =&\ a_{i-1,n-1} \oplus a_{i-1,0... |
Recently, the following code was written to help automate some processes that are typically executed while working with a Mercurial database. What is shown below is basically a first draft of the program and was quickly written to test out the idea of creating a GUI tool for others to use.
Question: Are there any obvio... |
I am starting to write code for a keyboard in iOS. It's pretty much hard-coded and I need suggestions on how I can make it more professional style and more efficient.
//row 1
UIButton *row1Btn1=(UIButton *)[_lettersRow1View viewWithTag:11];
UIButton *row1Btn2=(UIButton *)[_lettersRow1View viewWithTag:12];
UIButton *ro... |
In the UI I have a single search text box into which users can type a query. The query will split the string and compare each word to each configured column in the database and return the matches.
The following code works, but I don't know if there is a better way that I'm missing.
/// <summary>
/// Returns a list of u... |
I have a python AWS lambda function that takes JSON records, checks them to see if they have required keys, and then inserts into MySQL db. The function gets invoked whenever a new record comes into the stream def handler.
I'm looking for feedback on the class I've created, as well as implementing better exception han... |
Noobie here. I applied for a job as a Jr. engineer and they gave me this task. After they read through my solution they rejected my application because the code was hard to follow. I'd like to get an idea of what they meant by that and how I can improve the approach I took. The full assignment is below.
Write a progra... |
Here's an approach i came up with for checking IOS versions.
#define __PROCESS_INFO ([NSProcessInfo processInfo])
#define CURRENT_IOS ([__PROCESS_INFO operatingSystemVersion])
#define IOS(x) ((NSOperatingSystemVersion){[x integerValue], 0, 0})
#define IOS9 ((NSOperatingSystemVersion){9, 0, 0})... |
I've been glancing at Game of Life for quite a while, but been reluctant towards graphical packages like pygame. But today I finally got over myself and did it.
Did you know that there the "problem" computationally only depends on one condition? I didn't, and followed the conditions of the game at first.
At first I use... |
This code pulls JSON from a server and delivers some data like imageURL, titleString and videoURL. Then it places them in a UICollectionView and displays them.
import UIKit
import Alamofire
class vcWatch: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var myActivityIndicator: ... |
I responded to this question about designing around interdependant methods with the strategy pattern.
Afterwards I started thinking about the functional additions to java 8 and wondered if I was being an old foggy stuck in the past and if maybe there was a better way with all these fancy new tricks.
So I started hammer... |
I am new to Go. I am trying to implement a simple watchdog. It calls a function once after a certain delay has elapsed; kicking it resets the delay. Kicking it after the function has already been called restarts it.
type watchdog struct {
interval time.Duration
timer *time.Timer
}
func NewWatchdog(interval tim... |
I need to compute the summation of:
$$\left\lfloor\frac{\text{sum of triplets}}{\text{product of triplets}}\right\rfloor$$
from integers of an array.
Input:
5
1 2 1 7 3
Output:
6
Explanation:
The following triplets exists in the given array:
1 2 1
1 2 7
1 2 3
1 1 7
1 1 3
1 7 3
2 1 7
2 1 3
2 7 3
1 7 3
Considering th... |
Given n and k, I need to find Euler's totient exactly k times where n and k are very large numbers. Can anyone help with an optimized solution for a large number?
#include <iostream>
using namespace std;
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
int phi(unsigned int n)
{
... |
(See the previous iteration.)
What does this program do?
This program gives you a command line interface for managing your personal telephone book. The program supports three actions:
Adding a telephone book entry.
Removing entries by their IDs.
Listing the entries.
Synopsis
For adding an entry, type:
./TelephoneBook... |
I'm working on my first jQuery plugin for a lightweight dropdown. This dropdown behaves just like a ordinary <select>.
Before implementing new features I'd like to know if my current approach is clean and efficient (I care about readability and performance).
/**
* Dropdown plugin.
*
* @license MIT (https://opensour... |
I wrote a script which logs memory usage of a process (pid in file), and reacts in case a limit is reached. I run the script nightly. In my case, the process concerned propably has a memory leak and locks up the whole system after a couple of days. Hence, the script should reboot the system if excess memory is used. Lo... |
I recently coded the Dutch national flag problem in Java and wrote some tests.
The array in zero-indexed.
Please take a look at how I verify that elements of the output array are in the right order. It's the method verifyDutch
The Dutch national flag problem
public static void dutchFlag(int[] input, int mid) {
if ... |
I'm implementing an iterator which takes a single value and which you can advance for n times with a dereferencing yielding the single value - but before or after that range of n 'positions' you can't dereference. So it's as though you filled a length-n std::vector with a single value and were taking a const iterator o... |
I've implemented a Game of Life Kata with the aim to get to know Consul's K/V store. Although not the main purpose of the exercise, it would be nice if somebody reviewed some of the bash code in the Kata, as my experience with bash is not as extended as I would like. My main concern is about writing idiomatic bash (ie.... |
The code below is an attempt to mimic std::vector from the C++ standard library in the C language.
The implementation is purely macros, in the C99 dialect, and requires the non-standard __typeof__ keyword.
I am interested to learn of both coding mistakes and design mistakes.
The project resides on SourceForge, in case ... |
I am a beginner in Zend Framework 3 and I want to hear your opinions about the code that I wrote. I don't know how exactly I can connect forms, and validators together that the code will be quite nice and readable.
Register method
public function registerAction()
{
$form = $this->form;
$viewModel =... |
I've always loved making games and using SFML, and up until a few days ago, I've had to re-write code over and over again. So I decided to write a game engine so I can reuse my code.
I've never done something like this before. I've read about it, and I watched a few videos. I'd love if you could look around, give me so... |
I have just completed an implementation a like button for an Instagram-like app, but now that I am looking at it I feel that there is something off. Maybe it is my formatting or maybe I am not quite conforming to the MVC pattern I am not sure. I am not very experienced, so I was hoping someone with more knowledge would... |
I have been working my way through the problems in the book Cracking the Coding Interview. The instructions were to maintain an animal shelter that operates on a first in, first out basis (i.e. it is a queue). People must adopt the "oldest" (based on arrival time) of all animals at the shelter, or if they would prefer... |
I'm trying to figure out how my code could be improved. I solved a HackerRank problem from the Cracking the Coding Interview section, and am thinking that it should be able to be solved a simpler than what I did.
The problem is as follows:
Strings: Making Anagrams
Alice is taking a cryptography class and finding anagr... |
I have a tab delimited file which contains about 2207 rows with 4 columns of floats or int types:
Id pos value1 value2
01 1123 0.76483 0.9001
02 1124 0.20 0.9800
Another file is to be compared with which contains about 27041 rows with also 4 columns:
name Id pos1 pos2
s13e 01 ... |
I am currently working in a project (I have simplified it for the sake of question) that requires a container to store students and retrieve them as fast as possible or access them with \$O(1)\$ if possible. I will also be deleting students from any place but always adding them at the end of the queue.
I have three st... |
This code will return a list of the prime factors of n, and the prime factors are repeated so that the product of the list is equal to n.
import math
def product(iterable):
"""
Returns product of all elements in iterable
"""
p = 1
for x in iterable:
p *= x
return p
def generate_pri... |
Consider the following piece of code.
public static String[] choosePatterns(int total, int toChoose, int numOfPatterns1) {
String[] patterns = new String[numOfPatterns1];
int x = 0;
StringBuilder data = new StringBuilder("");
List<Integer> indices = IntStream.range(1, toChoose + 1).mapToObj(i -> Integer... |
I took a stab at solving this problem from Hackerrank in Javascript, and would like your valuable feedback as to time/space complexity and just about any additional improvements.
Problem URL: https://www.hackerrank.com/challenges/cut-the-sticks
My JS implementation:
function main() {
var n = parseInt(readLine... |
Given a set of items with a weight and a value, this problem gives the subset of items which maximize value so that their combined weights is less or equal than a given maximum weight. This solution runs in \$O(w\cdot n)\$ where \$n\$ is the number of items and \$w\$ is the max weight.
#[derive(Debug, Clone)]
struct It... |
I have only been self teaching myself programming on and off for about 5 months. The purpose of me writing this class is to incorporate the knowledge that I have gathered since I started.
using System;
using System.Collections;
using System.Linq;
namespace GenericDataStructures
{
public sealed class ArrayList<T>: I... |
The objective is given a list of items, remove the last occurrence of a specified item from the list using only user-defined functions except for very basic built-in ones like car, cdr, =, - etc. For example, if we've been given the list (A B A C), using our procedure to remove the last occurrence of A from the list sh... |
This post elaborates on NBA*: Very efficient bidirectional heuristic search algorithm in Java.
I have made the following changes:
Added an explicit type for representing digraph paths: DirectedGraphPath.
If the target node is unreachable from the source node, a TargetUnreachableException is thrown instead of returnin... |
I was trying to create a function to delete the node at index i from its current position and insert it after node at index j from a std::vector<Node> nodes. These container is logically a circular container of nodes, that is there's no actual first or last node, i.e. after nodes.back() comes nodes[0].
I really need th... |
I've been doing some 3D graphics in OpenGL lately and I needed a way to work with 4x4 matrices. My implementation supports the following operations:
Matrix-matrix addition.
Matrix-matrix subtraction.
Matrix-matrix multiplication.
Transformation matrix creation.
View matrix creation.
Perspective projection matrix creat... |
I'm new to php and OOP, and for learning I started writing an application that would help me and my flatmates to manage our expenses and debts to one another.
The full source is available at https://bitbucket.org/nicocool84/coloc-web/src. I tried to use the MVC(S) architecture without using a framework.
The project tre... |
I am using Mongoose ODM and NodeJS to implement CRUDL operations on MongoDB for further use with REST API. Initially, I've implemented functions using Promises but then switched back to callback style.
My questions are:
Should I stick to traditional callbacks or to the default Promises? In this context, I got back to ... |
Python lacks dynamic unpacking. Example: You want to unpack a list, let's say coordinates, but don't know whether it contains 3 items or just 2.
x, y, z = [1,2,3] works only if len([x,y,z]) == len([1,2,3]).
x, y, z = [1,2] results in an error. You could add try and except blocks but that could be complicated.
The best ... |
I'm trying to improve my code to find all the prime numbers within a set range as fast as possible, and I am trying to make it even faster. On my github page here, I have some optimization settings within Visual Studio that help improve the speed.
#include <iostream>
#include <fstream>
#include <Windows.h>
#include <co... |
I am a beginner in JavaScript and Phaser and wrote a Snake game. I think there are lot of things I could have done better. I am looking for some advice on how I can improve the design and refactoring of the code. You can play the game here.
var mainGame = {
preload: function() {
game.load.image('snake', 'im... |
Yesterday, I was bored and decided to write a random password generator. At first it used numerous temporary files, changed that by using arrays.
This was written on OS X and should work on Linux with minor tweaks (at least change all gshuf to shuf).
Example use:
$ pw -c 3 -l 20 -a b -nsr
Vh.9"7`gN;;$kV*/LddE
q);S;byf... |
I've made a program in C# that generates Mersenne numbers starting from the current largest known Mersenne prime. It then calculates the modulo between those numbers and smaller ones starting from 3 in order to figure out if it is divisible.
I've used some math tricks to make the process pretty fast, and so I can check... |
The program consists of two functions: the helper predicate function singleton-list? that checks whether a given list contains only one item and the function that does the actual job all-same?.
;; Predicate function: singleton-list?
;; -----------------------------------
;; The singleton-list? predicate function tests ... |
This is a continued improvement from discussion here (Find the shortest whole repetitive substring), since code has changed a lot dues to improvement, I post it here. Major smart ideas are from arvindpdmn.
Major algorithm ideas,
since we need to find wholly repetitive sub-strings, we only build Trie tree if the sub-s... |
Input:
Input contains one string S which consists of big and small latin
letters, digits, punctuation marks and brackets from the set []{}().
Constraint:
Constraints. The length of S is at least 1 and at most 105
Output:
If the code in S uses brackets correctly, output “Success" (without
the quotes). Otherwise, ou... |
I have the following functions in JavaScript:
function SelectFirstVisiblePublicationAndHideIt ( PageObj )
{
var hideButtonXpath = "//img[@title='To hide this item in your profile, mark it as invisible']";
var hideButtonArray;
var numberOfHideButton;
var publicationTitle;
aqUtils.Delay(500);
hid... |
I wrote a game solver similar (but with reduced features) to an application called GamesmanClassic but in C++. The general idea is that (roughly speaking) board games can be represented with the four following functions:
initial_position -> Starting board position
generate_moves(pos) -> Generate all valid moves give... |
I have to co-operate with third party APIs from where I get a list and I have to remove certain elements before passing it toward.
I have a working solution but I am opened for every suggestion to make it better or more reliable (assuming the third party API maybe will change a bit in the future):
public List<Column> r... |
Project Euler Problem 10 asks for the sum of all the primes below two million.
I'm creating a list of primes and keep checking any new number for divisibility with only prime numbers. I thought it should take less time but it is going over 4 minutes. How should I approach such a problem?
#include<iostream>
#include<lis... |
Here is my code:
def read_Coordinates_Atoms2(fileName, only_CA = True):
'''
in : PDB file
out : matrix with coordinates of atoms
'''
with open(fileName, 'r') as infile:
for line in infile :
if only_CA == True :
if line.startswith('ATOM') and line[13:15] == 'CA': ... |
I've followed the steps from this video from railscasts for setting ENV variables.
This is my configuration:
config/database.yml
default: &default
adapter: mysql2
encoding: utf8
pool: 5
username: <%= ENV['DATABASE_USERNAME'] %>
password: <%= ENV['DATABASE_PASSWORD'] %>
socket: /var/run/mysqld/mysqld.sock
d... |
Its been years (10+) since I have worked with sorting algorithms directly. So I have been trying to go over them again to refresh my memory. The thing is my ideas of how to do it doesn't seam to match the way I have the tutorials doing it.
Does it matter? Assuming that my code is working I would almost mean that its ... |
I want to pass errors in errors in order to know exactly the chain of causes, but without augmenting or even reading any stack until this becomes really necessary. And this is how I would achieve this:
class RError extends Error {
constructor(options = {}) {
super();
this.name = options.name;
... |
Take in a natural number n ∈ N, then process and output a(n), with a(n) being the number of quaternary strings (with 0, 1, 2, 3) of length n, where (from left to right) there never follows a character (i + 1) directly after the character i.
For example, n=3 results in a(3) = 42: 000, 002, 003, 020, 021, 022, 030, 031,... |
I've just refactored some code for a search box which takes a user search term, hits an API, returns a list of possible locations, and processes the users chosen result by sending them to a map page with their chosen result populated in the URL. I'm trying to improve my JS skills from just getting stuff done, to doing ... |
Recently I came across this, here is an excerpt from it,
This is another problem about Indraneel's library. His library has one
long shelf. His books are numbered and he identifies the books by
their number. Each book has a distinct number.
He has lost many books, since many of his friends borrow his books and
n... |
I'm working on an isomorphic javascript module (query-hash) to handle query strings and base64 tokens. It's essentially a simple key-value object with methods for taking in data and giving it back in the format you ask for.
function queryToObject(queryString) {
return queryString.split('&')
.map(kv => kv.sp... |
Yesterday I posted my Generic List and received great feedback from it. I have taken the feedback to heart. Today I'm posting my take on the linked list in c#.
LinkedList.cs
using System;
using System.Collections;
using System.Linq;
namespace GenericDataStructures
{
/// <summary>
/// This is a singly Linked Li... |
I have written yet another n-puzzle solver. I used the A* algorithm to search with the Manhattan Distance heuristic. It worked very well for the 9-puzzle (3x3) but was unusable for most instances of the 15-puzzle (4x4.) In fact I would exhaust all RAM before I got anywhere near the result.
So I switched to IDA* and ... |
The app is functioning but I am not sure if I have done it properly. The code is present in my GitHub repository. The demo can be viewed here.
In this application a user can search for anything in a location of choice. I have used Foursquare (used for getting search results) and the Google Maps API (used for getting lo... |
I am trying to fully understand interfaces and abstract classes in Java and from what I understood, I created a sample console application. Is there an error in the design or is this basically what interfaces and abstract classes are?
Animals.java (interface):
interface Animals {
void callSound();
int run();
... |
I'm trying to implement a stack data structure, but not on the heap but using the stack. Also not using any Node or Element struct but raw ints. Is this feasible? This is my code (with debug printfs) and the output is below. It doesn't seem to work atm.
My general idea was:
Get some stack address (see create_stack()).... |
I want to improve my code. Is it possible to get the plot without repeating the same instructions multiple lines?
The data comes from a Pandas' dataframe, but I am only plotting the last column (Total Acc.)
e=df['Total Acc'].round(4)*100
#The repetitions start:
row_awa = e.loc['AWA']
row_rem = e.loc['REM']
row_s1 =... |
This is my first attempt at creating a Ruby script. I set up a Cron job to run this script every hour. I'm requesting constructive critiques and suggestions for making this better.
Sidenote: I've hard coded the location to my hometown. I don't plan on changing it to another location.
Here's an example of the expected o... |
This works, but is very very slow. Any recommendations on better, less trivial ways of accomplishing this would be appreciated. With a smaller dictionary it's fine, but the dictionary is about 80 different mappings. I also hardly ever work with JS so any input would be great. Obviously I have not included the dictiona... |
Nodes will be for simply linked lists, circular lists, maybe later on extending them to work with graphs. I'm trying to be as defensive as possible, will this leak memory? It runs perfectly I'm just concerned about coding style and best practices. Especially regarding the allocation I'm not 100% convinced of my solutio... |
I've got a solution for Project Euler's problem 45.
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
$$\begin{array}{lll}
\textrm{Triangle} & T_n=n(n+1)/2 & 1, 3, 6, 10, 15, \ldots \\
\textrm{Pentagonal} & P_n=n(3n−1)/2 & 1, 5, 12, 22, 35, \ldots \\
\textrm{Hexagonal} & H_... |
I am using the SICP book. There is an exercise in which you need to create a function that will receive a list as an argument and return a list with the same elements in a reverse order.
I know there are more efficient solutions than the one I am going to present. However, I really learn by analyzing things that came u... |
I'm working on simulating a number of processing elements (nodes) which do some work in parallel and communicate by exchanging messages. The message exchange is not in the scope of this post, but it restricts the modelling of the parallel tasks because they are not completely independent and thus cannot run in any orde... |
Have some ideas to improve code from this discussion (Find valid triples for a sorted list of integers) and post new code in a new post.
The new idea is to try to remember where low bound searched last time, and when doing the search, only search from the lower bound where last search is satisfied, since with j increas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.