Snippets Collections
def hanoi(n, source, helper, target):
    if n > 0:
        # move tower of size n - 1 to helper:
        hanoi(n - 1, source, target, helper)
        # move disk from source peg to target peg
        if source:
            target.append(source.pop())
        # move tower of size n-1 from helper to target
        hanoi(n - 1, helper, source, target)
        
source = [4,3,2,1]
target = []
helper = []
hanoi(len(source),source,helper,target)

print source, helper, target
    
Result:
    Move disk 1 from A to B
    Move disk 2 from A to C
    Move disk 1 from B to C
    Move disk 3 from A to B
    Move disk 1 from C to A
    Move disk 2 from C to B
    Move disk 1 from A to B
tortoise = top
hare = top

forever:
     if hare == end :
         return 'No Loop Found'
     hare = hare.next
 
     if hare == end :
         return 'No Loop Found'
     hare = hare.next
 
     tortoise = tortoise.next
 
     if hare == tortoise:
         return 'Loop Found'
import re
from collections import Counter

def words(text): return re.findall(r'\w+', text.lower())

WORDS = Counter(words(open('big.txt').read()))

def P(word, N=sum(WORDS.values())): 
    "Probability of `word`."
    return WORDS[word] / N

def correction(word): 
    "Most probable spelling correction for word."
    return max(candidates(word), key=P)

def candidates(word): 
    "Generate possible spelling corrections for word."
    return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

def known(words): 
    "The subset of `words` that appear in the dictionary of WORDS."
    return set(w for w in words if w in WORDS)

def edits1(word):
    "All edits that are one edit away from `word`."
    letters    = 'abcdefghijklmnopqrstuvwxyz'
    splits     = [(word[:i], word[i:])    for i in range(len(word) + 1)]
    deletes    = [L + R[1:]               for L, R in splits if R]
    transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
    replaces   = [L + c + R[1:]           for L, R in splits if R for c in letters]
    inserts    = [L + c + R               for L, R in splits for c in letters]
    return set(deletes + transposes + replaces + inserts)

def edits2(word): 
    "All edits that are two edits away from `word`."
    return (e2 for e1 in edits1(word) for e2 in edits1(e1))
quicksort :: Ord a => [a] -> [a] 
quicksort [] = [] 
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater) 
  where 
     lesser = filter (< p) xs 
     greater = filter (>= p) xs
module.exports = leftpad;
function leftpad (str, len, ch){
   str = String(str);
   var i = -1;
   if (!ch && ch !== 0) ch = ' ';
   len = len - str.length;
   while (++i < len){
      str = ch + str;
   }
   return str;
}
ip addr | grep eth0 | grep inet | awk '{print $2}' | awk -F '/' '{print $1}' | awk '{printf "%s:3000", $0}' | clip.exe
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;

class Pair {
    int x, y;

    public Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

class FloodFill
{
    // Below arrays details all 8 possible movements
    private static final int[] row = { -1, -1, -1, 0, 0, 1, 1, 1 };
    private static final int[] col = { -1, 0, 1, -1, 1, -1, 0, 1 };

    // check if it is possible to go to pixel (x, y) from
    // current pixel. The function returns false if the pixel
    // has different color or it is not a valid pixel
    public static boolean isSafe(char[][] M, int m, int n,
                                int x, int y, char target)
    {
        return x >= 0 && x < m && y >= 0 && y < n
                && M[x][y] == target;
    }

    // Flood fill using BFS
    public static void floodfill(char[][] M, int x, int y, char replacement)
    {
        int m = M.length;
        int n = M[0].length;

        // create a queue and enqueue starting pixel
        Queue<Pair> q = new ArrayDeque<>();
        q.add(new Pair(x, y));

        // get target color
        char target = M[x][y];

        // run till queue is not empty
        while (!q.isEmpty())
        {
            // pop front node from queue and process it
            Pair node = q.poll();

            // (x, y) represents current pixel
            x = node.x;
            y = node.y;

            // replace current pixel color with that of replacement
            M[x][y] = replacement;

            // process all 8 adjacent pixels of current pixel and
            // enqueue each valid pixel
            for (int k = 0; k < row.length; k++)
            {
                // if adjacent pixel at position (x + row[k], y + col[k]) is
                // a valid pixel and have same color as that of current pixel
                if (isSafe(M, m, n, x + row[k], y + col[k], target))
                {
                    // enqueue adjacent pixel
                    q.add(new Pair(x + row[k], y + col[k]));
                }
            }
        }
    }

