instruction
stringlengths
71
71.9k
This was the problem from "30 Days of Code" on Hackerrank: Given set \$S = \lbrace{1,2,3,\dots,N}\rbrace\$, find two integers \$A\$ and \$B\$ (where \$A \lt B\$), from set \$S\$ such that the value of \$A\&B\$ is the maximum possible and also less than a given integer, \$K\$. In this case, \$\&\$ represents the bitwi...
This is a simple Ruby program to analyze the number of lines characters speak in Shakespeare's Macbeth using Nokogiri and open-uri to parse a given url containing xml. I wrote this as practice getting used to Ruby and TDD. I'm new to Ruby so I'm wondering if anything looks strange to more experienced Rubyists. Note: I ...
I receive HTML-encoded text that includes named and numbered entities, and I need the decoded HTML. There were just too many bad solutions for this online. I use regex pattern &(#x|#){0,1}(\w{1,8}); to find the entities in an HTML text (capturing the numeric prefix and the numeric expression), and I use a Static Script...
I'm working on a car move problem. Suppose we have origin parking position for each car, [-1,1,2,3,7,6,4,5] (which means first position is empty, car with ID 1 parked at 2nd position, car with ID 2 parked at 3rd position), we want to find the minimal move to re-park car as specific desired positions. For example specif...
I have a simple javascript randomizer that compares two random numbers with values 1 to 6. I want to get a good estimate about the probability of the first been greater than the second. I could do it using math, probability theory e.t.c. but lets say that I want to stick to javascript. Using millions or billions of itt...
I've got these two template functions responsible of adding/removing actors in-game in GameEngine.h: template<typename T> void add(T actor); template<typename T> void remove(T actor); And these arrays: std::set<std::shared_ptr<Tickable>> tickables; std::set<std::shared_ptr<Hitbox>> hitboxes; std::set<std::shared_ptr<...
In our application we have data which needs to be shared between multiple threads. Now and then we ran into a race condition and we could not figure out where that was. So I have implemented a deadlock watchdog. It is supposed to be used like this (example): public bool GetFromElementExistsCache(string id) { using (n...
The project below is about a Telegram bot that implements both inline and offline modes. The idea is to get a brief info about a book, searched by title(it's author, rating, short description). I decided to retrieve the info from GoodReads. Besides the parse implementation, I have trouble in correctly accessing the Tel...
I'm pretty new to ruby and programming in general. I had an idea for a fun little project that I could use to gain a little experience. I wrote a simple program that takes a 4 bit binary sequence (ie. 1001, 1110, etc) and converts it into its decimal counterpart (ie 1111 = 15). I got the program working but even I can ...
Those unfamiliar with that algorithm can have a deeper look here, in a few words, there are two arrays where you subtract each element ar1[0][0]-ar2[0][0] and add that result using the absolute values. My implementation is this: #include <stdio.h> #include <stdlib.h> #define LEN(arr) ((int) (sizeof (arr) / sizeof (arr...
It's my university task. Can I get some opinions on it? #include <iostream> #include <vector> using namespace std; string toBinary(short n) { string r; while(n != 0) { r = ( n % 2 == 0 ? "0" : "1" ) + r; n /= 2; } return r; } int has_even_parity(int c) { int k = 0; if (c != 0) k+...
I have a very basic XMLHttpRequest function that would be used with web workers. I would like to know how I could improve it to handle possible errors better: var ThreadedXhrRequest = function(url) { var worker = new Worker("xhrWorker.js"); worker.postMessage([url]); worker.onmessage = function(d) { ...
I often find myself having to do np.intersect1d() multiple times because I need to find the intersection of a number of list like or array like things. So I ended up creating a function for it. Though, if possible I'd like to simplify / and or speed up the code for when the input becomes rather large. def overlap(spli...
I have to develop a class that creates new files. If a file with the given name already exists, it should be renamed by addition of the timestamp to the file name. The file name should be human-readable, so I can use neither UUID nor createTempFile. The code works, but looks too bulky. public class FileBackup { /*...
I have a quiz app that gets data from a questions.json file using AJAX, loads them into my script file, and then use Handlebars to compile templates so I don't have to mix HTML in my JavaScript code. I welcome any improvements on my current code. app.js (function($, Handlebars) { "use strict"; // Get all the q...
Is this a correct linked list implementation of binary heap insertion? This is not a homework exercise. public BinaryHeap insert(int value , BinaryHeap node , int count) { //1. Insert into a binary tree breadth wise( satisfy complete binary property) (left to right) //2. Once inserted ,fix the tree...
I put together a code will allow me to toggle a class and save it in local storage. Now I need to add 2 more classes to be toggled and be saved in the same manner. I don't know how to iterate properly with the code and the DOM to achieve this. This is my "semi-working" example: http://jsbin.com/nimekebura/1/edit?html,...
I wrote a node script to traverse a folder of hour-long mp3s and upload them to Mixcloud via their API. It works, but I suspect it's fairly inefficient - the computer it's going to run on at our radio station is an old white Macbook. Would appreciate any insight for how to improve it. const restler = require('restler...
I wrote a little bit of code to brute force disprove the Euler proposition that states: $$a^4 + b^4 + c^4 = d^4$$ has no solution when \$a\$, \$b\$, \$c\$, \$d\$ are positive integers. I'm no mathematician, but reading around this, at least one solution was found by Noam Elkies in 1987 (a = 95800; b = 217519; c = 414...
This is my wrapper, how can i improve this? (With a Singleton too) <?php define("DB_HOST", ""); define("DB_USER", ""); define("DB_PASS", ""); define("DB_DATA", ""); class Connection extends PDO{ public function __construct($host = DB_HOST , $data = DB_DATA , $user = DB_USER , $pass = DB_PASS){ ...
I'm reviewing MIT Introduction to Algorithm lectures/exercises and am trying to implement a one dimensional peak finder algorithm. I've got a working copy but it's a bit messy and I've had to put some array size constraints to get it working properly. How can I improve this implementation? def peakfinder(arr): if ...
I have implemented a Gibbs sampler to generate textured images. According to the beta parameters (array of shape(4)), we can generate various textures. Here is my initial function using Numpy: def gibbs_sampler(img_label, betas, burnin, nb_samples): nb_iter = burnin + nb_samples lst_samples = [] labels = ...
I am trying to turn namespace DevComponents.WpfEditors.Primitives { /// <summary> /// Interaction logic for EditorFreeTextButton.xaml /// </summary> public partial class EditorFreeTextButton : EditorButton { public EditorFreeTextButton() { InitializeComponent(); }...
I'm lately messing up with handling joystick in java. So here is the thing. I wrote a simple class that handle input from joystick, but I'm no certain if I'm doing it well. Here is what I want to achieve. So i have joypad, I'm using jinput from LWJGL 2, and want to bind axis and buttons state to Javafx application, an...
Recently, I was learning about greedy algorithms. One example that was given was an algorithm for exchanging a given money amount using the smallest number of coins. After the lecture, I wrote a C program implementing this: #include <stdlib.h> #include <stdio.h> #include <errno.h> static int compareDenominations(const...
I have always disliked the way PHP printed stacktraces, coming from a Java world. So I decided to implement my own ExceptionFormatter, a class that will format Exceptions/Throwables to my liking. class ExceptionFormatter { /** @var \Exception|\Throwable */ private $exception; /** @var string */ privat...
I making simple multithreading signature program (it calculate SHA256 hash for parts of file). Please check my code and I would be grateful if you tell me about errors in my code Program.cs using System; using System.IO; namespace Signature { class Program { public static TaskQueue Tasks; publi...
This is an mqtt driven, interactive, and asynchronous remote shell daemon written in bash. I call it "MqSH" or simply "mq". It works with bash, the busybox ash shell, and perhaps other Bourne-like shells. It's designed for embedded devices with low system resource, so I wrote to be friendly to busybox-based systems. It...
I have written the following thread pool implementation in C++14. It appears to work fine on my system, but I am looking for a second opinion on the thread safety of my implementation and any other possible implementation flaws or concerns. #include <atomic> #include <condition_variable> #include <exception> #include <...
I use MultiMarkdown tables more than I thought I ever would. In my .md files, I would like the source table code to be neat, evenly spaced, and resemble (in an alignment sense) the final HTML rendered table. Solution Select the source of the table, press a hotkey on my computer, replace the untidy table with the tidy t...
I am working on Oracle SQL. What I am trying to do is: Query a record with ID If the record does not exists use user input value If the record exists, compare last_login_date column and user input value (I put to_date('20160401', 'yyyymmdd') then pick recent one) Add not_change_day to result of 3, then compare the val...
I want to check whether or not an object exists in an array given its key (key is not unique). The object takes the form: class item { key: string, value: (string|int|boolean), id: Guid } And this._items is an item array. First approach is simply filtering the array and checking its length: has(key) { ...
I am a beginner Java programmer. I have just finished up an assignment and would appreciate some advice and/or criticism on my program. For context, I have the assignment details, followed by the full code below: Create an Employee Records program that incorporates the following properties: employeeIdNumber; firstNam...
This is an interview question from Interview Cake: Given a list_of_ints, find the highest_product you can get from three of the integers. The input list_of_ints will always have at least three integers. I'm looking for feedback on how to improve readability, space, time complexity, using Python idiomatic code and g...
Total newbie here and wouldn't mind learning from Rubyists to look at how I tried to solve this challenge. I started with 2 variables n which starts at 0 and total which is an array where I intend to push n if it satisfy the condition set by the 2 modulo. Using the until loop with a max of 1000, my intention was to cha...
My program makes a conversion between Roman and decimal numbers. Can you give me some advice on how to make it look more readable or to improve in general? Would code extraction of similar-looking logic from switch cases into helper methods do the job? Or can we take some other approach and use recursion, enums or regu...
I wrote this in 78 minutes as part of an application to an internship program. We were allowed to use whatever language we wanted, so I picked Rust because that's what I use the most. I'm a Sophomore CS/Data Science major and I just wanted to get a feel for how you more experienced among us feel about what I made. I'...
I have submitted here my solution to the LCD Diplay programming challege(detailed here) Please review my code and let me know what you think. // ConsoleApplication3.cpp : Defines the entry point for the console application. // //#include "stdafx.h" #include <iostream> #include <string> using namespace std; /*We use...
As a pet project I implemented a neural network. I am looking for general advice, since I am a self tought programmer, but I have few specific questions I stated at the end of this post. Let's dig into it: Code Neuron.hpp: //------------------------------------------------ // NEURON.HPP //-----------------------------...
Is there a way make the code better so that it does not have repeated code? int totalDistance; if (totalDistance < pow(10, 3)) { cout << "\nTotal (approx) travel distance = " << totalDistance << " million km\n" << endl; } else if (totalDistance < pow(10, 6)) { totalDistance = totalDistance / pow(10, 3); co...
Telegram Bot that retrieves book information from GoodReads I've created a Telegram bot that implements the inline/offline modes to get the brief info about a book, searched by title(inline mode) or with command /random. The data is retrieved from GoodReads. I was wondering how can I modify the body of 'description', s...
I've created function that will display a league competition from the total team numbers. For example if we have 4 teams it will display (a vs b) vs (c vs d) and if we have 5 teams it will diplay ((a vs b) vs c) vs (d vs e) and so on. It will display the competition looks square or equal. here is the complete code : ...
To sum up my project was about making cool animation of titles appearance with an effect of a colored block coming from one side while expanding and disappearing from the others side while contracting and let the text appear. My goal was to achieve something simple, that can be used again easily on different elements j...
The project is an API that will itself make HTTP requests to external webservices. Since this is PHP, we actually chose to use guzzlehttp. Now the library itself doesn't matter much, but I'm scared we'll be stuck with it if it ever has a major change (it already happened in the past). So I thought I'd create an inte...
I have been using Tweeepy to connect to the Twitter Streaming API to collect tweets, parse that data, and then write select fields to a CSV file. Based on some examples that I found, I put together the following code to manage that connection. One thing that I had to work around was how to handle the connection getti...
I'm trying to come up with a smart wordpress inspired PHP function that builds an url for my CMS. It has some different requirements that are almost all fulfilled so far. Must use correct domain Must be able to use subfolder (Eg. /blog/index.php) Must be able to specify protocol (if http or https) Must accept queries ...
What can be done better? What should I learn to make these tasks better and more efficiently? The template (template.h): #pragma once #include <iostream> template <typename TData> class CArray { public: CArray(int capacity = 0); CArray( const CArray & _array ); ~CArray(); void push_back( const ...
I've completed this Tic Tac Toe simulator in java and so far it's working. It's just supposed to generate a pre-played game and announce the winner. I'm required to use a 2D array and this is the way I've found to get it done. But I ask more experienced developers if there is a way to do this that is a little less conv...
For one of my assignments, we were asked to create a data structure similar to Bags using dynamic arrays where the order would be important - which I was able to do successfully, that is, the code that follows works fine. We now have to optimize the code according to the memory usage and timing. One of the functions th...
I've created an asynchronous parallel ForEach mechanism so I could enumerate an enumerable by N degrees of concurrency and process an action for each item. Additionally, I have the option of stopping when first exception is encountered or processing the entire enumerable and returning all exceptions at the end. I'm t...
I am new to concurrent dictionaries and all their new methods involving "Try". I have coded a simple method below that retrieves roomInformation from a dictionary (roomInformation is a class) and then prints it if it exists as well as returns true. Have I done this right? is there a better way? please do let me know i...
I have this little class for parsing, comparing and sorting semantic versions. I did my best to implement the specification at semver.org with one exception - it doesn't support the build metadata. Now you can tear it apart ;-) I removed all parameter checks to make it shorter. [DebuggerDisplay("{ToString(),nq}")] publ...
For an outsourced job (implementation of a network client) I will provide a simple server for protocol-testing. This is the code. Do you consider this code readable/ comprehensible? using System; using System.Text; using System.IO; using System.Net.Sockets; namespace SimplePictureReceiverServer { class Program ...
In our latest Veracode scan for an application, I have come across the issue of Improper Resource Shutdown or Release. It is pointing at a function. Here's what the code looks like: Imports System.Data.SqlClient Public Class DAL Public Shared ConnString As String = ConfigurationManager.ConnectionStrings("connect...
I have spent a decent amount of (waaay too much) time trying to write the below function and get my head around recursion. The aim was to return all permutations of an int vector (assuming no duplications of input). I would like to know people's thoughts on my code. One downfall that I can identify is that it is pretty...
It feels like there's quite a lot of code involved in order to manually build up an animation using the libGDX framework. In my specific case, I am creating a number of animations for a portrait view of a character. The character will do things like talk, blink, and laugh. There are a handful of different characters t...
I am new to Ruby and not familiar with a lot of Array features. I feel like this code can be written in a couple of fewer lines. The idea is: I have a Definition class and a Field class. I abstracted them as Hashes to make my life easier although they should be classes. Definition contains an Id and a Name Field conta...
I have this Python project to draw tessellated triangles on the screen. It takes the height to form the size of the triangle, cols to specify how many triangles on a line, and rows which is how many lines it outputs. This program has taken me some time to put together and I'm not sure if this is the best way to do this...
Because my job needed something like this, I created a Python script that'll connect to an IMAP server, get all the emails, and then calculate the very rough daily average of emails received to the Inbox (as well as the 'smallest' number of emails handled per day, and the 'largest' number of emails handled per day, for...
The below may not look like much, but the ability to call methods in other classes, offloading all the work onto other classes from MainClass, and returning a variable to be passed to the next method is a rather large leap for me at least. using System; namespace CSharpTutoriel { class Work { public st...
I'm a node beginner and I'm trying to write fewer lines of code by finding out which lines are redundant. var express = require('express'); var app = express(); var server = require('http').Server(app); var port = process.env.PORT || 8080; var mongoose = require('mongoose'); var passport = require('passport'); var ...
This is a follow up to Maximum product of 3 integers in an int array using Python Changes to the code include renamed variables for improved readability and I added more test cases. import unittest def highest_product(list_of_ints): max_seen = [float("-inf"), float("-inf"), float("-inf")] min_seen = [float("i...
I'm trying to print a diamond of asterisks of an arbitrary size. I'm new to F#, so I'm interested in virtually any feedback, but especially adherence to idioms, convention, and functional orientation. module Diamond open System let rangeWithInverse (max) = List.zip [ 1 .. max ] [ max .. -1 .. 1] let listAscDesc ...
I am currently using the BestFirst algorithm to solve the puzzle 15. It works well when I have a simple inputs and takes about 1-20 seconds to solve the puzzle. But when it comes to complicated inputs, it might takes forever to run. I'm just wondering if there is any way to improve my algorithm's performance. Main.java...
Here is a continued discussion (Game where two players take turns picking numbers until a target sum) from here since my previous code has bug, I fixed it with totally new algorithm implementation. Working on the problem of sum game. Suppose we have consecutive numbers from 1 to n, and an expected sum number, there are...
This solves Project Euler 4: Largest palindrome product using Python (not limited to 3 digit numbers). I need suggestions for improvements to either the Python code or the math/algorithm since time of execution increases exponentially as number of digits in multipliers increase. A palindromic number reads the same bot...
I've written a Node js server that create, read, and update user data from a SQL server hosted in Azure. Clients connect to the server using a standard TCP socket, every message sent or received will be encrypted/decrypted using AES 256 CBC. Communication protocol TCP is used to create a simple communication mean with...
I stumbled my way through some Rust yesterday and today to make a simple ASCII art API. It can draw lines, circles, and a canvas. use std::collections::HashMap; #[derive(PartialEq, PartialOrd, Debug)] struct Point(u32, u32); #[derive(PartialEq, PartialOrd, Debug)] struct Dimension(u32, u32); #[derive(PartialEq, Par...
I use the following code which is working OK to register and emit event for local storage on the browser. It will be great if you can give me some ideas on how to improve it for production use since I'm fairly new to JS. "use strict"; function lsHelper() { let status = "available"; let timeout = 500...
I need help moving my solve code in my calculator into its own separate class. import java.awt.*; import java.applet.*; public class Calculator extends Applet { private Label calculatorL; //Sets the label private boolean firstDigit = true; //Sets Boolean firstDigit to be true private float savedValue = 0.0f;//Sets s...
I am reading from a file containing some segments (irregular parcels of the image) and trying to average the entire segment to have one pixel value. This is the code I use: band = band[:,:,0] #take the first band of the image for i in range(numSegments): #for every segment tx = band[segments==i] #select all the...
I have a drop down menu that will run a function onchange. The function takes times from an array , adds a specific amount of time , then changes the innerHTML of the table. The code works , but is there a simpler version? I plan on adding more options to the drop down menu. HTML <select id="sel1" onchange="myFunction(...
I was writing a function that takes an argument and returns a truth value. My initial idea was just return !!value, but this will fail for '0', {} or []. I know that '0' should be true but in my application we are considering it false. So, my function should return false for: Falsey values: false, 0, undefined, null, ...
Below's some code I knocked up to escape the account name to be used in creating an ADSI reference to an account (e.g. escaping $sAmAccountName before using in [ADSI]"WinNT://$Domain/$sAmAccountName,user" function ConvertTo-LdapEscapedString { param ( [Parameter(Mandatory,ValueFromPipeline)] [string...
I have written a JavaScript that can read every defined html element and changes the color for each char inside the selected element. It works fine for smaller projects / sites, however will be laggy and even crash the browser if there are too many elements to process. Appart from 'Use JQuery', what could I do to impro...
I went through some of the stuffs on net regarding spring AOP and wrote a Spring AOP logger. Can you guys check my code and give your valuable inputs to improve it or if it is not proper, give me an another example of how can I achieve it? My Code is as below : @Aspect public class SpringAOPLogger { @Around("exec...
I am working on a function that will take a an array of options. These options are retrived from a database, and could have other options inputted throughout the system. When adding my options, I am constrained by only being able to add a single option at a time. I can't currently add an array of options. The options t...
This is my first attempt at writing code that moves files at the end of the day, from my local work folder to an network archive. The program works but, any tips, tricks, or ideas to make this code better would be most appreciated. import shutil, os, datetime, time, sys os.system('TASKKILL /F /IM FlashRen.exe') new...
Here is a plan for generating the permutations of S: For each item x in S, recursively generate the sequence of permutations of S - x, and adjoin x to the front of each one. This yields, for each x in S, the sequence of permutations of S that begin with x. Combining these sequences for all x gives all the perm...
I have some set of if conditions for a particular array using JavaScript. activity is the array containing 10-12 items. This array is converted to a multiple select dropdown. Depending upon the value selected, I need to hide and show divs. I also need to set values of another input choice as "NA". Here's the code writt...
I'm a beginner: I have learned concepts and features which I think I need in my project, but this is my first serious program and it is my internship project. I'm totally confused and need help to tell me is my way of thinking about OOP, this project and etc correct or not? As you know already from the title, this proj...
I simply want to organize some data (class= MarketOnCloseSecurity) to be used in another class MarketOnClosePortfolio. The former class would not have any methods but just a constructor that includes a ticker for a company symbol and two Pandas dataframes bars and signals. class MarketOnCloseSecurity(): """Encapsul...
The Josh Bloch Builder Pattern (here after JBBuilder) introduced me to the idea of using a nested class to aid in construction. In Java the JBBuilder pattern is aimed at fixing the telescoping constructor problem. That problem occurs in java mostly because java doesn't have named and optional arguments the way C# do...
This is a simple circular progress with Canvas. Is there any way to make it shorter and easier to read? Another concept for a better performance? I guess clear and re-draw the whole canvas in every input change is not a good thing. I might be wrong. var canvas = document.getElementById('canvas'), ctx = canvas.getCo...
I've wrote the code for Project Euler #15 and it runs amazingly fast. I know I can write it using binomials but I wanted to calculate by brute force as if I do not know Binomials. But I think it must be taking huge amount of memory so I want to know how I can reduce amount of memory used by program. I've tried to reduc...
I need to time a few functions that I'm implementing, so I decided to implement a way of timing even multiple or sub calls based on the stack data structure and on the tic and toc commands of Matlab. tictoc.h #include <assert.h> #include <cmath> #include <ctime> #include <iostream> #include <stack> static std::stack<s...
I started learning Racket recently and decide to revisit the problem that introduced me to computer programming: making a Tic-Tac-Toe game with AI. Here's the code: #lang racket (require math/array) ;; PLAYER DEFINITION (define empty 'EMPTY) (define draw 'DRAW) (define player1 'PLAYER_ONE) (define player2 'PLAYER_TWO...
This code creates a truth table from a statement in logic. The statement is input as a string, and it is identified as a tautology if it is true for all true and false combinations of the variables. Note: brackets must contain only one logical operator. For example, \$(A \lor B \lor C)\$ does not work, but \$(A \lor B...
The purpose of this program is to implement logic of autocomplete feature (Google Search, for instance). The code is divided into 3 parts: Term - represents single search term with the query and the weight (number of times this query was searched for). BinarySearchDeluxe - utility class that provides methods for findi...
I keep having to write state machines that depend on time for various experiments I run and I'd like to know how to write them better. This state machine is for training a neural network by feeding in keys and expected values. import numpy as np dt = 0.001 period = 0.1 class SimpleEnv(object): def __init__(self...
I'm making a Python-like range() function (see Python docs) using JavaScript. This function can take from 1 to 3 arguments. There are 3 variables (start, stop and step) that need to have some value, either from arguments, or a default value. If only one argument is passed, start is 0, stop is the first argument and st...
My situation is as such: I must connect to a server via TCP, at the end of the session (several hours), they will close the connection - throwing an exception that should be gracefully handled I need to both send and receive messages, they are delineated by '\n' Per the specs if the server doesn't send a message withi...
I'm learning Ruby and as an exercise I decided to build this little temperature converter app (C to F, F to C, F to K, etc). Looking back at it, it's pretty much just a bunch of boilerplate code. Any ideas on how I could shorten this up and make it a little more dynamic would really be appreciated! #!/usr/bin/ruby # My...
I have an implementation for a graph node class that I'd like to have function as a directed acyclic graph. The associations are roughly as follows class Node has_many :parents, class_name: 'Edge', foreign_key: :child_id has_many :children, class_name: 'Edge', foreign_...
Instead of using a MinHeap that will allow me to change the vertex priorities I am using the Java library PriorityQueue. Here is how I have implemented the vertices which will generate the vertex array. Also, I have not maintained any separate array for storing the shortest distance to a vertex from source. Instead, I ...
I have been trying to learn backbone.js and I thought the best way to learn it is by writing a dynamic table (i.e. add, edit and delete rows of data). I am very familiar with Node.js (back-end). Any comments or suggestions to improve this backbone.js code would be appreciated. This code works fine but I did not use any...
I took the code from internet and tried to simplify it. So, what can I do? How can I simplify my code more to make it easily understandable? public class NaiveBayesAlgorithm { private static List<Training> trainingDataSet = new List<Training>(); private static Dictionary<string, HeightWeightSize> gaussianDataSe...
Previously I created a C# script that used trial division to check to see whether or not certain Mersenne numbers were prime. Since these numbers are so big, I employed some math shortcuts to reduce the amount of division I needed to do. It was brought to my attention that using the Lucas-Lehmer formula would speed up ...
# Filename: P05_Strings.py # Author: Joseph Chua # Date: 10/18/2016 # Purpose: Slicing a string into THREE pieces. # Other: http://repeatercreeper.me #======================================================================= # Logic - Assignment #1 #=======================================================================...
I have solved the LeetCode Remove Duplicates From Sorted Array problem: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. It doesn't matter what you leave beyond the new length. I was able to come up with a approach but only when I submitted this s...