├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── gui_search_and_launch ├── README.md ├── __init__.py ├── build.spec ├── core.py └── exercise_launcher.py ├── housekeeping ├── CONTRIBUTING.md ├── LICENSE ├── TODO.md ├── images │ └── interview-with-python-hero.png ├── repo_health_checkup.py └── repo_stats.py ├── problems ├── adjacency-list │ └── README.md ├── adjacency-matrix │ └── README.md ├── all-unique-characters │ └── README.md ├── anagram-detection │ ├── Readme.md │ └── anagram-detection-answer.py ├── array-pair-sum │ ├── Readme.md │ └── array-pair-sum-answer.py ├── arraylist │ └── README.md ├── balanced-brackets │ ├── Readme.md │ └── balanced-brackets-answer.py ├── base-ten-to-binary │ └── README.md ├── binary-islands │ └── README.md ├── binary-search-rotated │ └── README.md ├── binary-search-sorted │ └── README.md ├── binary-search-tree-check │ ├── Readme.md │ └── binary-search-tree-check-answer.py ├── binary-search-tree │ ├── Readme.md │ └── binary-search-tree-answer.py ├── breadth-first-traversal │ └── README.md ├── bubble-sort │ ├── Readme.md │ └── bubble-sort-answer.py ├── byte-format │ ├── README.md │ └── byte-format-answer.py ├── closest-sum │ ├── closest-sum-answer.py │ └── problem.txt ├── combine-two-strings │ ├── Readme.md │ └── combine-two-strings-answer.py ├── construst-bst-from-string │ └── README.md ├── convert-array │ ├── Readme.md │ └── convert-array-answer.py ├── count-string-characters │ └── README.md ├── counting-sort │ └── README.md ├── create_answer_files.py ├── csv-parsing │ ├── Readme.md │ └── csv-parsing-answer.py ├── csv_sorting │ └── README.md ├── debounce │ ├── Readme.md │ └── debounce-answer.py ├── depth-first-traversal │ └── README.md ├── deterministic-quick-select │ └── README.md ├── dict-of-squared-ints │ └── README.md ├── dijkstras_algorithm │ └── README.md ├── dir-function-equivelant │ └── README.md ├── dynamic-programming-primes │ └── README.md ├── euclids-algorithm │ └── README.md ├── even-occuring-element │ ├── Readme.md │ └── even-occuring-element-answer.py ├── factorial │ ├── factorial-answer.py │ └── readme.md ├── fibonacci │ ├── Readme.md │ └── fibonacci-answer.py ├── find-intersection │ └── README.md ├── find-lonely-element │ └── README.md ├── find-missing-element │ ├── Readme.md │ └── find-missing-element-answer.py ├── find-pairs-summing-to-ten │ └── README.md ├── find_anagrams_in_list │ └── README.md ├── first-non-repeated-character │ ├── Readme.md │ └── first-non-repeated-character-answer.py ├── first-nonrepeating-character │ └── README.md ├── fizz-buzz │ └── README.md ├── flatten-array │ ├── Readme.md │ └── flatten-array-answer.py ├── floyd-warshall-algorithm │ └── README.md ├── full-justification │ └── README.md ├── gender_inheritance │ └── README.md ├── generator-problems │ └── README.md ├── get-elements-by-class-name │ ├── Readme.md │ └── get-elements-by-class-name-answer.py ├── hashtable │ └── README.md ├── head-legs-chinese-puzzle │ └── README.md ├── hotel-room │ ├── Readme.md │ └── hotel-room-answer.py ├── insertion-sort │ ├── README.md │ └── insertion-sort-answer.py ├── integer-difference │ ├── Readme.md │ └── integer-difference-answer.py ├── integer-length │ ├── Readme.md │ └── integer-length-answer.py ├── knapsack-problems │ └── README.md ├── kth-largest-element-in-array │ ├── Readme.md │ └── kth-largest-element-in-array-answer.py ├── largest-continuous-sum │ ├── Readme.md │ └── largest-continuous-sum-answer.py ├── largest-palindrome │ ├── Readme.md │ └── largest-palindrome-answer.py ├── linked-list │ ├── Readme.md │ └── linked-list-answer.py ├── list-isa-rotation │ └── README.md ├── longest-common-prefix │ ├── Readme.md │ └── longest-common-prefix-answer.py ├── longest-compound-word │ ├── Readme.md │ └── longest-compound-word-answer.py ├── longest-words │ ├── Readme.md │ └── longest-words-answer.py ├── make-exponent │ └── README.md ├── map-reduce-filter-iter-problems │ └── README.md ├── markov-chain-monte-carlo │ └── README.md ├── matching-nodes │ ├── Readme.md │ └── matching-nodes-answer.py ├── median-integer-stream │ ├── Readme.md │ └── median-integer-stream-answer.py ├── merge-sort │ ├── Readme.md │ └── merge-sort-answer.py ├── missing-number │ ├── Readme.md │ └── missing-number-answer.py ├── money-format │ ├── Readme.md │ └── money-format-answer.py ├── most-frequent-integer │ └── README.md ├── multiples-of-3-and-5 │ ├── Readme.md │ └── multiples-of-3-and-5-answer.py ├── n-choose-k-problems │ └── README.md ├── next-highest-number │ ├── Readme.md │ └── next-highest-number-answer.py ├── next-palindrome-number │ ├── Readme.md │ └── next-palindrome-number-answer.py ├── number-format │ ├── Readme.md │ └── number-format-answer.py ├── odd-occuring-element │ ├── Readme.md │ └── odd-occuring-element-answer.py ├── once │ ├── Readme.md │ └── once-answer.py ├── page-rank │ └── README.md ├── palindrome-detection │ └── README.md ├── palindrome-shortest │ └── README.md ├── pancake-sort │ └── README.md ├── permutations-of-list │ └── README.md ├── prime-number │ ├── Readme.md │ └── prime-number-answer.py ├── probability-problems │ └── README.md ├── queen-threatens-king │ ├── queen-threatens-king-answer.py │ ├── queen-threatens-king.png │ └── readme.md ├── queue-from-two-stacks │ └── README.md ├── queue │ ├── Readme.md │ └── queue-answer.py ├── quick-sort │ ├── Readme.md │ └── quick-sort-answer.py ├── remove-duplicates-from-string │ ├── Readme.md │ └── remove-duplicates-from-string-answer.py ├── remove-duplicates │ └── README.md ├── reset_your_answers.py ├── reverse-words-in-string │ ├── Readme.md │ └── reverse-words-in-string-answer.py ├── rotate-matrix │ └── README.md ├── search-unknown-length-array │ ├── Readme.md │ └── search-unknown-length-array-answer.py ├── selection-sort │ ├── readme.md │ └── selection-sort-answer.py ├── shortest-fizz-buzz │ ├── Readme.md │ └── shortest-fizz-buzz-answer.py ├── skiing-in-singapore │ ├── README.md │ └── skiing-in-singapore-answer.py ├── sorted-array-search │ ├── Readme.md │ └── sorted-array-search-answer.py ├── spiral │ ├── Readme.md │ ├── input-1.png │ ├── input-2.png │ └── spiral-answer.py ├── spreadsheet │ ├── README.md │ └── spreadsheet-answer.py ├── square-root │ └── README.md ├── stack-machine │ ├── Readme.md │ └── stack-machine-answer.py ├── stack-sort │ └── README.md ├── stack │ ├── Readme.md │ └── stack-answer.py ├── stocks-max-subarray │ └── README.md ├── string-format │ ├── Readme.md │ └── string-format-answer.py ├── string-permutations │ ├── Readme.md │ └── string-permutations-answer.py ├── string-problems-general │ └── README.md ├── string-rotation │ ├── Readme.md │ └── string-rotation-answer.py ├── sum-of-array-plus-one │ ├── Readme.md │ └── sum-of-array-plus-one-answer.py ├── this-repos-scripts │ └── README.md ├── throttle │ ├── Readme.md │ └── throttle-answer.py ├── transform-word │ ├── Readme.md │ └── transform-word-answer.py ├── travelling-salesman-problem │ └── README.md ├── tree-level-order-print │ ├── Readme.md │ └── tree-level-order-print-answer.py ├── triples_summing_to_x │ └── README.md ├── type-function-equivalent │ └── README.md ├── type-function-equivelant │ └── README.md ├── word-analytics │ ├── Readme.md │ ├── huckleberry-finn.txt │ └── word-analytics-answer.py └── word-positions │ ├── Readme.md │ └── word-positions-answer.py ├── search_and_launch.py ├── solutions ├── README.md ├── c │ ├── bubble-sort.c │ ├── factorial.c │ ├── find-missing-element.c │ ├── multiples-of-3-and-5.c │ ├── selection-sort.c │ ├── sgski.c │ ├── shortest-fizz-buzz.c │ ├── spreadsheet │ │ ├── 3x2.txt │ │ ├── Makefile │ │ ├── README.md │ │ ├── commons.c │ │ ├── commons.h │ │ ├── matrix.c │ │ ├── matrix.h │ │ ├── matrixTest │ │ ├── regex.c │ │ ├── regex.h │ │ ├── spreadsheet │ │ ├── spreadsheet.c │ │ ├── stackcalc.c │ │ ├── stackcalc.h │ │ └── tests │ │ │ ├── Makefile │ │ │ ├── core │ │ │ ├── matrixTest │ │ │ └── matrix_test.c │ ├── stack.c │ └── stack.h ├── cpp │ ├── once.hpp │ ├── queue.hpp │ ├── spiral.hpp │ └── stack.hpp └── python │ ├── adjacency-list.py │ ├── adjacency-matrix.py │ ├── all-unique-characters.py │ ├── anagram-detection.py │ ├── array-pair-sum.py │ ├── arraylist.py │ ├── balanced-brackets.py │ ├── base-ten-to-binary.py │ ├── binary-islands.py │ ├── binary-search-sorted.py │ ├── bubble-sort.py │ ├── closetsum.py │ ├── convert-array.py │ ├── count-string-characters.py │ ├── csv-parsing.py │ ├── csv-sort.py │ ├── deterministic-quick-select.py │ ├── dict-of-squared-ints.py │ ├── dijsktra.py │ ├── dir-function-equivelant.py │ ├── euclids-algorithm.py │ ├── even-occuring-element.py │ ├── factorial.py │ ├── fibonacci.py │ ├── find-missing-element.py │ ├── find-pairs-summing-to-ten.py │ ├── find_anagrams_in_list.py │ ├── first-non-repeated-character.py │ ├── fizz-buzz.py │ ├── flatten-array.py │ ├── gender-inheritance.py │ ├── hashtable.py │ ├── head-tails-chinese-puzzle.py │ ├── knapsack-problems.py │ ├── kruskals-algorithm │ ├── kruskal-one.py │ └── kruskal-two.py │ ├── largest-continuous-sum.py │ ├── linked-list.py │ ├── merge-sort.py │ ├── multiples-of-3-and-5.py │ ├── n-choose-k.py │ ├── once.py │ ├── permutations-of-list.py │ ├── prime-number.py │ ├── probability-problems.py │ ├── quick-sort.py │ ├── remove-duplicates.py │ ├── rotate-matrix.py │ ├── shortest-fizz-buzz.py │ ├── stock-max-subarray.py │ ├── string-permutations.py │ ├── sum-of-array-plus-one.py │ ├── this-repos-scripts.py │ ├── travelling-salesman-problem.py │ ├── travelling-salesman │ └── travelling-salesman-problem.py │ ├── tree-level-order-print.py │ ├── triples_summing_to_x.py │ └── type-function-equivelant.py ├── test_yourself.py ├── tests └── cpp │ ├── common.cpp │ ├── common.hpp │ ├── once.cpp │ ├── queue.cpp │ ├── spiral.cpp │ └── stack.cpp └── worded_questions ├── README.md └── answers ├── 3-ways-of-getting-every-third-from-list.ipynb ├── difference-between-_getattr_-and-_getattribute__.ipynb ├── how-does-garbage-collection-work.ipynb ├── how-to-read-8gb-file.ipynb ├── is-multithreading-in-python-a-good-idea.ipynb ├── maximum-recursion-depth-problem.ipynb ├── tell-me-about-GIL-concurrency-impact.ipynb ├── what-do-@classmethod-@staticmethod-@property-mean-to-you.ipynb ├── what-does-star-and-doublestar-do-to-args.ipynb ├── what-dont-you-like-about-python.ipynb ├── what-is-monkey-patching-is-it-a-good-idea.ipynb └── what-is-python-really.ipynb /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | #*.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | # Ipython notebook checkpoints 92 | */*/.ipynb_checkpoints 93 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Jonathon Belotti 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/sh 2 | TEST_DIR := tests 3 | GTEST_DIR := $(TEST_DIR)/cpp/gtest 4 | 5 | 6 | # C++11 tests 7 | CPP_TESTS := stack-machine.cpp once.cpp stack.cpp queue.cpp spiral.cpp 8 | CPP_SOURCES := $(addprefix $(TEST_DIR)/cpp/, $(CPP_TESTS)) 9 | 10 | 11 | # OS specific settings 12 | UNAME_S = $(shell uname -s) 13 | ifeq ($(UNAME_S),Darwin) 14 | CXXFLAGS += -std=c++11 -stdlib=libc++ 15 | LDFLAGS += -lc++ 16 | CXX := clang++ 17 | else ifeq ($(UNAME_S),Linux) 18 | CXXFLAGS += --std=c++11 -g 19 | CXX := g++ 20 | endif 21 | 22 | 23 | # Languages 24 | default: 25 | @echo "Usage: make " 26 | @echo "Available languages: cpp, js" 27 | 28 | 29 | # Not recommended 30 | .IGNORE: cpp js 31 | all: .IGNORE 32 | 33 | 34 | # C++ build rules 35 | OTHER_SOURCES := $(TEST_DIR)/cpp/common.cpp 36 | FUSED_GTEST_SOURCES := $(GTEST_DIR)/gtest-all.cc $(GTEST_DIR)/gtest_main.cc 37 | CXXFLAGS += -DGTEST_HAS_PTHREAD=0 -DGTEST_HAS_TR1_TUPLE=0 -g 38 | CPP_OBJECTS := $(CPP_SOURCES:.cpp=.o) 39 | FUSED_GTEST_OBJECTS := $(FUSED_GTEST_SOURCES:.cc=.o) 40 | OTHER_OBJECTS := $(OTHER_SOURCES:.cpp=.o) 41 | cpp: hasGTest $(FUSED_GTEST_OBJECTS) $(CPP_OBJECTS) $(OTHER_OBJECTS) 42 | @$(CXX) $(LDFLAGS) \ 43 | $(CPP_OBJECTS) $(FUSED_GTEST_OBJECTS) $(OTHER_OBJECTS)\ 44 | -o cpp 45 | @./cpp 46 | @rm -rf cpp 47 | hasGTest: 48 | @if [ ! -f $(GTEST_DIR)/gtest.h ]; then \ 49 | git submodule update --init -f $(GTEST_DIR); \ 50 | fi 51 | .cpp.o: 52 | @$(CXX) $(CXXFLAGS) -c $< -o $@ 53 | .cc.o: 54 | @$(CXX) $(CXXFLAGS) -c $< -o $@ 55 | 56 | 57 | # JS build rules 58 | js: 59 | @npm install 2> /dev/null 60 | @npm test 61 | 62 | 63 | # Cleanup 64 | clean: 65 | @rm -f $(CPP_OBJECTS) $(FUSED_GTEST_OBJECTS) 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # INTERVIEW WITH PYTHON 2 | 3 | ### More python code examples and exercises than you could ever need, all documented and explained for effective and fast learning. Comes with a *GUI Exercise Search and Launcher* out of the box*. 4 | 5 |

6 | 7 |

8 | 9 | ### Why Use This Repo Over Others? 10 | #### 1. It has the most python code exercises of any repo on Github, and they're *EASILY SEARCHABLE*. 11 | #### 2. The code exercises are *ACTUALLY DOCUMENTED AND EXPLAINED*. 12 | #### 3. You can easily *TEST YOURSELF* with the `test_yourself.py` script*. 13 | #### 4. All the code exercises have *SOLUTIONS*, with code comment explanations included. 14 | #### 4. All the code in this repo has *UNIT TESTING* for you to verify against. It also checks the *solutions* code. 15 | 16 | ### ```* Coming Soon :)``` 17 | 18 | ## SETUP AND USAGE 19 | 20 | Either *fork* or *clone* this repo, and you are good to go! There are `-answer.py` files to add your solutions, and these are found in `/solutions//`. 21 | 22 | Dependencies have been avoided and should be in the future, so now `pip` installing need be done. It's standard library or nothing. 23 | 24 | ## ADDITIONAL 25 | 26 | #### Searching For Exercises 27 | 28 | Run `python search_and_launch.py your search terms here` to return a list of exercises whose *tags* match your terms. 29 | 30 | #### Tags? 31 | 32 | I am tagging all exercises, because maybe you want to work on *graph-search* algorithms specifically and who wants to search through 100 problem folders just going off the folder name. Tags are found in the *problem answer file* which are located at `/problems//-answer.py` 33 | 34 | ## FAQ & TROUBLESHOOT 35 | 36 | #### What's Housekeeping For? 37 | 38 | This repo already contains a lot of problems, and thus a lot of files and supporting files. It's only going to get bigger, so I'm working on some basic scripts to manage the repo's 'health' and to track its growth. 39 | 40 | Other things related to the repo but not the questions and exercises directly are in here to. Like the [CONTRIBUTING.md](/Housekeeping/CONTRIBUTING.md) file and the [LICENSE](/housekeeping/LICENSE) and the [TODO.md](/housekeeping/TODO.md). 41 | 42 | #### Why Am I Seeing C++ In Here? 43 | 44 | When you need speed and a deeper understanding of a problem Python can be a too slow and too 'high-level'. Where it's useful I aim to include C++ solutions (or maybe Java, C) to show a solution that is efficient and doesn't hide away some of the complexity. 45 | 46 | ## CONTRIBUTING 47 | 48 | I would be very happy to receive contributions. Find some simple guidelines in the [CONTRIBUTING.md](/housekeeping/CONTRIBUTING.md) doc. 49 | -------------------------------------------------------------------------------- /gui_search_and_launch/README.md: -------------------------------------------------------------------------------- 1 | # GUI SEARCH AND LAUNCH WIDGET 2 | 3 | Use this to quick find the code exercises and questions that you want. There are *a lot* of files in this repository, and it's not getting any smaller. 4 | 5 | ### !STATUS! Command-Line Program in development... 6 | 7 | ### USAGE 8 | 9 | Open up the widget and enter in a query as a series of **tags**. All files in this repository have a header with tags, so that their contents are revealed to this searcher. 10 | 11 | The widget will return as list of files which you can launch from there. 12 | -------------------------------------------------------------------------------- /gui_search_and_launch/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thundergolfer/interview-with-python/b5ce31c8bdca754a76762d2734dcf494a302e487/gui_search_and_launch/__init__.py -------------------------------------------------------------------------------- /gui_search_and_launch/build.spec: -------------------------------------------------------------------------------- 1 | import gooey 2 | gooey_root = os.path.dirname(gooey.__file__) 3 | gooey_languages = Tree(os.path.join(gooey_root, 'languages'), prefix = 'gooey/languages') 4 | gooey_images = Tree(os.path.join(gooey_root, 'images'), prefix = 'gooey/images') 5 | a = Analysis(['core.py'], # might need to change 6 | pathex=['c:\\Python27\\Scripts'], 7 | hiddenimports=[], 8 | hookspath=None, 9 | runtime_hooks=None, 10 | ) 11 | pyz = PYZ(a.pure) 12 | 13 | options = [('u', None, 'OPTION'), ('u', None, 'OPTION'), ('u', None, 'OPTION')] 14 | 15 | exe = EXE(pyz, 16 | a.scripts, 17 | a.binaries, 18 | a.zipfiles, 19 | a.datas, 20 | options, 21 | gooey_languages, # Add them in to collected files 22 | gooey_images, # Same here. 23 | name='Search And Launch Widget', 24 | debug=False, 25 | strip=None, 26 | upx=True, 27 | console=False, 28 | windowed=True, 29 | icon=os.path.join(gooey_root, 'images', 'program_icon.ico')) 30 | -------------------------------------------------------------------------------- /gui_search_and_launch/core.py: -------------------------------------------------------------------------------- 1 | # 2 | # Author: Jonathon Belotti 3 | # 4 | from __future__ import print_function 5 | import os 6 | from argparse import ArgumentParser 7 | from exercise_launcher import launch_python_script 8 | 9 | def main(): 10 | 11 | parser = ArgumentParser(description='Get your search query') 12 | parser.add_argument('query', type=str, nargs='+', help='enter some tags to search for') 13 | list_of_arg_words = vars(parser.parse_args())['query'] # SO SORRY FOR THIS LINE. IN A RUSH DON'T JUDGE ME 14 | query = [tag.lower() for tag in list_of_arg_words] # search query as a list of 'tokens'. eg ['this','is','my','search'] 15 | print("query is: ", query) 16 | 17 | file_matches = [] 18 | 19 | # TODO: Make this code not kinda rubbish 20 | # Search through all questions in "problems" and "worded_questions" 21 | for folder, subfolders, files in os.walk(os.getcwd(), topdown=False): 22 | for f in files: 23 | fullpath = os.path.join(folder,f) 24 | if (('problems' in fullpath or 'worded_questions' in fullpath) 25 | and not fullpath.endswith('.md')): # This will very likely admit TOO MANY files. TODO: fix it 26 | with open(fullpath, 'r') as question_file: 27 | try: 28 | lines = question_file.readlines() 29 | except UnicodeDecodeError: 30 | print("Couldn't read: ", fullpath) 31 | 32 | # if at least one tag matches, add the file with its tags to our list 33 | matched_tags = match_tags( get_tags_from_file(lines), query) 34 | if matched_tags: 35 | file_matches.append( (matched_tags, fullpath ) ) # TODO: fix this hammy way of handling filename 36 | 37 | # order the matched files by number of matched tags. Ascending order 38 | file_matches = sorted(file_matches, key=lambda x: len(x[0]), reverse=True) 39 | print("Matched Files: ") # TODO replace this print to console bit with something more useful 40 | for i, match in enumerate(file_matches): 41 | tags, name = match[0], '...' + match[1][-60:] 42 | print(str(i), ': ', name) 43 | print("\tMatches on: " , tags) 44 | 45 | choice = get_menu_choice( len(file_matches) ) 46 | fp = file_matches[choice][1] 47 | launch_python_script(fp) 48 | 49 | def match_tags( tags, query_tags ): 50 | return [tag.lower() for tag in tags if tag.lower() in query_tags] 51 | 52 | def get_menu_choice( max_item ): 53 | while True: 54 | choice = input("Choose a file to open: ") 55 | try: 56 | choice = int(choice) 57 | if choice > 0 and choice <= max_item: 58 | break 59 | else: 60 | print("Invalid input. Please try again.") 61 | except ValueError: 62 | print("Please enter an integer.") 63 | 64 | return choice 65 | 66 | def get_tags_from_file( lines ): 67 | """ 68 | Extract the tags from a file and return them as a list 69 | """ 70 | tags_header = "##$$##" 71 | for i, line in enumerate(lines): 72 | if tags_header in line: 73 | break 74 | else: # didn't break out of loop so no tags header 75 | return [] 76 | tags_line = lines[i+1] 77 | just_tags = (''.join(ch for ch in tags_line if (ch.isalnum()) or ch == ',')).split(',') 78 | return [word.strip() for word in just_tags] # remove trailing and leading whitespace 79 | 80 | if __name__ == '__main__': 81 | main() 82 | -------------------------------------------------------------------------------- /gui_search_and_launch/exercise_launcher.py: -------------------------------------------------------------------------------- 1 | import subprocess # for running subprocesses like we are in the command line 2 | import os 3 | import sys 4 | 5 | def launch_notebook( filepath ): 6 | """ Launch a python notebook for the user. To make their life easier. """ 7 | raise NotImplementedError 8 | 9 | ## This might be a problem as we won't know which editor to open... 10 | ## Also the opening process will be diffenent for different systems. 11 | ## Even finding the "default" way to open a .py file for editing might be 12 | ## different across systems. 13 | ## 14 | ## SOLUTION: Just open default .txt editor and say "it's a good thing you're working barebones. No crutches." 15 | ## 16 | def launch_python_script( filepath ): 17 | """ Launch an editor for the named python script. """ 18 | 19 | import subprocess, os 20 | if sys.platform.startswith('darwin'): 21 | subprocess.call(('open', filepath)) 22 | elif os.name == 'nt': 23 | os.startfile(filepath) 24 | elif os.name == 'posix': 25 | subprocess.call(('xdg-open', filepath)) 26 | 27 | 28 | if __name__ == '__main__': 29 | launch_python_script("hello.py") 30 | -------------------------------------------------------------------------------- /housekeeping/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # CONTRIBUTING 2 | 3 | ### First up, thanks for thinking of contributing to this repo. Here's what you need to do if... 4 | 5 | 1. [You're adding a new exercise](#if-you-are-adding-a-new-exercise) 6 | 1. [You're improving existing code](#if-you-are-improving-the-code-in-an-existing-exercise) 7 | 1. [You're improving documentation or explanations](#if-you-are-changing-documentation-and-explanation) 8 | 9 | ### If You Are Adding A New Exercise... 10 | `coming-soon` 11 | 12 | ### If You Are Improving The Code In An Existing Exercise... 13 | `coming-soon` 14 | 15 | ### If You Are Changing Documentation And Explanation.... 16 | `coming-soon` 17 | -------------------------------------------------------------------------------- /housekeeping/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Jonathon Belotti 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /housekeeping/TODO.md: -------------------------------------------------------------------------------- 1 | # TODO 2 | 3 | ### FOR... GUI SEARCH AND LAUNCH 4 | 5 | * Implement ability to track when files were last modified on **your** machine. We could then give a summary of what you might be 'rusty' on. 6 | 7 | ### FOR... PROBLEMS 8 | 9 | * Document and Explain all code exercises that don't have it. 10 | * We want to include all the CodeJam problems. There are a lot of them so we need either a lot of time, or a scraping solution. So investigate a scraping solution for CodeJam past problems. 11 | * Go through this https://www.quora.com/What-algorithms-and-data-structures-should-any-software-engineer-know page and extract good problem ideas. 12 | * Go throuh project euler https://projecteuler.net/archives to extract good problems 13 | 14 | ### FOR... WORDED PROBLEMS 15 | -------------------------------------------------------------------------------- /housekeeping/images/interview-with-python-hero.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thundergolfer/interview-with-python/b5ce31c8bdca754a76762d2734dcf494a302e487/housekeeping/images/interview-with-python-hero.png -------------------------------------------------------------------------------- /housekeeping/repo_stats.py: -------------------------------------------------------------------------------- 1 | # Get stats on the number of questions, answers, lines of code etc etc in the repo. 2 | 3 | import os 4 | import sys 5 | from os import listdir 6 | from os.path import isfile, isdir, join, splitext 7 | 8 | def main(): 9 | """ Run through all relevant files in the projet and print to console some stats. """ 10 | nloc_in_project, num_problems, num_questions = 0,0,0 11 | search_dir = os.path.dirname(os.getcwd()) # we want the parent directory 12 | for folder, subfolders, files in os.walk(search_dir, topdown=False): 13 | for f in files: 14 | fullpath = os.path.join(folder,f) 15 | if (not fullpath.endswith('.py') 16 | and not fullpath.endswith('.ipynb') 17 | and not fullpath.endswith('.md')): continue # ignore .git hidden folder files and others 18 | with open(fullpath, 'r') as f: 19 | try: 20 | lines = f.readlines() 21 | except UnicodeDecodeError: continue 22 | if fullpath.endswith('.py'): nloc_in_project += len(lines) 23 | if fullpath.endswith('.py') and '-answer' in fullpath: num_problems += 1 24 | if fullpath.endswith('.ipynb'): num_questions += 1 25 | 26 | print("Lines of code in project: ", nloc_in_project) 27 | print("Number of Code Exercises: ", num_problems) 28 | print("Number of Worded Questions: ", num_questions ) 29 | 30 | 31 | 32 | def line_count_file(file_path, flags=None): 33 | """ Counts lines for given file in file_name """ 34 | try: 35 | count = 0 36 | with open(file_path) as current_file: 37 | for line in current_file: 38 | if line.strip() == "" and flags != None and \ 39 | "--noempty" in flags: 40 | continue 41 | count += 1 42 | 43 | return count 44 | except IOError: 45 | return -1 46 | 47 | def line_count_files(file_name_list, flags=None): 48 | """ Counts lines for given set of files """ 49 | total = 0 50 | for file_name in file_name_list: 51 | current = line_count_file(file_name, flags) 52 | if current >= 0: 53 | total += current 54 | print("%6d lines in %s" % (current, file_name)) 55 | else: 56 | print("error: file not found (" + file_name + ")") 57 | return total 58 | 59 | def line_count_dir(dir_path, flags, filters): 60 | """ Counts lines for files which are in given directory path and matches 61 | filter requirements """ 62 | total = 0 63 | 64 | if "--filter" in flags: 65 | file_list = [join(dir_path, file_p) for file_p in listdir(dir_path) 66 | if isfile(join(dir_path, file_p)) and 67 | splitext(join(dir_path, file_p))[1] in filters] 68 | else: 69 | file_list = [join(dir_path, file_p) for file_p in listdir(dir_path) 70 | if isfile(join(dir_path, file_p))] 71 | 72 | total += line_count_files(file_list, flags) 73 | 74 | if "-r" in flags: 75 | dir_list = [join(dir_path, directory) for directory in listdir(dir_path) 76 | if isdir(join(dir_path, directory))] 77 | for directory in dir_list: 78 | total += line_count_dir(directory, flags, filters) 79 | 80 | return total 81 | 82 | if __name__ == '__main__': 83 | main() 84 | -------------------------------------------------------------------------------- /problems/adjacency-list/README.md: -------------------------------------------------------------------------------- 1 | # Adjacency List 2 | 3 | Implement an adjacency list in python code. 4 | -------------------------------------------------------------------------------- /problems/adjacency-matrix/README.md: -------------------------------------------------------------------------------- 1 | # Adjacency Matrix 2 | 3 | Implement an adjacency matrix graph in python code. 4 | -------------------------------------------------------------------------------- /problems/all-unique-characters/README.md: -------------------------------------------------------------------------------- 1 | # All Unique Characters 2 | 3 | Check if a string is composed of all unique characters. 4 | 5 | ```python 6 | all_unique("abekdop") # > True 7 | all_unique("I am a man.") # > False 8 | ``` 9 | -------------------------------------------------------------------------------- /problems/anagram-detection/Readme.md: -------------------------------------------------------------------------------- 1 | # Anagram Detection 2 | 3 | Write a function that accepts two parameters, a parent and a child string. Determine how many times the child string - or an anagram of the child string - appears in the parent string. There is a solution which can be done in near instant time. 4 | 5 | ```js 6 | f('AdnBndAndBdaBn', 'dAn') // 4 ("Adn", "ndA", "dAn", "And") 7 | f('AbrAcadAbRa', 'cAda') // 2 8 | ``` 9 | -------------------------------------------------------------------------------- /problems/anagram-detection/anagram-detection-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## anagram,detection 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/array-pair-sum/Readme.md: -------------------------------------------------------------------------------- 1 | # Array Pair Sum 2 | 3 | Given an integer array, output all distinct pairs that sum up to a specific value k. Consider the fact that the same number can add up to `k` with its duplicates in the array. 4 | 5 | > For example the array is [1, 1, 2, 3, 4] and the desired sum is 4. Should we output the pair (1, 3) twice or just once? Also do we output the reverse of a pair, meaning both (3, 1) and (1, 3)? Let’s keep the output as short as possible and print each pair only once. So, we will output only one copy of (1, 3). Also note that we shouldn’t output (2, 2) because it’s not a pair of two distinct elements. 6 | 7 | ## Example 8 | 9 | ``` 10 | f(10, [3, 4, 5, 6, 7]) // [ [4, 6], [3, 7] ] 11 | f(8, [3, 4, 5, 4, 4]) // [ [3, 5], [4, 4], [4, 4], [4, 4] ] 12 | f(10, [3, 5, 6, 8]) // [] 13 | ``` 14 | 15 | ## Source 16 | 17 | [http://www.ardendertat.com/2011/09/17/programming-interview-questions-1-array-pair-sum/](http://www.ardendertat.com/2011/09/17/programming-interview-questions-1-array-pair-sum/) 18 | -------------------------------------------------------------------------------- /problems/array-pair-sum/array-pair-sum-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## array,pair,sum 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/arraylist/README.md: -------------------------------------------------------------------------------- 1 | # Arraylist 2 | 3 | Implement the Arraylist data structure in python. 4 | -------------------------------------------------------------------------------- /problems/balanced-brackets/Readme.md: -------------------------------------------------------------------------------- 1 | # Balanced Brackets 2 | 3 | Write a function that accepts a string consisting entirely of brackets (`[](){}`) and returns whether it is balanced. Every "opening" bracket must be followed by a closing bracket of the same type. There can also be nested brackets, which adhere to the same rule. 4 | 5 | ```js 6 | f('()[]{}(([])){[()][]}') // true 7 | f('())[]{}') // false 8 | f('[(])') // false 9 | ``` 10 | -------------------------------------------------------------------------------- /problems/balanced-brackets/balanced-brackets-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## balanced,brackets 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/base-ten-to-binary/README.md: -------------------------------------------------------------------------------- 1 | # Base 10 to Binary 2 | 3 | Write a function that prints out the binary form of an int. 4 | 5 | ```python 6 | base_ten_to_binary(17) # > 10001 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/binary-islands/README.md: -------------------------------------------------------------------------------- 1 | # Binary Islands 2 | 3 | Given a 2D array of 1's and 0's, count the number of "islands of 1s". (eg. groups of connecting 1s) 4 | 5 | ```python 6 | binary_islands([[0,0,0,0,0,1], 7 | [0,0,1,1,0,0], 8 | [0,0,0,0,0,0]]) # > 2 9 | ``` 10 | -------------------------------------------------------------------------------- /problems/binary-search-rotated/README.md: -------------------------------------------------------------------------------- 1 | # Binary Search Rotated 2 | 3 | Implement binary search on a rotated array. 4 | 5 | ```python 6 | bin_search_rotated([5,6,7,8,1,2,3,4], 1) # > True 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/binary-search-sorted/README.md: -------------------------------------------------------------------------------- 1 | # Binary Search Sorted 2 | 3 | Implement binary search of a sorted array of integers. 4 | 5 | ```python 6 | bin_search_sorted([1,3,4,5,99,100,434], 99) # > True 7 | ``` 8 | 9 | // TODO 10 | -------------------------------------------------------------------------------- /problems/binary-search-tree-check/Readme.md: -------------------------------------------------------------------------------- 1 | # Binary Search Tree Check 2 | 3 | Given a binary tree, check whether it’s a binary search tree or not. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/10/10/programming-interview-questions-7-binary-search-tree-check/](http://www.ardendertat.com/2011/10/10/programming-interview-questions-7-binary-search-tree-check/) 8 | -------------------------------------------------------------------------------- /problems/binary-search-tree-check/binary-search-tree-check-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## binary,search,tree,check 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/binary-search-tree/Readme.md: -------------------------------------------------------------------------------- 1 | # Binary Search Tree 2 | 3 | Gives methods to create a binary search tree. 4 | 5 | ## Source 6 | 7 | [http://en.wikipedia.org/wiki/Binary_search_tree](http://en.wikipedia.org/wiki/Binary_search_tree) 8 | -------------------------------------------------------------------------------- /problems/binary-search-tree/binary-search-tree-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## binary,search,tree 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/breadth-first-traversal/README.md: -------------------------------------------------------------------------------- 1 | # Breadth First Traversal Problems 2 | 3 | Problems tied to the classic searching algorithm. 4 | 5 | // TODO 6 | -------------------------------------------------------------------------------- /problems/bubble-sort/Readme.md: -------------------------------------------------------------------------------- 1 | # Bubble Sort 2 | 3 | Implement the [bubble sort algorithm](http://en.wikipedia.org/wiki/Bubble_sort). 4 | -------------------------------------------------------------------------------- /problems/bubble-sort/bubble-sort-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## bubble,sort 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/byte-format/README.md: -------------------------------------------------------------------------------- 1 | # Byte String 2 | 3 | Convert a number to a string that represents a rounded size in bytes. 4 | 5 | ## Example 6 | 7 | ``` 8 | f(156833213) // => "149.57 MB" 9 | f(8101) // => "7.91 KB" 10 | f(12331, 3) // => "12.042 KB" 11 | ``` 12 | 13 | ## Source 14 | 15 | By [Riga](https://github.com/riga). 16 | -------------------------------------------------------------------------------- /problems/byte-format/byte-format-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## byte,format 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/closest-sum/closest-sum-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## closest,sum 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/closest-sum/problem.txt: -------------------------------------------------------------------------------- 1 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. 2 | Return the sum of the three integers. 3 | You may assume that each input would have exactly one solution. 4 | 5 | Example: 6 | given array S = {-1 2 1 -4}, 7 | and target = 1. 8 | 9 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2) -------------------------------------------------------------------------------- /problems/combine-two-strings/Readme.md: -------------------------------------------------------------------------------- 1 | # Combine Two Strings 2 | 3 | We are given 3 strings: str1, str2, and str3. Str3 is said to be a shuffle of str1 and str2 if it can be formed by interleaving the characters of str1 and str2 in a way that maintains the left to right ordering of the characters from each string. For example, given str1="abc" and str2="def", str3="dabecf" is a valid shuffle since it preserves the character ordering of the two strings. So, given these 3 strings write a function that detects whether str3 is a valid shuffle of str1 and str2. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/10/10/programming-interview-questions-6-combine-two-strings/](http://www.ardendertat.com/2011/10/10/programming-interview-questions-6-combine-two-strings/) 8 | -------------------------------------------------------------------------------- /problems/combine-two-strings/combine-two-strings-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## combine,two,strings 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/construst-bst-from-string/README.md: -------------------------------------------------------------------------------- 1 | # Construct BST from String 2 | 3 | Construct BST from the pre-order and in-order traversal strings 4 | 5 | // TODO. example 6 | -------------------------------------------------------------------------------- /problems/convert-array/Readme.md: -------------------------------------------------------------------------------- 1 | # Convert Array 2 | 3 | Given an array `[a1, a2, ..., aN, b1, b2, ..., bN, c1, c2, ..., cN]` convert it to `[a1, b1, c1, a2, b2, c2, ..., aN, bN, cN]` in-place using constant extra space. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/10/18/programming-interview-questions-9-convert-array/](http://www.ardendertat.com/2011/10/18/programming-interview-questions-9-convert-array/) 8 | -------------------------------------------------------------------------------- /problems/convert-array/convert-array-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## convert,array 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/count-string-characters/README.md: -------------------------------------------------------------------------------- 1 | # Count String Characters 2 | 3 | Please write a program which counts and returns the numbers of each character in a string input by console. 4 | 5 | ``` 6 | count_characters( "abcdegabc" ) # { 'a':2, 'c':2, 'b':2, 'e':1, 'd':1, 'g':1 } 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/counting-sort/README.md: -------------------------------------------------------------------------------- 1 | # Counting Sort 2 | 3 | // TODO: do problem description 4 | -------------------------------------------------------------------------------- /problems/create_answer_files.py: -------------------------------------------------------------------------------- 1 | # 2 | # Create a file in each problem directory named -answer.py, if that file doesn't already exist. 3 | # 4 | # Author: Jonathon Belotti 5 | # 6 | import os 7 | 8 | tags_header = "##$$## ---------- TAGS ----------- ##$$##\n" 9 | tags_footer = "##$$## --------- ENDTAGS --------- ##$$##\n" 10 | user_prompt = "###### - Write your answer below - ######\n" 11 | 12 | for root, dirs, files in os.walk(".", topdown=False): 13 | for name in dirs: 14 | new_fp = os.path.join(root,name, name + '-answer.py') 15 | if not os.path.isfile(new_fp): 16 | with open(new_fp, 'w') as newfile: 17 | # write the directory name in as tags 18 | tag_tokens = name.split('-') 19 | newfile.write(tags_header) 20 | newfile.write('##$$## ' + ','.join(tag_tokens)+'\n') 21 | newfile.write(tags_footer) 22 | newfile.write('\n') 23 | newfile.write(user_prompt) 24 | -------------------------------------------------------------------------------- /problems/csv-parsing/Readme.md: -------------------------------------------------------------------------------- 1 | # CSV Parsing 2 | 3 | Write a function that accepts a string as it's only argument. The string consists of comma-separated values and all values are either an integer or a string. Return an array of the parsed input string. 4 | 5 | ```js 6 | f('2,6,3,2,5') // [ 2, 6, 3, 2, 5 ] 7 | 8 | f('"pears","apples","walnuts","grapes","cheese,cake"') // [ "pears", "apples", "walnuts", "grapes", "cheese,cake" ] 9 | 10 | f('1,"Que?","Kay?",2,"Si.","Sea? Kay, sea?","No, no, no. Que... ‘what’.",234,"Kay Watt?","Si, que ‘what’.","C.K. Watt?",3,"Yes!","comma,comma, comma , :)"') // [ 1, "Que?", "Kay?", 2, "Si.", "Sea? Kay, sea?", "No, no, no. Que... ‘what’." 234, "Kay Watt?", "Si, que ‘what’.", "C.K. Watt?", 3, "Yes!", "comma,comma, comma , :)" ] 11 | ``` 12 | -------------------------------------------------------------------------------- /problems/csv-parsing/csv-parsing-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## csv,parsing 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/csv_sorting/README.md: -------------------------------------------------------------------------------- 1 | # CSV Sorting 2 | 3 | Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. 4 | 5 | ``` 6 | sort_csv("without,hello,bag,world") # > bag,hello,without,world 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/debounce/Readme.md: -------------------------------------------------------------------------------- 1 | # Debounce 2 | 3 | Write a function that accepts a function and timeout, `x`, in number of milliseconds. It will return a new function that can only be executed on per timeout period - and if the function is invoked during the timeout period, the timeout period restarts. This is useful for functions that can be need to be blocked on subsequent attempts over short period of times. Once such is example, is clicks on a button. 4 | 5 | Once written, add a third parameter that will allow the function to be executed immediately if set to true. Otherwise the function will run at the end of the timeout period. 6 | -------------------------------------------------------------------------------- /problems/debounce/debounce-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## debounce 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/depth-first-traversal/README.md: -------------------------------------------------------------------------------- 1 | # Depth first traversal problems 2 | 3 | Problems relating to depth first graph/tree traversal. 4 | 5 | // TODO 6 | -------------------------------------------------------------------------------- /problems/deterministic-quick-select/README.md: -------------------------------------------------------------------------------- 1 | # Deterministic Quick Select 2 | 3 | Implement the [Deterministic Selection Algorithm](https://www.ics.uci.edu/~eppstein/161/960130.html) in python code. 4 | 5 | // TODO 6 | -------------------------------------------------------------------------------- /problems/dict-of-squared-ints/README.md: -------------------------------------------------------------------------------- 1 | # Dictionary of squared ints 2 | 3 | With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. 4 | Suppose the following input is supplied to the program: 5 | 8 6 | Then, the output should be: 7 | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} 8 | 9 | ``` 10 | dict_of_squared_ints( 4 ) # {1: 1, 2: 4, 3: 9, 4: 16} 11 | ``` 12 | -------------------------------------------------------------------------------- /problems/dijkstras_algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Dijkstra's Algorithm 2 | 3 | Implement [Dijkstra's Algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm) in python code. Try to use not code 'crutches'. 4 | -------------------------------------------------------------------------------- /problems/dir-function-equivelant/README.md: -------------------------------------------------------------------------------- 1 | # dir() function equivelant 2 | 3 | Write a function that is the equivelant to python's `dir()` 4 | 5 | # TODO 6 | -------------------------------------------------------------------------------- /problems/dynamic-programming-primes/README.md: -------------------------------------------------------------------------------- 1 | # Dynamic Programming Primes 2 | 3 | Use dynamic programming to find the first X prime numbers. 4 | 5 | ```python 6 | dynamic_primes(4) # > [2,3,5,7] 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/euclids-algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Euclid's Algorithm 2 | 3 | Implement Euclid's algorithm for finding the GCD of two integers. The algorithm is described below. 4 | 5 | // TODO; describe it 6 | -------------------------------------------------------------------------------- /problems/even-occuring-element/Readme.md: -------------------------------------------------------------------------------- 1 | # Find Even Occurring Element 2 | 3 | Given an integer array, one element occurs even number of times and all others have odd occurrences. Find the element with even occurrences. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/11/29/programming-interview-questions-18-find-even-occurring-element/](http://www.ardendertat.com/2011/11/29/programming-interview-questions-18-find-even-occurring-element/) 8 | -------------------------------------------------------------------------------- /problems/even-occuring-element/even-occuring-element-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## even,occuring,element 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/factorial/factorial-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## factorial 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/factorial/readme.md: -------------------------------------------------------------------------------- 1 | Factorial 2 | ========== 3 | 4 | Factorial of any number n is defined as the multiplication of numbers from one to the given number. 5 | 6 | `` 7 | n! = 1 x 2 x 3 x 4 x ........ x n 8 | `` 9 | -------------------------------------------------------------------------------- /problems/fibonacci/Readme.md: -------------------------------------------------------------------------------- 1 | # Fibonacci 2 | 3 | By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. 4 | 5 | For example, the first ten Fibonacci numbers are: 6 | 7 | ``` 8 | 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 9 | ``` 10 | 11 | Write a function that accepts a number and returns the number at that position in the fibonnaci sequence. 12 | 13 | # Bonus: Use dynamic programming 14 | -------------------------------------------------------------------------------- /problems/fibonacci/fibonacci-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## fibonacci recursion iteration easy 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/find-intersection/README.md: -------------------------------------------------------------------------------- 1 | # Find Intersection 2 | 3 | Find the common elements of 2 integer arrays. This is basically the 'intersection' set operation. 4 | 5 | ```python 6 | find_intersection([1,4,4,66,77,100], [3,4,100]) # > [4, 100] 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/find-lonely-element/README.md: -------------------------------------------------------------------------------- 1 | # Find Lonely Element 2 | 3 | Find the only element in an array that only occurs once. If no element appear only once, just return False. 4 | 5 | ```python 6 | lonely_element([1,1,33,4,55,55,33]) # > 4 7 | lonely_element([1,2,3,4,5,6]) # > False 8 | ``` 9 | -------------------------------------------------------------------------------- /problems/find-missing-element/Readme.md: -------------------------------------------------------------------------------- 1 | # Find Missing Element 2 | 3 | There is an array of non-negative integers. A second array is formed by shuffling the elements of the first array and deleting a random element. Given these two arrays, find which element is missing in the second array. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/09/27/programming-interview-questions-4-find-missing-element/](http://www.ardendertat.com/2011/09/27/programming-interview-questions-4-find-missing-element/) 8 | -------------------------------------------------------------------------------- /problems/find-missing-element/find-missing-element-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## find,missing,element 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/find-pairs-summing-to-ten/README.md: -------------------------------------------------------------------------------- 1 | # Find pairs in an integer array whose sum is equal to 10 2 | 3 | Given an array/list, find all pairs of integers that sum to 10. A number can appear in multiple pairs. 4 | 5 | ### Bonus: Do it in linear time 6 | 7 | ```python 8 | pairs_sum_to_ten([1,4,6,9]) # > (1,9), (6,4) 9 | ``` 10 | 11 | // TODO 12 | -------------------------------------------------------------------------------- /problems/find_anagrams_in_list/README.md: -------------------------------------------------------------------------------- 1 | # Find Anagrams In List 2 | 3 | Given a **long** list of words, and a *target word*, find and return all words from the list that are an anagram of the target. 4 | 5 | This function will be run many times so aim for a solution that is efficient when run over and over again on the same list. 6 | 7 | #### Note: Technical Interview question at Zendesk (Undergraduate Internship) 8 | 9 | ```python 10 | lst = ['dog','apple','odg','pen'] # list will be much longer 11 | find_anagrams( 'god', lst ) 12 | > ['dog', 'odg'] 13 | find_anagrams( 'pelap', lst) 14 | > ['apple'] 15 | # etc, etc 16 | 17 | ``` 18 | -------------------------------------------------------------------------------- /problems/first-non-repeated-character/Readme.md: -------------------------------------------------------------------------------- 1 | # First Non-repeated character 2 | 3 | Write a function that accepts a single string input and returns the first non-repeated character. 4 | 5 | ```js 6 | "AABBC" // "C" 7 | "AABBCCDEEFF" // "D" 8 | ``` 9 | -------------------------------------------------------------------------------- /problems/first-non-repeated-character/first-non-repeated-character-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## first,non,repeated,character 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/first-nonrepeating-character/README.md: -------------------------------------------------------------------------------- 1 | # First Non-Repeating Character 2 | 3 | Find the first non-repeating character in a string. 4 | 5 | ```python 6 | first_non_repeating_char("aardvark") # > 'd' 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/fizz-buzz/README.md: -------------------------------------------------------------------------------- 1 | # Fizz Buzz 2 | 3 | Write a program that prints the numbers within a range `start` to `end`, or alternatively returns the values in a `list`. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". 4 | 5 | The number `33` would be `'Fizz'`, the number `30` (**3** x **5** x 2) would be `'Fizzbuzz'`. 6 | 7 | ``` 8 | fizzbuzz( 10, 18 ) # > "Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz" 9 | # Alternatively 10 | fizzbuzz( 4, 10 ) # > [4, 'Buzz', 6, 7, 8, 'Fizz', 'Buzz'] 11 | ``` 12 | -------------------------------------------------------------------------------- /problems/flatten-array/Readme.md: -------------------------------------------------------------------------------- 1 | # Flatten Array 2 | 3 | Write a function that accepts a multi dimensional array and returns a flattened version. 4 | 5 | ```python 6 | flatten([1, 2, [3, [4], 5, 6], 7]) // [1, 2, 3, 4, 5, 6, 7] 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/flatten-array/flatten-array-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## flatten,array 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/floyd-warshall-algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Floyd-Warshall Algorithm 2 | 3 | Implement the Floyd-Warshall algorithm in python code. 4 | 5 | // TODO: Finish problem description 6 | -------------------------------------------------------------------------------- /problems/full-justification/README.md: -------------------------------------------------------------------------------- 1 | # Full Justification [HARD] 2 | 3 | Given a single-line text String and a maximum width value, write the function 'String justify(String text, int maxWidth)' that formats the input text using full-justification, i.e., extra spaces on each line are equally distributed between the words; the first word on each line is flushed left and the last word on each line is flushed right. 4 | 5 | ```python 6 | full_justification("Justify this sentence." , 40) # > "Justify this sentence." 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/gender_inheritance/README.md: -------------------------------------------------------------------------------- 1 | # Gender inheritance 2 | 3 | Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class. 4 | -------------------------------------------------------------------------------- /problems/generator-problems/README.md: -------------------------------------------------------------------------------- 1 | # Generator Problems 2 | 3 | A series of quick problems to test your knowledge and capabilities with python's generator. 4 | 5 | # Problem One 6 | -------------------------------------------------------------------------------- /problems/get-elements-by-class-name/Readme.md: -------------------------------------------------------------------------------- 1 | # Get Elements by Class Name 2 | 3 | Implement the `getElementsByClassName(element, className)` function in Javascript. 4 | 5 | ## Source 6 | 7 | [GlassDoor](http://www.glassdoor.com/Interview/Implement-the-getElementsByClassName-element-className-function-in-Javascript-QTN_226449.htm) 8 | -------------------------------------------------------------------------------- /problems/get-elements-by-class-name/get-elements-by-class-name-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## get,elements,by,class,name 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/hashtable/README.md: -------------------------------------------------------------------------------- 1 | # Hashtable 2 | 3 | Implement a [hashtable](https://en.wikipedia.org/wiki/Hash_table) in python code. 4 | -------------------------------------------------------------------------------- /problems/head-legs-chinese-puzzle/README.md: -------------------------------------------------------------------------------- 1 | # Head Legs Chinese Puzzle 2 | 3 | Write a program to solve a classic ancient Chinese puzzle: 4 | We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? 5 | -------------------------------------------------------------------------------- /problems/hotel-room/Readme.md: -------------------------------------------------------------------------------- 1 | # Room Number 2 | 3 | You're in a hotel and you forgot what room number you were in but remember that the sum of it's divisors is greater than the number, yet there is no subset of those divisors that add up to the number itself. There are 100 rooms in the Hotel, what's your room number? 4 | 5 | ## Source 6 | 7 | [Reddit](http://www.reddit.com/r/javascript/comments/1ftyjh/common_code_problems_solved_in_javascript_xpost/cae25ra) 8 | -------------------------------------------------------------------------------- /problems/hotel-room/hotel-room-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## hotel,room 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/insertion-sort/README.md: -------------------------------------------------------------------------------- 1 | # Insertion Sort 2 | 3 | Implement the [insertion sort algorithm](http://en.wikipedia.org/wiki/Insertion_sort). 4 | -------------------------------------------------------------------------------- /problems/insertion-sort/insertion-sort-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## insertion,sort 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/integer-difference/Readme.md: -------------------------------------------------------------------------------- 1 | # Integer Difference 2 | 3 | Write a function that accepts an array of random integers and an integer *n*. Determine the number of times where two integers in the array have the difference of *n*. 4 | 5 | ```js 6 | f(4, [1, 1, 5, 6, 9, 16, 27]) // 3 (Due to 2x [1, 5], and [5, 9]) 7 | f(2, [1, 1, 3, 3]) // 4 (Due to 4x [1, 3]) 8 | ``` 9 | -------------------------------------------------------------------------------- /problems/integer-difference/integer-difference-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## integer,difference 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/integer-length/Readme.md: -------------------------------------------------------------------------------- 1 | # Integer Length 2 | 3 | Write a function that takes an integer as input and returns the number of digits in that integer. 4 | -------------------------------------------------------------------------------- /problems/integer-length/integer-length-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## integer,length 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/knapsack-problems/README.md: -------------------------------------------------------------------------------- 1 | # Knapsack Problem 2 | 3 | The Classic Knapsack problem and a couple of its variants. 4 | 5 | # Class Knapsack problem 6 | 7 | Implement an algorithm to solve the knapsack problem. 8 | 9 | 10 | # Multi-choice Knapsack Problem 11 | 12 | Implement an algorithm to solve the multiple choice knapsack problem. 13 | -------------------------------------------------------------------------------- /problems/kth-largest-element-in-array/Readme.md: -------------------------------------------------------------------------------- 1 | # Kth Largest Element in Array 2 | 3 | Given an array of integers find the kth element in the sorted order (not the kth distinct element). So, if the array is `[3, 1, 2, 1, 4]` and k is 3 then the result is 2, because it’s the 3rd element in sorted order (but the 3rd distinct element is 3). 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/10/27/programming-interview-questions-10-kth-largest-element-in-array/](http://www.ardendertat.com/2011/10/27/programming-interview-questions-10-kth-largest-element-in-array/) 8 | -------------------------------------------------------------------------------- /problems/kth-largest-element-in-array/kth-largest-element-in-array-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## kth,largest,element,in,array 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/largest-continuous-sum/Readme.md: -------------------------------------------------------------------------------- 1 | # Largest Continuous Sum 2 | 3 | Given an array of integers (positive and negative) find the largest continuous sum. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/09/24/programming-interview-questions-3-largest-continuous-sum/](http://www.ardendertat.com/2011/09/24/programming-interview-questions-3-largest-continuous-sum/) 8 | -------------------------------------------------------------------------------- /problems/largest-continuous-sum/largest-continuous-sum-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## largest,continuous,sum 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/largest-palindrome/Readme.md: -------------------------------------------------------------------------------- 1 | # Largest Palindrome 2 | 3 | Write a function that finds the largest palindrome in a string. All characters can be valid for the palindrome, including whitespace. In the string "I am a red racecar driver" - the largest palindrome would be "d racecar d". 4 | -------------------------------------------------------------------------------- /problems/largest-palindrome/largest-palindrome-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## largest,palindrome 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/linked-list/Readme.md: -------------------------------------------------------------------------------- 1 | # Linked List 2 | 3 | Write a linked list implementation, better yet - make it doubly linked. 4 | 5 | ### Problem Two 6 | 7 | Reverse a linked list iteratively and recursively. 8 | -------------------------------------------------------------------------------- /problems/linked-list/linked-list-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## linked,list 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/list-isa-rotation/README.md: -------------------------------------------------------------------------------- 1 | # List is a rotation of another 2 | 3 | Given 2 integer arrays, determine of the 2nd array is a rotated version of the 1st array. Ex. Original Array A={1,2,3,5,6,7,8} Rotated Array B={5,6,7,8,1,2,3}. 4 | 5 | ```python 6 | list_is_rotation([1,2,3,4,5,6], [5,6,1,2,3,4]) # > True 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/longest-common-prefix/Readme.md: -------------------------------------------------------------------------------- 1 | # Longest Common Prefix 2 | 3 | Given a String array, find the longest common prefix. 4 | 5 | ## Example 6 | 7 | ``` 8 | f([‘rocket’, ‘rockstar’, ‘rockbottom’, ‘rock’, ‘rollingstone’] // ‘ro’ 9 | f([‘shuffle’, ‘shuttle’, ‘shut’] // ‘shu’ 10 | ``` 11 | 12 | ## Source 13 | Personal Phone Interview 14 | -------------------------------------------------------------------------------- /problems/longest-common-prefix/longest-common-prefix-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## longest,common,prefix 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/longest-compound-word/Readme.md: -------------------------------------------------------------------------------- 1 | # Longest Compound Word 2 | 3 | Given a sorted list of words, find the longest compound word in the list that is constructed by concatenating the words in the list. For example, if the input list is: `['cat', 'cats', 'catsdogcats', 'catxdogcatsrat', 'dog', 'dogcatsdog', 'hippopotamuses', 'rat', 'ratcat', 'ratcatdog', 'ratcatdogcat']`. Then the longest compound word is ‘ratcatdogcat’ with 12 letters. Note that the longest individual words are ‘catxdogcatsrat’ and ‘hippopotamuses’ with 14 letters, but they’re not fully constructed by other words. Former one has an extra ‘x’ letter, and latter is an individual word by itself not a compound word. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2012/06/15/programming-interview-questions-28-longest-compound-word/](http://www.ardendertat.com/2012/06/15/programming-interview-questions-28-longest-compound-word/) 8 | -------------------------------------------------------------------------------- /problems/longest-compound-word/longest-compound-word-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## longest,compound,word 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/longest-words/Readme.md: -------------------------------------------------------------------------------- 1 | # Longest Words 2 | 3 | Write a function that returns the longest word(s) from a sentence. The function should not return any duplicate words (case-insensitive). 4 | 5 | ## Example 6 | 7 | ```js 8 | longestWords("You are just an old antidisestablishmentarian") // ["antidisestablishmentarian"] 9 | longestWords("I gave a present to my parents") // ["present", "parents"] 10 | longestWords("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo") // ["buffalo"] or ["Buffalo"] 11 | ``` 12 | -------------------------------------------------------------------------------- /problems/longest-words/longest-words-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## longest,words 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/make-exponent/README.md: -------------------------------------------------------------------------------- 1 | # Make Exponent 2 | 3 | Implement an exponent function. 4 | 5 | ### Bonus: Now try in log(n) time 6 | 7 | ```python 8 | exponent(5, 2) # > 25 9 | ``` 10 | -------------------------------------------------------------------------------- /problems/map-reduce-filter-iter-problems/README.md: -------------------------------------------------------------------------------- 1 | # Map, Filter, Reduce, Iter Problems 2 | 3 | A series of quick problems to test your understanding and capabilities with the above functions. 4 | 5 | # Map - Problem One 6 | 7 | # Map - Problem Two 8 | 9 | # Filter - Problem One 10 | -------------------------------------------------------------------------------- /problems/markov-chain-monte-carlo/README.md: -------------------------------------------------------------------------------- 1 | # Markov Chain Monte Carlo 2 | 3 | Approximate integral, expected value computation based on a conditional specification of the probability distribution. This gives us a general way of doing data analysis. 4 | 5 | // TODO: Finish problem description 6 | -------------------------------------------------------------------------------- /problems/matching-nodes/Readme.md: -------------------------------------------------------------------------------- 1 | # Matching Nodes 2 | 3 | Given two identical tree structures (consider them DOM tree if you want) and a node from the first tree, find and return the same node on the second tree. Assume you have access to a function that can test whether two nodes are the same (E.g. the node in the first tree matches the one in the second tree). Consider ways to optimize your approach. 4 | 5 | ## Source 6 | 7 | In-person interview question using whiteboard 8 | -------------------------------------------------------------------------------- /problems/matching-nodes/matching-nodes-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## matching,nodes 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/median-integer-stream/Readme.md: -------------------------------------------------------------------------------- 1 | # Median of Integer Stream 2 | 3 | Given a stream of unsorted integers, find the median element in sorted order at any given time. So, we will be receiving a continuous stream of numbers in some random order and we don’t know the stream length in advance. Write a function that finds the median of the already received numbers efficiently at any time. We will be asked to find the median multiple times. Just to recall, median is the middle element in an odd length sorted array, and in the even case it’s the average of the middle elements. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/11/03/programming-interview-questions-13-median-of-integer-stream/](http://www.ardendertat.com/2011/11/03/programming-interview-questions-13-median-of-integer-stream/) 8 | -------------------------------------------------------------------------------- /problems/median-integer-stream/median-integer-stream-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## median,integer,stream 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/merge-sort/Readme.md: -------------------------------------------------------------------------------- 1 | # Merge Sort 2 | 3 | Implement the [merge sort algorithm](http://en.wikipedia.org/wiki/Merge_sort). 4 | -------------------------------------------------------------------------------- /problems/merge-sort/merge-sort-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## merge,sort 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/missing-number/Readme.md: -------------------------------------------------------------------------------- 1 | # Missing Number 2 | 3 | Write a function that accepts an array of integers in random order of unknown length, but with one number missing. Return the missing number. 4 | -------------------------------------------------------------------------------- /problems/missing-number/missing-number-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## missing,number 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/money-format/Readme.md: -------------------------------------------------------------------------------- 1 | # Money Formatting 2 | 3 | Given an amount of money as a float, format it as a string. 4 | 5 | ```python 6 | formatMoney(2310000.159897) # '2 310 000.16' 7 | formatMoney(1600) # '1 600.00' 8 | ``` 9 | -------------------------------------------------------------------------------- /problems/money-format/money-format-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## money,format 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/most-frequent-integer/README.md: -------------------------------------------------------------------------------- 1 | # Most Frequent Integer 2 | 3 | Given an array/list, find and return the integer which appears most frequently. 4 | 5 | // TODO 6 | 7 | ```python 8 | most_frequent_int([1,2,3,3,3,3,4,5,111,12]) # > 3 9 | ``` 10 | -------------------------------------------------------------------------------- /problems/multiples-of-3-and-5/Readme.md: -------------------------------------------------------------------------------- 1 | # Multiples of 3 and 5 2 | 3 | If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. 4 | 5 | Find the sum of all the multiples of 3 or 5 below 1000. 6 | 7 | ## Source 8 | 9 | [http://projecteuler.net/problem=1](http://projecteuler.net/problem=1) 10 | -------------------------------------------------------------------------------- /problems/multiples-of-3-and-5/multiples-of-3-and-5-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## multiples,of,3,and,5 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/n-choose-k-problems/README.md: -------------------------------------------------------------------------------- 1 | # N Choose K Problems 2 | 3 | A series of problems related to N choose K problems in mathematics. 4 | 5 | # Problem One 6 | 7 | // TODO 8 | -------------------------------------------------------------------------------- /problems/next-highest-number/Readme.md: -------------------------------------------------------------------------------- 1 | # Find Next Higher Number With Same Digits 2 | 3 | Given a number, find the next higher number using only the digits in the given number. For example if the given number is 1234, next higher number with same digits is 1243. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2012/01/02/programming-interview-questions-24-find-next-higher-number-with-same-digits/](http://www.ardendertat.com/2012/01/02/programming-interview-questions-24-find-next-higher-number-with-same-digits/) 8 | -------------------------------------------------------------------------------- /problems/next-highest-number/next-highest-number-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## next,highest,number 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/next-palindrome-number/Readme.md: -------------------------------------------------------------------------------- 1 | # Find Next Palindrome Number 2 | 3 | Given a number, find the next smallest palindrome larger than the number. For example if the number is 125, next smallest palindrome is 131. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/12/01/programming-interview-questions-19-find-next-palindrome-number/](http://www.ardendertat.com/2011/12/01/programming-interview-questions-19-find-next-palindrome-number/) 8 | -------------------------------------------------------------------------------- /problems/next-palindrome-number/next-palindrome-number-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## next,palindrome,number 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/number-format/Readme.md: -------------------------------------------------------------------------------- 1 | # Numeric String 2 | 3 | Format any number into a string with "," (commas) in the correct places. E.g. "1,000,000". 4 | -------------------------------------------------------------------------------- /problems/number-format/number-format-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## number,format 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/odd-occuring-element/Readme.md: -------------------------------------------------------------------------------- 1 | # Find Odd Occurring Element 2 | 3 | Given an integer array, one element occurs odd number of times and all others have even occurrences. Find the element with odd occurrences. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/12/13/programming-interview-questions-22-find-odd-occurring-element/](http://www.ardendertat.com/2011/12/13/programming-interview-questions-22-find-odd-occurring-element/) 8 | -------------------------------------------------------------------------------- /problems/odd-occuring-element/odd-occuring-element-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## odd,occuring,element 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/once/Readme.md: -------------------------------------------------------------------------------- 1 | # Once 2 | 3 | Write a function that accepts a function as it's only argument and returns a new function that can only ever be executed once. 4 | 5 | Once completed, add a second arguments that allows the function to be executed `x` number of times before it stops working. 6 | -------------------------------------------------------------------------------- /problems/once/once-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## once 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/page-rank/README.md: -------------------------------------------------------------------------------- 1 | # Page Rank 2 | 3 | Implement Google's famous page rank algorithm in python code. 4 | 5 | 6 | // TODO finish problem descr. 7 | -------------------------------------------------------------------------------- /problems/palindrome-detection/README.md: -------------------------------------------------------------------------------- 1 | # Palindrome Detection 2 | 3 | Check if a string is a palindrome. 4 | 5 | ```python 6 | is_palindrome("repeat") # > False 7 | is_palindrome("A car, a man, a maraca.") # > True 8 | ``` 9 | -------------------------------------------------------------------------------- /problems/palindrome-shortest/README.md: -------------------------------------------------------------------------------- 1 | # Shortest Palindrome [HARD] 2 | 3 | Find the shortest palindrome in a string. 4 | 5 | ```python 6 | shortest_palindrome("I am a man ") # > ["ama", "mam"] 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/pancake-sort/README.md: -------------------------------------------------------------------------------- 1 | # Pancake Sort 2 | 3 | // TODO: Finish problem description 4 | -------------------------------------------------------------------------------- /problems/permutations-of-list/README.md: -------------------------------------------------------------------------------- 1 | # Permutations of a list 2 | 3 | Please write a program which prints all permutations of a list. 4 | 5 | ``` 6 | permutations( [1,2,3] ) # [[1,2,3,],[1,3,2],[2,1,3],[2,3,1],[3,2,1],[3,1,2]] 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/prime-number/Readme.md: -------------------------------------------------------------------------------- 1 | # Prime Number 2 | 3 | Write a function that accepts a number and return a boolean based on whether it's a prime number. 4 | -------------------------------------------------------------------------------- /problems/prime-number/prime-number-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## prime,number 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/probability-problems/README.md: -------------------------------------------------------------------------------- 1 | # Probablity Problems 2 | 3 | A series of problems aiming to test some basic probablity knowledge. 4 | -------------------------------------------------------------------------------- /problems/queen-threatens-king/queen-threatens-king-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## queen,threatens,king 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/queen-threatens-king/queen-threatens-king.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thundergolfer/interview-with-python/b5ce31c8bdca754a76762d2734dcf494a302e487/problems/queen-threatens-king/queen-threatens-king.png -------------------------------------------------------------------------------- /problems/queen-threatens-king/readme.md: -------------------------------------------------------------------------------- 1 | # The Queen threatens the King 2 | 3 | ![Chessboard](queen-threatens-king.png) 4 | 5 | Given an imaginary chess board of size _m_ x _n_ including only the Queen and the King write a function that takes the positions (coordinates) of both the Queen and the King as parameters and returns a boolean telling whether or not the King is threatened by the Queen: 6 | 7 | ```js 8 | function threatens(qX, qY, kX, kY) { 9 | // ... 10 | } 11 | ``` 12 | 13 | Extra: how would you modify your solution if the rest of the chessmen were included in the board? 14 | 15 | If you are not familiar with the rules of chess, please refer to the [related Wikipedia page](http://en.wikipedia.org/wiki/Queen_(chess)) to learn how the Queen can move around the chess board and threaten other chessmen. 16 | -------------------------------------------------------------------------------- /problems/queue-from-two-stacks/README.md: -------------------------------------------------------------------------------- 1 | # Queue from two stacks 2 | 3 | Implement a queue using 2 stacks. 4 | -------------------------------------------------------------------------------- /problems/queue/Readme.md: -------------------------------------------------------------------------------- 1 | # Basic Queue 2 | 3 | Implement a basic queue function with the ability to `add` and `remove` values. 4 | -------------------------------------------------------------------------------- /problems/queue/queue-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## queue 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/quick-sort/Readme.md: -------------------------------------------------------------------------------- 1 | # Quick Sort 2 | 3 | Implement the [quick sort algorithm](http://en.wikipedia.org/wiki/Quicksort). 4 | -------------------------------------------------------------------------------- /problems/quick-sort/quick-sort-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## quick,sort 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/remove-duplicates-from-string/Readme.md: -------------------------------------------------------------------------------- 1 | # Remove Duplicate Characters in String 2 | 3 | Remove duplicate characters in a given string keeping only the first occurrences. For example, if the input is ‘tree traversal’ the output will be "tre avsl". 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2012/01/06/programming-interview-questions-25-remove-duplicate-characters-in-string/](http://www.ardendertat.com/2012/01/06/programming-interview-questions-25-remove-duplicate-characters-in-string/) 8 | -------------------------------------------------------------------------------- /problems/remove-duplicates-from-string/remove-duplicates-from-string-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## remove,duplicates,from,string 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/remove-duplicates/README.md: -------------------------------------------------------------------------------- 1 | # Remove Duplicates 2 | 3 | 4 | With a given list, eg. [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved. 5 | -------------------------------------------------------------------------------- /problems/reset_your_answers.py: -------------------------------------------------------------------------------- 1 | # 2 | # Remove of a user's code from the answer files in each folder. 3 | # 4 | # Author: Jonathon Belotti 5 | import os 6 | 7 | for root, dirs, files in os.walk(".", topdown=False): 8 | for name in dirs: 9 | if not os.path.isfile(os.path.join(root,name, name + '-answer.py')): 10 | with open(os.path.join(root, name, name+'-answer.py'), 'w') as newfile: 11 | # Remove everything below the tags section 12 | # *How to do this?* 13 | -------------------------------------------------------------------------------- /problems/reverse-words-in-string/Readme.md: -------------------------------------------------------------------------------- 1 | # Reverse Words in a String 2 | 3 | Given an input string, reverse all the words. To clarify, input: "Interviews are awesome!" output: "awesome! are Interviews". Consider all consecutive non-whitespace characters as individual words. If there are multiple spaces between words reduce them to a single white space. Also remove all leading and trailing whitespaces. So, the output for " CS degree", "CS degree", "CS degree ", or " CS degree " are all the same: "degree CS". 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/10/31/programming-interview-questions-12-reverse-words-in-a-string/](http://www.ardendertat.com/2011/10/31/programming-interview-questions-12-reverse-words-in-a-string/) 8 | -------------------------------------------------------------------------------- /problems/reverse-words-in-string/reverse-words-in-string-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## reverse,words,in,string 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/rotate-matrix/README.md: -------------------------------------------------------------------------------- 1 | # Rotate A Matrix 2 | -------------------------------------------------------------------------------- /problems/search-unknown-length-array/Readme.md: -------------------------------------------------------------------------------- 1 | # Search Unknown Length Array 2 | 3 | Given a sorted array of unknown length and a number to search for, return the index of the number in the array. Accessing an element out of bounds throws exception. If the number occurs multiple times, return the index of any occurrence. If it isn’t present, return -1. 4 | -------------------------------------------------------------------------------- /problems/search-unknown-length-array/search-unknown-length-array-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## search,unknown,length,array 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/selection-sort/readme.md: -------------------------------------------------------------------------------- 1 | # Selection Sort 2 | 3 | Implement the [selection sort algorithm](http://en.wikipedia.org/wiki/Selection_sort). 4 | -------------------------------------------------------------------------------- /problems/selection-sort/selection-sort-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## selection,sort 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/shortest-fizz-buzz/Readme.md: -------------------------------------------------------------------------------- 1 | # Shortest Fizz Buzz 2 | 3 | Write a program that prints (to STDOUT) the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. 4 | 5 | The goal is to write the shortest code possible. 6 | 7 | Expected output: [http://cdn.hackerrank.com/fizzbuzz.txt](http://cdn.hackerrank.com/fizzbuzz.txt) 8 | 9 | Your output should exactly match the above. 10 | 11 | ## Source 12 | 13 | [https://www.hackerrank.com/challenges/fizzbuzz](https://www.hackerrank.com/challenges/fizzbuzz) 14 | -------------------------------------------------------------------------------- /problems/shortest-fizz-buzz/shortest-fizz-buzz-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## shortest,fizz,buzz 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/skiing-in-singapore/README.md: -------------------------------------------------------------------------------- 1 | # Skiing in Singapore 2 | Sometimes it's nice to take a break and code up a solution to a small, fun problem. Here is one some of our engineers enjoyed recently called Skiing In Singapore. 3 | 4 | Well you can’t really ski in Singapore. But let’s say you hopped on a flight to the Niseko ski resort in Japan. Being a software engineer you can’t help but value efficiency, so naturally you want to ski as long as possible and as fast as possible without having to ride back up on the ski lift. So you take a look at the map of the mountain and try to find the longest ski run down. 5 | 6 | In digital form the map looks like the number grid below. 7 | 8 | 4 4 9 | 4 8 7 3 10 | 2 5 9 3 11 | 6 3 2 5 12 | 4 4 1 6 13 | 14 | The first line (4 4) indicates that this is a 4x4 map. Each number represents the elevation of that area of the mountain. From each area (i.e. box) in the grid you can go north, south, east, west - but only if the elevation of the area you are going into is less than the one you are in. I.e. you can only ski downhill. You can start anywhere on the map and you are looking for a starting point with the longest possible path down as measured by the number of boxes you visit. And if there 15 | are several paths down of the same length, you want to take the one with the steepest vertical drop, i.e. the largest difference between your starting elevation and your ending elevation. 16 | 17 | On this particular map the longest path down is of length=5 and it’s highlighted in bold below: 9-5-3-2-1. 18 | 19 | 4 4 20 | 4 8 7 3 21 | 2 5 9 3 22 | 6 3 2 5 23 | 4 4 1 6 24 | 25 | There is another path that is also length five: 8-5-3-2-1. However the tie is broken by the first path being steeper, dropping from 9 to 1, a drop of 8, rather than just 8 to 1, a drop of 7. 26 | 27 | Your challenge is to write a program in your favorite programming language to find the longest (and then steepest) path on this map specified in the format above. It’s 1000x1000 in size, and all the numbers on it are between 0 and 1500. 28 | 29 | Send your code or a github link (and a resume if you like) to [?????? at redmart dot com], replacing “??????” with the concatenation of the length of the longest path with the largest drop, and the size of the drop. So in the simple example above length=5, drop=8, so the email address would be [58 at redmart dot com]. If your e-mail gets through - you got the right answer. 30 | 31 | Good luck and have fun! 32 | -------------------------------------------------------------------------------- /problems/skiing-in-singapore/skiing-in-singapore-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## skiing,in,singapore 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/sorted-array-search/Readme.md: -------------------------------------------------------------------------------- 1 | # Sorted Array Search 2 | 3 | Given an array of numbers sorted in ascending order, write a function that will return the index at which the number is found. 4 | -------------------------------------------------------------------------------- /problems/sorted-array-search/sorted-array-search-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## sorted,array,search 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/spiral/Readme.md: -------------------------------------------------------------------------------- 1 | # Spiral 2 | 3 | Write a function that accepts four arguments. The first two arguments are the size of the grid (*h x w*), filled with ascending integers from left to right, top to bottom, starting from 1. The next two arguments are the starting positions, the row (*r*) and column (*c*). 4 | 5 | Return an array of integers obtained by spiralling outward anti-clockwise from the *r* and *c*, starting upward. 6 | 7 | ``` 8 | f(5, 5, 3, 3) // [ 13, 8, 7, 12, 17, 18, 19, 14, 9, 4, 3, 2, 1, 6, 11, 16, 21, 22, 23, 24, 25, 20, 15, 10, 5 ] 9 | 10 | f(2, 4, 1, 2) // [ 2, 1, 5, 6, 7, 3, 8, 4 ] 11 | ``` 12 | 13 | **Supporting Content** 14 | 15 | The following graphics show the grid in question and the spiral generated, beginning at cell (3, 3). 16 | 17 | ![Grid 1](input-1.png) 18 | 19 | ![Grid 2](input-2.png) 20 | -------------------------------------------------------------------------------- /problems/spiral/input-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thundergolfer/interview-with-python/b5ce31c8bdca754a76762d2734dcf494a302e487/problems/spiral/input-1.png -------------------------------------------------------------------------------- /problems/spiral/input-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thundergolfer/interview-with-python/b5ce31c8bdca754a76762d2734dcf494a302e487/problems/spiral/input-2.png -------------------------------------------------------------------------------- /problems/spiral/spiral-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## spiral 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/spreadsheet/README.md: -------------------------------------------------------------------------------- 1 | # Programming Challenge 2 | 3 | A spreadsheet consists of a two-dimensional array of cells, labeled A1, A2, etc. Rows are identified using letters, columns by numbers. Each cell contains either an integer (its value) or an expression. Expressions contain integers, cell references, and the operators '+', '-', '\*', '/' with the usual rules of evaluation – note that the input is RPN and should be evaluated in stack order. 4 | 5 | The spreadsheet input is defined as follows: 6 | 7 | 1. Line 1: two integers, defining the width and height of the spreadsheet (n, m) 8 | 9 | 2. n\*m lines each containing an expression which is the value of the corresponding cell (cells enumerated in the order A1, A2, A, B1, ...) 10 | 11 | ## The Input 12 | 3 2 13 | A2 14 | 4 5 * 15 | A1 16 | A1 B2 / 2 + 17 | 3 18 | 39 B1 B2 * / 19 | 20 | ## The Output 21 | 3 2 22 | 20.00000 23 | 20.00000 24 | 20.00000 25 | 8.66667 26 | 3.00000 27 | 1.50000 28 | -------------------------------------------------------------------------------- /problems/spreadsheet/spreadsheet-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## spreadsheet 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/square-root/README.md: -------------------------------------------------------------------------------- 1 | # Square Root Function 2 | 3 | Implement the square root function. 4 | 5 | ```python 6 | square_root(16) # > 4 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/stack-machine/Readme.md: -------------------------------------------------------------------------------- 1 | # Stack Machine 2 | 3 | A stack machine is a simple system that performs arithmetic operations on an input string of numbers and operators. It contains a stack that can store an arbitrary number of 12-bit unsigned integers. Initially the stack is empty. The machine processes a string of characters in the following way: 4 | 5 | - the characters of the string are processed one by one; 6 | - if the current character is a digit `[0-9]`, the machine pushes the value of that digit onto its stack; 7 | - if the current character is `+`, the machine pops the two topmost values from its stack, adds them and pushes the result onto the stack; 8 | - if the current character is `*`, the machine pops the two topmost values from its stack, multiplies them and pushes the result onto the stack; 9 | - after the machine has processed the whole string it returns the topmost value of its stack as the result; 10 | - the machine reports an error if any operation it performs (addition or multiplication) results in an overflow; 11 | - the machine reports an error if it tries to pop an element from its stack when the stack is empty, or if the stack is empty after the machine has processed the whole string. 12 | 13 | For example, given the string "13+62*7+*" the machine will perform the following operations: 14 | ``` 15 | character | comment | stack 16 | ----------------------------------------------- 17 | | | [empty] 18 | '1' | push 1 onto the stack | 19 | | | 1 20 | '3' | push 3 onto the stack | 21 | | | 1, 3 22 | '+' | perform addition | 23 | | | 4 24 | '6' | push 6 onto the stack | 25 | | | 4, 6 26 | '2' | push 2 onto the stack | 27 | | | 4, 6, 2 28 | '*' | perform multiplication | 29 | | | 4, 12 30 | '7' | push 7 onto the stack | 31 | | | 4, 12, 7 32 | '+' | perform addition | 33 | | | 4, 19 34 | '*' | perform multiplication | 35 | | | 76 36 | ``` 37 | 38 | The machine will return `76` as the result as it is the topmost element of its stack. 39 | 40 | Write a function: 41 | class Solution { public int solution(string S); } 42 | 43 | that, given a string S consisting of N characters containing input for the stack machine, returns the result the machine would return if given this string. The function should return −1 if the machine would report an error when processing the string. 44 | 45 | For example, given `String S = "13+62*7+*"` the function should return `76`, as explained in the example above. Given `String S = "11++"` the function should return `-1`. 46 | 47 | Assume that: 48 | - the length of S is within the range [0..200,000]; 49 | - string S consists only of the following characters: "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+" and/or "*". 50 | 51 | In your solution, focus on **correctness**. The performance of your solution will not be the focus of the assessment. 52 | 53 | **Solution:** https://github.com/AntonioRedondo/CodingInterviewProblems/blob/master/src/StackMachine.java 54 | -------------------------------------------------------------------------------- /problems/stack-machine/stack-machine-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## stack,machine 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/stack-sort/README.md: -------------------------------------------------------------------------------- 1 | # Stack sort 2 | 3 | Write a function that sorts a stack. 4 | 5 | ### Bonus: sort the stack in-place without extra memory 6 | -------------------------------------------------------------------------------- /problems/stack/Readme.md: -------------------------------------------------------------------------------- 1 | # Basic Stack 2 | 3 | Implement a basic stack function with the ability to `add` and `remove` values. 4 | -------------------------------------------------------------------------------- /problems/stack/stack-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## stack 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/stocks-max-subarray/README.md: -------------------------------------------------------------------------------- 1 | # Stocks Maximum Sub-Array Problem 2 | 3 | You've been offered the opportunity to invest in a stock, but the opportunity has some conditions. 4 | 5 | 1. You are allowed to buy one unit of stock only one time and then sell it all at a later date. 6 | 2. You can only buy and sell at close of trading. 7 | 3. You are allowed to know the future price of the stock. 8 | 9 | 10 | Your goal is to maximise your profit from this single trade, which comes down to finding the greatest difference between two closing prices over a given period. 11 | This period has a `start` and an `end`. 12 | 13 | We represent prices for this solution as the price[i-1] - price[i] for price[i]. This is the *difference*, or price movement. 14 | 15 | ```python 16 | # where returned values x, y are the indexes of the days to buy sell 17 | find-max-subarray( prices, 0, 132) # > 3, 45 18 | ``` 19 | -------------------------------------------------------------------------------- /problems/string-format/Readme.md: -------------------------------------------------------------------------------- 1 | # String Format 2 | 3 | Create a string formatting function that accepts an input string and a number of arguments to replace positions in the input string. 4 | 5 | ## Example 6 | 7 | ``` 8 | f('Hello {0} {1}', 'Mr.', 'X') // => 'Hello Mr. X' 9 | f('{1}_{0}', '{1}', '{0}') // => '{0}_{1}' 10 | ``` 11 | 12 | By [Riga](https://github.com/riga). 13 | -------------------------------------------------------------------------------- /problems/string-format/string-format-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## string,format 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/string-permutations/Readme.md: -------------------------------------------------------------------------------- 1 | # All Permutations of a String 2 | 3 | Generate all permutations of a given string. (Note: also known as the generating anagrams problem). 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/10/28/programming-interview-questions-11-all-permutations-of-string/](http://www.ardendertat.com/2011/10/28/programming-interview-questions-11-all-permutations-of-string/) 8 | -------------------------------------------------------------------------------- /problems/string-permutations/string-permutations-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## string,permutations 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/string-problems-general/README.md: -------------------------------------------------------------------------------- 1 | # General String Problems 2 | 3 | ### String Reverse 4 | 5 | Please write a program which accepts a string from console and print it in reverse order. 6 | 7 | ``` 8 | str_reverse( "string" ) # "gnirts" 9 | ``` 10 | 11 | ### Even index characters 12 | 13 | Please write a program which accepts a string from console and print the characters that have even indexes. 14 | 15 | ``` 16 | even_index_chars( "H1e2l3l4o5w6o7r8l9d" ) # "Helloworld" 17 | ``` 18 | -------------------------------------------------------------------------------- /problems/string-rotation/Readme.md: -------------------------------------------------------------------------------- 1 | # String Rotation 2 | 3 | Find out if a string is a rotation of another string. E.g. `ABCD` is a rotation of `BCDA` but not `ACBD`. 4 | 5 | ## Source 6 | 7 | [Reddit](http://www.reddit.com/r/javascript/comments/1ftyjh/common_code_problems_solved_in_javascript_xpost/cae25ra) 8 | -------------------------------------------------------------------------------- /problems/string-rotation/string-rotation-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## string,rotation 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/sum-of-array-plus-one/Readme.md: -------------------------------------------------------------------------------- 1 | # Sum of Array Plus One 2 | 3 | Write a function that takes an array of integers and returns the sum of the integers after adding 1 to each. 4 | 5 | ``` 6 | plusOneSum([1, 2, 3, 4]); // 14 7 | ``` 8 | -------------------------------------------------------------------------------- /problems/sum-of-array-plus-one/sum-of-array-plus-one-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## sum,of,array,plus,one 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/this-repos-scripts/README.md: -------------------------------------------------------------------------------- 1 | # This Repo's Scripts 2 | 3 | Re-implement the scripts from this repo, which involve scraping and directory walking. 4 | -------------------------------------------------------------------------------- /problems/throttle/Readme.md: -------------------------------------------------------------------------------- 1 | # Throttle 2 | 3 | Write a function that accepts a function and timeout, `x`, in number of milliseconds. It returns a function that can only be executed once per `x` milliseconds. This can be useful for limiting the number of time and computation heavy function that are run. For example, making AJAX requests to an autocompletion API. 4 | 5 | Once written, add a third parameter that will allow the function to be executed immediately if set to true. Otherwise the function will run at the end of the timeout period. 6 | -------------------------------------------------------------------------------- /problems/throttle/throttle-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## throttle 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/transform-word/Readme.md: -------------------------------------------------------------------------------- 1 | # Transform Word 2 | 3 | Given a source word, target word and an English dictionary, transform the source word to target by changing/adding/removing 1 character at a time, while all intermediate words being valid English words. Return the transformation chain which has the smallest number of intermediate words. 4 | 5 | ## Example 6 | 7 | ```js 8 | transformWord(['cat', 'bat', 'bet', 'bed', 'at', 'ad', 'ed'], 'cat', 'bed'); 9 | ``` 10 | 11 | ## Source 12 | 13 | [http://www.ardendertat.com/2011/10/17/programming-interview-questions-8-transform-word/](http://www.ardendertat.com/2011/10/17/programming-interview-questions-8-transform-word/) 14 | -------------------------------------------------------------------------------- /problems/transform-word/transform-word-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## transform,word 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/travelling-salesman-problem/README.md: -------------------------------------------------------------------------------- 1 | # Travelling Salesman Problem 2 | 3 | Given a list of city coordinates (eg. (23.33, 455.0), (23,4), (0.05, 0.09) ), calculate the shortest path that visits all cities only **once**, and returns to the first city. The algorithm should return/print the total path length. 4 | 5 | ## WARNING: The complexity for the problem can be O(2!) so running the algorithm on N > 15 is not advised. O(n^2 * 2^n) algorithms can handle around N = 20 6 | 7 | ```python 8 | cites = { 1: City(0.14, 100), 2 : City(234.3, 21.1), ... } 9 | tsp(cities) # > 776.0021 10 | ``` 11 | -------------------------------------------------------------------------------- /problems/tree-level-order-print/Readme.md: -------------------------------------------------------------------------------- 1 | # Tree Level Order Print 2 | 3 | Given a binary tree of integers, print it in level order. The output will contain space between the numbers in the same level, and new line between different levels. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/12/05/programming-interview-questions-20-tree-level-order-print/](http://www.ardendertat.com/2011/12/05/programming-interview-questions-20-tree-level-order-print/) 8 | -------------------------------------------------------------------------------- /problems/tree-level-order-print/tree-level-order-print-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## tree,level,order,print 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/triples_summing_to_x/README.md: -------------------------------------------------------------------------------- 1 | # Triples Summing To X 2 | 3 | For a given sorted list of values, return all *unique* groups of 3 elements that sum to the value passed as argument. Note that elements cannot be used twice in the same triplet. 4 | 5 | ```python 6 | lst = [-10, -7, -5, -1, 0, 2, 3, 5, 8, 10] 7 | triples_adding_to( 5, lst ) 8 | 9 | > {(-7, 2, 10), (0, 2, 3), (-5, 0, 10), (-10, 5, 10), (-5, 2, 8)} 10 | ``` 11 | -------------------------------------------------------------------------------- /problems/type-function-equivalent/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thundergolfer/interview-with-python/b5ce31c8bdca754a76762d2734dcf494a302e487/problems/type-function-equivalent/README.md -------------------------------------------------------------------------------- /problems/type-function-equivelant/README.md: -------------------------------------------------------------------------------- 1 | # `type()` function equivelant 2 | 3 | Write a function that is an equivalent to python's `type()`. 4 | 5 | # TODO 6 | -------------------------------------------------------------------------------- /problems/word-analytics/Readme.md: -------------------------------------------------------------------------------- 1 | # Word Analytics 2 | 3 | You're a newly hired engineer for a brand-new company that's building a "killer Word-like application". You've been specifically assigned to implement a tool that gives the user some details on common word usage, letter usage, and some other analytics for a given document! More specifically, you must read a given text file (no special formatting, just a plain ASCII text file) and print off the following details: 4 | 5 | 1. Number of words 6 | 2. Number of letters 7 | 3. Number of symbols (any non-letter and non-digit character, excluding white spaces) 8 | 4. Top three most common words (you may count "small words", such as "it" or "the") 9 | 5. Top three most common letters 10 | 6. Most common first word of a paragraph (paragraph being defined as a block of text with an empty line above it) (Optional bonus) 11 | 7. Number of words only used once (Optional bonus) 12 | 8. All letters not used in the document (Optional bonus) 13 | 14 | Please note that your tool does not have to be case sensitive, meaning the word "Hello" is the same as "hello" and "HELLO". 15 | 16 | *Author: nint22* 17 | 18 | ## Formal Inputs & Outputs 19 | 20 | ### Input Description 21 | 22 | As an argument to your program on the command line, you will be given a text file location (such as "C:\Users\nint22\Document.txt" on Windows or "/Users/nint22/Document.txt" on any other sane file system). This file may be empty, but will be guaranteed well-formed (all valid ASCII characters). You can assume that line endings will follow the UNIX-style new-line ending (unlike the Windows carriage-return & new-line format ). 23 | 24 | ### Output Description 25 | 26 | For each analytic feature, you must print the results in a special string format. Simply you will print off 6 to 8 sentences with the following format: 27 | 28 | ``` 29 | "A words", where A is the number of words in the given document 30 | "B letters", where B is the number of letters in the given document 31 | "C symbols", where C is the number of non-letter and non-digit character, excluding white spaces, in the document 32 | "Top three most common words: D, E, F", where D, E, and F are the top three most common words 33 | "Top three most common letters: G, H, I", where G, H, and I are the top three most common letters 34 | "J is the most common first word of all paragraphs", where J is the most common word at the start of all paragraphs in the document (paragraph being defined as a block of text with an empty line above it) (*Optional bonus*) 35 | "Words only used once: K", where K is a comma-delimited list of all words only used once (*Optional bonus*) 36 | "Letters not used in the document: L", where L is a comma-delimited list of all alphabetic characters not in the document (*Optional bonus*) 37 | ``` 38 | 39 | If there are certain lines that have no answers (such as the situation in which a given document has no paragraph structures), simply do not print that line of text. In this example, I've just generated some random Lorem Ipsum text. 40 | 41 | ## Testing 42 | 43 | ``` 44 | cat huckleberry-finn.txt | node index.js 45 | ``` 46 | 47 | ## Source 48 | 49 | [http://www.reddit.com/r/dailyprogrammer/comments/1e97ob/051313_challenge_125_easy_word_analytics/](http://www.reddit.com/r/dailyprogrammer/comments/1e97ob/051313_challenge_125_easy_word_analytics/) 50 | -------------------------------------------------------------------------------- /problems/word-analytics/word-analytics-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## word,analytics 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /problems/word-positions/Readme.md: -------------------------------------------------------------------------------- 1 | # Find Word Positions in Text 2 | 3 | Given a text file and a word, find the positions that the word occurs in the file. We’ll be asked to find the positions of many words in the same file. 4 | 5 | ## Source 6 | 7 | [http://www.ardendertat.com/2011/12/20/programming-interview-questions-23-find-word-positions-in-text/](http://www.ardendertat.com/2011/12/20/programming-interview-questions-23-find-word-positions-in-text/) 8 | -------------------------------------------------------------------------------- /problems/word-positions/word-positions-answer.py: -------------------------------------------------------------------------------- 1 | ##$$## ---------- TAGS ----------- ##$$## 2 | ##$$## word,positions 3 | ##$$## --------- ENDTAGS --------- ##$$## 4 | 5 | ###### - Write your answer below - ###### 6 | -------------------------------------------------------------------------------- /search_and_launch.py: -------------------------------------------------------------------------------- 1 | from gui_search_and_launch.core import main 2 | 3 | if __name__ == '__main__': 4 | main() 5 | -------------------------------------------------------------------------------- /solutions/README.md: -------------------------------------------------------------------------------- 1 | # SOLUTIONS 2 | 3 | ## HOW TO USE THEM 4 | 5 | ## WHY C++ SOLUTIONS? 6 | -------------------------------------------------------------------------------- /solutions/c/bubble-sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void bubblesort(int *v){ 4 | 5 | int i,j,aux; 6 | 7 | int size = sizeof(v) / sizeof(v[0]); // Number of indexes in the V array. 8 | 9 | for (i=0; i < size-1; i++) { 10 | for(j=i+1; j < size; j++) { 11 | if(v[i] > v[j]) { 12 | aux=v[i]; 13 | v[i]=v[j]; 14 | v[j]=aux; 15 | } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /solutions/c/factorial.c: -------------------------------------------------------------------------------- 1 | /* 2 | Observation: 3 | 4 | C Language doesn't have native support to Big Integer numbers, 5 | so on a x86 processor the maximum factorial number that can be reached is 12 6 | and on a x86_64 is 20. 7 | 8 | If you need to use big integer numbers, I recommend you search about the OpenSSL Big Numbers library. 9 | http://www.openssl.org/docs/crypto/bn.html 10 | 11 | To print a `unsigned long int` number use `%lu` on prinf() function. 12 | 13 | */ 14 | 15 | #include "stdio.h" 16 | 17 | // Interative Loop 18 | unsigned long int factorial (unsigned short int number){ 19 | unsigned long int factorial = 1; 20 | unsigned short int i=2; 21 | 22 | do { 23 | factorial *= i++; 24 | } while (i<=number); 25 | return factorial; 26 | } 27 | 28 | // Interative Reverse Loop 29 | unsigned long int factorialReverse (unsigned short int number){ 30 | unsigned long int factorial = 1; 31 | unsigned short int i; 32 | 33 | for (i = number; i > 0; i--){ 34 | factorial *= i; 35 | } 36 | return factorial; 37 | } 38 | 39 | // Recursive 40 | unsigned long int factorialRecursive(unsigned short int number){ 41 | if (number==1) { 42 | return 1; 43 | } else { 44 | return number * factorialRecursive(number-1); 45 | } 46 | } -------------------------------------------------------------------------------- /solutions/c/find-missing-element.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // The differnce in sum of two arrays will give us the desired value. 4 | // The other approach could be to look up for element each time but that will increase the time complexity of the program. 5 | int find_missing(int orig[],int On,int shuffled[]) 6 | { 7 | int i,sum=0; 8 | for(i=0;i 2 | 3 | int sum_of_multiples(int n) 4 | { int sum=0; 5 | n=n-1; 6 | sum=((n/3)*((n/3)*3 +3))/2 + ((n/5)*((n/5)*5 +5))/2 - ((n/15)*((n/15)*15 + 15))/2; // sum of airthmetic progressions & De-Morgan's Law 7 | return sum; 8 | } 9 | int main() 10 | { 11 | printf("%d\n",sum_of_multiples(1000)); 12 | return 0; 13 | } -------------------------------------------------------------------------------- /solutions/c/selection-sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void selectionsort(int *v) { 4 | 5 | int i, j, min, aux; 6 | 7 | int size = sizeof(v) / sizeof(v[0]); // Number of indexes in the V array. 8 | 9 | for(i = 0; i < n-1; i++){ 10 | min = i; 11 | for (j = i+1; j < n; j++) 12 | if (v[j] < v[min]) 13 | min = j; 14 | aux = v[i]; 15 | v[i] = v[min]; 16 | v[min] = aux; 17 | } 18 | } -------------------------------------------------------------------------------- /solutions/c/shortest-fizz-buzz.c: -------------------------------------------------------------------------------- 1 | main(i){for(;i<101;puts(i++%5?"":"Buzz"))printf(i%3?i%5?"%d":"":"Fizz",i);} 2 | -------------------------------------------------------------------------------- /solutions/c/spreadsheet/3x2.txt: -------------------------------------------------------------------------------- 1 | 3 2 2 | A2 3 | 4 5 * 4 | A1 5 | A1 B2 / 2 + 6 | 3 7 | 39 B1 B2 * / 8 | -------------------------------------------------------------------------------- /solutions/c/spreadsheet/Makefile: -------------------------------------------------------------------------------- 1 | 2 | all: spreadsheet 3 | 4 | spreadsheet: spreadsheet.c matrix.c matrix.h stackcalc.h stackcalc.c regex.h regex.c commons.h commons.c 5 | clang -ggdb3 -O0 -std=c99 -Wall -Werror -o spreadsheet spreadsheet.c matrix.c regex.c commons.c stackcalc.c -I/usr/local/include -L/usr/local/lib/ -lpcre2-8 6 | 7 | test: matrix_test.c regex.c commons.c regex.h matrix.h stackcalc.h stackcalc.c 8 | clang -o matrixTest -ggdb3 -Wall -Werror -O0 -std=c99 -I/usr/local/include matrix_test.c matrix.c regex.c commons.c stackcalc.c -L/usr/local/lib/ -lpcre2-8 -lcmocka 9 | 10 | clean: 11 | rm -f *.o a.out spreadsheet core 12 | -------------------------------------------------------------------------------- /solutions/c/spreadsheet/README.md: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | 3 | This program depends on the following: 4 | 1. pcre2-10.20 - Pattern matching, regular expression 5 | 2. cmocka-1.0.0 - For Unit Tests 6 | 7 | Please refer to their respective documentations on how to install these libraries into your respective system 8 | 9 | # Execution 10 | It is required that the $LD\_LIBRARY\_PATH environment variable be set to the directory where the pcre.so is located if it is located other than /usr/lib 11 | 12 | 13 | -------------------------------------------------------------------------------- /solutions/c/spreadsheet/commons.c: -------------------------------------------------------------------------------- 1 | #include "commons.h" 2 | 3 | int getNumberOfDigits(int n) 4 | { 5 | if (n < 0) return -1; 6 | if (n < 10) return 1; 7 | if (n < 100) return 2; 8 | if (n < 1000) return 3; 9 | if (n < 10000) return 4; 10 | if (n < 100000) return 5; 11 | if (n < 1000000) return 6; 12 | 13 | return -1; 14 | } 15 | -------------------------------------------------------------------------------- /solutions/c/spreadsheet/commons.h: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Returns the number of digits in the integer n 4 | */ 5 | int getNumberOfDigits(int n); 6 | 7 | -------------------------------------------------------------------------------- /solutions/c/spreadsheet/matrix.h: -------------------------------------------------------------------------------- 1 | 2 | typedef struct 3 | { 4 | char ***cells; 5 | int rows; 6 | int cols; 7 | } Worksheet; 8 | 9 | typedef struct 10 | { 11 | int row; 12 | int col; 13 | } MatrixLocation; 14 | 15 | typedef struct 16 | { 17 | char *cellReference; 18 | } CellReference; 19 | 20 | // The maximum content of a cell (4k) 21 | #define CELL_CONTENT_LIMIT 2048 22 | 23 | #define ROW_TO_ASCII_OFFSET 65 24 | 25 | /** 26 | * Initializes the 2d matrix of size rows * columns. 27 | * 28 | * Returns 0 if an error is encountered. 29 | */ 30 | int initWorksheet(Worksheet *worksheet, int rows, int columns); 31 | 32 | /** 33 | * Closes and releases the resources of the worksheet 34 | */ 35 | int closeWorksheet(Worksheet *w); 36 | 37 | /** 38 | * Returns 1 if a cyclic dependency is detected. 0 if otherwise. 39 | */ 40 | int isCyclicRefError(const Worksheet *worksheet, int row, int col); 41 | 42 | /** 43 | * Sets cellContent into the worksheet 44 | */ 45 | int setValue(Worksheet *worksheet, int row, int column, char *cellContent); 46 | 47 | /** 48 | * Returns the value at row, col 49 | */ 50 | char* getValue(const Worksheet *worksheet, int row, int column); 51 | 52 | /** 53 | * Returns the value at row, col and writes it into the buffer. 54 | * 55 | * Usage: 56 | * 57 | * char *buffer; 58 | * getValue2(w, &buffer, row, column); 59 | * 60 | */ 61 | int getValue2(const Worksheet *w, char **buffer, int row, int column); 62 | 63 | /** 64 | * Returns a pointer to a CellReference structure 65 | */ 66 | CellReference *convertToCellReference(const MatrixLocation *matrixLocation); 67 | 68 | /** 69 | * Returns a pointer to a MatrixLocation structure 70 | */ 71 | MatrixLocation *convertToMatrixLocation(const CellReference *cellReference); 72 | 73 | 74 | -------------------------------------------------------------------------------- /solutions/c/spreadsheet/matrixTest: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thundergolfer/interview-with-python/b5ce31c8bdca754a76762d2734dcf494a302e487/solutions/c/spreadsheet/matrixTest -------------------------------------------------------------------------------- /solutions/c/spreadsheet/regex.c: -------------------------------------------------------------------------------- 1 | #include "regex.h" 2 | 3 | pcre2_code * getCellReferencePattern(void) 4 | { 5 | int errorcode = 0; 6 | PCRE2_SIZE erroroffset; 7 | pcre2_code *re = pcre2_compile((PCRE2_SPTR8) CELL_REFERENCE_PATTERN, -1, 0, 8 | &errorcode, &erroroffset, NULL); 9 | if (re == NULL) 10 | { 11 | return 0; 12 | } 13 | 14 | return re; 15 | } 16 | 17 | pcre2_code *compilePattern(char *pattern) 18 | { 19 | int errorcode = 0; 20 | PCRE2_SIZE erroroffset; 21 | pcre2_code *re = pcre2_compile((PCRE2_SPTR8) pattern, -1, 0, 22 | &errorcode, &erroroffset, NULL); 23 | if (re == NULL) 24 | { 25 | return 0; 26 | } 27 | 28 | return re; 29 | } 30 | -------------------------------------------------------------------------------- /solutions/c/spreadsheet/regex.h: -------------------------------------------------------------------------------- 1 | #define PCRE2_CODE_UNIT_WIDTH 8 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | static const char *CELL_REFERENCE_PATTERN = "[A-Za-z]\\d+"; 9 | 10 | pcre2_code *getCellReferencePattern(void); 11 | 12 | /** 13 | * Creates a regular expression pattern based on {pattern} 14 | */ 15 | pcre2_code *compilePattern(char *pattern); 16 | 17 | 18 | -------------------------------------------------------------------------------- /solutions/c/spreadsheet/spreadsheet: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thundergolfer/interview-with-python/b5ce31c8bdca754a76762d2734dcf494a302e487/solutions/c/spreadsheet/spreadsheet -------------------------------------------------------------------------------- /solutions/c/spreadsheet/stackcalc.c: -------------------------------------------------------------------------------- 1 | #define PCRE2_CODE_UNIT_WIDTH 8 2 | 3 | #include 4 | #include 5 | 6 | #include "matrix.h" 7 | #include "stackcalc.h" 8 | 9 | void push(Stack *stack, Node *node) 10 | { 11 | // create new nodelist head 12 | node->next = stack->nodeList; 13 | stack->nodeList = node; 14 | stack->len++; 15 | } 16 | 17 | Node *pop(Stack *stack) 18 | { 19 | Node *nodeList = stack->nodeList; 20 | Node *newHead = nodeList->next; 21 | 22 | // remove reference to the next 23 | nodeList->next = NULL; 24 | stack->nodeList = newHead; 25 | 26 | return nodeList; 27 | } 28 | -------------------------------------------------------------------------------- /solutions/c/spreadsheet/stackcalc.h: -------------------------------------------------------------------------------- 1 | 2 | typedef struct Node 3 | { 4 | double value; 5 | struct Node *next; 6 | } Node; 7 | 8 | typedef struct 9 | { 10 | Node *nodeList; 11 | int len; 12 | } Stack; 13 | 14 | /** 15 | * Pushes node into the stack 16 | */ 17 | void push(Stack *stack, Node *node); 18 | 19 | /** 20 | * Pops a node from the stack. Returns NULL if stack is empty 21 | */ 22 | Node *pop(Stack *stack); 23 | -------------------------------------------------------------------------------- /solutions/c/spreadsheet/tests/Makefile: -------------------------------------------------------------------------------- 1 | all: tests 2 | 3 | tests: matrix_test.c ../regex.c ../commons.c ../regex.h ../matrix.h ../stackcalc.h 4 | clang -o matrixTest -ggdb3 -Wall -Werror -O0 -std=c99 -I/usr/local/include matrix_test.c ../matrix.c ../regex.c ../commons.c ../stackcalc.c -L/usr/local/lib/ -lpcre2-8 -lcmocka 5 | 6 | 7 | -------------------------------------------------------------------------------- /solutions/c/spreadsheet/tests/core: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thundergolfer/interview-with-python/b5ce31c8bdca754a76762d2734dcf494a302e487/solutions/c/spreadsheet/tests/core -------------------------------------------------------------------------------- /solutions/c/spreadsheet/tests/matrixTest: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thundergolfer/interview-with-python/b5ce31c8bdca754a76762d2734dcf494a302e487/solutions/c/spreadsheet/tests/matrixTest -------------------------------------------------------------------------------- /solutions/c/spreadsheet/tests/matrix_test.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "../matrix.h" 9 | #include "../regex.h" 10 | #include "../commons.h" 11 | #include "../stackcalc.h" 12 | 13 | static void testConvertToCellReference(void **state) 14 | { 15 | MatrixLocation m; 16 | m.row = 0; 17 | m.col = 0; 18 | 19 | CellReference *ref = convertToCellReference(&m); 20 | assert_string_equal("A1", ref->cellReference); 21 | 22 | free(ref); 23 | 24 | m.row = 1; 25 | m.col = 2; 26 | 27 | ref = convertToCellReference(&m); 28 | assert_string_equal("B3", ref->cellReference); 29 | 30 | free(ref); 31 | } 32 | 33 | static void testConvertToMatrixLocation(void **state) 34 | { 35 | CellReference c; 36 | c.cellReference = "A1"; 37 | 38 | MatrixLocation *m = convertToMatrixLocation(&c); 39 | 40 | assert_int_equal(0, m->row); 41 | assert_int_equal(0, m->col); 42 | 43 | free(m); 44 | 45 | c.cellReference = "B5"; 46 | m = convertToMatrixLocation(&c); 47 | assert_int_equal(1, m->row); 48 | assert_int_equal(4, m->col); 49 | 50 | free(m); 51 | } 52 | 53 | static void testSetAndGetWorkSheetValue(void **state) 54 | { 55 | Worksheet *w = malloc(sizeof(Worksheet)); 56 | initWorksheet(w, 4, 4); 57 | setValue(w, 0, 0, "A2 + 1"); 58 | assert_string_equal("A2 + 1", getValue(w, 0, 0)); 59 | free(w); 60 | } 61 | 62 | static void testCyclicDependency(void **state) 63 | { 64 | Worksheet *w = malloc(sizeof(Worksheet)); 65 | initWorksheet(w, 4, 4); 66 | 67 | setValue(w, 0, 0, "A2 + 1"); 68 | assert_string_equal("A2 + 1", getValue(w, 0, 0)); 69 | assert_int_equal(0, isCyclicRefError(w, 0, 0)); 70 | 71 | setValue(w, 0, 1, "A1"); 72 | assert_string_equal("A1", getValue(w, 0, 1)); 73 | assert_int_equal(1, isCyclicRefError(w, 0, 1)); 74 | } 75 | 76 | static void testStack(void **state) 77 | { 78 | Stack *stack = malloc(sizeof(Stack)); 79 | stack->len = 0; 80 | 81 | Node *node = malloc(sizeof(Node)); 82 | node->value = 10.0; 83 | push(stack, node); 84 | 85 | Node *node2 = malloc(sizeof(Node)); 86 | node2->value = 12.0; 87 | push(stack, node2); 88 | 89 | Node *poppedNode1 = pop(stack); 90 | assert_true(12.0 == poppedNode1->value); 91 | 92 | Node *poppedNode2 = pop(stack); 93 | assert_true(10.0 == poppedNode2->value); 94 | 95 | free(node); 96 | free(node2); 97 | free(stack); 98 | } 99 | 100 | int main(int argc, char *argv[]) 101 | { 102 | const struct CMUnitTest tests[] = { 103 | cmocka_unit_test(testConvertToCellReference), 104 | cmocka_unit_test(testConvertToMatrixLocation), 105 | cmocka_unit_test(testSetAndGetWorkSheetValue), 106 | cmocka_unit_test(testCyclicDependency), 107 | cmocka_unit_test(testStack), 108 | }; 109 | 110 | return cmocka_run_group_tests(tests, NULL, NULL); 111 | } 112 | -------------------------------------------------------------------------------- /solutions/c/stack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "stack.h" 3 | 4 | 5 | void _add(Stack *head,int value){ 6 | Stack node = (Stack)malloc(sizeof(Stack)); 7 | if(node !=NULL){ 8 | node->value = value; 9 | node->next = *head; 10 | *head = node; 11 | } 12 | } 13 | 14 | int _remove(Stack *head){ 15 | int value = -1; 16 | if(head!=NULL){ 17 | Stack top = *head; 18 | value = (*head)->value; 19 | *head = (*head)->next; 20 | free(top); 21 | 22 | } 23 | return value; 24 | } 25 | -------------------------------------------------------------------------------- /solutions/c/stack.h: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H_INCLUDED 2 | #define STACK_H_INCLUDED 3 | 4 | typedef struct Nodestack { 5 | int value; 6 | struct Nodestack *next; 7 | }NodeStack; 8 | 9 | typedef NodeStack *Stack; 10 | 11 | // add the element onto the stack 12 | void _add(Stack*,int); 13 | 14 | //returns the element on top of the stack 15 | int _remove(Stack*); 16 | 17 | 18 | #endif // STACK_H_INCLUDED 19 | -------------------------------------------------------------------------------- /solutions/cpp/once.hpp: -------------------------------------------------------------------------------- 1 | #ifndef ONCE_HPP_INCLUDED 2 | #define ONCE_HPP_INCLUDED 3 | 4 | #include // std::decay, std::is_same 5 | #include // std::runtime_error 6 | #include // std::size_t 7 | #include // std::forward 8 | #include // std::mem_fun 9 | 10 | struct out_of_calls : std::runtime_error { 11 | out_of_calls(std::string const& what_arg) : std::runtime_error{what_arg} {}; 12 | }; 13 | 14 | template 15 | struct once_t { 16 | typename std::decay::type functor; 17 | std::size_t times; 18 | 19 | template 20 | auto operator()(Args&&... args) -> decltype(functor(std::forward(args)...)) { 21 | if(times != 0) { 22 | --times; 23 | return functor(std::forward(args)...); 24 | } 25 | if(!std::is_same(args)...)), void>::value) 26 | throw out_of_calls{"Non-void function called beyond requested allowance."}; 27 | }; 28 | }; 29 | 30 | template 31 | auto once(Functor&& functor) -> once_t { 32 | return {std::forward(functor), 1}; 33 | } 34 | 35 | template 36 | auto once(Functor&& functor, std::size_t const times) -> once_t { 37 | return {std::forward(functor), times}; 38 | } 39 | 40 | template 41 | auto once(S(T::*fn)(A...)) -> once_t { 42 | return {std::mem_fun(fn), 1}; 43 | } 44 | 45 | template 46 | auto once(S(T::*fn)(A...), std::size_t const times) -> once_t { 47 | return {std::mem_fun(fn), times}; 48 | } 49 | 50 | template 51 | auto once(S(T::*fn)(A...) const) -> once_t { 52 | return {std::mem_fun(fn), 1}; 53 | } 54 | 55 | template 56 | auto once(S(T::*fn)(A...) const, std::size_t const times) -> once_t { 57 | return {std::mem_fun(fn), times}; 58 | } 59 | 60 | #endif //ONCE_HPP_INCLUDED 61 | -------------------------------------------------------------------------------- /solutions/cpp/queue.hpp: -------------------------------------------------------------------------------- 1 | #ifndef STACK_HPP_INCLUDED 2 | #define STACK_HPP_INCLUDED 3 | 4 | #include // std::forward 5 | #include // std::move 6 | #include // std::runtime_error 7 | 8 | class empty_queue : public std::runtime_error { 9 | public: 10 | empty_queue(std::string const& what_arg) : std::runtime_error{what_arg} {}; 11 | }; 12 | 13 | template 14 | class Queue { 15 | public: 16 | Queue() : head{nullptr}, tail{nullptr} {}; 17 | ~Queue(); 18 | 19 | template 20 | void enqueue(U&& t); 21 | T dequeue(); 22 | 23 | inline bool empty() const { return head == nullptr; }; 24 | 25 | private: 26 | struct Node { 27 | T data; 28 | Node* next; 29 | 30 | template 31 | Node(U&& d, Node* n) : data{std::forward(d)}, next{n} {}; 32 | }; 33 | 34 | Node* head; 35 | Node* tail; 36 | }; 37 | 38 | template 39 | Queue::~Queue() { 40 | // Rewriting functionality of dequeue here avoids a call to the move 41 | // constructor for each element in the stack. For code golf, use: 42 | // while(!empty()) dequeue(); 43 | while(!empty()) { 44 | auto old_head = head; 45 | head = head->next; 46 | delete old_head; 47 | } 48 | } 49 | 50 | template 51 | template 52 | void Queue::enqueue(U&& t) { 53 | auto node = new Node{std::forward(t), nullptr}; 54 | if(empty()) 55 | head = node; 56 | else 57 | tail->next = node; 58 | tail = node; 59 | } 60 | 61 | template 62 | T Queue::dequeue() { 63 | if(empty()) 64 | throw empty_queue{"Dequeue called on empty queue."}; 65 | 66 | auto old_head = head; 67 | auto old_data = std::move(head->data); 68 | head = head->next; 69 | 70 | // actually unnecessary 71 | /* if(empty()) */ 72 | /* tail = nullptr; */ 73 | 74 | delete old_head; 75 | return old_data; 76 | } 77 | 78 | #endif // STACK_HPP_INCLUDED 79 | -------------------------------------------------------------------------------- /solutions/cpp/spiral.hpp: -------------------------------------------------------------------------------- 1 | #ifndef SPIRAL_HPP_INCLUDED 2 | #define SPIRAL_HPP_INCLUDED 3 | 4 | #include // std::vector 5 | #include // std::move 6 | 7 | std::vector spiral(unsigned int height, unsigned int width, int row, int column) { 8 | enum { 9 | Up, Left, Down, Right 10 | } currentDirection = Up; 11 | unsigned int maxLength = 1, 12 | length = 0; 13 | std::vector visited; 14 | 15 | while(visited.size() != height*width) { 16 | if(width >= column && column > 0) 17 | if(height >= row && row > 0) 18 | visited.push_back(column + (row - 1)*width); 19 | 20 | switch(currentDirection) { 21 | case Up: 22 | --row; 23 | break; 24 | case Left: 25 | --column; 26 | break; 27 | case Down: 28 | ++row; 29 | break; 30 | case Right: 31 | ++column; 32 | break; 33 | } 34 | 35 | ++length; 36 | 37 | if(length == maxLength) { 38 | length = 0; 39 | 40 | switch(currentDirection) { 41 | case Up: 42 | currentDirection = Left; 43 | break; 44 | case Left: 45 | currentDirection = Down; 46 | ++maxLength; 47 | break; 48 | case Down: 49 | currentDirection = Right; 50 | break; 51 | case Right: 52 | currentDirection = Up; 53 | ++maxLength; 54 | break; 55 | } 56 | } 57 | } 58 | 59 | return std::move(visited); 60 | } 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /solutions/cpp/stack.hpp: -------------------------------------------------------------------------------- 1 | #ifndef STACK_HPP_INCLUDED 2 | #define STACK_HPP_INCLUDED 3 | 4 | #include // std::forward 5 | #include // std::move 6 | #include // std::runtime_error 7 | 8 | class empty_stack : public std::runtime_error { 9 | public: 10 | empty_stack(std::string const& what_arg) : std::runtime_error{what_arg} {}; 11 | }; 12 | 13 | template 14 | class Stack { 15 | public: 16 | Stack() : head{nullptr} {}; 17 | ~Stack(); 18 | 19 | template 20 | void add(U&&); 21 | T remove(); 22 | 23 | inline bool empty() const { return head == nullptr; }; 24 | 25 | private: 26 | struct Node { 27 | T data; 28 | Node* next; 29 | 30 | template 31 | Node(U&& d, Node* n) : data{std::forward(d)}, next{n} {}; 32 | }; 33 | 34 | Node* head; 35 | }; 36 | 37 | template 38 | Stack::~Stack() { 39 | // Rewriting functionality of remove here avoids a call to the move 40 | // constructor for each element in the stack. For code golf, use: 41 | // while(!empty()) remove(); 42 | while(!empty()) { 43 | auto old_head = head; 44 | head = head->next; 45 | delete old_head; 46 | } 47 | } 48 | 49 | template 50 | template 51 | void Stack::add(U&& t) { 52 | head = new Node{std::forward(t), head}; 53 | } 54 | 55 | template 56 | T Stack::remove() { 57 | if(empty()) 58 | throw empty_stack{"Remove called on empty stack."}; 59 | 60 | auto old_head = head; 61 | auto old_data = std::move(head->data); 62 | head = head->next; 63 | 64 | delete old_head; 65 | return old_data; 66 | } 67 | 68 | #endif // STACK_HPP_INCLUDED 69 | -------------------------------------------------------------------------------- /solutions/python/adjacency-list.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | ## SOLUTION ONE ########################## 4 | class Vertex: 5 | def __init__(self,key): 6 | self.id = key 7 | self.connectedTo = {} 8 | 9 | def addNeighbor(self,nbr,weight=0): 10 | self.connectedTo[nbr] = weight 11 | 12 | def __str__(self): 13 | return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo]) 14 | 15 | def getConnections(self): 16 | return self.connectedTo.keys() 17 | 18 | def getId(self): 19 | return self.id 20 | 21 | def getWeight(self,nbr): 22 | return self.connectedTo[nbr] 23 | 24 | class Graph: 25 | def __init__(self): 26 | self.vertList = {} 27 | self.numVertices = 0 28 | 29 | def addVertex(self,key): 30 | self.numVertices = self.numVertices + 1 31 | newVertex = Vertex(key) 32 | self.vertList[key] = newVertex 33 | return newVertex 34 | 35 | def getVertex(self,n): 36 | if n in self.vertList: 37 | return self.vertList[n] 38 | else: 39 | return None 40 | 41 | def __contains__(self,n): 42 | return n in self.vertList 43 | 44 | def addEdge(self,f,t,cost=0): 45 | if f not in self.vertList: 46 | nv = self.addVertex(f) 47 | if t not in self.vertList: 48 | nv = self.addVertex(t) 49 | self.vertList[f].addNeighbor(self.vertList[t], cost) 50 | 51 | def getVertices(self): 52 | return self.vertList.keys() 53 | 54 | def __iter__(self): 55 | return iter(self.vertList.values()) 56 | 57 | ## END SOLUTION ONE ##### 58 | -------------------------------------------------------------------------------- /solutions/python/adjacency-matrix.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | # TODO: // This whole thing. Wasn't easy to find a good implementation online. 4 | -------------------------------------------------------------------------------- /solutions/python/all-unique-characters.py: -------------------------------------------------------------------------------- 1 | # Check if a string is composed of all unique characters 2 | # author: Matt Box 3 | import unittest 4 | 5 | def all_unique(string): 6 | 7 | # Optimization that assumes only 255 ASCII characters are possible (ignores possibility of unicode) 8 | nLetters = len(letters) 9 | if (nLetters > 255): 10 | return False 11 | 12 | letters = sorted(string) 13 | for i in range(nLetters - 1): 14 | if letters[i] == letters[i + 1]: 15 | return False 16 | return True 17 | 18 | class Test(unittest.TestCase): 19 | def test_sanity(self): 20 | self.assertFalse(all_unique("foo")) 21 | self.assertTrue(all_unique("bar")) 22 | 23 | if __name__ == '__main__': 24 | unittest.main() 25 | 26 | -------------------------------------------------------------------------------- /solutions/python/anagram-detection.py: -------------------------------------------------------------------------------- 1 | # Simple function that will take a string of latin characters and return a unique hash 2 | def hashString(str): 3 | # Map characters to prime numbers to multiply 4 | charMap = { 5 | 'a': 2, 6 | 'b': 3, 7 | 'c': 5, 8 | 'd': 7, 9 | 'e': 11, 10 | 'f': 13, 11 | 'g': 17, 12 | 'h': 19, 13 | 'i': 23, 14 | 'j': 29, 15 | 'k': 31, 16 | 'l': 37, 17 | 'm': 41, 18 | 'n': 43, 19 | 'o': 47, 20 | 'p': 53, 21 | 'q': 59, 22 | 'r': 61, 23 | 's': 67, 24 | 't': 71, 25 | 'u': 73, 26 | 'v': 79, 27 | 'w': 83, 28 | 'x': 89, 29 | 'y': 97, 30 | 'z': 101, 31 | 'A': 103, 32 | 'B': 107, 33 | 'C': 109, 34 | 'D': 113, 35 | 'E': 127, 36 | 'F': 131, 37 | 'G': 137, 38 | 'H': 139, 39 | 'I': 149, 40 | 'J': 151, 41 | 'K': 163, 42 | 'L': 167, 43 | 'M': 173, 44 | 'N': 179, 45 | 'O': 181, 46 | 'P': 191, 47 | 'Q': 193, 48 | 'R': 197, 49 | 'S': 199, 50 | 'T': 211, 51 | 'U': 223, 52 | 'V': 227, 53 | 'W': 229, 54 | 'X': 233, 55 | 'Y': 239, 56 | 'Z': 241 57 | } 58 | 59 | return reduce(lambda memo, char: memo * charMap[char], list(str), 1); 60 | 61 | def anagramDetection(parent, child): 62 | length = len(child) 63 | anagram = hashString(child) 64 | total = 0 65 | 66 | for i in range(0, len(parent) - length): 67 | if hashString(parent[i: i + length]) == anagram: 68 | total = total + 1 69 | 70 | return total 71 | -------------------------------------------------------------------------------- /solutions/python/array-pair-sum.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | """solution to the array pair sum problem""" 4 | 5 | def array_pair_sum_iterative(arr, k): 6 | """ 7 | returns the array of pairs using an iterative method. 8 | complexity: O(n^2) 9 | """ 10 | 11 | result = [] 12 | 13 | for i in range(len(arr)): 14 | for j in range(i + 1, len(arr)): 15 | if arr[i] + arr[j] == k: 16 | result.append([arr[i], arr[j]]) 17 | 18 | return result 19 | 20 | 21 | def array_pair_sum_sort(arr, k): 22 | """ 23 | first sort the array and then use binary search to find pairs. 24 | complexity: O(nlogn) 25 | """ 26 | 27 | result = [] 28 | arr.sort() 29 | 30 | for i in range(len(arr)): 31 | if k - arr[i] in arr[i+1:]: 32 | result.append([arr[i], k - arr[i]]) 33 | 34 | return result 35 | 36 | 37 | def array_pair_sum_hash_table(arr, k): 38 | """ 39 | Use a hash table to store array elements of pairs. 40 | complexity: O(n) 41 | """ 42 | 43 | result = [] 44 | hash_table = {} 45 | 46 | for e in arr: 47 | if e in hash_table: 48 | result.append([k - e, e]) 49 | else: 50 | hash_table[k - e] = True 51 | result.reverse() 52 | 53 | return result 54 | 55 | 56 | # Unit tests 57 | class array_pair_sum_tests(unittest.TestCase): 58 | 59 | def setUp(self): 60 | self.arr1 = [3, 4, 5, 6, 7] 61 | self.arr2 = [3, 4, 5, 4, 4] 62 | self.result1 = [[3, 7], [4, 6]] 63 | self.result2 = [[3, 5], [4, 4], [4, 4], [4, 4]] 64 | 65 | def test_one(self): 66 | self.assertEqual( 67 | array_pair_sum_iterative(self.arr1, 10), self.result1) 68 | self.assertEqual( 69 | array_pair_sum_sort(self.arr1, 10), self.result1) 70 | self.assertEqual( 71 | array_pair_sum_hash_table(self.arr1, 10), self.result1) 72 | 73 | def test_two(self): 74 | self.assertEqual( 75 | array_pair_sum_iterative(self.arr2, 8), self.result2) # currently failing 76 | self.assertEqual( 77 | array_pair_sum_sort(self.arr2, 8), self.result2) 78 | self.assertEqual( 79 | array_pair_sum_hash_table(self.arr2, 8), self.result2) 80 | 81 | 82 | if __name__ == '__main__': 83 | unittest.main() 84 | -------------------------------------------------------------------------------- /solutions/python/arraylist.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class ArrayList(object): 4 | 5 | def __init__(self): 6 | self.list = [0] * 100 # init zeros in each cell 7 | self.numElems = 0 # list starts empty 8 | 9 | def append(self, x): 10 | # check if there's enough room 11 | if self.numElems >= len(self.list): 12 | self._double_size() 13 | self.list[self.numElems] = x 14 | self.numElems += 1 15 | 16 | def pop(self): 17 | popped = self.list[-1] 18 | self.list[-1] = 0 19 | return popped 20 | 21 | def insert(self, index, item): 22 | if self.numElems == len(self.list): 23 | self._double_size() 24 | for i in range(self.numElems, index, -1): 25 | self.list[i] = self.list[i-1] 26 | self.list[index] = item 27 | 28 | def _double_size(self): 29 | # allocate a bigger internal list 30 | newList = [0] * (2 * len(self.list)) 31 | # copy all the elements from the old list 32 | i = 0 33 | for i in range(len(self.list)): 34 | newList[i] = self.list[i] 35 | self.list = newList 36 | 37 | def __str__(self): 38 | s = "" 39 | for i in range(self.numElems): 40 | s += str(self.list[i]) 41 | if i != self.numElems: s += ',' 42 | return s 43 | 44 | 45 | 46 | class Test_ArrayList(unittest.TestCase): 47 | 48 | def setUp(self): 49 | pass 50 | 51 | def test_arraylist_one(self): 52 | pass 53 | 54 | 55 | if __name__ == '__name__': 56 | unittest.main() 57 | -------------------------------------------------------------------------------- /solutions/python/balanced-brackets.py: -------------------------------------------------------------------------------- 1 | # Use a dictionary to map sets of brackets to their opposites 2 | brackets = { 3 | '(': ')', 4 | '{': '}', 5 | '[': ']' 6 | } 7 | 8 | # On each input string, process it using the balance checker 9 | def balancedBrackets(string): 10 | stack = [] 11 | # Process every character on input 12 | for char in string: 13 | # Assign an initial value in case the stack is empty 14 | last = 0 15 | # Assign the value of the last element if stack is not empty 16 | if stack: 17 | last = stack[len(stack) - 1] 18 | if stack and last in brackets and brackets[last] == char: 19 | stack.pop() 20 | else: 21 | stack.append(char) 22 | 23 | return not stack 24 | -------------------------------------------------------------------------------- /solutions/python/base-ten-to-binary.py: -------------------------------------------------------------------------------- 1 | # base_ten_to_binary: takes an int, returns the binary representation as a string. 2 | # author: Matt Box 3 | def base_ten_to_binary(num): 4 | # we'll push the digits into this list, least significant first 5 | digits = [] 6 | while num: 7 | if num & 1: 8 | digits.append('1') 9 | else: 10 | digits.append('0') 11 | num = num >> 1 12 | # if we got here with an empty list num was 0 to begin with 13 | if digits == []: 14 | digits = ['0'] 15 | 16 | digits.reverse() 17 | return ''.join(digits) 18 | 19 | import unittest 20 | 21 | class Test(unittest.TestCase): 22 | def test_sanity(self): 23 | self.assertEqual(base_ten_to_binary(0), '0') 24 | self.assertEqual(base_ten_to_binary(1), '1') 25 | self.assertEqual(base_ten_to_binary(10), '1010') 26 | 27 | if __name__ == '__main__': 28 | unittest.main() 29 | 30 | -------------------------------------------------------------------------------- /solutions/python/binary-islands.py: -------------------------------------------------------------------------------- 1 | # binary_islands: count the number of connected groups of 1's in a binary matrix 2 | # author: Matt Box 3 | 4 | def binary_islands(matrix): 5 | # plan: 6 | # 1. find a one. 7 | # 2. tally up one island. 8 | # 3. mark this cell in a do not visit list and do the same with 9 | # any of our neighbours who are 1. 10 | # do this recursively so we mark a whole island at a time. 11 | # 4. repeat until the matrix is exhausted. 12 | 13 | height = len(matrix) 14 | width = len(matrix[0]) 15 | 16 | # setup do_not_visit[][] 17 | do_not_visit = [[False] * width for i in range(height)] 18 | # that was from: 19 | # https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list 20 | # ... python is weird. 21 | 22 | def visit(i, j): 23 | # don't come back 24 | do_not_visit[i][j] = True 25 | # visit neighbours who are 1 26 | if j < (width-1) and matrix[i][j+1] == 1 and not do_not_visit[i][j+1]: 27 | visit(i, j+1) 28 | if j > 0 and matrix[i][j-1] == 1 and not do_not_visit[i][j-1]: 29 | visit(i, j-1) 30 | if i < (height-1) and matrix[i+1][j] == 1 and not do_not_visit[i+1][j]: 31 | visit(i+1, j) 32 | if i > 0 and matrix[i-1][j] == 1 and not do_not_visit[i-1][j]: 33 | visit(i-1, j) 34 | 35 | def find_a_one(matrix): 36 | for i in range(height): 37 | for j in range(width): 38 | if matrix[i][j] == 1 and not do_not_visit[i][j]: 39 | return i, j 40 | return -1, -1 41 | 42 | islands = 0 43 | while True: 44 | i, j = find_a_one(matrix) 45 | if i < 0: 46 | # i.e. we could not find a one 47 | break 48 | islands += 1 49 | visit(i, j) 50 | 51 | return islands 52 | 53 | import unittest 54 | 55 | class Test(unittest.TestCase): 56 | def test_sanity(self): 57 | self.assertEqual(binary_islands([[0,0,0,0,0], 58 | [0,0,0,0,0], 59 | [0,0,0,0,0], 60 | [0,0,0,0,0]]), 0) 61 | self.assertEqual(binary_islands([[1,1,1,1,1], 62 | [1,1,1,1,1], 63 | [1,1,1,1,1], 64 | [1,1,1,1,1]]), 1) 65 | self.assertEqual(binary_islands([[1,1,0,0,1], 66 | [1,0,0,1,1], 67 | [0,0,0,0,1], 68 | [1,1,0,0,0]]), 3) 69 | 70 | if __name__ == '__main__': 71 | unittest.main() 72 | 73 | -------------------------------------------------------------------------------- /solutions/python/binary-search-sorted.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def binary_search_one(lst, item): 4 | first = 0 5 | last = len(lst) - 1 6 | found = False 7 | 8 | while first <= last and not found: 9 | midpoint = (first + last) // 2 10 | if lst[midpoint] == item: 11 | found = True 12 | else: 13 | if item < lst[midpoint]: 14 | last = midpoint - 1 15 | else: 16 | first = midpoint + 1 17 | return found 18 | 19 | def binary_search_two( item, lst, lo, hi): 20 | """ This binary search is recursive and also returns the index of the item. """ 21 | if len(lst) == 0: return -1 22 | if hi < lo: return -1 # no more numbers to search 23 | mid = (lo + hi) // 2 # midpoint in array 24 | if item == lst[mid]: 25 | return mid 26 | elif item < lst[mid]: 27 | return binary_search_two(item, lst, lo, mid -1) # try left side 28 | else: 29 | return binary_search_two(item, lst, mid + 1, hi) # try right side 30 | 31 | # Unit Testing 32 | class Test_Bin_Search(unittest.TestCase): 33 | 34 | def setUp(self): 35 | pass 36 | 37 | def test_binary_search_one(self): 38 | self.assertEqual( 39 | binary_search_one([1,2,3,4,5,6,7,8,9], 4), True 40 | ) 41 | self.assertEqual( binary_search_one([], 0), False) 42 | self.assertEqual( 43 | binary_search_one([1,2,3,4,5,6,7,8,9], 10), False 44 | ) 45 | 46 | def test_binary_search_two(self): 47 | lst = [1,2,3,4,5,6,7,8,9] 48 | self.assertEqual( 49 | binary_search_two(4, lst, 0, len(lst)-1), 3 # index 50 | ) 51 | self.assertEqual( binary_search_two(0,[], 0, 0), -1) # how does it handle empty list? 52 | self.assertEqual( 53 | binary_search_two(10, lst, 0, len(lst)-1), -1 54 | ) 55 | 56 | if __name__ == '__main__': 57 | unittest.main() 58 | -------------------------------------------------------------------------------- /solutions/python/bubble-sort.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def bubblesort(lst): 4 | for i in range(0, len(lst) - 1): 5 | for j in range(i + 1, len(lst)): 6 | if lst[i] > lst[j]: 7 | # swap values 8 | lst[i], lst[j] = lst[j], lst[i] 9 | return lst 10 | 11 | class Test(unittest.TestCase): 12 | def testUnsortedSmall(self): 13 | self.assertEqual([1,2,3,4], bubblesort([4,3,2,1])) 14 | 15 | def testSortedSmall(self): 16 | self.assertEqual([1,2,3,4], bubblesort([1,2,3,4])) 17 | 18 | def testUnsortedLarge(self): 19 | self.assertEqual([1,2,3,4,5,6,7,8,9,10], bubblesort([6,3,4,8,7,9,5,10,1,2])) 20 | 21 | def testSortedLarge(self): 22 | self.assertEqual([1,2,3,4,5,6,7,8,9,10], bubblesort([1,2,3,4,5,6,7,8,9,10])) 23 | 24 | def testSingleInput(self): 25 | self.assertEqual([1], bubblesort([1])) 26 | 27 | def testBlankInput(self): 28 | self.assertEqual([], bubblesort([])) 29 | 30 | if __name__ == '__main__': 31 | unittest.main() 32 | -------------------------------------------------------------------------------- /solutions/python/closetsum.py: -------------------------------------------------------------------------------- 1 | # In given A, find three elements whose sum is closest to give value. 2 | #author: Pankaj Kumar 3 | 4 | import sys 5 | def threeSumClosest(A, B): 6 | i , n = 0 , len(A) 7 | A = sorted(A) 8 | diff = sys.maxint 9 | close_sum = 0 10 | while i <= n-3: 11 | j , k = i+1 , n-1 12 | sum = A[i] + A[j] + A[k] 13 | if sum == B: 14 | return sum 15 | if diff > abs(sum - B): 16 | diff += abs(sum-B) 17 | close_sum = sum 18 | if sum < B: 19 | j += 1 20 | else: 21 | k -= 1 22 | i += 1 23 | return close_sum 24 | print threeSumClosest([-1, 2, 1, -4], 1) 25 | -------------------------------------------------------------------------------- /solutions/python/convert-array.py: -------------------------------------------------------------------------------- 1 | """solution to the convert array problem""" 2 | 3 | def f(arr): 4 | """sorts the array by numbers in place using constant extra space""" 5 | 6 | position = 0 7 | for i in xrange(len(arr) / 3): 8 | gap = (len(arr) - position) / 3 9 | arr.insert(position + 1, arr.pop(position + gap * 1)) 10 | arr.insert(position + 2, arr.pop(position + gap * 2)) 11 | position += 3 12 | 13 | return arr 14 | -------------------------------------------------------------------------------- /solutions/python/count-string-characters.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from collections import Counter 3 | 4 | def count_characters_one( string ): 5 | """ Counts with a for loop and a dict. """ 6 | d = {} 7 | for s in string: 8 | d[s] = d.get(s,0)+1 9 | return d 10 | 11 | def count_characters_two( string ): 12 | """ Counts using collections.Count """ 13 | counter = Counter(string) 14 | return counter 15 | 16 | 17 | -------------------------------------------------------------------------------- /solutions/python/csv-parsing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """solution to the csv parsing problem, handling quotes and numric values""" 4 | 5 | def convert_to_number(value): 6 | """converts the passed over string to a number, if possible""" 7 | 8 | try: 9 | return int(value) 10 | except ValueError: 11 | pass 12 | 13 | return value 14 | 15 | def csv_parsing(csv): 16 | """returns list of string/numeric csv values""" 17 | 18 | count = 0 19 | values = [] 20 | pos = 0 21 | while pos < len(csv): 22 | if csv[pos] == ',': # skip comma from previous iteration 23 | pos += 1 24 | 25 | values.insert(count, '') 26 | while pos < len(csv) and csv[pos] != ',': 27 | if csv[pos] == '"' or csv[pos] == "'": # handle quoted strings 28 | first_quote = pos 29 | pos += 1 30 | 31 | while pos < len(csv) and csv[pos] != csv[first_quote]: 32 | values[count] += csv[pos] 33 | pos += 1 34 | 35 | else: 36 | values[count] += csv[pos] 37 | 38 | pos += 1 39 | 40 | #if the value is numeric, this will convert it. 41 | values[count] = convert_to_number(values[count]) 42 | 43 | count += 1 44 | pos += 1 45 | 46 | return values 47 | -------------------------------------------------------------------------------- /solutions/python/csv-sort.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import unittest 3 | 4 | def csv_sort( string , console_out=True): 5 | items=[x for x in string.split(',')] 6 | items.sort() 7 | if console_out: 8 | print( ','.join(items) ) 9 | else: 10 | return ','.join(items) 11 | 12 | 13 | 14 | # Unit tests 15 | class csv_sort_tests(unittest.TestCase): 16 | 17 | def setUp(self): 18 | self.stringOne = "33,44,55,11,22" 19 | self.stringTwo = "a,f,d,z,y,e" 20 | self.stringEdge = "" 21 | self.stringEdgeTwo = "z,z,z,z,z,z,z" 22 | 23 | def test_csv_sort_one(self): 24 | self.assertEqual( 25 | csv_sort(self.stringOne, False), "11,22,33,44,55" 26 | ) 27 | self.assertEqual( 28 | csv_sort(self.stringTwo, False), "a,d,e,f,y,z" 29 | ) 30 | self.assertEqual( csv_sort(self.stringEdge, False), "" ) 31 | self.assertEqual( 32 | csv_sort(self.stringEdgeTwo, False), "z,z,z,z,z,z,z" 33 | ) 34 | 35 | if __name__ == '__main__': 36 | print("Tests started") 37 | unittest.main() 38 | -------------------------------------------------------------------------------- /solutions/python/deterministic-quick-select.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | # TODO: all of it 4 | -------------------------------------------------------------------------------- /solutions/python/dict-of-squared-ints.py: -------------------------------------------------------------------------------- 1 | from future import print_function 2 | import unittest 3 | 4 | def dict_of_squared_int( number ): 5 | """ Using a regular for loop. """ 6 | n=int(input()) 7 | d=dict() 8 | for i in range(1,n+1): 9 | d[i]=i*i 10 | 11 | print( d ) 12 | 13 | def dict_of_squared_int_two( number ): 14 | """ Using a dictionary comprehension. """ 15 | n=int(input()) 16 | d = { i: i*i for i in range(1, n+1)} 17 | 18 | print( d ) 19 | -------------------------------------------------------------------------------- /solutions/python/dir-function-equivelant.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | # TODO 4 | -------------------------------------------------------------------------------- /solutions/python/euclids-algorithm.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def euclids_algorithm(a, b): 4 | """ Calculate the Greatest Common Divisor of a and b. """ 5 | if 0 in [a,b]: return False # You can never divide by 0, so this should fail 6 | while b: 7 | a, b = b, a%b 8 | return a 9 | 10 | 11 | # Unit testing 12 | class euclids_algorithm_tests(unittest.TestCase): 13 | 14 | def setUp(self): 15 | pass 16 | 17 | def test_euclids_one(self): 18 | self.assertEqual( euclids_algorithm( 24, 30 ), 6 ) 19 | self.assertEqual( euclids_algorithm( 1, 10 ), 1 ) 20 | self.assertEqual( euclids_algorithm( 0, 1000), False ) 21 | self.assertEqual( euclids_algorithm( 300, 300), 300) 22 | 23 | 24 | if __name__ == '__main__': 25 | unittest.main() 26 | -------------------------------------------------------------------------------- /solutions/python/even-occuring-element.py: -------------------------------------------------------------------------------- 1 | def even_occuring_element(arr): 2 | """Returns the even occuring element within a list of integers""" 3 | 4 | dict = {} 5 | for num in arr: 6 | if num in dict: 7 | dict[num] += 1 8 | else: 9 | dict[num] = 1 10 | 11 | for num in dict: 12 | if not dict[num] & 1: # bitwise check for parity. 13 | return num 14 | -------------------------------------------------------------------------------- /solutions/python/factorial.py: -------------------------------------------------------------------------------- 1 | """solutions to the factorial problem""" 2 | 3 | def factorial_iterative(num): 4 | """returns the factorial of num using an iterative method.""" 5 | 6 | factor = 1 7 | 8 | for i in xrange(1, num + 1): 9 | factor *= i 10 | 11 | return factor 12 | 13 | def factorial_reduce(num): 14 | """returns the factorial of num using a reduce (shortest method).""" 15 | 16 | return reduce(lambda x, y: x * y, range(1, num + 1)) 17 | 18 | def factorial_recursive(num): 19 | """returns the factorial of num using a recursive method.""" 20 | 21 | if num == 1: 22 | return 1 23 | 24 | return num * factorial_recursive(num -1) 25 | -------------------------------------------------------------------------------- /solutions/python/fibonacci.py: -------------------------------------------------------------------------------- 1 | """solutions to the fibonacci problem""" 2 | 3 | def fibonacci_iterative(limit): 4 | """fibonacci sequence using an iterative approach.""" 5 | 6 | a, b = 0, 1 7 | for i in xrange(limit): 8 | a, b = b, a + b 9 | 10 | return a 11 | 12 | def fibonacci_recursive(limit): 13 | """fibonacci sequence using a recusive approach.""" 14 | 15 | if limit <= 1: 16 | return limit 17 | 18 | return fibonacci_recursive(limit - 1) + fibonacci_recursive(limit - 2) 19 | 20 | def fibonacci_reduce(limit): 21 | """fibonacci sequence using reduce (shortest option).""" 22 | 23 | return reduce(lambda x, y: x + [x[y] + x[y - 1]], range(1, limit), [0, 1])[-1] 24 | 25 | def fibonacci_comprehension(limit): 26 | """fibonacci sequence using a list comprehension.""" 27 | 28 | sequence = [0, 1] 29 | 30 | [sequence.append(sequence[i] + sequence[i-1]) for i in range(1, limit)] 31 | 32 | return sequence[-1] 33 | 34 | def fibonacci_generator(): 35 | """ fibonacci sequence using a generator.""" 36 | a, b = 0, 1 37 | yield a 38 | yield b 39 | while True: 40 | a, b = b, b + a 41 | yield b 42 | 43 | if __name__ == '__main__:' 44 | 45 | # Use generator version 46 | for i,value in zip(range(15),fibonacci_generator()): 47 | print(value) 48 | 49 | # Cant use this way. You will just get 0's 50 | for _ in range(15): 51 | print(next(fibonacci_generator())) # we just keep hitting the first "yeild a" 52 | -------------------------------------------------------------------------------- /solutions/python/find-missing-element.py: -------------------------------------------------------------------------------- 1 | """finds the missing element in the shuffled list""" 2 | 3 | def difference_set(orig, shuffled): 4 | """finds the missing element using a set.""" 5 | 6 | return set(orig).difference(set(shuffled)).pop() 7 | 8 | def difference_iterative(orig, shuffled): 9 | """finds the missing element by iterating over the list""" 10 | 11 | for x in orig: 12 | if not x in shuffled: 13 | return x 14 | -------------------------------------------------------------------------------- /solutions/python/find-pairs-summing-to-ten.py: -------------------------------------------------------------------------------- 1 | # pairs_sum_to_ten 2 | # find pairs in a list that sum to ten 3 | # author: Matt Box 4 | import unittest 5 | 6 | # 1. the easy way: quadratic time (O(n**2)) 7 | def pairs_sum_to_ten1(lst): 8 | pairs = [] 9 | lst.sort() 10 | for left in lst: 11 | # check against the numbers to the right of "left": 12 | for right in lst[(lst.index(left) + 1):]: 13 | if left + right == 10: 14 | pairs.append((left,right)) 15 | return pairs 16 | 17 | # 2. the tricky way: linear time (O(n)) 18 | # (not counting the sort) 19 | def pairs_sum_to_ten2(lst): 20 | pairs = [] 21 | lst.sort() 22 | l_index = 0; 23 | r_index = len(lst) - 1 24 | while l_index != r_index: 25 | left = lst[l_index] 26 | right = lst[r_index] 27 | s = left + right 28 | if s == 10: 29 | pairs.append((left, right)) 30 | l_index += 1 31 | continue 32 | # the sum != 10: 33 | if s < 10: 34 | l_index += 1 35 | continue 36 | # the sum is > 10: 37 | r_index -= 1 38 | 39 | return pairs 40 | 41 | class Test(unittest.TestCase): 42 | def test_sanity(self): 43 | self.assertEqual(pairs_sum_to_ten1([2,4,6,8]), 44 | [(2,8), (4,6)]) 45 | self.assertEqual(pairs_sum_to_ten2([2,4,6,8]), 46 | [(2,8), (4,6)]) 47 | 48 | self.assertEqual(pairs_sum_to_ten2([2,4,5,6,8]), 49 | [(2,8), (4,6)]) 50 | self.assertEqual(pairs_sum_to_ten1([2,4,5,6,8]), 51 | [(2,8), (4,6)]) 52 | 53 | self.assertEqual(pairs_sum_to_ten1([-10,-5,0,5,10,15,20]), 54 | [(-10,20), (-5,15), (0,10)]) 55 | self.assertEqual(pairs_sum_to_ten2([-10,-5,0,5,10,15,20]), 56 | [(-10,20), (-5,15), (0,10)]) 57 | 58 | if __name__ == '__main__': 59 | unittest.main() 60 | 61 | -------------------------------------------------------------------------------- /solutions/python/find_anagrams_in_list.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thundergolfer/interview-with-python/b5ce31c8bdca754a76762d2734dcf494a302e487/solutions/python/find_anagrams_in_list.py -------------------------------------------------------------------------------- /solutions/python/first-non-repeated-character.py: -------------------------------------------------------------------------------- 1 | """solution for the first-non-repeated-character problem""" 2 | 3 | def first_non_repeated_character(str): 4 | """finds the first character in a string that's not repreated""" 5 | 6 | for i, char in enumerate(str): 7 | if i - 1 >= 0 and char == str[i - 1]: 8 | continue 9 | if i + 1 < len(str) and char == str[i + 1]: 10 | continue 11 | 12 | return char 13 | -------------------------------------------------------------------------------- /solutions/python/fizz-buzz.py: -------------------------------------------------------------------------------- 1 | """ Implementations of the class Fizz-Buzz problem """ 2 | 3 | import unittest # TODO: 4 | 5 | 6 | def fizz_buzz_one( start, end ): 7 | """ Note: This method returns a long string not a list. """ 8 | fizzbuzz = '' 9 | # range is NOT inclusive of the 2nd number, so add 1 to include it. 10 | # range(1,4) > 1,2,3. range(1, 4 + 1) > 1,2,3,4. 11 | for i in range(start,end+1): 12 | if i%3 == 0: 13 | fizzbuzz += "fizz" 14 | if i%5 == 0: 15 | fizzbuzz += "buzz" 16 | if i%3 != 0 and i%5 != 0: 17 | fizzbuzz += str(i) 18 | 19 | fizzbuzz += ' ' 20 | return fizzbuzz.rstrip() # remove trailing whitespace 21 | 22 | 23 | def fizz_buzz_two( start, end ): 24 | fizzbuzz = [] 25 | for i in range(start,end+1): 26 | entry = '' # initialsing an empty string 27 | if i%3 == 0: 28 | entry += "fizz" # concatenating "fizz" to string 29 | if i%5 == 0: 30 | entry += "buzz" 31 | if i%3 != 0 and i%5 != 0: 32 | # this is dynamic typing. reassigning a prev. string to int 33 | entry = i 34 | fizzbuzz.append(entry) # stick entry onto end of list 35 | return fizzbuzz 36 | 37 | def fizz_buzz_three( start, end ): 38 | """ 39 | Returns the fizzbuzz string for a given range using an inner 40 | function and a list comprehension. 41 | """ 42 | def int_to_fizzbuzz(i): 43 | """ Output the 'fizzbuzz' string for a single number. """ 44 | entry = '' 45 | if i%3 == 0: # if i divided by 3 has no remainder 46 | entry += "fizz" 47 | if i%5 == 0: # if i divided by 5 has no remainder 48 | entry += "buzz" 49 | if i%3 != 0 and i%5 != 0: # i is not divisible by 3 or 5 without remainder 50 | entry = i 51 | return entry 52 | return [int_to_fizzbuzz(i) for i in range(start, end+1)] 53 | 54 | def fizz_buzz_four( start, end ): 55 | """ 56 | Fizz buzz showing compact if-elif-else form, 57 | and precalculatio of boolean values. 58 | """ 59 | result = [] # initalising a list to hold our result 60 | for i in range(start, end+1): 61 | fizz = (i % 3 == 0) 62 | buzz = (i % 5 == 0) 63 | if fizz and buzz: result.append('fizzbuzz') 64 | elif fizz: result.append('fizz') 65 | elif buzz: result.append('buzz') 66 | else: result.append(i) 67 | return result 68 | 69 | 70 | # Unit testing 71 | class fizz_buzz_tests(unittest.TestCase): 72 | 73 | def setUp(self): 74 | pass 75 | 76 | def test_fizz_buzz_one(self): 77 | self.assertEqual( 78 | fizz_buzz_one(0, 12), "fizzbuzz 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz" 79 | ) 80 | self.assertEqual(fizz_buzz_one(0, 0), "fizzbuzz") 81 | self.assertEqual(fizz_buzz_one(14,16), "14 fizzbuzz 16") 82 | 83 | def test_fizz_buzz_two(self): 84 | self.assertEqual( 85 | fizz_buzz_two(5, 12), ['buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz'] 86 | ) 87 | self.assertEqual( 88 | fizz_buzz_two(5, -2), [] 89 | ) 90 | 91 | def test_fizz_buzz_three(self): 92 | self.assertEqual( 93 | fizz_buzz_three(5, 12), ['buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz'] 94 | ) 95 | 96 | def test_fizz_buzz_four(self): 97 | self.assertEqual( 98 | fizz_buzz_four(5, 12), ['buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz'] 99 | ) 100 | 101 | 102 | if __name__ == '__main__': 103 | unittest.main() 104 | -------------------------------------------------------------------------------- /solutions/python/flatten-array.py: -------------------------------------------------------------------------------- 1 | """accepts a multi dimensional array and returns a flattened version""" 2 | 3 | def flatten_array(orig): 4 | """returns a new, flattened, list""" 5 | 6 | flattened_list = [] 7 | 8 | for item in orig: 9 | if isinstance(item, list): 10 | flattened_list += flatten_array(item) 11 | else: 12 | flattened_list.append(item) 13 | 14 | return flattened_list 15 | 16 | def flatten_in_place(orig): 17 | """flattens a given list in place""" 18 | 19 | is_flattened = False 20 | 21 | while not is_flattened: # iterating until no more lists are found 22 | 23 | is_flattened = True 24 | for i, item in enumerate(orig): 25 | 26 | if isinstance(item, list): 27 | is_flattened = False 28 | orig = orig[:i] + item + orig[i + 1:] 29 | 30 | return orig 31 | -------------------------------------------------------------------------------- /solutions/python/gender-inheritance.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class Person(object): 4 | def getGender( self ): 5 | return "Unknown" 6 | 7 | class Male( Person ): 8 | def getGender( self ): 9 | return "Male" 10 | 11 | class Female( Person ): 12 | def getGender( self ): 13 | return "Female" 14 | 15 | # Unittests 16 | class gender_inheritance_tests(unittest.TestCase): 17 | 18 | def setUp(self): 19 | self.male = Male() 20 | self.female = Female() 21 | 22 | def test_gender_inheritance(self): 23 | self.assertEqual( self.male.getGender(), "Male" ) 24 | self.assertEqual( self.female.getGender(), "Female") 25 | 26 | if __name__ == '__main__': 27 | aFemale = Female() 28 | aMale = Male() 29 | print( aMale.getGender() ) 30 | print( aFemale.getGender() ) 31 | unittest.main() 32 | -------------------------------------------------------------------------------- /solutions/python/head-tails-chinese-puzzle.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def solve_heads_tails_one( numheads, numlegs ): 4 | ns = 'No Solutions!' 5 | for i in range(numheads+1): # Using a loop to iterate all possible solutions 6 | j = numheads - i 7 | if 2*i+4*j == numlegs: 8 | return i, j 9 | return ns, ns 10 | 11 | def solve_heads_tails_two( numheads, numlegs ): 12 | raise NotImplementedError # nothing yet, somebody add something! 13 | 14 | 15 | # Unit Testing 16 | class solve_heads_tails_tests(unittest.TestCase): 17 | 18 | def setUp(self): 19 | pass 20 | 21 | def test_solve_heads_tails_one(self): 22 | self.assertEqual( 23 | solve_heads_tails_one(35, 94), (23, 12) 24 | ) 25 | 26 | 27 | if __name__ == '__main__': 28 | unittest.main() 29 | -------------------------------------------------------------------------------- /solutions/python/knapsack-problems.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | # TODO: Add knapsack problem variants 4 | 5 | # TODO: use this -> http://codereview.stackexchange.com/questions/20569/dynamic-programming-solution-to-knapsack-problem to implement a knapsack algorithm solution 6 | -------------------------------------------------------------------------------- /solutions/python/kruskals-algorithm/kruskal-one.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | parent = dict() 4 | rank = dict() 5 | 6 | def make_set(vertice): 7 | parent[vertice] = vertice 8 | rank[vertice] = 0 9 | 10 | def find(vertice): 11 | if parent[vertice] != vertice: 12 | parent[vertice] = find(parent[vertice]) 13 | return parent[vertice] 14 | 15 | def union(vertice1, vertice2): 16 | root1 = find(vertice1) 17 | root2 = find(vertice2) 18 | if root1 != root2: 19 | if rank[root1] > rank[root2]: 20 | parent[root2] = root1 21 | else: 22 | parent[root1] = root2 23 | if rank[root1] == rank[root2]: rank[root2] += 1 24 | 25 | def kruskal(graph): 26 | for vertice in graph['vertices']: 27 | make_set(vertice) 28 | 29 | minimum_spanning_tree = set() 30 | edges = list(graph['edges']) 31 | edges.sort() 32 | for edge in edges: 33 | weight, vertice1, vertice2 = edge 34 | if find(vertice1) != find(vertice2): 35 | union(vertice1, vertice2) 36 | minimum_spanning_tree.add(edge) 37 | return minimum_spanning_tree 38 | 39 | graph = { 40 | 'vertices': ['A', 'B', 'C', 'D', 'E', 'F'], 41 | 'edges': set([ 42 | (1, 'A', 'B'), 43 | (5, 'A', 'C'), 44 | (3, 'A', 'D'), 45 | (4, 'B', 'C'), 46 | (2, 'B', 'D'), 47 | (1, 'C', 'D'), 48 | ]) 49 | } 50 | minimum_spanning_tree = set([ 51 | (1, 'A', 'B'), 52 | (2, 'B', 'D'), 53 | (1, 'C', 'D'), 54 | ]) 55 | assert kruskal(graph) == minimum_spanning_tree 56 | -------------------------------------------------------------------------------- /solutions/python/kruskals-algorithm/kruskal-two.py: -------------------------------------------------------------------------------- 1 | #======================================================================= 2 | # Kruskal MST 3 | #======================================================================= 4 | 5 | def kruskal_mst(G): 6 | """Return a minimum spanning tree using kruskal's algorithm""" 7 | # sort the list of edges in G by their length 8 | Edges = [(u, v, G[u][v]['length']) for u,v in G.edges()] 9 | Edges.sort(cmp=lambda x,y: cmp(x[2],y[2])) 10 | 11 | UF = make_union_find(G.nodes()) # union-find data structure 12 | 13 | # for edges in increasing weight 14 | mst = [] # list of edges in the mst 15 | for u,v,d in Edges: 16 | setu = find(UF, u) 17 | setv = find(UF, v) 18 | # if u,v are in different components 19 | if setu != setv: 20 | mst.append((u,v)) 21 | union(UF, setu, setv) 22 | snapshot_kruskal(G, mst) 23 | return mst 24 | -------------------------------------------------------------------------------- /solutions/python/largest-continuous-sum.py: -------------------------------------------------------------------------------- 1 | """solution to the largest-continuous-sum problem""" 2 | import unittest 3 | from functools import reduce 4 | 5 | def largest_continuous_sum_one(arr): 6 | """ returns the largest continous sub sequence in the given list of numbers. """ 7 | largest = 0 8 | queue = [] 9 | for num in arr: 10 | queue.append(num) 11 | if len(queue) > 1: 12 | curr_sum = reduce(lambda x, y: x + y, queue) 13 | curr_sum = curr_sum if curr_sum > num else num 14 | if largest < curr_sum: 15 | largest = curr_sum 16 | 17 | return largest 18 | 19 | 20 | 21 | def largest_continous_sum_two(arr): 22 | if len(arr) == 0: # handle an edge case 23 | return None 24 | max_sum = current_sum = arr[0] 25 | for num in arr[1:]: 26 | current_sum=max(current_sum+num, num) 27 | max_sum=max(current_sum, max_sum) 28 | return max_sum 29 | 30 | 31 | # Unit testing 32 | class largest_continous_sum_test(unittest.TestCase): 33 | 34 | def setUp(self): 35 | self.arrOne = [1,2,3,4,5] 36 | self.arrTwo = [4,5,1,-1000] 37 | 38 | def test_largest_continuous_sum_one(self): 39 | self.assertEqual( 40 | largest_continuous_sum_one( self.arrOne ), 15 41 | ) 42 | self.assertEqual( 43 | largest_continuous_sum_one( self.arrTwo ), 10 44 | ) 45 | 46 | def test_largest_continous_sum_two(self): 47 | self.assertEqual( 48 | largest_continous_sum_two( self.arrOne ) , 15 49 | ) 50 | self.assertEqual( 51 | largest_continous_sum_two( self.arrTwo ), 10 52 | ) 53 | 54 | if __name__ == '__main__': 55 | unittest.main() 56 | -------------------------------------------------------------------------------- /solutions/python/linked-list.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class LinkedList(object): 4 | def __init__(self): 5 | self.length = 0 6 | self.head = None 7 | 8 | def insertStart(self, cargo): 9 | node = Node(cargo) 10 | node.next = self.head 11 | self.head = node 12 | self.length += 1 13 | 14 | def remove(self, elem): 15 | if self.head == None: 16 | return False # elem was not found 17 | elif self.head.cargo == elem: 18 | self.head = self.head.next 19 | self.length -= 1 20 | return True 21 | else: 22 | prevNode = self.head 23 | currNode = self.head.next 24 | while currNode: 25 | if currNode.cargo == elem: 26 | prevNode.next = currNode.next # link over the node to delete 27 | self.length -= 1 28 | return True 29 | return False # elem was not found 30 | 31 | def printBackward(self): 32 | print("[", end="") 33 | if self.head != None: 34 | self.head.printBackward() 35 | print("]") 36 | 37 | class Node(object): 38 | def __init__(self, cargo=None, next=None): 39 | self.cargo = cargo 40 | self.next = next 41 | 42 | def __str__(self): 43 | return str(self.cargo) 44 | 45 | def __eq__(self, other): 46 | if not isinstance(other, type(self)): 47 | return False 48 | if not self.cargo == other.cargo: 49 | return False 50 | return True 51 | 52 | 53 | class Test_LinkedList(unittest.TestCase): 54 | 55 | def setUp(self): 56 | pass 57 | 58 | def test_linked_list_one(self): 59 | ll = LinkedList() 60 | ll.insertStart(5) 61 | ll.insertStart(10) 62 | self.assertEqual( ll.length, 2 ) 63 | self.assertTrue( ll.remove(10) ) 64 | 65 | 66 | if __name__ == '__main__': 67 | unittest.main() 68 | -------------------------------------------------------------------------------- /solutions/python/merge-sort.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def mergesort_one(lst, show_trace=True): 4 | if show_trace: print("Splitting ", lst) 5 | if len(lst) > 1: 6 | mid = len(lst) // 2 7 | left_half = lst[:mid] 8 | right_half = lst[mid:] 9 | 10 | mergesort_one(left_half) 11 | mergesort_one(right_half) 12 | print("Merging ",left_half , right_half) 13 | i=0 14 | j=0 15 | k=0 16 | while i < len(left_half) and j < len(right_half): 17 | if left_half[i] < right_half[j]: 18 | lst[k]=left_half[i] 19 | i=i+1 20 | else: 21 | lst[k]=right_half[j] 22 | j=j+1 23 | k=k+1 24 | 25 | while i < len(left_half): 26 | lst[k]=left_half[i] 27 | i=i+1 28 | k=k+1 29 | 30 | while j < len(right_half): 31 | lst[k]=right_half[j] 32 | j=j+1 33 | k=k+1 34 | return lst 35 | 36 | def mergesort_two(lst): 37 | result = [] 38 | if len(lst) < 2: 39 | return lst 40 | mid = len(lst) // 2 41 | left = mergesort_two(lst[:mid]) 42 | right = mergesort_two(lst[mid:]) 43 | i, j = 0, 0 44 | while i < len(left) and j < len(right): 45 | if left[i] > right[j]: 46 | result.append(right[j]) 47 | j += 1 48 | else: 49 | result.append(left[i]) 50 | i += 1 51 | result += left[i:] # one of these will be empty so 52 | result += right[j:] # we don't need to sort anymore 53 | return result 54 | 55 | # Unit Tests 56 | class Test_Mergesort(unittest.TestCase): 57 | def setUp(self): 58 | pass 59 | 60 | def test_mergesort_one(self): 61 | self.assertEqual( 62 | mergesort_one([1,5,6,8,9,2,3,4,7]), [1,2,3,4,5,6,7,8,9] 63 | ) 64 | self.assertEqual( 65 | mergesort_one([1,2,3,3,4,4,3,3,2,1]), [1,1,2,2,3,3,3,3,4,4] 66 | ) 67 | 68 | def test_mergesort_two(self): 69 | self.assertEqual( 70 | mergesort_two([1,5,6,8,9,2,3,4,7]), [1,2,3,4,5,6,7,8,9] 71 | ) 72 | self.assertEqual( mergesort_two([1]), [1] ) # edge case 73 | self.assertEqual( mergesort_two([]), [] ) # edge case 74 | self.assertEqual( mergesort_two([1,2,3,4,5]), [1,2,3,4,5] ) # already sorted case 75 | 76 | if __name__ == '__main__': 77 | unittest.main() 78 | -------------------------------------------------------------------------------- /solutions/python/multiples-of-3-and-5.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | from math import ceil 3 | from itertools import combinations 4 | from operator import mul 5 | 6 | # Sum of multiples of 3 or 5 under 1000, simplified: 7 | # print (3 * 333 * 334 / 2) + (5 * 199 * 200 / 2) - (15 * 66 * 67 / 2) 8 | 9 | def getSumOfMultiple(num, limit): 10 | return int((ceil(limit / num) - 1) * ceil(limit / num) * num / 2) 11 | 12 | def getSumOfMultiples(multiples, limit): 13 | result = 0 14 | sign = 1 15 | for i in range(1, len(multiples) + 1): 16 | for x in combinations(multiples, i): 17 | result += sign * getSumOfMultiple(reduce(mul, x, 1), limit) 18 | sign *= -1 19 | return result 20 | -------------------------------------------------------------------------------- /solutions/python/n-choose-k.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | # TODO: put useful stuff in here 4 | -------------------------------------------------------------------------------- /solutions/python/once.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class once: 4 | """ THIS IS WRONG. THE PROMPT ASKED FOR A FUNCTION. """ 5 | def __init__(self, func, times=1): 6 | self.times = int(times) 7 | self.func = func 8 | def __call__(self, *args, **kwargs): 9 | if self.times > 0: 10 | self.times -= 1 11 | return self.func(*args, **kwargs) 12 | 13 | 14 | class test_once(unittest.TestCase): 15 | pass 16 | 17 | if __name___ == '__main__': 18 | unittest.main() 19 | -------------------------------------------------------------------------------- /solutions/python/permutations-of-list.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import itertools 3 | 4 | def permutations_one( l ): 5 | """ This is kind of cheating. """ 6 | print( list(itertools.permutations(l))) 7 | 8 | # TODO: Implement this problem without a 'crutch' 9 | -------------------------------------------------------------------------------- /solutions/python/prime-number.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | def is_prime(n): 4 | if n <= 1: 5 | return False 6 | elif n == 2: 7 | return True 8 | elif n % 2 == 0: 9 | return False 10 | for i in xrange(3, int(sqrt(n))+1, 2): 11 | if n % i == 0: 12 | return False 13 | return True 14 | -------------------------------------------------------------------------------- /solutions/python/probability-problems.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | # TODO: add useful stuff into here 4 | -------------------------------------------------------------------------------- /solutions/python/remove-duplicates.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def remove_duplicates( l ): 4 | return list(set(l)) 5 | 6 | def remove_duplicates_badSolution( li ): 7 | """ DO NOT DO THIS. It shows a lack of understanding of set(). """ 8 | newli=[] 9 | seen = set() 10 | for item in li: 11 | if item not in seen: 12 | seen.add( item ) 13 | newli.append(item) 14 | 15 | return newli 16 | 17 | if __name__ == '__main__': 18 | singles = remove_duplicates( [1,2,3,3,4,55,5,66,66,77,4]) 19 | print(singles) 20 | -------------------------------------------------------------------------------- /solutions/python/rotate-matrix.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def rotate_matrix( matrix ): 4 | matrix_two = [list() for i in range(len(matrix))] 5 | for i in range(len(matrix)): 6 | matrix.reverse() 7 | for i in range(len(matrix)): 8 | for j in range(len(matrix)): 9 | matrix_two[i].append(matrix[j][i]) 10 | return matrix_two 11 | 12 | def rotate_matrix_two( matrix ): 13 | return zip(*matrix[::-1]) 14 | 15 | class test_rotate_matrix(unittest.TestCase): 16 | 17 | def setUp(self): 18 | pass 19 | 20 | def test_rotate_matrix(self): 21 | matrix = [[1,2,3],[4,5,6],[7,8,9]] 22 | rotated = rotate_matrix( matrix ) 23 | self.assertEqual( rotated[0][0], 7) 24 | self.assertEqual( rotated[0][2], 1) 25 | 26 | if __name__ == '__main__': 27 | unittest.main() 28 | -------------------------------------------------------------------------------- /solutions/python/shortest-fizz-buzz.py: -------------------------------------------------------------------------------- 1 | def shortest_fizz_buz(): 2 | for i in xrange(0, 100): 3 | s = '' 4 | ss = False 5 | if ((i + 1) % 3 == 0): 6 | s +='Fizz' 7 | if ((i + 1) % 5 == 0): 8 | s +='Buzz' 9 | if ((i + 1) % 3 > 0 and (i + 1) % 5 > 0): 10 | print(i + 1) 11 | else: 12 | print(s) 13 | -------------------------------------------------------------------------------- /solutions/python/stock-max-subarray.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import math # for infinity, floor, ceiling 3 | 4 | def find_max_crossing_subarray( A, low, mid, high ): 5 | """ 6 | A Divide and Conquer strategy can split an array and find 7 | the max subarray of those two arrays by spliting those etc. etc. but it 8 | cannot find if there a subarray that crosses the boundary between the splits is 9 | the greatest subarray. 10 | 11 | This algorithm supplements the divide and conquer strategy and completes in linear time. 12 | """ 13 | 14 | left_total = -math.inf # negative infinity 15 | total = 0 16 | for i in range(mid, low, -1): # descending for-loop 17 | total += A[i] 18 | if total > left_total: # has including this new price, i, improved the total return? 19 | left_total = total # yes, so update total and 20 | max_left = i # update left boundary 21 | right_total = -math.inf 22 | total = 0 23 | for j in range(mid+1, high): # do the same for right side 24 | total += A[j] 25 | if total > right_total: 26 | right_total = total 27 | max_right = i 28 | return max_left, max_right, left_total + right_total 29 | 30 | def find_max_subarray( A, low, high ): 31 | """ 32 | Given an array/list of closing prices, find the 33 | sublist/subarray which gives the highest difference between 34 | the buy price (left) and the sell price (right) 35 | """ 36 | if high == low: 37 | return low, high, A[low] # base case: only 1 element 38 | mid = math.floor( (low+high) / 2 ) 39 | left_low, left_high, left_sum = find_max_subarray( A, low, mid ) # recursive call 40 | right_low, right_high, right_sum = find_max_subarray( A, mid+1, high) # recursive call right side 41 | cross_low, cross_high, cross_sum = find_max_subarray( A, low, mid, high ) # non-recursive linear time supplement function 42 | 43 | if left_sum >= right_sum and left_sum >= cross_sum: 44 | return left_low, left_high, left_sum 45 | elif right_sum >= left_sum and right_sum >= cross_sum: 46 | return right_low, right_high, right_sum 47 | else: 48 | return cross_low, cross_high, cross_sum # we are returning tuples. python is flexible like this :) 49 | -------------------------------------------------------------------------------- /solutions/python/sum-of-array-plus-one.py: -------------------------------------------------------------------------------- 1 | def plusOneSum(arr): 2 | """returns the sum of the integers after adding 1 to each element""" 3 | return sum(arr)+len(arr) -------------------------------------------------------------------------------- /solutions/python/this-repos-scripts.py: -------------------------------------------------------------------------------- 1 | import unittests 2 | -------------------------------------------------------------------------------- /solutions/python/travelling-salesman-problem.py: -------------------------------------------------------------------------------- 1 | 2 | # NOTE: Requires a space optimization to only use A[S of cardinality M] * 2 space 3 | # Run in 64-bit python to prevent Memory Error at 2GB 4 | import time 5 | import math 6 | import itertools 7 | 8 | 9 | ########## 10 | # IMPLEMENTATION 1 11 | ########## 12 | numCities = 0 13 | cities = {} # Contains cities[1] -> cities[numCities] 14 | 15 | class City: 16 | x = 0 17 | y = 0 18 | 19 | def __init__(self, x, y): 20 | self.x = x 21 | self.y = y 22 | 23 | def getDistanceTo(self, i2): 24 | return math.sqrt(math.pow(self.x - cities[i2].x, 2) + math.pow(self.y - cities[i2].y, 2)) 25 | 26 | def readGraph(filename): 27 | global cities 28 | global numCities 29 | 30 | file = open(filename, "r") 31 | isline1 = True 32 | cityIndex = 1 33 | for line in file: 34 | if isline1: 35 | numCities = int(line) 36 | isline1 = False 37 | continue 38 | cities[cityIndex] = City(float(line.split(" ")[0]), float(line.split(" ")[1])) 39 | cityIndex += 1 40 | 41 | def tsp(): 42 | vertices = cities.keys() 43 | A = {} 44 | 45 | # Do this here, as m starts from 2 46 | A[tuple([1])] = {} 47 | A[tuple([1])][1] = 0 48 | 49 | for m in range(2, numCities + 1): # m = subproblem size (cardinality of S) 50 | print("M =", m) 51 | combos = itertools.combinations(vertices, m) 52 | 53 | if m >= 4: 54 | toDel = itertools.combinations(vertices, m - 2) 55 | for key in toDel: 56 | if 1 in key: 57 | del A[key] 58 | 59 | for S in combos: # Take all possible subsets of size m 60 | # POSSIBLE OPTIMIZATION HERE: 61 | # Map all possible subsets as bitmap strings and just set cities which are included in the subset to 1. 62 | # This would reduce memory consumption a lot and speed up the loop operations. 63 | # E.G: 0000000000000000000000111 (single string) as a dictionary key instead of the tuple of n integers. 64 | if 1 not in S: # S has to contain 1 65 | continue 66 | # Set up base cases for this m 67 | A[S] = {} 68 | A[S][1] = float("inf") 69 | 70 | for j in S: # Iterate through all j in S where j != 1 (j = 1 has been taken care of in base cases) 71 | if j == 1: 72 | continue 73 | minASj = float("inf") 74 | for k in S: # Iterate through all k in S where k != j and find best k for the subproblem 75 | if k == j: 76 | continue 77 | sNew = list(S) 78 | sNew.remove(j) 79 | if A[tuple(sNew)][k] + cities[k].getDistanceTo(j) < minASj: 80 | minASj = A[tuple(sNew)][k] + cities[k].getDistanceTo(j) 81 | A[S][j] = minASj 82 | 83 | # Find the shortest tour out of all narrowed candidates 84 | minTour = float("inf") 85 | for j in range(2, numCities + 1): 86 | if A[tuple(range(1, numCities + 1))][j] + cities[j].getDistanceTo(1) < minTour: # Just compare the total distances including the final hop 87 | print(tuple(range(1, numCities + 1))) 88 | minTour = A[tuple(range(1, numCities + 1))][j] + cities[j].getDistanceTo(1) 89 | 90 | return minTour 91 | 92 | ########### 93 | # END IMPLEMENTATION 1 94 | ########### 95 | 96 | ########### 97 | # IMPLEMENTATION 2 98 | ########### 99 | -------------------------------------------------------------------------------- /solutions/python/travelling-salesman/travelling-salesman-problem.py: -------------------------------------------------------------------------------- 1 | 2 | # NOTE: Requires a space optimization to only use A[S of cardinality M] * 2 space 3 | # Run in 64-bit python to prevent Memory Error at 2GB 4 | import time 5 | import math 6 | import itertools 7 | 8 | 9 | ########## 10 | # IMPLEMENTATION 1 11 | ########## 12 | numCities = 0 13 | cities = {} # Contains cities[1] -> cities[numCities] 14 | 15 | class City: 16 | x = 0 17 | y = 0 18 | 19 | def __init__(self, x, y): 20 | self.x = x 21 | self.y = y 22 | 23 | def getDistanceTo(self, i2): 24 | return math.sqrt(math.pow(self.x - cities[i2].x, 2) + math.pow(self.y - cities[i2].y, 2)) 25 | 26 | def readGraph(filename): 27 | global cities 28 | global numCities 29 | 30 | file = open(filename, "r") 31 | isline1 = True 32 | cityIndex = 1 33 | for line in file: 34 | if isline1: 35 | numCities = int(line) 36 | isline1 = False 37 | continue 38 | cities[cityIndex] = City(float(line.split(" ")[0]), float(line.split(" ")[1])) 39 | cityIndex += 1 40 | 41 | def tsp(): 42 | vertices = cities.keys() 43 | A = {} 44 | 45 | # Do this here, as m starts from 2 46 | A[tuple([1])] = {} 47 | A[tuple([1])][1] = 0 48 | 49 | for m in range(2, numCities + 1): # m = subproblem size (cardinality of S) 50 | print("M =", m) 51 | combos = itertools.combinations(vertices, m) 52 | 53 | if m >= 4: 54 | toDel = itertools.combinations(vertices, m - 2) 55 | for key in toDel: 56 | if 1 in key: 57 | del A[key] 58 | 59 | for S in combos: # Take all possible subsets of size m 60 | # POSSIBLE OPTIMIZATION HERE: 61 | # Map all possible subsets as bitmap strings and just set cities which are included in the subset to 1. 62 | # This would reduce memory consumption a lot and speed up the loop operations. 63 | # E.G: 0000000000000000000000111 (single string) as a dictionary key instead of the tuple of n integers. 64 | if 1 not in S: # S has to contain 1 65 | continue 66 | # Set up base cases for this m 67 | A[S] = {} 68 | A[S][1] = float("inf") 69 | 70 | for j in S: # Iterate through all j in S where j != 1 (j = 1 has been taken care of in base cases) 71 | if j == 1: 72 | continue 73 | minASj = float("inf") 74 | for k in S: # Iterate through all k in S where k != j and find best k for the subproblem 75 | if k == j: 76 | continue 77 | sNew = list(S) 78 | sNew.remove(j) 79 | if A[tuple(sNew)][k] + cities[k].getDistanceTo(j) < minASj: 80 | minASj = A[tuple(sNew)][k] + cities[k].getDistanceTo(j) 81 | A[S][j] = minASj 82 | 83 | # Find the shortest tour out of all narrowed candidates 84 | minTour = float("inf") 85 | for j in range(2, numCities + 1): 86 | if A[tuple(range(1, numCities + 1))][j] + cities[j].getDistanceTo(1) < minTour: # Just compare the total distances including the final hop 87 | print(tuple(range(1, numCities + 1))) 88 | minTour = A[tuple(range(1, numCities + 1))][j] + cities[j].getDistanceTo(1) 89 | 90 | return minTour 91 | 92 | ########### 93 | # END IMPLEMENTATION 1 94 | ########### 95 | 96 | ########### 97 | # IMPLEMENTATION 2 98 | ########### 99 | -------------------------------------------------------------------------------- /solutions/python/tree-level-order-print.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | def __init__(self, value): 3 | self.value = value 4 | self.left = None 5 | self.right = None 6 | 7 | 8 | def traverse_levelorder(root): 9 | if not root: 10 | return 11 | q = [root, True] # Use True as sentinel for end of row 12 | while len(q) > 0: 13 | node = q.pop(0) 14 | print node.value, 15 | if node.left: 16 | q.append(node.left) 17 | if node.right: 18 | q.append(node.right) 19 | if q[0] is True: # End of row 20 | q.pop(0) 21 | if len(q) > 0: 22 | q.append(True) 23 | print 24 | -------------------------------------------------------------------------------- /solutions/python/triples_summing_to_x.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def triples_adding_to( x, lst ): 4 | if len(lst) < 3: return None 5 | results = set() 6 | for pos, elem in enumerate(lst): 7 | i, j = pos+1, len(lst) - 1 8 | complement = x - elem 9 | while i < len(lst) and j > -1 and i < j: 10 | if pos == i: 11 | i += 1 12 | continue 13 | elif pos == j: 14 | j -= 1 15 | continue 16 | pair_result = lst[i] + lst[j] 17 | if pair_result > complement: 18 | j -= 1 19 | elif pair_result < complement: 20 | i += 1 21 | elif pair_result == complement: 22 | results.add(tuple(sorted([elem, lst[i], lst[j]]))) 23 | i += 1 # could also do j -= 1 24 | 25 | return results 26 | 27 | 28 | class TestTriplesSummingToX(unittest.TestCase): 29 | def test_triples_adding_to(self): 30 | test_lst = [-10, -7, -5, -1, 0, 2, 3, 5, 8, 10] 31 | self.assertEqual( 32 | triples_adding_to(5, []), None 33 | ) 34 | self.assertEqual( 35 | triples_adding_to(5, test_lst), 36 | {(-7, 2, 10), (0, 2, 3), (-5, 0, 10), (-10, 5, 10), (-5, 2, 8)} 37 | ) 38 | 39 | if __name__ == '__main__': 40 | unittest.main() 41 | -------------------------------------------------------------------------------- /solutions/python/type-function-equivelant.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | # TODO 4 | -------------------------------------------------------------------------------- /test_yourself.py: -------------------------------------------------------------------------------- 1 | # 2 | # Author: Jonathon Belotti 3 | # 4 | # This script can either: 5 | # 1. Quick run through problems in the repo, asking you if you are confident in that area or not. 6 | # It builds a list of problems to brush up on and returns them to user 7 | # 8 | # 2. Be more interactive. Selecting an opening up exercises for users and then testing their solutions for them. [This would be non-trivial work] 9 | 10 | # TODO: Implement the simple (1) functionality 11 | -------------------------------------------------------------------------------- /tests/cpp/common.cpp: -------------------------------------------------------------------------------- 1 | #include "common.hpp" 2 | 3 | std::deque> eventLog; 4 | int nextId; 5 | -------------------------------------------------------------------------------- /tests/cpp/common.hpp: -------------------------------------------------------------------------------- 1 | #ifndef COMMON_HPP_INCLUDED 2 | #define COMMON_HPP_INCLUDED 3 | 4 | #include // std::deque 5 | #include // std::tuple 6 | 7 | enum class Event { 8 | DefaultConstructorCalled, 9 | CopyConstructorCalled, 10 | MoveConstructorCalled, 11 | AssignmentOperatorCalled, 12 | DestructorCalled 13 | }; 14 | 15 | extern std::deque> eventLog; 16 | extern int nextId; 17 | 18 | inline const int getId() { 19 | return nextId++; 20 | }; 21 | 22 | inline void log(int id, Event e) { 23 | eventLog.push_back(std::make_tuple(id, e)); 24 | }; 25 | 26 | class eventLogger { 27 | private: 28 | int id; 29 | public: 30 | eventLogger() : id{getId()} { 31 | log(id, Event::DefaultConstructorCalled); 32 | }; 33 | eventLogger(eventLogger const& t) : id{getId()} { 34 | log(id, Event::CopyConstructorCalled); 35 | }; 36 | eventLogger(eventLogger&& t) : id{getId()} { 37 | log(id, Event::MoveConstructorCalled); 38 | }; 39 | ~eventLogger() { 40 | log(id, Event::DestructorCalled); 41 | }; 42 | eventLogger& operator=(eventLogger const& t) { 43 | log(id, Event::AssignmentOperatorCalled); 44 | return *this; 45 | }; 46 | }; 47 | 48 | #endif 49 | -------------------------------------------------------------------------------- /tests/cpp/once.cpp: -------------------------------------------------------------------------------- 1 | #include "gtest/gtest.h" 2 | 3 | #include "../../solutions/cpp/once.hpp" 4 | #include 5 | #include 6 | using std::string; 7 | using std::to_string; 8 | using std::multiplies; 9 | 10 | std::size_t fibonacci(std::size_t n) { 11 | if(n == 0) return 0; 12 | if(n == 1) return 1; 13 | 14 | std::size_t a = 0, b = 1, c; 15 | for(; n > 1; --n) { 16 | c = a + b; 17 | a = b; 18 | b = c; 19 | } 20 | return b; 21 | } 22 | 23 | struct HolderOfTruth { 24 | bool theTruth; 25 | 26 | bool getTruth() const { 27 | return theTruth; 28 | }; 29 | 30 | void setTruth(bool newTruth) { 31 | theTruth = newTruth; 32 | } 33 | }; 34 | 35 | TEST(OnceTest, VoidLambdaJustOnce) { 36 | int i = 0; 37 | auto f = once( [&i](){ ++i; } ); 38 | ASSERT_EQ(0, i); 39 | 40 | f(); 41 | EXPECT_EQ(1, i); 42 | 43 | EXPECT_NO_THROW(f()); 44 | EXPECT_EQ(1, i); 45 | } 46 | 47 | TEST(OnceTest, VoidLambdaManyTimes) { 48 | int i = 0; 49 | auto f = once( [&i](){ ++i; }, 30); 50 | ASSERT_EQ(0, i); 51 | 52 | for(int j = 1; j <= 30; ++j) { 53 | f(); 54 | EXPECT_EQ(j, i); 55 | } 56 | 57 | EXPECT_NO_THROW(f()); 58 | EXPECT_EQ(30, i); 59 | } 60 | 61 | TEST(OnceTest, IntReturningLambda) { 62 | int i = 10; 63 | auto f = once( [&i](){ return i; }, 2); 64 | ASSERT_EQ(10, i); 65 | 66 | EXPECT_EQ(10, f()); 67 | i = 13; 68 | EXPECT_EQ(13, f()); 69 | 70 | EXPECT_THROW(f(), out_of_calls); 71 | } 72 | 73 | TEST(OnceTest, StringReturningLambda) { 74 | auto s = string{"Hi there!"}; 75 | auto f = once( [](){ return string{"Hi there!"}; } ); 76 | 77 | EXPECT_EQ(s, f()); 78 | 79 | EXPECT_THROW(f(), out_of_calls); 80 | } 81 | 82 | TEST(OnceTest, LambdaWithArgs) { 83 | auto f = once( [](int i, string s){ return to_string(i) + " " + s; }, 2); 84 | EXPECT_EQ("1 time", f(1, "time")); 85 | EXPECT_EQ("2 times", f(2, "times")); 86 | EXPECT_THROW(f(3, "times"), out_of_calls); 87 | } 88 | 89 | TEST(OnceTest, FunctorStruct) { 90 | auto f = once( multiplies(), 3); 91 | 92 | EXPECT_FLOAT_EQ(120.0, f(2.4, 50.0)); 93 | EXPECT_FLOAT_EQ(16.5, f(0.5, 33.0)); 94 | EXPECT_FLOAT_EQ(145.64, f(11., 13.24)); 95 | EXPECT_THROW(f(1.0, 1.0), out_of_calls); 96 | } 97 | 98 | TEST(OnceTest, FunctionPointer) { 99 | auto f = once( fibonacci, 30 ); 100 | for(int i = 0; i < 30; ++i) 101 | EXPECT_EQ(fibonacci(i), f(i)); 102 | EXPECT_THROW(f(0), out_of_calls); 103 | } 104 | 105 | TEST(OnceTest, MemberFunctions) { 106 | auto f = once(&HolderOfTruth::getTruth, 6); 107 | auto g = once(&HolderOfTruth::setTruth, 3); 108 | 109 | auto TrueHolder = new HolderOfTruth{true}; 110 | auto FakeHolder = new HolderOfTruth{false}; 111 | 112 | ASSERT_TRUE( TrueHolder->getTruth()); 113 | ASSERT_FALSE(FakeHolder->getTruth()); 114 | 115 | EXPECT_TRUE( f(TrueHolder)); 116 | EXPECT_FALSE(f(FakeHolder)); 117 | 118 | EXPECT_NO_THROW(g(TrueHolder, false)); 119 | EXPECT_NO_THROW(g(FakeHolder, true)); 120 | 121 | EXPECT_FALSE(f(TrueHolder)); 122 | EXPECT_TRUE( f(FakeHolder)); 123 | 124 | EXPECT_NO_THROW(g(TrueHolder, true)); 125 | EXPECT_NO_THROW(g(FakeHolder, false)); 126 | 127 | EXPECT_TRUE(f(TrueHolder)); 128 | EXPECT_TRUE(f(FakeHolder)); 129 | 130 | EXPECT_THROW(f(TrueHolder), out_of_calls); 131 | } 132 | -------------------------------------------------------------------------------- /tests/cpp/spiral.cpp: -------------------------------------------------------------------------------- 1 | #include "gtest/gtest.h" 2 | 3 | #include "../../solutions/cpp/spiral.hpp" 4 | 5 | TEST(SpiralTest, BasicTest) { 6 | typedef std::vector v; 7 | EXPECT_EQ(v({ 13, 8, 7, 12, 17, 18, 19, 14, 9, 4, 3, 2, 1, 6, 11, 16, 8 | 21, 22, 23, 24, 25, 20, 15, 10, 5 }), spiral(5, 5, 3, 3)); 9 | EXPECT_EQ(v({ 2, 1, 5, 6, 7, 3, 8, 4 }), spiral(2, 4, 1, 2)); 10 | } 11 | -------------------------------------------------------------------------------- /worded_questions/README.md: -------------------------------------------------------------------------------- 1 | # WORDED QUESTIONS 2 | 3 | ## NAVIGATION 4 | #### DIFFICULTY 5 | 1. [Easy](#easy) 6 | 2. [Medium](#medium) 7 | 3. [Hard](#hard) 8 | 4. [Expert](#expert) 9 | 5. [Master](#master) 10 | 11 | #### CATEGORIES 12 | 13 | | CATEGORY | EASY | MEDIUM | HARD | EXPERT | MASTER | 14 | |---------------|-------------------|-----------------------|-----------------------|---------------------------|--------------------| 15 | | **Uncategorized** | [Easy](#uncatergorized-easy) | [Medium](#uncatergorized-med) | [Hard](#uncatergorized-hard) | [Expert](#uncatergorized-expert) | | 16 | | **Regex** | [Easy](#regex-easy) | [Medium](#regex-medium) | [Hard](#regex-hard) | [Expert](#regex-expert) | | 17 | | **Threading** | [Easy](#threading-easy) | | | | | | 18 | 19 | # QUESTIONS 20 | 21 | ## EASY 22 | 23 | #### Regex Easy 24 | 25 | #### Regex Medium 26 | 27 | #### Uncategorized Easy 28 | 29 | * **[What is Python really? Compare with other languages.](/answers/what-is-python-really.ipynb)** 30 | * **[What is Monkey Patching and is it a good idea?](/answers/what-is-monkey-patching-is-it-a-good-idea.ipynb)** 31 | 32 | #### Threading Easy 33 | 34 | * **[Is multi-threading in python a good idea?](/answers/is-multithreading-in-python-a-good-idea.ipynb)** 35 | 36 | ## MEDIUM 37 | 38 | `coming-soon` 39 | 40 | ## HARD 41 | 42 | `coming-soon` 43 | 44 | ## EXPERT 45 | 46 | `coming-soon` 47 | 48 | ## MASTER 49 | 50 | `Know an insanely hard question? Please contribute to this section.` 51 | -------------------------------------------------------------------------------- /worded_questions/answers/3-ways-of-getting-every-third-from-list.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Suppose you have a list whose contents don't matter. Show me three different ways of fetching every third item in the list." 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "every_third = [] \n", 19 | "for index, item in enumerate(items, 1):\n", 20 | " if index % 3 == 0: every_third.append(item)" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": { 27 | "collapsed": true 28 | }, 29 | "outputs": [], 30 | "source": [] 31 | } 32 | ], 33 | "metadata": { 34 | "kernelspec": { 35 | "display_name": "Python 3", 36 | "language": "python", 37 | "name": "python3" 38 | }, 39 | "language_info": { 40 | "codemirror_mode": { 41 | "name": "ipython", 42 | "version": 3 43 | }, 44 | "file_extension": ".py", 45 | "mimetype": "text/x-python", 46 | "name": "python", 47 | "nbconvert_exporter": "python", 48 | "pygments_lexer": "ipython3", 49 | "version": "3.5.1" 50 | } 51 | }, 52 | "nbformat": 4, 53 | "nbformat_minor": 0 54 | } 55 | -------------------------------------------------------------------------------- /worded_questions/answers/difference-between-_getattr_-and-_getattribute__.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## What is the difference between __ getattr __ and __getattribute __?" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "A key difference between __getattr__ and __getattribute__ is that __getattr__ is only invoked if the attribute wasn't found the usual ways. It's good for implementing a fallback for missing attributes, and is probably the one of two you want.\n", 15 | "\n", 16 | "__getattribute__ is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly. You can end up in infinite recursions very easily.\n", 17 | "\n", 18 | "New-style classes derive from object, old-style classes are those in Python 2.x with no explicit base class. But the distinction between old-style and new-style classes is not the important one when choosing between __getattr__ and __getattribute__.\n", 19 | "\n", 20 | "You almost certainly want __getattr__." 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": { 27 | "collapsed": true 28 | }, 29 | "outputs": [], 30 | "source": [ 31 | "# TODO: Put some example code." 32 | ] 33 | } 34 | ], 35 | "metadata": { 36 | "kernelspec": { 37 | "display_name": "Python 3", 38 | "language": "python", 39 | "name": "python3" 40 | }, 41 | "language_info": { 42 | "codemirror_mode": { 43 | "name": "ipython", 44 | "version": 3 45 | }, 46 | "file_extension": ".py", 47 | "mimetype": "text/x-python", 48 | "name": "python", 49 | "nbconvert_exporter": "python", 50 | "pygments_lexer": "ipython3", 51 | "version": "3.5.1" 52 | } 53 | }, 54 | "nbformat": 4, 55 | "nbformat_minor": 0 56 | } 57 | -------------------------------------------------------------------------------- /worded_questions/answers/how-does-garbage-collection-work.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "## How does Python's garbage collection work?" 12 | ] 13 | } 14 | ], 15 | "metadata": { 16 | "kernelspec": { 17 | "display_name": "Python 3", 18 | "language": "python", 19 | "name": "python3" 20 | }, 21 | "language_info": { 22 | "codemirror_mode": { 23 | "name": "ipython", 24 | "version": 3 25 | }, 26 | "file_extension": ".py", 27 | "mimetype": "text/x-python", 28 | "name": "python", 29 | "nbconvert_exporter": "python", 30 | "pygments_lexer": "ipython3", 31 | "version": "3.5.1" 32 | } 33 | }, 34 | "nbformat": 4, 35 | "nbformat_minor": 0 36 | } 37 | -------------------------------------------------------------------------------- /worded_questions/answers/how-to-read-8gb-file.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## How to read a 8GB file in python?" 8 | ] 9 | } 10 | ], 11 | "metadata": { 12 | "kernelspec": { 13 | "display_name": "Python 3", 14 | "language": "python", 15 | "name": "python3" 16 | }, 17 | "language_info": { 18 | "codemirror_mode": { 19 | "name": "ipython", 20 | "version": 3 21 | }, 22 | "file_extension": ".py", 23 | "mimetype": "text/x-python", 24 | "name": "python", 25 | "nbconvert_exporter": "python", 26 | "pygments_lexer": "ipython3", 27 | "version": "3.5.1" 28 | } 29 | }, 30 | "nbformat": 4, 31 | "nbformat_minor": 0 32 | } 33 | -------------------------------------------------------------------------------- /worded_questions/answers/is-multithreading-in-python-a-good-idea.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Python and multi-threading. Is it a good idea? List some ways to get some Python code to run in a parallel way.\n" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "Python doesn't allow multi-threading in the truest sense of the word. It has a multi-threading package but if you want to multi-thread to speed your code up, then it's usually not a good idea to use it. Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your 'threads' can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core. All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn't a good idea.\n", 15 | "\n", 16 | "There are reasons to use Python's threading package. If you want to run some things simultaneously, and efficiency is not a concern, then it's totally fine and convenient. Or if you are running code that needs to wait for something (like some IO) then it could make a lot of sense. But the threading library wont let you use extra CPU cores.\n", 17 | "\n", 18 | "Multi-threading can be outsourced to the operating system (by doing multi-processing), some external application that calls your Python code (eg, Spark or Hadoop), or some code that your Python code calls (eg: you could have your Python code call a C function that does the expensive multi-threaded stuff).\n", 19 | "\n", 20 | "### Why is this Important?\n", 21 | "\n", 22 | "Because the GIL is an A-hole. Lots of people spend a lot of time trying to find bottlenecks in their fancy Python multi-threaded code before they learn what the GIL is." 23 | ] 24 | } 25 | ], 26 | "metadata": { 27 | "kernelspec": { 28 | "display_name": "Python 3", 29 | "language": "python", 30 | "name": "python3" 31 | }, 32 | "language_info": { 33 | "codemirror_mode": { 34 | "name": "ipython", 35 | "version": 3 36 | }, 37 | "file_extension": ".py", 38 | "mimetype": "text/x-python", 39 | "name": "python", 40 | "nbconvert_exporter": "python", 41 | "pygments_lexer": "ipython3", 42 | "version": "3.5.1" 43 | } 44 | }, 45 | "nbformat": 4, 46 | "nbformat_minor": 0 47 | } 48 | -------------------------------------------------------------------------------- /worded_questions/answers/maximum-recursion-depth-problem.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## I'm getting a maximum recursion depth error for a function. What does this mean? How can I mitigate the problem?" 8 | ] 9 | } 10 | ], 11 | "metadata": { 12 | "kernelspec": { 13 | "display_name": "Python 3", 14 | "language": "python", 15 | "name": "python3" 16 | }, 17 | "language_info": { 18 | "codemirror_mode": { 19 | "name": "ipython", 20 | "version": 3 21 | }, 22 | "file_extension": ".py", 23 | "mimetype": "text/x-python", 24 | "name": "python", 25 | "nbconvert_exporter": "python", 26 | "pygments_lexer": "ipython3", 27 | "version": "3.5.1" 28 | } 29 | }, 30 | "nbformat": 4, 31 | "nbformat_minor": 0 32 | } 33 | -------------------------------------------------------------------------------- /worded_questions/answers/tell-me-about-GIL-concurrency-impact.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Tell me about the GIL. How does it impact concurrency in Python? What kinds of applications does it impact more than others?" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [] 18 | } 19 | ], 20 | "metadata": { 21 | "kernelspec": { 22 | "display_name": "Python 3", 23 | "language": "python", 24 | "name": "python3" 25 | }, 26 | "language_info": { 27 | "codemirror_mode": { 28 | "name": "ipython", 29 | "version": 3 30 | }, 31 | "file_extension": ".py", 32 | "mimetype": "text/x-python", 33 | "name": "python", 34 | "nbconvert_exporter": "python", 35 | "pygments_lexer": "ipython3", 36 | "version": "3.5.1" 37 | } 38 | }, 39 | "nbformat": 4, 40 | "nbformat_minor": 0 41 | } 42 | -------------------------------------------------------------------------------- /worded_questions/answers/what-does-star-and-doublestar-do-to-args.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## What does \\*\\* (double star) and \\* (star) do for Python parameters?" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": { 13 | "collapsed": true 14 | }, 15 | "source": [ 16 | "The \\*args and \\*\\*kwargs is a common idiom to allow arbitrary number of arguments to functions.\n", 17 | "The *args will give you all function parameters as a tuple:" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": 7, 23 | "metadata": { 24 | "collapsed": false 25 | }, 26 | "outputs": [ 27 | { 28 | "name": "stdout", 29 | "output_type": "stream", 30 | "text": [ 31 | "(1, 2, 3)\n", 32 | "1__2__3__\n" 33 | ] 34 | } 35 | ], 36 | "source": [ 37 | "def foo(*args):\n", 38 | " print(args) # prints a tuple\n", 39 | " string = ''.join([str(a) + '__' for a in args])\n", 40 | " print(string)\n", 41 | " \n", 42 | "foo(1,2,3)" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": {}, 48 | "source": [ 49 | "The \\*\\*kwargs will give you all keyword arguments **except for** those corresponding to a formal parameter as a dictionary." 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": 11, 55 | "metadata": { 56 | "collapsed": false 57 | }, 58 | "outputs": [ 59 | { 60 | "name": "stdout", 61 | "output_type": "stream", 62 | "text": [ 63 | "lady diana\n", 64 | "fox saywhat\n" 65 | ] 66 | } 67 | ], 68 | "source": [ 69 | "def bar(**kwargs):\n", 70 | " for a in kwargs.keys():\n", 71 | " print( a, kwargs[a] )\n", 72 | " \n", 73 | "bar(fox='saywhat', lady='diana')" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "metadata": { 80 | "collapsed": true 81 | }, 82 | "outputs": [], 83 | "source": [] 84 | } 85 | ], 86 | "metadata": { 87 | "celltoolbar": "Raw Cell Format", 88 | "kernelspec": { 89 | "display_name": "Python 3", 90 | "language": "python", 91 | "name": "python3" 92 | }, 93 | "language_info": { 94 | "codemirror_mode": { 95 | "name": "ipython", 96 | "version": 3 97 | }, 98 | "file_extension": ".py", 99 | "mimetype": "text/x-python", 100 | "name": "python", 101 | "nbconvert_exporter": "python", 102 | "pygments_lexer": "ipython3", 103 | "version": "3.5.1" 104 | } 105 | }, 106 | "nbformat": 4, 107 | "nbformat_minor": 0 108 | } 109 | -------------------------------------------------------------------------------- /worded_questions/answers/what-dont-you-like-about-python.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## What don't you like about python?\n", 8 | "\n", 9 | "**Note this is a personal type question, but you should have a great understanding of the language to be able to criticize it well.**" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": { 16 | "collapsed": true 17 | }, 18 | "outputs": [], 19 | "source": [] 20 | } 21 | ], 22 | "metadata": { 23 | "kernelspec": { 24 | "display_name": "Python 3", 25 | "language": "python", 26 | "name": "python3" 27 | }, 28 | "language_info": { 29 | "codemirror_mode": { 30 | "name": "ipython", 31 | "version": 3 32 | }, 33 | "file_extension": ".py", 34 | "mimetype": "text/x-python", 35 | "name": "python", 36 | "nbconvert_exporter": "python", 37 | "pygments_lexer": "ipython3", 38 | "version": "3.5.1" 39 | } 40 | }, 41 | "nbformat": 4, 42 | "nbformat_minor": 0 43 | } 44 | -------------------------------------------------------------------------------- /worded_questions/answers/what-is-monkey-patching-is-it-a-good-idea.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## What is monkey patching and is it ever a good idea?" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "Monkey patching is changing the behaviour of a function or object after it has already been defined. " 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 1, 20 | "metadata": { 21 | "collapsed": false 22 | }, 23 | "outputs": [ 24 | { 25 | "ename": "TypeError", 26 | "evalue": "can't set attributes of built-in/extension type 'datetime.datetime'", 27 | "output_type": "error", 28 | "traceback": [ 29 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 30 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 31 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mdatetime\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mdatetime\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mdatetime\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mnow\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mlambda\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mdatetime\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mdatetime\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m2012\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m12\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m12\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# monkey-patch\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[0mdatetime\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mdatetime\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mnow\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", 32 | "\u001b[1;31mTypeError\u001b[0m: can't set attributes of built-in/extension type 'datetime.datetime'" 33 | ] 34 | } 35 | ], 36 | "source": [ 37 | "import datetime\n", 38 | "datetime.datetime.now = lambda: datetime.datetime(2012, 12, 12) # monkey-patch\n", 39 | "\n", 40 | "datetime.datetime.now # python won't allow this for built-in types" 41 | ] 42 | }, 43 | { 44 | "cell_type": "markdown", 45 | "metadata": {}, 46 | "source": [ 47 | "Most of the time it's a pretty terrible idea - it is usually best if things act in a well-defined way. One reason to monkey patch would be in testing. The mock package is very useful to this end.\n", 48 | "\n", 49 | "### Why does this matter?\n", 50 | "\n", 51 | "It shows that you understand a bit about methodologies in unit testing. Your mention of monkey avoidance will show that you aren't one of those coders who favor fancy code over maintainable code (they are out there, and they suck to work with). Remember the principle of KISS? And it shows that you know a little bit about how Python works on a lower level, how functions are actually stored and called and suchlike." 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "metadata": { 58 | "collapsed": true 59 | }, 60 | "outputs": [], 61 | "source": [] 62 | } 63 | ], 64 | "metadata": { 65 | "kernelspec": { 66 | "display_name": "Python 3", 67 | "language": "python", 68 | "name": "python3" 69 | }, 70 | "language_info": { 71 | "codemirror_mode": { 72 | "name": "ipython", 73 | "version": 3 74 | }, 75 | "file_extension": ".py", 76 | "mimetype": "text/x-python", 77 | "name": "python", 78 | "nbconvert_exporter": "python", 79 | "pygments_lexer": "ipython3", 80 | "version": "3.5.1" 81 | } 82 | }, 83 | "nbformat": 4, 84 | "nbformat_minor": 0 85 | } 86 | --------------------------------------------------------------------------------