    public static void main(String[] args)
    {
        // matrix showing portion of the screen having different colors
        char[][] M = {
            "YYYGGGGGGG".toCharArray(),
            "YYYYYYGXXX".toCharArray(),
            "GGGGGGGXXX".toCharArray(),
            "WWWWWGGGGX".toCharArray(),
            "WRRRRRGXXX".toCharArray(),
            "WWWRRGGXXX".toCharArray(),
            "WBWRRRRRRX".toCharArray(),
            "WBBBBRRXXX".toCharArray(),
            "WBBXBBBBXX".toCharArray(),
            "WBBXXXXXXX".toCharArray()
        };

        // start node
        int x = 3, y = 9;   // target color = "X"

        // replacement color
        char replacement = 'C';

        // replace target color with replacement color
        floodfill(M, x, y, replacement);

        // print the colors after replacement
        for (int i = 0; i < M.length; i++) {
            System.out.println(Arrays.toString(M[i]));
        }
    }
}
class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        
double AttackerSuccessProbability(double q, int z)
{
    double p = 1.0 - q;
    double lambda = z * (q / p);
    double sum = 1.0;
    int i, k;
    for (k = 0; k <= z; k++)
    {
        double poisson = exp(-lambda);
        for (i = 1; i <= k; i++)
            poisson *= lambda / i;
        sum -= poisson * (1 - pow(q / p, z - k));
    }
    return sum;
}
# Python3 implementation of the approach 

# Function to sort the array such that 
# negative values do not get affected 
def sortArray(a, n): 

	# Store all non-negative values 
	ans=[] 
	for i in range(n): 
		if (a[i] >= 0): 
			ans.append(a[i]) 

	# Sort non-negative values 
	ans = sorted(ans) 

	j = 0
	for i in range(n): 

		# If current element is non-negative then 
		# update it such that all the 
		# non-negative values are sorted 
		if (a[i] >= 0): 
			a[i] = ans[j] 
			j += 1

	# Print the sorted array 
	for i in range(n): 
		print(a[i],end = " ") 


# Driver code 

arr = [2, -6, -3, 8, 4, 1] 

n = len(arr) 

sortArray(arr, n) 

<?php 
function count_num_finger( $n ) 
{ 
	$r = $n % 8; 
	if ($r == 1) 
		return $r; 
	if ($r == 5) 
		return $r; 
	if ($r == 0 or $r == 2) 
		return 2; 
	if ($r == 3 or $r == 7) 
		return 3; 
	if ($r == 4 or $r == 6) 
		return 4; 
}	 

// Driver Code 
$n = 30; 
echo(count_num_finger($n)); 
 
?> 
star

Wed Jan 01 2020 19:00:00 GMT+0000 (Coordinated Universal Time) https://www.python-course.eu/towers_of_hanoi.php

#python #puzzles #interesting
star

Sun Dec 29 2019 19:13:40 GMT+0000 (Coordinated Universal Time) http://norvig.com/spell-correct.html

#python #interesting #logic
star

Sat Dec 28 2019 19:41:55 GMT+0000 (Coordinated Universal Time) https://m.slashdot.org/story/178605

#interesting #BASIC #funcode
star

Fri Dec 27 2019 19:07:08 GMT+0000 (Coordinated Universal Time) https://qz.com/646467/how-one-programmer-broke-the-internet-by-deleting-a-tiny-piece-of-code/

#javascript #interesting #historicalcode #leftpad
star

Fri Dec 27 2019 13:19:35 GMT+0000 (Coordinated Universal Time) https://dev.to/codeluggage/today-i-wrote-a-handy-little-snippet-to-easily-access-ubuntu-from-windows-in-wsl2-19l

#commandline #interesting #windows #ubuntu #linux
star

Thu Dec 26 2019 19:01:13 GMT+0000 (Coordinated Universal Time) https://www.techiedelight.com/flood-fill-algorithm/

#java #logic #algorithms #interesting #arrays
star

Thu Dec 26 2019 18:45:53 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/letter-combinations-of-a-phone-number/

#python #interviewquestions #interesting
star

Thu Dec 26 2019 15:35:22 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/sort-an-array-without-changing-position-of-negative-numbers/

#python #interesting #arrays #sorting #interviewquestions
star

Thu Dec 26 2019 15:18:45 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/program-count-numbers-fingers/

#php #interesting #interviewquestions #logic

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension