Giter Club home page Giter Club logo

grokking_algorithms's Introduction

Grokking Algorithms

This is the code in my book Grokking Algorithms.

Check out Python Tutor, a great website that guides you through Python code line by line.

Errata

Here's the errata page.

Images

This repository contains every image in Grokking Algorithms in high resolution. These images are available for non-commercial use. If you use an image, please add "copyright Manning Publications, drawn by adit.io". You are welcome to use these images in any non-commercial materials (i.e. teaching materials, presentations, etc.)

Contributing

  • The examples in this book are written in Python, but I'd like examples in Ruby, JavaScript, C, and other languages too. Please add examples in other languages!
  • Pull request are the quickest way to contribute to this repository but unfortunately I am not as responsive to them as I'd like to be. I'll get to them but it might take a while!
  • This repo is for easy to read examples. So even though I love well tested, optimized code, I won't be merging PRs related to tests or optimization, since those will increase cognitive load for readers.

grokking_algorithms's People

Contributors

alexandrshy avatar alterevit avatar andriinyzhnyk avatar antonlipilin avatar bijoythomas avatar biosta avatar chase-g avatar coditori avatar crr004 avatar drytikov avatar egonschiele avatar fhl43211 avatar joeczar avatar kde0820 avatar kevinwin avatar linehk avatar magistr-bit avatar miholeus avatar nikitalipatov avatar oleksandrdanylchenko avatar polurival avatar seanyu4296 avatar seong954t avatar spadarjauhien avatar spainn avatar timosci avatar vendin avatar voloshchenkoal avatar yuriymarad avatar zhangjiongwx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grokking_algorithms's Issues

Longest common substring wrongly coded.

The longest common substring is wrongly in Python coded and throws an error anytime it runs, this should be prioritized since it is a core part of the book.

dp_table_blue = ["b", "l", "u", "e"]
dp_table_clues = ["c", "l", "u", "e", "s"]
dp_table = [[0 for i in range(len(dp_table_blue))] for i in range(len(dp_table_clues))] # (5,4)
print(dp_table)

for i in range(0, len(dp_table_blue)):
    for j in range(0, len(dp_table_clues)):
        if dp_table_clues[j] == dp_table_blue[i]:
            dp_table[i][j] = dp_table[i-1][i-1] + 1

print(dp_table)

copy this code and try to run it here https://onecompiler.com/python or click this link https://onecompiler.com/python/3znsmgdbr to run it directly to get the errors.

JavaScript/ES6 solution has formatting problems and non-working example

  1. The solution in the 01_binary_search.js file has several problems in its implementation (for example, unnecessary use while), and this solution doesn't work for all cases (for example, binarySearch([1,2,3,4,5,6,7,8,9,10], 3) return null);
  2. For formatting JavaScript code is better to use Prettier. This will help in all examples to make the same formatting and it will look better.

As I read the book, I can create issues and fix them for JavaScript/ES6 code examples.

Understanding Quick Sort Algorithm

Thanks for this great work on algorithms book. I now understand many of concepts which seemed difficult to me but now I'm stuck on Quick Sort algorithm and I cannot fully understand how its work.

JavaScript Version of Code (from repository):

function quicksort(array) {
    if (array.length < 2) {
        // base case, arrays with 0 or 1 element are already "sorted"
        return array
    } else {
        // recursive case
        let pivot = array[0]

        // sub-array of all the elements less than the pivot
        let less = array.slice(1).filter(function(el) {
            return el <= pivot
        })

        // sub-array of all the elements greater than the pivot
        let greater = array.slice(1).filter(function(el) {
            return el > pivot
        })

        return quicksort(less).concat([pivot], quicksort(greater))
    }
}

How I understanding parts of work this algorithm:

console.log(quicksort([10, 5, 2, 3]))

first step:

quicksort([10, 5, 2, 3])
pivot = 10 // get first item from array[0]
less = [5, 2, 3] // list of all item less than pivot
greater = [] // no items greater than pivot
quicksort([5, 2, 3]).concat([10], quicksort([]))

untitled - copy 2

now we save this step ☝️ in stack and adding new step to up of stack 👇:

quicksort([5, 2, 3])
pivot = 5
less = [2, 3]
greater = []
quicksort([2, 3]).concat([5], quicksort([]))

untitled

and last step:

quicksort([2, 3])
pivot = 2
less = []
greater = [3]
quicksort([]).concat([2], quicksort([3]))

untitledasdsad

AND now the part I'm not sure I understand correctly:

now we concat array down to up i.e.:

[] + [2] + [3] + [5] + [10]

Why it's confusing for me? Because In "Recursion" chapter says that stack runs from up to down like on following screenshot:

16-07-2017 00-02-30

also on last part:

quicksort([]).concat([2], quicksort([3]))

when quicksort function gets array [3]:

quicksort([3])

but since base case return true if (array.length < 2) { return array } we just return [3] array and code stop working.

last

What happens on this part?

Can anyone help me to understand where I made a mistake in my explanations? What am I wrong about?

7.1_C Answer - 4

Hi, thanks for this great work,

Yes, negative weighted edge there in 7.1 C graph, but no negative cycle, right?

Thus we do have a shortest path from start to finish, whose weight is 4, true?

Screenshot 2020-01-30 at 1 23 07 PM

JavaScript/ES6 solution has formatting problems for chapter six

  1. For formatting JavaScript code is better to use Prettier. This will help in all examples to make the same formatting and it will look better.
  2. Function 02_breadth-first_search_by_Rytikov_Dmitrii has problems: functions need a second argument to work correctly, you must add default values ​​so that the function doesn't cause errors when there aren't enough arguments

Problem regarding Dijkstra's algorithm with changed values

For the given graph, when I changed the values of A and B, where A < B. I don't get the desired path.
Here's the link to the code. I have checked for negative-weight edges and found none. I have also implemented a function that shows the final path.

Result for the given graph:
firstprint

Result with changed values
secondprint

spelling mistake

page 59. "Sneak peak at functional programming"

I guess it's Sneak peek rather than Sneak peak.

Providing code examples for data structures

I've just started to read the book and went across all the repo in search for the example of linked list in JS, so it occurred to me it would be handy for the programming newcomers to have code examples of all the themes that your book covers, not only the main ones.

Java Chapter 1

In BinarySearch.java
Since the array myList is unsorted, the binary search algorithm may not produce the correct result. While the algorithm might still run without errors, the output cannot be guaranteed to be accurate because it's searching in an unsorted context.

If you provide me permission I will open the Merge Request for the bug.

C# Examples

I would like to contribute C# examples to your project. I have a question though. Do you prefer idiomatic examples or examples that are essentially translations of the Python code? I can do either.

answer to question # 2.2

Answer to question 2.2 says - A linked list because Lots of inserts are happening (servers
adding orders), which linked lists excel at. You don’t need search
or random access (what arrays excel at), because the chefs always
take the first order off the queue.

Isn't in queue insert always happens at last and array would be better choice ?

Or this answer is driven by considering factor - "what if required space is not available in existing contiguous block ? "

JavaScript/ES6 solution has formatting problems for chapter nine

  1. For formatting JavaScript code is better to use Prettier. This will help in all examples to make the same formatting and it will look better.
  2. Example in folder grokking_algorithms/09_dynamic_programming/ES6/examples/ describes the same example as grokking_algorithms/09_dynamic_programming/ES6/01_longest_common_subsequence.js
    I think need to remove duplication and leave only a working example. Non-working input diff('fosh', 'fish') // displays 2, but correct 3

Dijkstra Algorithm Golang Issue

Hi guys, I am trying to run the Golang implementation on the graph below and the cost to the stop is the MaxInt set in the beginning.

	graph["start"] = map[string]int{}
	graph["start"]["b"] = 5
	graph["start"]["c"] = 2

	graph["b"] = map[string]int{}
	graph["b"]["d"] = 1
	graph["b"]["e"] = 4

	graph["c"] = map[string]int{}
	graph["c"]["b"] = 8
	graph["c"]["d"] = 7

	graph["d"] = map[string]int{}
	graph["d"]["stop"] = 1

	graph["e"] = map[string]int{}
	graph["e"]["d"] = 6
	graph["e"]["stop"] = 3
	
	graph["stop"] = map[string]int{}

I have added the following lines in the implementation while looping through the nodes of the lowestCostNode and it seems to now be working but I am not certain if that's the best approach or otherwise.

		for lowestCostNode != "" {
		for node, cost := range graph[lowestCostNode] {
			// The following three lines have been added
			if _, isSet := costs[node]; !isSet {
				costs[node] = cost
			}
			
			newCost := costs[lowestCostNode] + cost

			if newCost < costs[node] {
				costs[node] = newCost
				parents[node] = lowestCostNode
			}
		}

		processed[lowestCostNode] = true
		lowestCostNode = findLowestCostNode(costs, processed)
	}

08_greedy_algorithms/python/01_set_covering.py

......
for station, states in stations.items():
covered = (states_needed & states)
if len(covered) > len(states_covered):
best_station = station
states_covered = covered
......

should be like this:

......
for station, states in stations.items():
covered = (states_needed & states).union(states)
if len(covered) > len(states_covered):
best_station = station
states_covered = covered
......

Typo in the book page 9 Binary Search Code

In the book on page 9 there is binary search code written in python.
In the while loop you have assigned mid = (low + high) instead of mid = (low + high) / 2.

This is not a major issue but in your future copies if you correct it then it would be great.
I hope this is useful.
The book is amazing and easy to grasp I am enjoying it.

Typo in load factor (Chapter #5 hash tables)

Description

Hey, I wanted to point out that I found a discrepancy on the recommended time to resize a hash table. The images are from chapter 5 Hash tables, pages 92 & 94.

I'm guessing that in page 94, the highlighted load factor should also be 0.7 instead of .07.

image

image

Thanks for the amazing work on the book btw! I'm really loving how well concepts are explained.

Typo in python selection sort

Hi,
Current
if arr[i] < smallest: smallest_index = I

should be

if arr[i] < smallest: smallest_index = i smallest = arr[i]

Hacktoberfest Inclusion

Can you add the topic of Hacktoberfest, as I'm aiming to supply a few solutions for some languages that aren't fully covered in this book.

Prob in Contribution

Hey , I also want to contribute , but I am not able to create a branch in repo for pushing my contribution . It is giving Permission Denied error .

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.