├── shell ├── paste-3.sh ├── paste-4.sh ├── paste-1.sh ├── paste-2.sh ├── text-processing-sort-1.sh ├── text-processing-sort-2.sh ├── text-processing-sort-3.sh ├── text-processing-tr-3.sh ├── text-processing-head-1.sh ├── text-processing-head-2.sh ├── text-processing-sort-4.sh ├── text-processing-tail-1.sh ├── text-processing-tail-2.sh ├── text-processing-tr-1.sh ├── bash-tutorials-lets-echo.sh ├── text-processing-tr-2.sh ├── text-processing-sort-5.sh ├── text-processing-sort-6.sh ├── text-processing-sort-7.sh ├── text-processing-cut-6.sh ├── text-processing-in-linux-the-uniq-command-1.sh ├── text-processing-cut-5.sh ├── text-processing-cut-9.sh ├── text-processing-in-linux-the-uniq-command-4.sh ├── sed-command-4.sh ├── text-processing-in-linux-the-grep-command-1.sh ├── text-processing-in-linux-the-grep-command-2.sh ├── text-processing-in-linux-the-grep-command-3.sh ├── text-processing-in-linux-the-grep-command-5.sh ├── text-processing-in-linux-the-sed-command-1.sh ├── text-processing-in-linux-the-sed-command-3.sh ├── text-processing-in-linux-the-sed-command-2.sh ├── awk-1.sh ├── bash-tutorials---a-personalized-echo.sh ├── bash-tutorials---looping-with-numbers.sh ├── text-processing-in-linux---the-middle-of-a-text-file.sh ├── text-processing-in-linux-the-grep-command-4.sh ├── text-processing-in-linux-the-uniq-command-3.sh ├── bash-tutorials-count-the-number-of-elements-in-an-array.sh ├── bash-tutorials-display-the-third-element-of-an-array.sh ├── bash-tutorials---looping-and-skipping.sh ├── sed-command-5.sh ├── text-processing-cut-8.sh ├── text-processing-cut-7.sh ├── bash-tutorials---arithmetic-operations.sh ├── bash-tutorials-read-in-an-array.sh ├── bash-tutorials-filter-an-array-with-patterns.sh ├── bash-tutorials-concatenate-an-array-with-itself.sh ├── bash-tutorials-slice-an-array.sh ├── text-processing-in-linux-the-uniq-command-2.sh ├── bash-tutorials---the-world-of-numbers.sh ├── awk-4.sh ├── text-processing-cut-1.sh ├── text-processing-cut-3.sh ├── bash-tutorials-remove-the-first-capital-letter-from-each-array-element.sh ├── lonely-integer-2.sh ├── text-processing-cut-2.sh ├── text-processing-cut-4.sh ├── bash-tutorials---comparing-numbers.sh ├── bash-tutorials---getting-started-with-conditionals.sh ├── bash-tutorials---compute-the-average.sh ├── bash-tutorials---more-on-conditionals.sh ├── awk-3.sh ├── awk-2.sh └── fractal-trees-all.sh ├── python part2 ├── py-hello-world.py ├── python-eval.py ├── py-introduction-to-sets.py ├── np-eye-and-identity.py ├── np-shape-reshape.py ├── python-mod-divmod.py ├── python-division.py ├── python-mutations.py ├── python-quest-1.py ├── python-loops.py ├── python-print.py ├── np-polynomials.py ├── py-if-else.py ├── python-arithmetic-operators.py ├── np-zeros-and-ones.py ├── np-linear-algebra.py ├── polar-coordinates.py ├── np-min-and-max.py ├── np-sum-and-prod.py ├── np-inner-and-outer.py ├── py-the-captains-room.py ├── python-power-mod-power.py ├── py-check-subset.py ├── np-transpose-and-flatten.py ├── np-dot-and-cross.py ├── python-integers-come-in-all-sizes.py ├── py-set-add.py ├── np-mean-var-and-std.py ├── py-set-difference-operation.py ├── py-set-intersection-operation.py ├── py-set-union.py ├── py-set-symmetric-difference-operation.py ├── np-concatenate.py ├── py-check-strict-superset.py ├── py-set-discard-remove-pop.py ├── py-collections-namedtuple.py ├── py-collections-ordereddict.py ├── py-collections-deque.py ├── python-lists.py ├── piling-up.py └── py-set-mutations.py ├── python part1 ├── np-arrays.py ├── text-wrap.py ├── python-string-split-and-join.py ├── write-a-function.py ├── whats-your-name.py ├── validate-a-roman-number.py ├── reduce-function.py ├── xml-1-find-the-score.py ├── capitalize.py ├── validating-postalcode.py ├── triangle-quest-2.py ├── python-tuples.py ├── decorators-2-name-directory.py ├── re-split.py ├── floor-ceil-and-rint.py ├── default-arguments.py ├── ginorts.py ├── find-second-maximum-number-in-a-list.py ├── validate-list-of-email-address-with-filter.py ├── calendar-module.py ├── validating-the-phone-number.py ├── any-or-all.py ├── input.py ├── re-group-groups.py ├── introduction-to-regex.py ├── find-angle.py ├── list-comprehensions.py ├── validating-named-email-addresses.py ├── itertools-permutations.py ├── compress-the-string.py ├── xml2-find-the-maximum-depth.py ├── maximize-it.py ├── standardize-mobile-number-using-decorators.py ├── find-a-string.py ├── string-validators.py ├── designer-door-mat.py ├── swap-case.py ├── itertools-combinations-with-replacement.py ├── most-commons.py ├── itertools-combinations.py ├── itertools-product.py ├── re-sub-regex-substitution.py ├── incorrect-regex.py ├── python-string-formatting.py ├── symmetric-difference.py ├── matrix-script.py ├── zipped.py ├── np-array-mathematics.py ├── map-and-lambda-expression.py ├── re-findall-re-finditer.py ├── re-start-re-end.py ├── words-score.py ├── exceptions.py ├── finding-the-percentage.py ├── python-sort-sort.py ├── alphabet-rangoli.py ├── hex-color-code.py ├── iterables-and-iterators.py ├── validating-credit-card-number.py ├── nested-list.py ├── no-idea.py ├── word-order.py ├── collections-counter.py ├── validating-uid.py ├── defaultdict-tutorial.py ├── python-time-delta.py ├── the-minion-game.py ├── detect-html-tags-attributes-and-attribute-values.py ├── html-parser-part-2.py ├── class-2-find-the-torsional-angle.py ├── merge-the-tools.py ├── html-parser-part-1.py └── text-alignment.py ├── cpp ├── cpp-hello-world.cpp ├── inherited-code.cpp ├── cpp-input-and-output.cpp ├── exceptional-server.cpp ├── c-tutorial-basic-data-types.cpp ├── c-tutorial-pointer.cpp ├── arrays-introduction.cpp ├── classes-objects.cpp ├── prettyprint.cpp ├── c-tutorial-strings.cpp ├── c-tutorial-struct.cpp ├── c-tutorial-functions.cpp ├── vector-sort.cpp ├── c-tutorial-for-loop.cpp ├── vector-erase.cpp ├── variable-sized-arrays.cpp ├── c-tutorial-stringstream.cpp ├── cpp-lower-bound.cpp └── cpp-sets.cpp ├── algorithms part2 ├── solve-me-first.py ├── flipping-bits.py ├── extra-long-factorials.py ├── lonely-integer.py ├── repeated-string.py ├── simple-array-sum.py ├── pangrams.py ├── drawing-book.py ├── find-the-median.py ├── string-construction.py ├── the-hurdle-race.py ├── designer-pdf-viewer.py ├── migratory-birds.py ├── save-the-prisoner.py ├── staircase.py ├── sum-vs-xor.py ├── game-of-stones-1.py ├── marcs-cakewalk.py ├── find-digits.py ├── gem-stones.py ├── sherlock-and-squares.py ├── the-great-xor.py ├── priyanka-and-toys.py ├── the-birthday-bar.py ├── manasa-and-stones.py ├── equality-in-a-array.py ├── mars-exploration.py ├── permutation-equation.py ├── service-lane.py ├── minimum-absolute-difference-in-an-array.py ├── jumping-on-the-clouds.py ├── sock-merchant.py ├── game-of-thrones.py ├── strange-advertising.py ├── divisible-sum-pairs.py ├── jumping-on-the-clouds-revisited.py ├── minimum-distances.py ├── recursive-digit-sum.py ├── sansa-and-xor.py ├── grading.py ├── mark-and-toys.py ├── diagonal-difference.py ├── fair-rations.py ├── strange-code.py ├── halloween-sale.py ├── making-anagrams.py ├── plus-minus.py ├── flatland-space-stations.py ├── hackerrank-in-a-string.py ├── quicksort1.py ├── sherlock-and-array.py ├── sherlock-and-the-beast.py ├── insertionsort1.py ├── library-fine.py ├── insertionsort2.py ├── nim-game-1.py ├── reduced-string.py ├── funny-string.py ├── jim-and-the-orders.py ├── icecream-parlor.py ├── kangaroo.py ├── mini-max-sum.py ├── separate-the-numbers.py ├── pairs.py ├── poker-nim-1.py ├── palindrome-index.py ├── picking-numbers.py ├── misere-nim-1.py ├── two-characters.py ├── missing-numbers.py ├── larrys-array.py ├── minimum-swaps-2.py └── nimble-game-1.py ├── data-structures ├── arrays-ds.py ├── tree-inorder-traversal.py ├── tree-postorder-traversal.py ├── sparse-arrays.py ├── tree-preorder-traversal.py ├── x-and-his-shots.py ├── print-the-elements-of-a-linked-list.py ├── array-left-rotation.py ├── dynamic-array.py ├── tree-height-of-a-binary-tree.py ├── tree-top-view.py ├── qheap1.py ├── truck-tour.py ├── and-xor-or.py ├── binary-search-tree-lowest-common-ancestor.py ├── crush.py ├── jim-and-the-skyscrapers.py ├── is-binary-search-tree.py ├── detect-whether-a-linked-list-contains-a-cycle.py ├── maximum-element.py ├── 2d-array.py ├── insert-a-node-at-the-head-of-a-linked-list.py ├── delete-a-node-from-a-linked-list.py ├── jesse-and-cookies.py ├── reverse-a-linked-list.py ├── delete-duplicate-value-nodes-from-a-sorted-linked-list.py ├── tree-level-order-traversal.py ├── insert-a-node-at-the-tail-of-a-linked-list.py ├── reverse-a-doubly-linked-list.py ├── print-the-elements-of-a-linked-list-in-reverse.py ├── largest-rectangle.py ├── equal-stacks.py ├── binary-search-tree-insertion.py ├── get-the-value-of-the-node-at-a-specific-position-from-the-tail.py ├── down-to-zero-ii.py ├── insert-a-node-into-a-sorted-doubly-linked-list.py ├── queries-with-fixed-length.py └── queue-using-two-stacks.py ├── c ├── students-marks-sum.c ├── hello-world-c.c ├── sum-of-digits-of-a-five-digit-number.c ├── pointer-in-c.c ├── reverse-array-c.c ├── sum-numbers-c.c ├── playing-with-characters.c ├── printing-tokens-.c ├── functions-in-c.c ├── 1d-arrays-in-c.c ├── too-high-boxes.c ├── for-loop-in-c.c ├── frequency-of-digits-1.c ├── recursion-in-c.c ├── small-triangles-large-triangles.c ├── dynamic-array-in-c.c └── printing-pattern-2.c ├── interview-preparation-kit ├── ctci-fibonacci-numbers.py ├── repeated-string.py ├── two-strings.py ├── flipping-bits.py ├── ctci-big-o.py ├── minimum-absolute-difference-in-an-array.py ├── jumping-on-the-clouds.py ├── sock-merchant.py ├── alternating-characters.py ├── tree-height-of-a-binary-tree.py ├── ctci-comparator-sorting.py ├── ctci-is-binary-search-tree.py ├── recursive-digit-sum.py ├── mark-and-toys.py ├── ctci-bubble-sort.py ├── binary-search-tree-lowest-common-ancestor.py ├── ctci-recursive-staircase.py ├── crush.py ├── ctci-linked-list-cycle.py ├── counting-valleys.py ├── ctci-queue-using-two-stacks.py ├── angry-children.py ├── 2d-array.py ├── ctci-making-anagrams.py ├── reverse-a-doubly-linked-list.py ├── new-year-chaos.py ├── greedy-florist.py ├── largest-rectangle.py ├── pairs.py ├── ctci-ice-cream-parlor.py ├── ctci-ransom-note.py ├── minimum-swaps-2.py └── insert-a-node-into-a-sorted-doubly-linked-list.py └── algorithms part1 ├── birthday-cake-candles.py ├── a-very-big-sum.py ├── two-strings.py ├── camelcase.py ├── correctness-invariant.py ├── countingsort1.py ├── beautiful-binary-string.py ├── beautiful-triplets.py ├── big-sorting.py ├── countingsort4.py ├── angry-professor.py ├── bon-appetit.py ├── alternating-characters.py ├── beautiful-days-at-the-movies.py ├── chocolate-feast.py ├── cut-the-sticks.py ├── utopian-tree.py ├── cats-and-a-mouse.py ├── breaking-best-and-worst-records.py ├── counting-valleys.py ├── angry-children.py ├── compare-the-triplets.py ├── anagram.py ├── countingsort2.py ├── acm-icpc-team.py ├── a-chessboard-game-1.py ├── absolute-permutation.py ├── counter-game.py ├── caesar-cipher-1.py ├── closest-numbers.py ├── bigger-is-greater.py ├── circular-array-rotation.py ├── weighted-uniform-string.py ├── xor-se.py ├── apple-and-orange.py └── beautiful-pairs.py /shell/paste-3.sh: -------------------------------------------------------------------------------- 1 | tr '\n' '\t' -------------------------------------------------------------------------------- /shell/paste-4.sh: -------------------------------------------------------------------------------- 1 | paste - - - -------------------------------------------------------------------------------- /shell/paste-1.sh: -------------------------------------------------------------------------------- 1 | paste -d';' -s -------------------------------------------------------------------------------- /shell/paste-2.sh: -------------------------------------------------------------------------------- 1 | paste -d';' - - - -------------------------------------------------------------------------------- /shell/text-processing-sort-1.sh: -------------------------------------------------------------------------------- 1 | sort -------------------------------------------------------------------------------- /shell/text-processing-sort-2.sh: -------------------------------------------------------------------------------- 1 | sort -r -------------------------------------------------------------------------------- /shell/text-processing-sort-3.sh: -------------------------------------------------------------------------------- 1 | sort -n -------------------------------------------------------------------------------- /shell/text-processing-tr-3.sh: -------------------------------------------------------------------------------- 1 | tr -s ' ' -------------------------------------------------------------------------------- /shell/text-processing-head-1.sh: -------------------------------------------------------------------------------- 1 | head -n 20 -------------------------------------------------------------------------------- /shell/text-processing-head-2.sh: -------------------------------------------------------------------------------- 1 | head -c 20 -------------------------------------------------------------------------------- /shell/text-processing-sort-4.sh: -------------------------------------------------------------------------------- 1 | sort -nr -------------------------------------------------------------------------------- /shell/text-processing-tail-1.sh: -------------------------------------------------------------------------------- 1 | tail -n 20 -------------------------------------------------------------------------------- /shell/text-processing-tail-2.sh: -------------------------------------------------------------------------------- 1 | tail -c 20 -------------------------------------------------------------------------------- /shell/text-processing-tr-1.sh: -------------------------------------------------------------------------------- 1 | tr '()' '[]' -------------------------------------------------------------------------------- /shell/bash-tutorials-lets-echo.sh: -------------------------------------------------------------------------------- 1 | echo 'HELLO' -------------------------------------------------------------------------------- /shell/text-processing-tr-2.sh: -------------------------------------------------------------------------------- 1 | tr -d [:lower:] -------------------------------------------------------------------------------- /shell/text-processing-sort-5.sh: -------------------------------------------------------------------------------- 1 | sort -t$'\t' -k2 -nr -------------------------------------------------------------------------------- /shell/text-processing-sort-6.sh: -------------------------------------------------------------------------------- 1 | sort -t$'\t' -k2 -n -------------------------------------------------------------------------------- /shell/text-processing-sort-7.sh: -------------------------------------------------------------------------------- 1 | sort -t'|' -k2 -rn -------------------------------------------------------------------------------- /shell/text-processing-cut-6.sh: -------------------------------------------------------------------------------- 1 | # Solution 1 2 | cut -c13- -------------------------------------------------------------------------------- /shell/text-processing-in-linux-the-uniq-command-1.sh: -------------------------------------------------------------------------------- 1 | uniq -------------------------------------------------------------------------------- /shell/text-processing-cut-5.sh: -------------------------------------------------------------------------------- 1 | awk -F'\t' '{print $1, $2, $3}' -------------------------------------------------------------------------------- /shell/text-processing-cut-9.sh: -------------------------------------------------------------------------------- 1 | # Solution 1 2 | cut -d$'\t' -f2- -------------------------------------------------------------------------------- /shell/text-processing-in-linux-the-uniq-command-4.sh: -------------------------------------------------------------------------------- 1 | uniq -u -------------------------------------------------------------------------------- /shell/sed-command-4.sh: -------------------------------------------------------------------------------- 1 | # solution 1 2 | sed 's/[0-9]\+ /****\ /g' -------------------------------------------------------------------------------- /shell/text-processing-in-linux-the-grep-command-1.sh: -------------------------------------------------------------------------------- 1 | grep -w 'the' -------------------------------------------------------------------------------- /shell/text-processing-in-linux-the-grep-command-2.sh: -------------------------------------------------------------------------------- 1 | grep -iw 'the' -------------------------------------------------------------------------------- /shell/text-processing-in-linux-the-grep-command-3.sh: -------------------------------------------------------------------------------- 1 | grep -vwi 'that' -------------------------------------------------------------------------------- /shell/text-processing-in-linux-the-grep-command-5.sh: -------------------------------------------------------------------------------- 1 | grep "\([0-9]\)\ *\1" -------------------------------------------------------------------------------- /shell/text-processing-in-linux-the-sed-command-1.sh: -------------------------------------------------------------------------------- 1 | sed 's/\bthe\b/this/' -------------------------------------------------------------------------------- /shell/text-processing-in-linux-the-sed-command-3.sh: -------------------------------------------------------------------------------- 1 | sed 's/thy/{&}/ig' -------------------------------------------------------------------------------- /shell/text-processing-in-linux-the-sed-command-2.sh: -------------------------------------------------------------------------------- 1 | sed 's/[tT][hH][Yy]/your/g' -------------------------------------------------------------------------------- /shell/awk-1.sh: -------------------------------------------------------------------------------- 1 | awk '!length($4) {printf("Not all scores are available for %s\n", $1)}' -------------------------------------------------------------------------------- /shell/bash-tutorials---a-personalized-echo.sh: -------------------------------------------------------------------------------- 1 | read name 2 | 3 | echo "Welcome $name" -------------------------------------------------------------------------------- /shell/bash-tutorials---looping-with-numbers.sh: -------------------------------------------------------------------------------- 1 | for num in {1..50} ; do echo ${num} ;done -------------------------------------------------------------------------------- /shell/text-processing-in-linux---the-middle-of-a-text-file.sh: -------------------------------------------------------------------------------- 1 | head -n 22 | tail -n 11 -------------------------------------------------------------------------------- /shell/text-processing-in-linux-the-grep-command-4.sh: -------------------------------------------------------------------------------- 1 | grep -iw 'the\|that\|then\|those' -------------------------------------------------------------------------------- /shell/text-processing-in-linux-the-uniq-command-3.sh: -------------------------------------------------------------------------------- 1 | # solution 1 2 | uniq -ic | cut -c7- -------------------------------------------------------------------------------- /python part2/py-hello-world.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | print("Hello, World!") 3 | -------------------------------------------------------------------------------- /python part1/np-arrays.py: -------------------------------------------------------------------------------- 1 | def arrays(arr): 2 | return numpy.array(arr[::-1], float) 3 | 4 | -------------------------------------------------------------------------------- /python part1/text-wrap.py: -------------------------------------------------------------------------------- 1 | def wrap(string, max_width): 2 | return textwrap.fill(string, max_width) -------------------------------------------------------------------------------- /shell/bash-tutorials-count-the-number-of-elements-in-an-array.sh: -------------------------------------------------------------------------------- 1 | arr=( $(cat) ) 2 | 3 | echo ${#arr[@]} -------------------------------------------------------------------------------- /shell/bash-tutorials-display-the-third-element-of-an-array.sh: -------------------------------------------------------------------------------- 1 | arr=( $(cat) ) 2 | 3 | echo ${arr[3]} -------------------------------------------------------------------------------- /shell/bash-tutorials---looping-and-skipping.sh: -------------------------------------------------------------------------------- 1 | for i in {1..99} ; do 2 | ((i%2)) && echo "$i" 3 | done -------------------------------------------------------------------------------- /python part1/python-string-split-and-join.py: -------------------------------------------------------------------------------- 1 | def split_and_join(line): 2 | return "-".join(line.split(" ")) -------------------------------------------------------------------------------- /shell/sed-command-5.sh: -------------------------------------------------------------------------------- 1 | sed -E 's/([[:digit:]]{4}) ([[:digit:]]{4}) ([[:digit:]]{4}) ([[:digit:]]{4})/\4 \3 \2 \1/' -------------------------------------------------------------------------------- /shell/text-processing-cut-8.sh: -------------------------------------------------------------------------------- 1 | # Solution 1 2 | #cut -d' ' -f1-3 3 | # Solution 2 4 | awk '{print $1, $2, $3}' -------------------------------------------------------------------------------- /python part2/python-eval.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | eval(input().strip()) -------------------------------------------------------------------------------- /shell/text-processing-cut-7.sh: -------------------------------------------------------------------------------- 1 | # Solution 1 2 | cut -d' ' -f4 3 | # Solution 2 4 | #awk -F'\t' '{print $1, $2, $3}' -------------------------------------------------------------------------------- /python part1/write-a-function.py: -------------------------------------------------------------------------------- 1 | def is_leap(year): 2 | return (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)) -------------------------------------------------------------------------------- /python part2/py-introduction-to-sets.py: -------------------------------------------------------------------------------- 1 | def average(array): 2 | uniq = set(array) 3 | 4 | return sum(uniq)/len(uniq) -------------------------------------------------------------------------------- /shell/bash-tutorials---arithmetic-operations.sh: -------------------------------------------------------------------------------- 1 | read string 2 | 3 | res=$(echo "$string" | bc -l) 4 | 5 | printf "%.3f" "$res" -------------------------------------------------------------------------------- /python part1/whats-your-name.py: -------------------------------------------------------------------------------- 1 | def print_full_name(a, b): 2 | print("Hello {} {}! You just delved into python.".format(a, b)) -------------------------------------------------------------------------------- /shell/bash-tutorials-read-in-an-array.sh: -------------------------------------------------------------------------------- 1 | readarray array 2 | for el in ${array[@]} ; do 3 | echo -ne "$el " 4 | done 5 | echo -------------------------------------------------------------------------------- /python part1/validate-a-roman-number.py: -------------------------------------------------------------------------------- 1 | regex_pattern = r"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$" # Do not delete 'r'. -------------------------------------------------------------------------------- /python part2/np-eye-and-identity.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | 3 | n, m = [int(x) for x in input().strip().split()] 4 | 5 | print(numpy.eye(n, m)) -------------------------------------------------------------------------------- /python part1/reduce-function.py: -------------------------------------------------------------------------------- 1 | def product(fracs): 2 | t = reduce(lambda x, y : x * y, fracs) 3 | return t.numerator, t.denominator -------------------------------------------------------------------------------- /shell/bash-tutorials-filter-an-array-with-patterns.sh: -------------------------------------------------------------------------------- 1 | readarray array 2 | declare -a output=( ${array[@]/*[a,A]*/} ) 3 | 4 | echo ${output[@]} -------------------------------------------------------------------------------- /python part2/np-shape-reshape.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | arr = numpy.array([int(x) for x in input().strip().split()]) 3 | arr.shape = (3, 3) 4 | print(arr) -------------------------------------------------------------------------------- /shell/bash-tutorials-concatenate-an-array-with-itself.sh: -------------------------------------------------------------------------------- 1 | # solution 2 2 | 3 | arr=( $(cat) ) 4 | 5 | echo "${arr[@]}" "${arr[@]}" "${arr[@]}" 6 | -------------------------------------------------------------------------------- /shell/bash-tutorials-slice-an-array.sh: -------------------------------------------------------------------------------- 1 | readarray array 2 | 3 | for i in {3..7} ; do 4 | echo -ne ${array[${i}]} 5 | echo -ne " " 6 | done -------------------------------------------------------------------------------- /shell/text-processing-in-linux-the-uniq-command-2.sh: -------------------------------------------------------------------------------- 1 | # solution 1 2 | #uniq -c | cut -c7- 3 | 4 | # solution 2 5 | uniq -c | sed -e 's/^[ \t]*//' -------------------------------------------------------------------------------- /python part2/python-mod-divmod.py: -------------------------------------------------------------------------------- 1 | output = divmod(int(input().strip()), int(input().strip())) 2 | print(output[0]) 3 | print(output[1]) 4 | print(output) -------------------------------------------------------------------------------- /shell/bash-tutorials---the-world-of-numbers.sh: -------------------------------------------------------------------------------- 1 | read x 2 | read y 3 | 4 | echo "$((x + y))" 5 | echo "$((x - y))" 6 | echo "$((x * y))" 7 | echo "$((x / y))" -------------------------------------------------------------------------------- /python part1/xml-1-find-the-score.py: -------------------------------------------------------------------------------- 1 | def get_attr_number(node): 2 | return len(node.attrib) + sum([get_attr_number(child) for child in node]) 3 | 4 | 5 | -------------------------------------------------------------------------------- /python part2/python-division.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | a = int(input()) 3 | b = int(input()) 4 | 5 | print(a//b) 6 | print(a/b) 7 | -------------------------------------------------------------------------------- /shell/awk-4.sh: -------------------------------------------------------------------------------- 1 | awk ' 2 | { 3 | if (++newline % 2) 4 | printf("%s;", $0) 5 | else 6 | printf("%s\n", $0) 7 | } 8 | ' -------------------------------------------------------------------------------- /shell/text-processing-cut-1.sh: -------------------------------------------------------------------------------- 1 | #echo "${line:2:1}" <(/dev/stdin) 2 | echo "$(cut -c3)" 3 | #while IFS='' read -r line ; do 4 | # echo "${line:2:1}" 5 | #done -------------------------------------------------------------------------------- /shell/text-processing-cut-3.sh: -------------------------------------------------------------------------------- 1 | # Solution #1 2 | echo "$(cut -c2-7)" 3 | 4 | # Solution #2 5 | #while IFS= read -r line ; do 6 | # echo "${line:1:6}" 7 | #done -------------------------------------------------------------------------------- /python part1/capitalize.py: -------------------------------------------------------------------------------- 1 | def capitalize(string): 2 | for word in string.split(): 3 | string = string.replace(word, word.capitalize()) 4 | return string -------------------------------------------------------------------------------- /python part1/validating-postalcode.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | num = input() 4 | print(bool(re.match(r'^[1-9][\d]{5}$', num) and len(re.findall(r'(\d)(?=\d\1)', num))<2 )) -------------------------------------------------------------------------------- /python part2/python-mutations.py: -------------------------------------------------------------------------------- 1 | def mutate_string(string, position, character): 2 | out = list(string) 3 | out[position] = character 4 | return "".join(out) -------------------------------------------------------------------------------- /python part2/python-quest-1.py: -------------------------------------------------------------------------------- 1 | for i in range(1,int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also 2 | print(10**i//9 * i) 3 | -------------------------------------------------------------------------------- /cpp/cpp-hello-world.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | cout << "Hello, World!"; 7 | return 0; 8 | } 9 | -------------------------------------------------------------------------------- /python part1/triangle-quest-2.py: -------------------------------------------------------------------------------- 1 | for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also 2 | print((10**i//9)**2) 3 | -------------------------------------------------------------------------------- /shell/bash-tutorials-remove-the-first-capital-letter-from-each-array-element.sh: -------------------------------------------------------------------------------- 1 | arr=( $(cat) ) 2 | 3 | for elem in ${arr[@]} ; do 4 | echo -ne ".${elem:1} " 5 | done -------------------------------------------------------------------------------- /shell/lonely-integer-2.sh: -------------------------------------------------------------------------------- 1 | read len 2 | readarray arr 3 | 4 | res=0 5 | 6 | for elem in ${arr[@]} ; do 7 | res=$(( res ^ elem )) 8 | done 9 | 10 | echo "$res" -------------------------------------------------------------------------------- /shell/text-processing-cut-2.sh: -------------------------------------------------------------------------------- 1 | # Solution #1 2 | echo "$(cut -c2,7)" 3 | 4 | # Solution #2 5 | #while IFS= read -r line ; do 6 | # echo "${line:1:1}${line:6:1}" 7 | #done -------------------------------------------------------------------------------- /python part2/python-loops.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | n = int(input()) 3 | 4 | num = 0 5 | while num < n: 6 | print(pow(num, 2)) 7 | num += 1 -------------------------------------------------------------------------------- /python part1/python-tuples.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | n = int(input()) 3 | integer_list = map(int, input().split()) 4 | 5 | print(hash(tuple(integer_list))) 6 | -------------------------------------------------------------------------------- /python part2/python-print.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | n = int(input()) 3 | 4 | num = 1 5 | while num <= n: 6 | print(num, end='') 7 | num += 1 8 | -------------------------------------------------------------------------------- /algorithms part2/solve-me-first.py: -------------------------------------------------------------------------------- 1 | def solveMeFirst(a,b): 2 | return a + b 3 | 4 | 5 | num1 = int(input()) 6 | num2 = int(input()) 7 | res = solveMeFirst(num1,num2) 8 | print(res) 9 | -------------------------------------------------------------------------------- /python part2/np-polynomials.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | array = np.array(list(map(float, input().strip().split()))) 4 | x = float(input().strip()) 5 | 6 | print(np.polyval(array, x)) 7 | -------------------------------------------------------------------------------- /python part2/py-if-else.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | n = int(input()) 3 | if n % 2 == 1 or 6 <= n <= 20: 4 | print("Weird") 5 | else: 6 | print("Not Weird") 7 | -------------------------------------------------------------------------------- /shell/text-processing-cut-4.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Solution #1 4 | echo "$(cut -c1-4)" 5 | 6 | # Solution #2 7 | #while IFS= read -r line ; do 8 | # echo "${line:0:4}" 9 | #done -------------------------------------------------------------------------------- /python part2/python-arithmetic-operators.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | a = int(input()) 3 | b = int(input()) 4 | 5 | print(a + b) 6 | print(a - b) 7 | print(a * b) 8 | -------------------------------------------------------------------------------- /shell/bash-tutorials---comparing-numbers.sh: -------------------------------------------------------------------------------- 1 | read x 2 | read y 3 | 4 | (( $x > $y )) && echo 'X is greater than Y' 5 | (( $x < $y )) && echo 'X is less than Y' 6 | (( $x == $y )) && echo 'X is equal to Y' -------------------------------------------------------------------------------- /shell/bash-tutorials---getting-started-with-conditionals.sh: -------------------------------------------------------------------------------- 1 | read answer 2 | 3 | if [[ ${answer,,} == 'y' ]] ; then 4 | echo 'YES' 5 | elif [[ ${answer,,} == 'n' ]] ; then 6 | echo 'NO' 7 | fi -------------------------------------------------------------------------------- /python part1/decorators-2-name-directory.py: -------------------------------------------------------------------------------- 1 | def person_lister(func): 2 | def inner(people): 3 | return [ func(p) for p in sorted(people, key = lambda x: (int(x[2])))] 4 | return inner 5 | 6 | -------------------------------------------------------------------------------- /python part2/np-zeros-and-ones.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | dims = [int(x) for x in input().strip().split()] 3 | 4 | print(numpy.zeros(tuple(dims), dtype = numpy.int)) 5 | print(numpy.ones(tuple(dims), dtype = numpy.int)) -------------------------------------------------------------------------------- /data-structures/arrays-ds.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | n = int(input().strip()) 7 | arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] 8 | 9 | print(" ".join(map(str, arr[::-1]))) -------------------------------------------------------------------------------- /python part1/re-split.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import re 4 | 5 | if __name__ == "__main__": 6 | out = list(re.split('[.,]', input())) 7 | print("\n".join(filter(lambda x: re.match('[0-9]+',x), out))) -------------------------------------------------------------------------------- /python part2/np-linear-algebra.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | n = int(input().strip()) 4 | array = np.array([[float(x) for x in input().strip().split()] for _ in range(n)], dtype = float) 5 | 6 | print(np.linalg.det(array)) -------------------------------------------------------------------------------- /python part2/polar-coordinates.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import cmath 4 | 5 | if __name__ == "__main__": 6 | cnum = complex(input().strip()) 7 | 8 | print(abs(cnum)) 9 | print(cmath.phase(cnum)) -------------------------------------------------------------------------------- /python part1/floor-ceil-and-rint.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | array = np.array(list(input().strip().split()), dtype = float) 4 | 5 | print(np.floor(array)) 6 | print(np.ceil(array)) 7 | print(np.rint(array)) -------------------------------------------------------------------------------- /python part2/np-min-and-max.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | n, m = [int(x) for x in input().strip().split()] 4 | array = np.array([[int(x) for x in input().strip().split()] for _ in range(n)]) 5 | print(np.max(np.min(array, axis = 1))) -------------------------------------------------------------------------------- /shell/bash-tutorials---compute-the-average.sh: -------------------------------------------------------------------------------- 1 | read all 2 | 3 | for ((i=0;i<$all;i++)) ; do 4 | read num 5 | sum=$((sum + num)) 6 | done 7 | 8 | result=$(echo "$sum/$all" | bc -l) 9 | 10 | printf "%.3f" "$result" -------------------------------------------------------------------------------- /python part1/default-arguments.py: -------------------------------------------------------------------------------- 1 | raw_input = input 2 | 3 | def print_from_stream(n, stream = None): 4 | if not stream: 5 | stream = EvenStream() 6 | 7 | for _ in range(n): 8 | print(stream.get_next()) -------------------------------------------------------------------------------- /python part1/ginorts.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | string = input().strip() 5 | 6 | print(*sorted(string, key = lambda x: (-x.islower(), x.isdigit() - x.isupper(), x in '02468', x)), sep='') -------------------------------------------------------------------------------- /python part2/np-sum-and-prod.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | n, m = [int(x) for x in input().strip().split()] 4 | array = np.array([[int(x) for x in input().strip().split()] for _ in range(n)]) 5 | print(np.prod(np.sum(array, axis = 0))) -------------------------------------------------------------------------------- /algorithms part2/flipping-bits.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | T = int(input().strip()) 3 | 4 | correct = 1 << 32 5 | 6 | for _ in range(T): 7 | num = int(input().strip()) 8 | print(~num + correct) 9 | 10 | -------------------------------------------------------------------------------- /python part1/find-second-maximum-number-in-a-list.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | n = int(input()) 3 | arr = list(map(int, input().split())) 4 | first = max(arr) 5 | 6 | print(max(list(filter(lambda a: a != first, arr)))) 7 | -------------------------------------------------------------------------------- /python part1/validate-list-of-email-address-with-filter.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def fun(email): 4 | #pattern = '[^@]+@[^@]+\.[^@]{1,3}' 5 | pattern = '^[a-zA-Z][\w-]*@[a-zA-Z0-9]+\.[a-zA-Z]{1,3}$' 6 | return re.match(pattern, email) 7 | -------------------------------------------------------------------------------- /python part2/np-inner-and-outer.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | arr1 = np.array(list(map(int, input().strip().split()))) 4 | arr2 = np.array(list(map(int, input().strip().split()))) 5 | 6 | print(np.inner(arr1, arr2)) 7 | print(np.outer(arr1, arr2)) 8 | -------------------------------------------------------------------------------- /python part1/calendar-module.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import calendar 4 | 5 | if __name__ == "__main__": 6 | date = list(map(int, input().strip().split(' '))) 7 | print(calendar.day_name[calendar.weekday(date[2], date[0], date[1])].upper()) -------------------------------------------------------------------------------- /python part1/validating-the-phone-number.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | n = int(input().strip()) 4 | 5 | for _ in range(n): 6 | tel = input().strip() 7 | pattern = '^[789][0-9]{9}$' 8 | print("{}".format("YES" if bool(re.match(pattern, tel)) else "NO")) -------------------------------------------------------------------------------- /python part2/py-the-captains-room.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | k = int(input().strip()) 5 | numbers = list(map(int, input().strip().split(' '))) 6 | 7 | print((sum(set(numbers))*k - sum(numbers))//(k-1)) -------------------------------------------------------------------------------- /python part2/python-power-mod-power.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | a = int(input().strip()) 5 | b = int(input().strip()) 6 | m = int(input().strip()) 7 | 8 | print(pow(a, b)) 9 | print(pow(a, b, m)) -------------------------------------------------------------------------------- /cpp/inherited-code.cpp: -------------------------------------------------------------------------------- 1 | class BadLengthException { 2 | private: 3 | int n; 4 | public: 5 | BadLengthException(int errornumber) { 6 | n = errornumber; 7 | } 8 | 9 | int what() {return n;} 10 | }; -------------------------------------------------------------------------------- /python part1/any-or-all.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | num_cnt = int(input().strip()) 5 | arr = list(input().strip().split()) 6 | print(all([all([int(x) > 0 for x in arr]), any([x == x[::-1] for x in arr])])) 7 | -------------------------------------------------------------------------------- /c/students-marks-sum.c: -------------------------------------------------------------------------------- 1 | int marks_summation(int *marks, int number_of_students, char gender) { 2 | int result = 0; 3 | 4 | for (int i = gender == 'b' ? 0 : 1; i < number_of_students; i += 2) 5 | result += marks[i]; 6 | 7 | return result; 8 | } -------------------------------------------------------------------------------- /python part1/input.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | x, k = map(int, input().strip().split()) 5 | string = input().strip() 6 | 7 | if eval(string) == k: 8 | print(True) 9 | else: 10 | print(False) -------------------------------------------------------------------------------- /python part1/re-group-groups.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import re 4 | 5 | if __name__ == "__main__": 6 | string = input() 7 | 8 | match = re.search(r'([a-zA-Z0-9])\1+', string) 9 | 10 | print(match.group(1) if match else -1) 11 | -------------------------------------------------------------------------------- /interview-preparation-kit/ctci-fibonacci-numbers.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n): 2 | if n == 0: 3 | return 0 4 | if n == 1: 5 | return 1 6 | 7 | return fibonacci(n-1) + fibonacci(n-2) 8 | 9 | n = int(input()) 10 | print(fibonacci(n)) 11 | -------------------------------------------------------------------------------- /python part2/py-check-subset.py: -------------------------------------------------------------------------------- 1 | for i in range(int(input())): #More than 4 lines will result in 0 score. Blank lines won't be counted. 2 | a = int(input()); A = set(input().split()) 3 | b = int(input()); B = set(input().split()) 4 | print(len((A - B)) == 0) 5 | -------------------------------------------------------------------------------- /python part2/np-transpose-and-flatten.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | n, m = [int(x) for x in input().strip().split()] 3 | arr = [] 4 | for _ in range(n): 5 | arr.append([int(x) for x in input().strip().split()]) 6 | print(numpy.array(arr).transpose()) 7 | print(numpy.array(arr).flatten()) -------------------------------------------------------------------------------- /python part1/introduction-to-regex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import re 4 | 5 | if __name__ == "__main__": 6 | t = int(input().strip()) 7 | pattern = '^[+-]?[0-9]*\.[0-9]+$' 8 | 9 | for _ in range(t): 10 | print(bool(re.match(pattern, input()))) -------------------------------------------------------------------------------- /python part2/np-dot-and-cross.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | n = int(input().strip()) 4 | arr1 = np.array([[int(x) for x in input().strip().split()] for _ in range(n)]) 5 | arr2 = np.array([[int(x) for x in input().strip().split()] for _ in range(n)]) 6 | 7 | print(np.dot(arr1, arr2)) -------------------------------------------------------------------------------- /python part2/python-integers-come-in-all-sizes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | a = int(input().strip()) 5 | b = int(input().strip()) 6 | c = int(input().strip()) 7 | d = int(input().strip()) 8 | 9 | print(pow(a, b) + pow(c, d)) -------------------------------------------------------------------------------- /python part1/find-angle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from math import atan 4 | from math import degrees 5 | 6 | if __name__ == "__main__": 7 | ab = int(input().strip()) 8 | bc = int(input().strip()) 9 | 10 | print("{}°".format(int(round(degrees(atan(ab/bc)))))) -------------------------------------------------------------------------------- /python part2/py-set-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | N = int(input().strip()) 5 | stamps = set() 6 | 7 | for _ in range(N): 8 | stamp = input().strip() 9 | stamps.add(stamp) 10 | 11 | print(len(stamps)) -------------------------------------------------------------------------------- /python part1/list-comprehensions.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | x = int(input()) 3 | y = int(input()) 4 | z = int(input()) 5 | n = int(input()) 6 | 7 | print([ [ i, j, k] for i in range(x + 1) for j in range(y + 1) for k in range(z + 1) if ( (i + j + k) != n )]) 8 | -------------------------------------------------------------------------------- /python part1/validating-named-email-addresses.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | t = int(input().strip()) 4 | for _ in range(t): 5 | name, email = input().strip().split() 6 | 7 | if re.match(r'<[A-Za-z](\w|-|\.|_)+@[A-Za-z]+\.[A-Za-z]{1,3}>', email): 8 | print("{} {}".format(name, email)) -------------------------------------------------------------------------------- /python part1/itertools-permutations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from itertools import permutations 4 | 5 | if __name__ == "__main__": 6 | in_data = list(input().strip().split(' ')) 7 | 8 | for el in permutations(sorted(in_data[0]), int(in_data[1])): 9 | print("".join(el)) -------------------------------------------------------------------------------- /python part2/np-mean-var-and-std.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | n, m = [int(x) for x in input().strip().split()] 4 | array = np.array([[int(x) for x in input().strip().split()] for _ in range(n)], dtype = float) 5 | print(np.mean(array, axis = 1)) 6 | print(np.var(array, axis = 0)) 7 | print(np.std(array)) -------------------------------------------------------------------------------- /algorithms part1/birthday-cake-candles.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def birthdayCakeCandles(n, ar): 6 | return ar.count(max(ar)) 7 | 8 | n = int(input().strip()) 9 | ar = list(map(int, input().strip().split(' '))) 10 | result = birthdayCakeCandles(n, ar) 11 | print(result) 12 | -------------------------------------------------------------------------------- /python part1/compress-the-string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from itertools import groupby 4 | 5 | if __name__ == "__main__": 6 | #in_data = input().strip().split(' ') 7 | 8 | for el, el_list in groupby(input()): 9 | print((len(list(el_list)), int(el)), end=' ') 10 | -------------------------------------------------------------------------------- /python part1/xml2-find-the-maximum-depth.py: -------------------------------------------------------------------------------- 1 | maxdepth = 0 2 | def depth(elem, level): 3 | #print(elem) 4 | if level == -1: 5 | level = 0 6 | global maxdepth 7 | if level > maxdepth: 8 | maxdepth = level 9 | for el in elem: 10 | depth(el, level+1) 11 | 12 | -------------------------------------------------------------------------------- /shell/bash-tutorials---more-on-conditionals.sh: -------------------------------------------------------------------------------- 1 | read x 2 | read y 3 | read z 4 | 5 | if (( $x == "$y")) && (( $y == "$z")) ; then 6 | echo 'EQUILATERAL' 7 | elif (( $x == "$y" )) || (( $x == "$z" )) || (( $y == "$z" )) ; then 8 | echo 'ISOSCELES' 9 | else 10 | echo 'SCALENE' 11 | fi 12 | -------------------------------------------------------------------------------- /python part1/maximize-it.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | 4 | from itertools import product 5 | 6 | K,M = map(int,input().split()) 7 | N = (list(map(int, input().split()))[1:] for _ in range(K)) 8 | results = map(lambda x: sum(i**2 for i in x)%M, product(*N)) 9 | print(max(results)) 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /python part1/standardize-mobile-number-using-decorators.py: -------------------------------------------------------------------------------- 1 | def wrapper(func): 2 | def fun(l): 3 | out = [] 4 | for telnum in l: 5 | barenum = telnum[-10:] 6 | telnum = '+91 ' + barenum[:5] + ' ' + barenum[5:] 7 | out.append(telnum) 8 | func(out) 9 | return fun -------------------------------------------------------------------------------- /algorithms part2/extra-long-factorials.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # this should work 3 | 4 | import sys 5 | from math import factorial 6 | 7 | def extraLongFactorials(n): 8 | return factorial(n) 9 | 10 | 11 | if __name__ == "__main__": 12 | n = int(input().strip()) 13 | print(extraLongFactorials(n)) 14 | -------------------------------------------------------------------------------- /algorithms part2/lonely-integer.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def lonely_integer(a): 6 | res = 0 7 | for elem in a: 8 | res ^= elem 9 | return res 10 | 11 | 12 | n = int(input().strip()) 13 | a = [int(a_temp) for a_temp in input().strip().split(' ')] 14 | print(lonely_integer(a)) -------------------------------------------------------------------------------- /python part1/find-a-string.py: -------------------------------------------------------------------------------- 1 | def count_substring(string, sub_string): 2 | res = 0 3 | len_sub = len(sub_string) 4 | 5 | for i in range(len(string) - len_sub + 1): 6 | if string[i:i + len_sub] == sub_string: 7 | res += 1 8 | i += 1 9 | 10 | return res 11 | -------------------------------------------------------------------------------- /cpp/cpp-input-and-output.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main() { 10 | int a, b, c; 11 | cin >> a; 12 | cin >> b; 13 | cin >> c; 14 | cout << a + b + c; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /python part1/string-validators.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | s = input() 3 | 4 | print(any(char.isalnum() for char in s)) 5 | print(any(char.isalpha() for char in s)) 6 | print(any(char.isdigit() for char in s)) 7 | print(any(char.islower() for char in s)) 8 | print(any(char.isupper() for char in s)) 9 | -------------------------------------------------------------------------------- /algorithms part1/a-very-big-sum.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def aVeryBigSum(n, ar): 6 | sum = 0 7 | for elem in ar: 8 | sum += elem 9 | return sum 10 | 11 | n = int(input().strip()) 12 | ar = list(map(int, input().strip().split(' '))) 13 | result = aVeryBigSum(n, ar) 14 | print(result) 15 | -------------------------------------------------------------------------------- /python part1/designer-door-mat.py: -------------------------------------------------------------------------------- 1 | N, M = map(int,input().split()) # More than 6 lines of code will result in 0 score. Blank lines are not counted. 2 | for i in range(1, N, 2): 3 | print((i*".|.").center(3*N, "-")) 4 | print ("-WELCOME-".center(3*N, "-")) 5 | for i in range(N - 2, -1, -2): 6 | print((i*".|.").center(3*N, "-")) 7 | -------------------------------------------------------------------------------- /python part2/py-set-difference-operation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | n = int(input().strip()) 5 | english = set(map(int, input().strip().split(' '))) 6 | m = int(input().strip()) 7 | french = set(map(int, input().strip().split(' '))) 8 | 9 | print(len(english.difference(french))) -------------------------------------------------------------------------------- /algorithms part2/repeated-string.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def repeatedString(s, n): 6 | return s.count('a') * (n//len(s)) + s[:n%len(s)].count('a') 7 | 8 | if __name__ == "__main__": 9 | s = input().strip() 10 | n = int(input().strip()) 11 | result = repeatedString(s, n) 12 | print(result) 13 | -------------------------------------------------------------------------------- /algorithms part2/simple-array-sum.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def simpleArraySum(n, ar): 6 | sum = 0 7 | for elem in ar: 8 | sum += elem 9 | return sum 10 | 11 | n = int(input().strip()) 12 | ar = list(map(int, input().strip().split(' '))) 13 | result = simpleArraySum(n, ar) 14 | print(result) 15 | -------------------------------------------------------------------------------- /python part1/swap-case.py: -------------------------------------------------------------------------------- 1 | def swap_case(s): 2 | out = '' 3 | for ind, let in enumerate(s): 4 | if let.isalpha(): 5 | if let.islower(): 6 | out += s[ind].capitalize() 7 | else: 8 | out += s[ind].lower() 9 | else: 10 | out += let 11 | return out -------------------------------------------------------------------------------- /python part2/py-set-intersection-operation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | n = int(input().strip()) 5 | english = set(map(int, input().strip().split(' '))) 6 | m = int(input().strip()) 7 | french = set(map(int, input().strip().split(' '))) 8 | 9 | print(len(english.intersection(french))) -------------------------------------------------------------------------------- /python part2/py-set-union.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | n = int(input().strip()) 5 | english = set(map(int, input().strip().split(' '))) 6 | m = int(input().strip()) 7 | french = set(map(int, input().strip().split(' '))) 8 | 9 | print(len(english.union(french))) 10 | 11 | -------------------------------------------------------------------------------- /algorithms part2/pangrams.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import string 4 | alphabet = string.ascii_lowercase 5 | 6 | def is_pangram(s): 7 | return set(alphabet) < set(s.lower()) 8 | 9 | if __name__ == "__main__": 10 | if is_pangram(input().strip()): 11 | print("pangram") 12 | else: 13 | print("not pangram") -------------------------------------------------------------------------------- /python part1/itertools-combinations-with-replacement.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from itertools import combinations_with_replacement 4 | 5 | if __name__ == "__main__": 6 | in_data = list(input().strip().split(' ')) 7 | 8 | for el in combinations_with_replacement(sorted(in_data[0]), int(in_data[1])): 9 | print("".join(el)) -------------------------------------------------------------------------------- /python part1/most-commons.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from collections import Counter 5 | 6 | if __name__ == "__main__": 7 | s = input().strip() 8 | best = Counter(s) 9 | sortit = sorted(best.items(), key = lambda x: (-x[1], x[0]))[:3] 10 | 11 | print("\n".join(x[0]+" "+str(x[1]) for x in sortit)) 12 | -------------------------------------------------------------------------------- /algorithms part2/drawing-book.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def get_open(page): 6 | return 1 + (page//2) 7 | 8 | def solve(n, p): 9 | return min(get_open(p) - get_open(1), get_open(n) - get_open(p)) 10 | 11 | n = int(input().strip()) 12 | p = int(input().strip()) 13 | result = solve(n, p) 14 | print(result) 15 | -------------------------------------------------------------------------------- /algorithms part2/find-the-median.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def findMedian(arr): 6 | arr = sorted(arr) 7 | return arr[len(arr)//2] 8 | 9 | if __name__ == "__main__": 10 | n = int(input().strip()) 11 | arr = list(map(int, input().strip().split(' '))) 12 | result = findMedian(arr) 13 | print(result) 14 | -------------------------------------------------------------------------------- /interview-preparation-kit/repeated-string.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def repeatedString(s, n): 6 | return s.count('a') * (n//len(s)) + s[:n%len(s)].count('a') 7 | 8 | if __name__ == "__main__": 9 | s = input().strip() 10 | n = int(input().strip()) 11 | result = repeatedString(s, n) 12 | print(result) 13 | -------------------------------------------------------------------------------- /python part1/itertools-combinations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from itertools import combinations 4 | 5 | if __name__ == "__main__": 6 | in_data = list(input().strip().split(' ')) 7 | 8 | for lng in range(1, int(in_data[1])+1): 9 | for el in combinations(sorted(in_data[0]), lng): 10 | print("".join(el)) -------------------------------------------------------------------------------- /python part1/itertools-product.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from itertools import product 4 | 5 | if __name__ == "__main__": 6 | arr1 = list(map(int, input().strip().split(' '))) 7 | arr2 = list(map(int, input().strip().split(' '))) 8 | 9 | for el in product(arr1, arr2): 10 | print("{} ".format(el), end='') 11 | -------------------------------------------------------------------------------- /python part1/re-sub-regex-substitution.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def change(match): 4 | symb = match.group(0) 5 | 6 | if symb == "&&": 7 | return "and" 8 | elif symb == "||": 9 | return "or" 10 | 11 | n = int(input().strip()) 12 | for _ in range(n): 13 | print(re.sub(r'(?<= )(&&|\|\|)(?= )', change, input())) -------------------------------------------------------------------------------- /data-structures/tree-inorder-traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Node is defined as 3 | self.left (the left child of the node) 4 | self.right (the right child of the node) 5 | self.data (the value of the node) 6 | """ 7 | def inOrder(root): 8 | if root is not None: 9 | inOrder(root.left) 10 | print root.data, 11 | inOrder(root.right) 12 | -------------------------------------------------------------------------------- /python part2/py-set-symmetric-difference-operation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | n = int(input().strip()) 5 | english = set(map(int, input().strip().split(' '))) 6 | m = int(input().strip()) 7 | french = set(map(int, input().strip().split(' '))) 8 | 9 | print(len(english.symmetric_difference(french))) -------------------------------------------------------------------------------- /algorithms part2/string-construction.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def stringConstruction(s): 6 | return len(set(s)) 7 | 8 | 9 | if __name__ == "__main__": 10 | q = int(input().strip()) 11 | for a0 in range(q): 12 | s = input().strip() 13 | result = stringConstruction(s) 14 | print(result) 15 | -------------------------------------------------------------------------------- /c/hello-world-c.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() 7 | { 8 | 9 | char s[100]; 10 | scanf("%[^\n]%*c", &s); 11 | 12 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 13 | printf("Hello, World!\n%s", s); 14 | return 0; 15 | } -------------------------------------------------------------------------------- /python part1/incorrect-regex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import re 4 | 5 | if __name__ == "__main__": 6 | t = int(input().strip()) 7 | 8 | for _ in range(t): 9 | try: 10 | re.compile(input().strip()) 11 | res = True 12 | except BaseException: 13 | res = False 14 | print(res) -------------------------------------------------------------------------------- /data-structures/tree-postorder-traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Node is defined as 3 | self.left (the left child of the node) 4 | self.right (the right child of the node) 5 | self.data (the value of the node) 6 | """ 7 | def postOrder(root): 8 | if root is not None: 9 | postOrder(root.left) 10 | postOrder(root.right) 11 | print root.data, 12 | -------------------------------------------------------------------------------- /shell/awk-3.sh: -------------------------------------------------------------------------------- 1 | awk ' 2 | { 3 | avg = ($2 + $3 + $4)/3 ; 4 | if (avg >= 80) 5 | printf("%s : A\n", $0) ; 6 | else if (avg >= 60) 7 | printf("%s : B\n", $0) ; 8 | else if (avg >= 50) 9 | printf("%s : C\n", $0) ; 10 | else 11 | printf("%s : FAIL\n", $0) ; 12 | } 13 | ' -------------------------------------------------------------------------------- /cpp/exceptional-server.cpp: -------------------------------------------------------------------------------- 1 | try { 2 | Server s; 3 | int ret = s.compute(A, B); 4 | cout << ret << endl; 5 | } 6 | catch (bad_alloc& error) { 7 | cout << "Not enough memory" << endl; 8 | } 9 | catch (exception& error) { 10 | cout << "Exception: " << error.what() << endl; 11 | } 12 | catch (...) { 13 | cout << "Other Exception" << endl; 14 | } -------------------------------------------------------------------------------- /cpp/c-tutorial-basic-data-types.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | int i; 7 | long l; 8 | char c; 9 | float f; 10 | double d; 11 | 12 | scanf("%d %ld %c %f %lf", &i, &l, &c, &f, &d); 13 | printf("%d\n%ld\n%c\n%f\n%lf\n", i, l, c, f, d); 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /python part1/python-string-formatting.py: -------------------------------------------------------------------------------- 1 | def print_formatted(number): 2 | align = len(bin(number)[2:]) 3 | for num in range(1, number + 1): 4 | n_dec = str(num) 5 | n_oct = oct(num)[2:] 6 | n_hex = hex(num)[2:].upper() 7 | n_bin = bin(num)[2:] 8 | print(n_dec.rjust(align), n_oct.rjust(align), n_hex.rjust(align), n_bin.rjust(align)) -------------------------------------------------------------------------------- /python part1/symmetric-difference.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | 4 | if __name__ == "__main__": 5 | M = int(input().strip()) 6 | set_m = set(map(int, input().strip().split(' '))) 7 | 8 | N = int(input().strip()) 9 | set_n = set(map(int, input().strip().split(' '))) 10 | 11 | for el in sorted(set_m ^ set_n): 12 | print(el) 13 | -------------------------------------------------------------------------------- /data-structures/sparse-arrays.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | strings = [] 5 | N = int(input().strip()) 6 | for _ in range(N): 7 | strings.append(input().strip()) 8 | 9 | Q = int(input().strip()) 10 | for _ in range(Q): 11 | substr = input().strip() 12 | print(strings.count(substr)) 13 | -------------------------------------------------------------------------------- /c/sum-of-digits-of-a-five-digit-number.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | 8 | int n, res; 9 | scanf("%d", &n); 10 | 11 | res = n%10; 12 | 13 | while (n = n/10) { 14 | res += n%10; 15 | } 16 | 17 | printf("%d\n", res); 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /python part1/matrix-script.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | n, m = input().strip().split(' ') 4 | n, m = [int(n), int(m)] 5 | matrix = [] 6 | for _ in range(n): 7 | matrix_t = str(input()) 8 | matrix.append(matrix_t) 9 | 10 | complete = "" 11 | for el in zip(*matrix): 12 | complete += "".join(el) 13 | print(re.sub(r'(?<=\w)([^\w]+)(?=\w)', " ", complete)) 14 | 15 | 16 | -------------------------------------------------------------------------------- /python part1/zipped.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | st_num, sb_num = map(int, input().strip().split()) 5 | scores = [] 6 | 7 | for _ in range(sb_num): 8 | scores.append(map(float, input().strip().split())) 9 | 10 | for el in zip(*scores): 11 | print(sum(el)/sb_num) 12 | 13 | 14 | -------------------------------------------------------------------------------- /algorithms part1/two-strings.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def twoStrings(s1, s2): 6 | if len(set(s1) & set(s2)) > 0: 7 | return 'YES' 8 | else: 9 | return 'NO' 10 | 11 | q = int(input().strip()) 12 | for a0 in range(q): 13 | s1 = input().strip() 14 | s2 = input().strip() 15 | result = twoStrings(s1, s2) 16 | print(result) 17 | -------------------------------------------------------------------------------- /algorithms part2/the-hurdle-race.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def hurdleRace(k, height): 6 | return max(0, max(height) - k) 7 | 8 | if __name__ == "__main__": 9 | n, k = input().strip().split(' ') 10 | n, k = [int(n), int(k)] 11 | height = list(map(int, input().strip().split(' '))) 12 | result = hurdleRace(k, height) 13 | print(result) 14 | -------------------------------------------------------------------------------- /python part1/np-array-mathematics.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | 3 | n, m = [int(x) for x in input().strip().split()] 4 | 5 | a = numpy.array([[int(x) for x in input().strip().split()] for _ in range(n)]) 6 | b = numpy.array([[int(x) for x in input().strip().split()] for _ in range(n)]) 7 | 8 | print(a + b) 9 | print(a - b) 10 | print(a * b) 11 | print(a // b) 12 | print(a % b) 13 | print(a**b) -------------------------------------------------------------------------------- /algorithms part1/camelcase.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def camelcase(s): 6 | res = 1 7 | for let in s: 8 | if let.isupper(): 9 | res += 1 10 | 11 | if not s: 12 | res = 0 13 | 14 | return res 15 | 16 | if __name__ == "__main__": 17 | s = input().strip() 18 | result = camelcase(s) 19 | print(result) 20 | -------------------------------------------------------------------------------- /algorithms part2/designer-pdf-viewer.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def designerPdfViewer(h, word): 6 | return len(word) * max(list(map(lambda x: h[ord(x) - ord('a')], word))) 7 | 8 | if __name__ == "__main__": 9 | h = list(map(int, input().strip().split(' '))) 10 | word = input().strip() 11 | result = designerPdfViewer(h, word) 12 | print(result) 13 | -------------------------------------------------------------------------------- /algorithms part2/migratory-birds.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def migratoryBirds(n, ar): 6 | count = [0] * 6 7 | 8 | for bird in ar: 9 | count[bird] += 1 10 | 11 | return count.index(max(count)) 12 | 13 | n = int(input().strip()) 14 | ar = list(map(int, input().strip().split(' '))) 15 | result = migratoryBirds(n, ar) 16 | print(result) 17 | -------------------------------------------------------------------------------- /c/pointer-in-c.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void update(int *a, int *b) { 5 | int buf = *a; 6 | 7 | *a = *a + *b; 8 | *b = abs(buf - *b); 9 | } 10 | 11 | int main() { 12 | int a, b; 13 | int *pa = &a, *pb = &b; 14 | 15 | scanf("%d %d", &a, &b); 16 | update(pa, pb); 17 | printf("%d\n%d", a, b); 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /python part1/map-and-lambda-expression.py: -------------------------------------------------------------------------------- 1 | cube = lambda x: x**3 2 | 3 | def fibonacci(n): 4 | if n == 0: 5 | return [] 6 | if n == 1: 7 | return [0] 8 | prev = 0 9 | cur = 1 10 | out = [prev, cur] 11 | 12 | for _ in range(n-2): 13 | prev, cur = cur, prev + cur 14 | out.append(cur) 15 | 16 | return out 17 | -------------------------------------------------------------------------------- /shell/awk-2.sh: -------------------------------------------------------------------------------- 1 | awk ' 2 | { 3 | result = 1 4 | for ( i = 1; i < NF; i++ ) { 5 | if ($i < 50 && $i >= 0) { 6 | result = 0; 7 | break; 8 | } 9 | } 10 | printf("%s : ", $1); 11 | if (result) 12 | printf("Pass\n"); 13 | else 14 | printf("Fail\n"); 15 | } 16 | ' -------------------------------------------------------------------------------- /algorithms part2/save-the-prisoner.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def saveThePrisoner(n, m, s): 6 | res = (s + m-1) % n 7 | return res if res != 0 else n 8 | 9 | t = int(input().strip()) 10 | for a0 in range(t): 11 | n, m, s = input().strip().split(' ') 12 | n, m, s = [int(n), int(m), int(s)] 13 | result = saveThePrisoner(n, m, s) 14 | print(result) 15 | -------------------------------------------------------------------------------- /c/reverse-array-c.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int num, i; 7 | int *arr; 8 | 9 | scanf("%d", &num); 10 | arr = (int*) malloc(num * sizeof(int)); 11 | 12 | for(i = num-1; i >= 0; i--) 13 | scanf("%d", arr + i); 14 | 15 | for(i = 0; i < num; i++) 16 | printf("%d ", *(arr + i)); 17 | return 0; 18 | } -------------------------------------------------------------------------------- /c/sum-numbers-c.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() 7 | { 8 | int int1, int2; 9 | float fl1, fl2; 10 | scanf("%d %d", &int1, &int2); 11 | scanf("%f %f", &fl1, &fl2); 12 | 13 | printf("%d %d\n", int1 + int2, int1 - int2); 14 | printf("%.1f %.1f\n", fl1 + fl2, fl1 - fl2); 15 | return 0; 16 | } -------------------------------------------------------------------------------- /cpp/c-tutorial-pointer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void update(int *a, int *b) { 5 | int buf = *a; 6 | *a = *a + *b; 7 | *b = abs(buf - *b); 8 | } 9 | 10 | int main() { 11 | int a, b; 12 | int *pa = &a, *pb = &b; 13 | 14 | scanf("%d %d", &a, &b); 15 | update(pa, pb); 16 | printf("%d\n%d", a, b); 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /interview-preparation-kit/two-strings.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def twoStrings(s1, s2): 6 | if len(set(s1) & set(s2)) > 0: 7 | return 'YES' 8 | else: 9 | return 'NO' 10 | 11 | q = int(input().strip()) 12 | for a0 in range(q): 13 | s1 = input().strip() 14 | s2 = input().strip() 15 | result = twoStrings(s1, s2) 16 | print(result) 17 | -------------------------------------------------------------------------------- /python part1/re-findall-re-finditer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import re 4 | 5 | cons = 'QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm' 6 | vowels = 'AEIOUaeiou' 7 | 8 | if __name__ == "__main__": 9 | string = input().strip() 10 | 11 | m = re.findall(r"(?<=[%s])([%s]{2,})[%s]" % (cons, vowels, cons), string) 12 | 13 | print("\n".join(m or ['-1'])) 14 | 15 | -------------------------------------------------------------------------------- /algorithms part2/staircase.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def staircase(n): 6 | for i in range(n): 7 | for j in range(1, n+1): 8 | if i + j >= n: 9 | print("#", end='') 10 | else: 11 | print(" ", end='') 12 | print() 13 | 14 | if __name__ == "__main__": 15 | n = int(input().strip()) 16 | staircase(n) 17 | -------------------------------------------------------------------------------- /algorithms part2/sum-vs-xor.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def solve(n): 6 | res = 1 7 | n_bin = bin(n).replace('0b', '') 8 | 9 | if (n == 0): 10 | return 1 11 | 12 | for digit in n_bin: 13 | if digit == '0': 14 | res *= 2 15 | 16 | return res 17 | 18 | n = int(input().strip()) 19 | result = solve(n) 20 | print(result) 21 | -------------------------------------------------------------------------------- /python part1/re-start-re-end.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import re 4 | 5 | if __name__ == "__main__": 6 | string = input() 7 | sub = input() 8 | 9 | matches = list(re.finditer(r'(?={})'.format(sub), string)) 10 | 11 | if matches: 12 | for match in matches: 13 | print((match.start(), match.end() + len(sub) - 1)) 14 | else: 15 | print((-1, -1)) -------------------------------------------------------------------------------- /algorithms part2/game-of-stones-1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def gameOfStones(n): 6 | if n%7 == 1 or n%7 == 0: 7 | return 'Second' 8 | else: 9 | return 'First' 10 | 11 | if __name__ == "__main__": 12 | t = int(input().strip()) 13 | for a0 in range(t): 14 | n = int(input().strip()) 15 | result = gameOfStones(n) 16 | print(result) 17 | -------------------------------------------------------------------------------- /algorithms part1/correctness-invariant.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(l): 2 | for i in range(1, len(l)): 3 | j = i-1 4 | key = l[i] 5 | while (j >= 0) and (l[j] > key): 6 | l[j+1] = l[j] 7 | j -= 1 8 | l[j+1] = key 9 | 10 | 11 | m = int(input().strip()) 12 | ar = [int(i) for i in input().strip().split()] 13 | insertion_sort(ar) 14 | print(" ".join(map(str,ar))) 15 | -------------------------------------------------------------------------------- /cpp/arrays-introduction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main() { 10 | int N; 11 | int array[1010]; 12 | cin >> N; 13 | for (int i = N; i; i--) 14 | cin >> array[i]; 15 | for (int i = 1; i <= N; i++) 16 | cout << array[i] << " "; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /data-structures/tree-preorder-traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Node is defined as 3 | self.left (the left child of the node) 4 | self.right (the right child of the node) 5 | self.data (the value of the node) 6 | """ 7 | 8 | 9 | def preOrder(root): 10 | print root.data, 11 | if root.left is not None: 12 | preOrder(root.left) 13 | if root.right is not None: 14 | preOrder(root.right) 15 | 16 | -------------------------------------------------------------------------------- /algorithms part2/marcs-cakewalk.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def marcsCakewalk(arr): 6 | arr = sorted(arr, key = lambda x: -x) 7 | 8 | return sum([el * (2**mult) for mult, el in enumerate(arr)]) 9 | 10 | if __name__ == "__main__": 11 | n = int(input().strip()) 12 | calorie = list(map(int, input().strip().split(' '))) 13 | result = marcsCakewalk(calorie) 14 | print(result) 15 | -------------------------------------------------------------------------------- /cpp/classes-objects.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Student { 3 | private: 4 | vector scores = vector(5); 5 | 6 | public: 7 | void input() { 8 | for (int i = 0; i < 5; i++) 9 | cin >> scores[i]; 10 | } 11 | 12 | int calculateTotalScore() { 13 | int sum = 0; 14 | for (int i = 0; i < 5; i++) 15 | sum += scores[i]; 16 | return sum; 17 | } 18 | }; -------------------------------------------------------------------------------- /interview-preparation-kit/flipping-bits.py: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | int T; 8 | unsigned int number; 9 | unsigned int mask = -1; 10 | 11 | scanf("%d", &T); 12 | 13 | for (int i = 0; i < T; i++) { 14 | scanf("%u", &number); 15 | printf("%u\n", number^mask); 16 | } 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /python part2/np-concatenate.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | n, m, p = [int(x) for x in input().strip().split()] 3 | arr1 = [] 4 | arr2 = [] 5 | 6 | for _ in range(n): 7 | arr1.append([int(x) for x in input().strip().split()] ) 8 | 9 | for _ in range(m): 10 | arr2.append([int(x) for x in input().strip().split()] ) 11 | 12 | arr1 = numpy.array(arr1) 13 | arr2 = numpy.array(arr2) 14 | 15 | print(numpy.concatenate((arr1, arr2))) -------------------------------------------------------------------------------- /algorithms part2/find-digits.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def findDigits(n): 6 | res = 0 7 | for dig in n: 8 | if dig != '0' and int(n) % int(dig) == 0: 9 | res += 1 10 | 11 | return res 12 | 13 | if __name__ == "__main__": 14 | t = int(input().strip()) 15 | for a0 in range(t): 16 | n = input().strip() 17 | result = findDigits(n) 18 | print(result) 19 | -------------------------------------------------------------------------------- /python part1/words-score.py: -------------------------------------------------------------------------------- 1 | def is_vowel(letter): 2 | return letter in ['a', 'e', 'i', 'o', 'u', 'y'] 3 | 4 | def score_words(words): 5 | score = 0 6 | for word in words: 7 | num_vowels = 0 8 | for letter in word: 9 | if is_vowel(letter): 10 | num_vowels += 1 11 | if num_vowels % 2 == 0: 12 | score += 2 13 | else: 14 | score += 1 15 | return score -------------------------------------------------------------------------------- /algorithms part2/gem-stones.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def gemstones(arrays): 6 | superset = set(arrays[0]) 7 | 8 | for arr in arrays[1:]: 9 | superset &= set(arr) 10 | 11 | return len(superset) 12 | 13 | n = int(input().strip()) 14 | arr = [] 15 | arr_i = 0 16 | for arr_i in range(n): 17 | arr_t = str(input().strip()) 18 | arr.append(arr_t) 19 | result = gemstones(arr) 20 | print(result) 21 | -------------------------------------------------------------------------------- /algorithms part1/countingsort1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def countingSort(arr): 6 | output = [0] * (max(arr) + 1) 7 | 8 | for el in arr: 9 | output[el] += 1 10 | 11 | return output 12 | 13 | if __name__ == "__main__": 14 | n = int(input().strip()) 15 | arr = list(map(int, input().strip().split(' '))) 16 | result = countingSort(arr) 17 | print (" ".join(map(str, result))) 18 | 19 | 20 | -------------------------------------------------------------------------------- /python part2/py-check-strict-superset.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | A = set(map(int, input().strip().split(' '))) 5 | t = int(input().strip()) 6 | superset = True 7 | 8 | for _ in range(t): 9 | subset = set(map(int, input().strip().split(' '))) 10 | if len(subset - A) != 0 or len(A - subset) == 0: 11 | superset = False 12 | break 13 | 14 | print(superset) -------------------------------------------------------------------------------- /algorithms part2/sherlock-and-squares.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from math import ceil, floor 5 | 6 | def squares(a, b): 7 | res = 0 8 | res = floor(b**0.5)+1 - ceil(a**0.5) 9 | return res 10 | 11 | if __name__ == "__main__": 12 | q = int(input().strip()) 13 | for a0 in range(q): 14 | a, b = input().strip().split(' ') 15 | a, b = [int(a), int(b)] 16 | result = squares(a, b) 17 | print(result) 18 | -------------------------------------------------------------------------------- /cpp/prettyprint.cpp: -------------------------------------------------------------------------------- 1 | cout << hex << left << showbase << nouppercase; // formatting 2 | cout << (long long) A << endl; // actual printed part 3 | 4 | cout << dec << right << setw(15) << setfill('_') << showpos << fixed << setprecision(2); // formatting 5 | cout << B << endl; // actual printed part 6 | 7 | cout << scientific << uppercase << noshowpos << setprecision(9); // formatting 8 | cout << C << endl; // actual printed part -------------------------------------------------------------------------------- /python part1/exceptions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | t = int(input().strip()) 5 | 6 | for _ in range(t): 7 | a, b = input().strip().split(' ') 8 | 9 | try: 10 | print(int(a)//int(b)) 11 | except ZeroDivisionError as e: 12 | print("Error Code: {}".format(e)) 13 | except ValueError as e: 14 | print("Error Code: {}".format(e)) 15 | -------------------------------------------------------------------------------- /cpp/c-tutorial-strings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | string a, b, aa, bb; 7 | cin >> a; 8 | cin >> b; 9 | aa = a; 10 | bb = b; 11 | char buf = aa[0]; 12 | aa[0] = bb[0]; 13 | bb[0] = buf; 14 | 15 | cout << a.size() << " " << b.size() << endl; 16 | cout << a+b << endl; 17 | cout << aa << " " << bb << endl; 18 | 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /python part1/finding-the-percentage.py: -------------------------------------------------------------------------------- 1 | def get_avg(marks, student): 2 | return (sum(marks[student])/len(marks[student])) 3 | 4 | if __name__ == '__main__': 5 | n = int(input()) 6 | student_marks = {} 7 | for _ in range(n): 8 | name, *line = input().split() 9 | scores = list(map(float, line)) 10 | student_marks[name] = scores 11 | query_name = input() 12 | print("{:.2f}".format(get_avg(student_marks, query_name))) 13 | -------------------------------------------------------------------------------- /algorithms part2/the-great-xor.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def theGreatXor(x): 6 | res = 0 7 | n_bin = bin(x).replace('0b', '') 8 | 9 | for ind, digit in enumerate(reversed(n_bin)): 10 | if digit == '0': 11 | res += pow(2, ind) 12 | 13 | return res 14 | 15 | 16 | q = int(input().strip()) 17 | for a0 in range(q): 18 | x = int(input().strip()) 19 | result = theGreatXor(x) 20 | print(result) 21 | -------------------------------------------------------------------------------- /algorithms part2/priyanka-and-toys.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def toys(w): 6 | w = sorted(w) 7 | res = 0 8 | limit = -1 9 | 10 | for el in w: 11 | if el > limit: 12 | limit = el + 4 13 | res += 1 14 | 15 | return res 16 | 17 | if __name__ == "__main__": 18 | n = int(input().strip()) 19 | w = list(map(int, input().strip().split(' '))) 20 | result = toys(w) 21 | print(result) 22 | -------------------------------------------------------------------------------- /algorithms part2/the-birthday-bar.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def solve(n, bar, d, m): 6 | res = 0 7 | 8 | for a_i in range(len(bar)-m+1): 9 | if sum(bar[a_i:a_i+m]) == d: 10 | res += 1 11 | 12 | return res 13 | 14 | n = int(input().strip()) 15 | bar = list(map(int, input().strip().split(' '))) 16 | d, m = input().strip().split(' ') 17 | d, m = [int(d), int(m)] 18 | result = solve(n, bar, d, m) 19 | print(result) 20 | -------------------------------------------------------------------------------- /c/playing-with-characters.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAX_LEN 128 7 | 8 | int main() 9 | { 10 | char ch; 11 | char word[MAX_LEN]; 12 | char sen[MAX_LEN]; 13 | 14 | scanf("%c", &ch); 15 | scanf("%s\n", &word); 16 | scanf("%[^\n]%*c", &sen); 17 | 18 | printf("%c\n", ch); 19 | printf("%s\n", word); 20 | printf("%s\n", sen); 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /c/printing-tokens-.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | 8 | char *s; 9 | s = malloc(1024 * sizeof(char)); 10 | scanf("%[^\n]", s); 11 | s = realloc(s, strlen(s) + 1); 12 | 13 | for (int i = 0; i < strlen(s); i++) { 14 | if (s[i] == ' ') 15 | printf("\n"); 16 | else 17 | printf("%c", s[i]); 18 | } 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /data-structures/x-and-his-shots.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | n,m = map(int, input().split()) 4 | 5 | t1 = [0] * 100010 6 | t2 = [0] * 100010 7 | tt = int(0) 8 | 9 | for i in range(n): 10 | l,r = map(int, input().split()) 11 | t1[l] += 1 12 | t2[r+1] -= 1 13 | 14 | for i in range(1,100010): 15 | t1[i] += t1[i-1] 16 | t2[i] += t2[i-1] 17 | 18 | for i in range(m): 19 | l,r = map(int, input().split()) 20 | tt += t1[r] + t2[l] 21 | 22 | print(tt) -------------------------------------------------------------------------------- /python part1/python-sort-sort.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | n, m = input().strip().split(' ') 7 | n, m = [int(n), int(m)] 8 | arr = [] 9 | for arr_i in range(n): 10 | arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')] 11 | arr.append(arr_t) 12 | k = int(input().strip()) 13 | 14 | for el in sorted(arr, key = lambda x: x[k]): 15 | print(" ".join(map(str, el))) 16 | -------------------------------------------------------------------------------- /algorithms part2/manasa-and-stones.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def stones(n, a, b): 6 | return sorted(set([(n-1)*min(a, b) + x*abs(a-b) for x in range(n)])) 7 | 8 | 9 | if __name__ == "__main__": 10 | T = int(input().strip()) 11 | for a0 in range(T): 12 | n = int(input().strip()) 13 | a = int(input().strip()) 14 | b = int(input().strip()) 15 | result = stones(n, a, b) 16 | print (" ".join(map(str, result))) 17 | -------------------------------------------------------------------------------- /algorithms part2/equality-in-a-array.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from collections import Counter 5 | 6 | def equalizeArray(arr): 7 | cnt = Counter(arr) 8 | 9 | m_el_num = max(cnt.items(), key = lambda x: x[1]) 10 | 11 | return len(arr) - m_el_num[1] 12 | 13 | 14 | if __name__ == "__main__": 15 | n = int(input().strip()) 16 | arr = list(map(int, input().strip().split(' '))) 17 | result = equalizeArray(arr) 18 | print(result) 19 | -------------------------------------------------------------------------------- /c/functions-in-c.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int max_of_four(int a, int b, int c, int d) 4 | { 5 | int res = a; 6 | 7 | if (b > res) 8 | res = b; 9 | if (c > res) 10 | res = c; 11 | if (d > res) 12 | res = d; 13 | 14 | return res; 15 | } 16 | 17 | 18 | int main() { 19 | int a, b, c, d; 20 | scanf("%d %d %d %d", &a, &b, &c, &d); 21 | int ans = max_of_four(a, b, c, d); 22 | printf("%d", ans); 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /data-structures/print-the-elements-of-a-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Print elements of a linked list on console 3 | head input could be None as well for empty list 4 | Node is defined as 5 | 6 | class Node(object): 7 | 8 | def __init__(self, data=None, next_node=None): 9 | self.data = data 10 | self.next = next_node 11 | 12 | 13 | """ 14 | def print_list(head): 15 | node = head 16 | while node != None: 17 | print(node.data) 18 | node = node.next 19 | -------------------------------------------------------------------------------- /interview-preparation-kit/ctci-big-o.py: -------------------------------------------------------------------------------- 1 | def is_prime(num): 2 | if num < 2: 3 | return False 4 | else: 5 | sqrt = int(num**(1/2)) 6 | for i in range(2,sqrt+1): 7 | if n % i == 0: 8 | return False 9 | return True 10 | 11 | 12 | 13 | p = int(input().strip()) 14 | for a0 in range(p): 15 | n = int(input().strip()) 16 | if is_prime(n): 17 | print("Prime") 18 | else: 19 | print("Not prime") 20 | -------------------------------------------------------------------------------- /algorithms part1/beautiful-binary-string.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def beautifulBinaryString(b): 6 | res = 0 7 | 8 | while '010' in b: 9 | #print("found res = {} b = {}".format(res, b)) 10 | res += 1 11 | b = b.replace("010","011", 1) 12 | 13 | return res 14 | 15 | 16 | if __name__ == "__main__": 17 | n = int(input().strip()) 18 | b = input().strip() 19 | result = beautifulBinaryString(b) 20 | print(result) 21 | -------------------------------------------------------------------------------- /c/1d-arrays-in-c.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | int n; 8 | int sum = 0; 9 | int *arr; 10 | 11 | scanf("%d", &n); 12 | arr = (int*) malloc(n * sizeof(int)); 13 | 14 | for (int i = 0; i < n; i++) 15 | scanf("%d", &arr[i]); 16 | 17 | for (int i = 0; i < n; i++) 18 | sum += arr[i]; 19 | 20 | printf("%d\n", sum); 21 | 22 | free(arr); 23 | return 0; 24 | } -------------------------------------------------------------------------------- /python part1/alphabet-rangoli.py: -------------------------------------------------------------------------------- 1 | import string 2 | alpha = string.ascii_lowercase 3 | 4 | def print_rangoli(size): 5 | lines = [] 6 | for row in range(size): 7 | to_print = "-".join(alpha[row:size]) 8 | lines.append(to_print[::-1] + to_print[1:]) 9 | width = len(lines[0]) 10 | 11 | for row in range(size-1, 0, -1): 12 | print(lines[row].center(width, '-')) 13 | 14 | for row in range(size): 15 | print(lines[row].center(width, '-')) 16 | -------------------------------------------------------------------------------- /python part1/hex-color-code.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | n = int(input().strip()) 4 | inside = False 5 | for _ in range(n): 6 | line = input() 7 | 8 | for el in line.split(' '): 9 | if el == "{": 10 | inside = True 11 | continue 12 | elif el == "}": 13 | inside = False 14 | continue 15 | elif inside: 16 | found = re.search(r'\#[0-9a-fA-F]{3,6}', el) 17 | if found: 18 | print(found.group(0)) -------------------------------------------------------------------------------- /python part1/iterables-and-iterators.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import string 4 | symbols = string.ascii_lowercase 5 | 6 | from itertools import combinations 7 | 8 | if __name__ == "__main__": 9 | n = int(input().strip()) 10 | arr = list(map(str, input().strip().split(' '))) 11 | times = int(input().strip()) 12 | cmbts = list(combinations(sorted(arr), times)) 13 | 14 | print("{:.4f}".format(len(list(filter(lambda a: a[0] == 'a', cmbts)))/(len(cmbts)))) 15 | 16 | -------------------------------------------------------------------------------- /python part1/validating-credit-card-number.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | if __name__ == "__main__": 4 | t = int(input().strip()) 5 | 6 | for _ in range(t): 7 | num = "".join(input()) 8 | if (re.match(r'^[456]', num) and 9 | (re.match(r'([\d]{4}-){3}[\d]{4}$', num) or 10 | re.match(r'[\d]{16}', num)) and 11 | not re.search(r'(\d)\1{3,}', num.replace("-", ""))): 12 | print("Valid") 13 | else: 14 | print("Invalid") 15 | -------------------------------------------------------------------------------- /algorithms part2/mars-exploration.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def marsExploration(s): 6 | res = 0 7 | for ind in range(0, len(s), 3): 8 | if s[ind] != 'S': 9 | res += 1 10 | if s[ind+1] != 'O': 11 | res += 1 12 | if s[ind+2] != 'S': 13 | res += 1 14 | 15 | return res 16 | 17 | 18 | if __name__ == "__main__": 19 | s = input().strip() 20 | result = marsExploration(s) 21 | print(result) 22 | -------------------------------------------------------------------------------- /algorithms part2/permutation-equation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys 4 | 5 | def permutationEquation(p): 6 | output = [] 7 | 8 | for num in range(1, max(p)+1): 9 | output.append(p.index(p.index(num)+1)+1) 10 | 11 | return output 12 | 13 | 14 | if __name__ == "__main__": 15 | n = int(input().strip()) 16 | p = list(map(int, input().strip().split(' '))) 17 | result = permutationEquation(p) 18 | print ("\n".join(map(str, result))) 19 | 20 | 21 | -------------------------------------------------------------------------------- /algorithms part2/service-lane.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def check_interval(i, j): 6 | res = 3 7 | for inter in range(i, j + 1): 8 | res = min(res, width[inter]) 9 | 10 | return res 11 | 12 | n,t = input().strip().split(' ') 13 | n,t = [int(n),int(t)] 14 | width = [int(width_temp) for width_temp in input().strip().split(' ')] 15 | for a0 in range(t): 16 | i,j = input().strip().split(' ') 17 | i,j = [int(i),int(j)] 18 | 19 | print(check_interval(i, j)) 20 | -------------------------------------------------------------------------------- /python part1/nested-list.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | students = [] 3 | for _ in range(int(input())): 4 | name = input() 5 | score = float(input()) 6 | 7 | students.append([name, score]) 8 | 9 | lowest = min([el[1] for el in students]) 10 | second_low = min(list(filter(lambda a: a > lowest, [el[1] for el in students]))) 11 | 12 | out = [el[0] for el in students if (el[1] == second_low)] 13 | out.sort() 14 | 15 | print("\n".join(out)) 16 | -------------------------------------------------------------------------------- /algorithms part1/beautiful-triplets.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def beautifulTriplets(d, arr): 6 | res = 0 7 | 8 | for el in arr: 9 | if el + d in arr and el + 2*d in arr: 10 | res += 1 11 | 12 | return res 13 | 14 | 15 | if __name__ == "__main__": 16 | n, d = input().strip().split(' ') 17 | n, d = [int(n), int(d)] 18 | arr = list(map(int, input().strip().split(' '))) 19 | result = beautifulTriplets(d, arr) 20 | print(result) 21 | -------------------------------------------------------------------------------- /python part1/no-idea.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | happiness = 0 5 | n, m = map(int, input().strip().split(' ')) 6 | arr = list(map(int, input().strip().split(' '))) 7 | 8 | good = set(map(int, input().strip().split(' '))) 9 | bad = set(map(int, input().strip().split(' '))) 10 | 11 | for el in arr: 12 | if el in good: 13 | happiness += 1 14 | elif el in bad: 15 | happiness -= 1 16 | 17 | print(happiness) -------------------------------------------------------------------------------- /algorithms part2/minimum-absolute-difference-in-an-array.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def minimumAbsoluteDifference(n, arr): 6 | arr = sorted(arr) 7 | res = 10**9 8 | 9 | for ind in range(1, len(arr)): 10 | res = min(res, arr[ind] - arr[ind-1]) 11 | 12 | return res 13 | 14 | if __name__ == "__main__": 15 | n = int(input().strip()) 16 | arr = list(map(int, input().strip().split(' '))) 17 | result = minimumAbsoluteDifference(n, arr) 18 | print(result) 19 | -------------------------------------------------------------------------------- /c/too-high-boxes.c: -------------------------------------------------------------------------------- 1 | struct box { 2 | /** 3 | * Define three fields of type int: length, width and height 4 | */ 5 | int length, width, height; 6 | }; 7 | 8 | typedef struct box box; 9 | 10 | int get_volume(box b) { 11 | /** 12 | * Return the volume of the box 13 | */ 14 | return b.length * b.width * b.height; 15 | } 16 | 17 | int is_lower_than_max_height(box b) { 18 | /** 19 | * Return 1 if the box's height is lower than MAX_HEIGHT and 0 otherwise 20 | */ 21 | return (b.height < MAX_HEIGHT) ? 1 : 0; 22 | } -------------------------------------------------------------------------------- /python part1/word-order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from collections import OrderedDict 4 | 5 | if __name__ == "__main__": 6 | num = int(input().strip()) 7 | history = OrderedDict() 8 | 9 | for _ in range(num): 10 | word = str(input().strip().split()) 11 | if word not in history.keys(): 12 | history[word] = 1 13 | else: 14 | history[word] += 1 15 | 16 | print(len(history.keys())) 17 | print(" ".join(map(str, history.values()))) 18 | -------------------------------------------------------------------------------- /algorithms part1/big-sorting.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from bisect import insort 5 | 6 | def bigSorting(arr): 7 | return sorted(arr, key=int) 8 | 9 | if __name__ == "__main__": 10 | n = int(input().strip()) 11 | arr = [] 12 | arr_i = 0 13 | for arr_i in range(n): 14 | arr_t = input().strip() 15 | arr.append(arr_t) 16 | #insort(arr, arr_t) 17 | result = bigSorting(arr) 18 | print ("\n".join(map(str, result))) 19 | #print ("\n".join(map(str, arr))) 20 | 21 | -------------------------------------------------------------------------------- /algorithms part1/countingsort4.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | n = int(input().strip()) 7 | array = [] 8 | print_dict = {} 9 | for a0 in range(n): 10 | x, s = input().strip().split(' ') 11 | x, s = [int(x), str(s)] 12 | 13 | if a0 < n//2: 14 | array.append((x, "-")) 15 | else: 16 | array.append((x, s)) 17 | 18 | print(" ".join(map(lambda x: x[1], sorted(array, key = lambda x: x[0])))) 19 | -------------------------------------------------------------------------------- /cpp/c-tutorial-struct.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | struct Student { 9 | int age; 10 | string first_name, last_name; 11 | int standard; 12 | }; 13 | 14 | int main() { 15 | Student st; 16 | 17 | cin >> st.age >> st.first_name >> st.last_name >> st.standard; 18 | cout << st.age << " " << st.first_name << " " << st.last_name << " " << st.standard; 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /data-structures/array-left-rotation.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def leftRotation(a, d): 6 | out = list(a) 7 | a_len = len(a) 8 | for ind, el in enumerate(a): 9 | out[(ind + a_len - d) % a_len] = el 10 | 11 | return out 12 | 13 | if __name__ == "__main__": 14 | n, d = input().strip().split(' ') 15 | n, d = [int(n), int(d)] 16 | a = list(map(int, input().strip().split(' '))) 17 | result = leftRotation(a, d) 18 | print (" ".join(map(str, result))) 19 | 20 | 21 | -------------------------------------------------------------------------------- /algorithms part1/angry-professor.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def angryProfessor(k, a): 6 | res = 'NO' 7 | if len(list(filter(lambda x: x <= 0, a))) < k: 8 | res = 'YES' 9 | return res 10 | 11 | if __name__ == "__main__": 12 | t = int(input().strip()) 13 | for a0 in range(t): 14 | n, k = input().strip().split(' ') 15 | n, k = [int(n), int(k)] 16 | a = list(map(int, input().strip().split(' '))) 17 | result = angryProfessor(k, a) 18 | print(result) 19 | -------------------------------------------------------------------------------- /algorithms part2/jumping-on-the-clouds.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def jump(c): 6 | res = 0 7 | ind = 0 8 | 9 | while ind != len(c)-1: 10 | if ind != len(c)-2 and c[ind+2] == 0: 11 | ind += 2 12 | else: 13 | ind += 1 14 | res += 1 15 | 16 | return res 17 | 18 | 19 | if __name__ == "__main__": 20 | n = int(input().strip()) 21 | c = list(map(int, input().strip().split(' '))) 22 | result = jump(c) 23 | print(result) 24 | -------------------------------------------------------------------------------- /interview-preparation-kit/minimum-absolute-difference-in-an-array.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def minimumAbsoluteDifference(n, arr): 6 | arr = sorted(arr) 7 | res = 10**9 8 | 9 | for ind in range(1, len(arr)): 10 | res = min(res, arr[ind] - arr[ind-1]) 11 | 12 | return res 13 | 14 | if __name__ == "__main__": 15 | n = int(input().strip()) 16 | arr = list(map(int, input().strip().split(' '))) 17 | result = minimumAbsoluteDifference(n, arr) 18 | print(result) 19 | -------------------------------------------------------------------------------- /algorithms part1/bon-appetit.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def bonAppetit(n, skip, b, ar): 6 | sum_actual = 0 7 | 8 | ar.pop(skip) 9 | sum_actual = sum(ar)//2 10 | 11 | if sum_actual == b: 12 | return 'Bon Appetit' 13 | else: 14 | return b - sum_actual 15 | 16 | 17 | n, k = input().strip().split(' ') 18 | n, k = [int(n), int(k)] 19 | ar = list(map(int, input().strip().split(' '))) 20 | b = int(input().strip()) 21 | result = bonAppetit(n, k, b, ar) 22 | print(result) 23 | -------------------------------------------------------------------------------- /algorithms part2/sock-merchant.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def sockMerchant(n, ar): 6 | socks = {} 7 | res = 0 8 | 9 | for el in ar: 10 | if el not in socks.keys(): 11 | socks[el] = 1 12 | else: 13 | socks[el] += 1 14 | 15 | for key in socks.keys(): 16 | res += socks[key]//2 17 | 18 | return res 19 | 20 | n = int(input().strip()) 21 | ar = list(map(int, input().strip().split(' '))) 22 | result = sockMerchant(n, ar) 23 | print(result) 24 | -------------------------------------------------------------------------------- /interview-preparation-kit/jumping-on-the-clouds.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def jump(c): 6 | res = 0 7 | ind = 0 8 | 9 | while ind != len(c)-1: 10 | if ind != len(c)-2 and c[ind+2] == 0: 11 | ind += 2 12 | else: 13 | ind += 1 14 | res += 1 15 | 16 | return res 17 | 18 | 19 | if __name__ == "__main__": 20 | n = int(input().strip()) 21 | c = list(map(int, input().strip().split(' '))) 22 | result = jump(c) 23 | print(result) 24 | -------------------------------------------------------------------------------- /algorithms part2/game-of-thrones.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from collections import Counter 5 | 6 | def gameOfThrones(s): 7 | cnt = Counter(s) 8 | if len(s)%2 == 0: 9 | ret = all([x%2 == 0 for x in cnt.values()]) 10 | else: 11 | if len(list(filter(lambda x: x%2 == 1, cnt.values()))) == 1: 12 | ret = True 13 | else: 14 | ret = False 15 | 16 | return 'YES' if ret else 'NO' 17 | 18 | s = input().strip() 19 | result = gameOfThrones(s) 20 | print(result) 21 | -------------------------------------------------------------------------------- /algorithms part2/strange-advertising.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def calc_pattern(): 6 | max_n = 50 7 | ads = 5 8 | output = [] 9 | for i in range(max_n): 10 | output.append(ads//2) 11 | ads = (ads//2)*3 12 | 13 | return output 14 | 15 | def viralAdvertising(n, pattern): 16 | return sum(pattern[:n]) 17 | 18 | if __name__ == "__main__": 19 | n = int(input().strip()) 20 | pattern = calc_pattern() 21 | result = viralAdvertising(n, pattern) 22 | print(result) 23 | -------------------------------------------------------------------------------- /interview-preparation-kit/sock-merchant.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def sockMerchant(n, ar): 6 | socks = {} 7 | res = 0 8 | 9 | for el in ar: 10 | if el not in socks.keys(): 11 | socks[el] = 1 12 | else: 13 | socks[el] += 1 14 | 15 | for key in socks.keys(): 16 | res += socks[key]//2 17 | 18 | return res 19 | 20 | n = int(input().strip()) 21 | ar = list(map(int, input().strip().split(' '))) 22 | result = sockMerchant(n, ar) 23 | print(result) 24 | -------------------------------------------------------------------------------- /python part2/py-set-discard-remove-pop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | n = int(input()) 5 | s = set(map(int, input().split())) 6 | num_cmds = int(input()) 7 | 8 | for _ in range(num_cmds): 9 | cmd = list(input().strip().split(' ')) 10 | if cmd[0] == 'pop': 11 | s.pop() 12 | elif cmd[0] == 'remove': 13 | s.remove(int(cmd[1])) 14 | elif cmd[0] == 'discard': 15 | s.discard(int(cmd[1])) 16 | 17 | print(sum(s)) 18 | 19 | -------------------------------------------------------------------------------- /algorithms part1/alternating-characters.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def alternatingCharacters(s): 6 | string = list(s) 7 | last = string.pop() 8 | res = 0 9 | 10 | while string: 11 | newone = string.pop() 12 | if newone == last: 13 | res += 1 14 | else: 15 | last = newone 16 | 17 | return res 18 | 19 | q = int(input().strip()) 20 | for a0 in range(q): 21 | s = input().strip() 22 | result = alternatingCharacters(s) 23 | print(result) 24 | -------------------------------------------------------------------------------- /algorithms part2/divisible-sum-pairs.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from itertools import combinations 5 | 6 | def divisibleSumPairs(n, k, ar): 7 | res = 0 8 | comb = list(combinations(ar, 2)) 9 | 10 | for pair in comb: 11 | if sum(pair) % k == 0: 12 | res += 1 13 | 14 | return res 15 | 16 | 17 | 18 | n, k = input().strip().split(' ') 19 | n, k = [int(n), int(k)] 20 | ar = list(map(int, input().strip().split(' '))) 21 | result = divisibleSumPairs(n, k, ar) 22 | print(result) 23 | -------------------------------------------------------------------------------- /algorithms part2/jumping-on-the-clouds-revisited.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def jumpingOnClouds(c, k): 6 | cur = k % n 7 | energy = 100 - 1 - c[cur]*2 8 | 9 | while cur != 0: 10 | cur = (cur + k) % n 11 | energy -= 1 + c[cur]*2 12 | 13 | return energy 14 | 15 | if __name__ == "__main__": 16 | n, k = input().strip().split(' ') 17 | n, k = [int(n), int(k)] 18 | c = list(map(int, input().strip().split(' '))) 19 | result = jumpingOnClouds(c, k) 20 | print(result) 21 | -------------------------------------------------------------------------------- /cpp/c-tutorial-functions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | int max_of_four(int a, int b, int c, int d) { 7 | int ret = a; 8 | if (b > ret) 9 | ret = b; 10 | if (c > ret) 11 | ret = c; 12 | if (d > ret) 13 | ret = d; 14 | return ret; 15 | } 16 | 17 | 18 | int main() { 19 | int a, b, c, d; 20 | scanf("%d %d %d %d", &a, &b, &c, &d); 21 | int ans = max_of_four(a, b, c, d); 22 | printf("%d", ans); 23 | 24 | return 0; 25 | } 26 | 27 | -------------------------------------------------------------------------------- /data-structures/dynamic-array.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | if __name__ == "__main__": 4 | N, Q = map(int, input().strip().split(' ')) 5 | sequences = [[] for _ in range(N)] 6 | last_answer = 0 7 | 8 | for q in range(Q): 9 | q_type, x, y = map(int, input().strip().split(' ')) 10 | seq_num = (x ^ last_answer) % N 11 | 12 | if q_type == 2: 13 | last_answer = sequences[seq_num][y % len(sequences[seq_num])] 14 | print(last_answer) 15 | else: 16 | sequences[seq_num].append(y) -------------------------------------------------------------------------------- /data-structures/tree-height-of-a-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Enter your code here. Read input from STDIN. Print output to STDOUT 2 | ''' 3 | class Node: 4 | def __init__(self,info): 5 | self.info = info 6 | self.left = None 7 | self.right = None 8 | 9 | 10 | // this is a node of the tree , which contains info as data, left , right 11 | ''' 12 | def height(root): 13 | if root is not None: 14 | return max(1 + height(root.left), 1 + height(root.right)) 15 | else: 16 | return -1 17 | -------------------------------------------------------------------------------- /interview-preparation-kit/alternating-characters.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def alternatingCharacters(s): 6 | string = list(s) 7 | last = string.pop() 8 | res = 0 9 | 10 | while string: 11 | newone = string.pop() 12 | if newone == last: 13 | res += 1 14 | else: 15 | last = newone 16 | 17 | return res 18 | 19 | q = int(input().strip()) 20 | for a0 in range(q): 21 | s = input().strip() 22 | result = alternatingCharacters(s) 23 | print(result) 24 | -------------------------------------------------------------------------------- /cpp/vector-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main() { 10 | int n; 11 | vector vec; 12 | cin >> n; 13 | 14 | for (int i = 0; i < n; i++) { 15 | int tmp; 16 | cin >> tmp; 17 | vec.push_back(tmp); 18 | } 19 | 20 | sort(vec.begin(), vec.end()); 21 | 22 | for (int i = 0; i < n; i++) { 23 | cout << vec[i] << " "; 24 | } 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /algorithms part1/beautiful-days-at-the-movies.py: -------------------------------------------------------------------------------- 1 | #!/bin/python 2 | 3 | import sys 4 | 5 | def is_beautiful(num, k): 6 | rev_num = int(str(num)[::-1]) 7 | return abs(num - rev_num)%k == 0 8 | 9 | def beautifulDays(i, j, k): 10 | res = 0 11 | for num in range(i, j+1): 12 | if is_beautiful(num, k): 13 | res += 1 14 | return res 15 | 16 | if __name__ == "__main__": 17 | i, j, k = raw_input().strip().split(' ') 18 | i, j, k = [int(i), int(j), int(k)] 19 | result = beautifulDays(i, j, k) 20 | print result 21 | -------------------------------------------------------------------------------- /algorithms part2/minimum-distances.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def minimumDistances(array): 6 | res = -1 7 | memo = [-1] * (10**5 + 3) 8 | 9 | for ind, el in enumerate(array): 10 | if memo[el] >= 0: 11 | res = min(res if res >= 0 else 10**5 + 2, ind - memo[el]) 12 | memo[el] = ind 13 | 14 | return res 15 | 16 | if __name__ == "__main__": 17 | n = int(input().strip()) 18 | a = list(map(int, input().strip().split(' '))) 19 | result = minimumDistances(a) 20 | print(result) 21 | -------------------------------------------------------------------------------- /data-structures/tree-top-view.py: -------------------------------------------------------------------------------- 1 | """ 2 | Node is defined as 3 | self.left (the left child of the node) 4 | self.right (the right child of the node) 5 | self.data (the value of the node)""" 6 | 7 | def _topLeft(root): 8 | if root is not None: 9 | _topLeft(root.left) 10 | print root.data, 11 | 12 | def _topRight(root): 13 | if root is not None: 14 | print root.data, 15 | _topRight(root.right) 16 | 17 | def topView(root): 18 | _topLeft(root.left) 19 | print root.data, 20 | _topRight(root.right) 21 | 22 | -------------------------------------------------------------------------------- /interview-preparation-kit/tree-height-of-a-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Enter your code here. Read input from STDIN. Print output to STDOUT 2 | ''' 3 | class Node: 4 | def __init__(self,info): 5 | self.info = info 6 | self.left = None 7 | self.right = None 8 | 9 | 10 | // this is a node of the tree , which contains info as data, left , right 11 | ''' 12 | def height(root): 13 | if root is not None: 14 | return max(1 + height(root.left), 1 + height(root.right)) 15 | else: 16 | return -1 17 | -------------------------------------------------------------------------------- /python part1/collections-counter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from collections import Counter 4 | 5 | if __name__ == "__main__": 6 | X = int(input().strip()) 7 | shoes = list(map(int, input().strip().split())) 8 | N = int(input().strip()) 9 | result = 0 10 | 11 | warhs = Counter(shoes) 12 | for _ in range(N): 13 | size, money = map(int, input().strip().split(' ')) 14 | 15 | if warhs[size] > 0: 16 | result += money 17 | warhs[size] -= 1 18 | 19 | print(result) 20 | -------------------------------------------------------------------------------- /python part1/validating-uid.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | if __name__ == "__main__": 4 | t = int(input().strip()) 5 | 6 | for _ in range(t): 7 | uid = "".join(sorted(input())) 8 | if (len(uid) == 10 and 9 | re.match(r'', uid) and 10 | re.search(r'[A-Z]{2}', uid) and 11 | re.search(r'\d\d\d', uid) and 12 | not re.search(r'[^a-zA-Z0-9]', uid) and 13 | not re.search(r'(.)\1', uid)): 14 | print("Valid") 15 | else: 16 | print("Invalid") 17 | -------------------------------------------------------------------------------- /data-structures/qheap1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import heapq as hq 4 | from bisect import insort 5 | 6 | if __name__ == "__main__": 7 | t = int(input().strip()) 8 | q = [] 9 | 10 | for _ in range(t): 11 | args = input().strip().split() 12 | if args[0] == '1': 13 | insort(q, int(args[1])) 14 | #hq.heappush(q, int(args[1])) 15 | elif args[0] == '2': 16 | q.remove(int(args[1])) 17 | #hq.heapify(q) 18 | elif args[0] == '3': 19 | print(q[0]) 20 | -------------------------------------------------------------------------------- /python part1/defaultdict-tutorial.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from collections import defaultdict 4 | 5 | if __name__ == "__main__": 6 | n, m = map(int, input().strip().split(' ')) 7 | library = defaultdict(list) 8 | 9 | for ind in range(1, n + 1): 10 | word = input().strip() 11 | library[word].append(ind) 12 | 13 | for ind in range(m): 14 | word = input().strip() 15 | if len(library[word]) > 0: 16 | print(" ".join(map(str, library[word]))) 17 | else: 18 | print("-1") 19 | -------------------------------------------------------------------------------- /python part1/python-time-delta.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from datetime import datetime as dt 5 | 6 | dformat = "%a %d %b %Y %H:%M:%S %z" 7 | def time_delta(t1, t2): 8 | first = dt.strptime(t1, dformat) 9 | second = dt.strptime(t2, dformat) 10 | 11 | return int(abs((first - second).total_seconds())) 12 | 13 | if __name__ == "__main__": 14 | t = int(input().strip()) 15 | for a0 in range(t): 16 | t1 = input().strip() 17 | t2 = input().strip() 18 | delta = time_delta(t1, t2) 19 | print(delta) 20 | -------------------------------------------------------------------------------- /algorithms part1/chocolate-feast.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def wrappers(wr, m): 6 | res = 0 7 | if wr//m > 0: 8 | res += wr//m + wrappers(wr//m + wr%m, m) 9 | return res 10 | 11 | 12 | def chocolateFeast(n, c, m): 13 | return n//c + wrappers(n//c, m) 14 | 15 | 16 | if __name__ == "__main__": 17 | t = int(input().strip()) 18 | for a0 in range(t): 19 | n, c, m = input().strip().split(' ') 20 | n, c, m = [int(n), int(c), int(m)] 21 | result = chocolateFeast(n, c, m) 22 | print(result) 23 | -------------------------------------------------------------------------------- /algorithms part2/recursive-digit-sum.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def _digitSum(number): 6 | if len(number) == 1: 7 | return int(number) 8 | else: 9 | temp = str(sum([int(x) for x in number])) 10 | return _digitSum(temp) 11 | 12 | def digitSum(number, k): 13 | temp = str(k*sum([int(x) for x in number])) 14 | return _digitSum(temp) 15 | 16 | 17 | if __name__ == "__main__": 18 | n, k = input().strip().split(' ') 19 | n, k = [str(n), int(k)] 20 | result = digitSum(n, k) 21 | print(result) 22 | -------------------------------------------------------------------------------- /algorithms part2/sansa-and-xor.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def sansaXor(arr): 6 | res = 0 7 | arr_len = len(arr) 8 | 9 | if arr_len % 2 == 0: 10 | return 0 11 | 12 | for ind in range(0, arr_len, 2): 13 | res ^= arr[ind] 14 | 15 | return res 16 | 17 | if __name__ == "__main__": 18 | t = int(input().strip()) 19 | for a0 in range(t): 20 | n = int(input().strip()) 21 | arr = list(map(int, input().strip().split(' '))) 22 | result = sansaXor(arr) 23 | print(result) 24 | -------------------------------------------------------------------------------- /data-structures/truck-tour.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import queue 4 | 5 | if __name__ == "__main__": 6 | n = int(input().strip()) 7 | res = 0 8 | tank = 0 9 | q = queue.Queue() 10 | 11 | 12 | for ind in range(n): 13 | petr, dist = [int(arg) for arg in input().strip().split()] 14 | tank += petr 15 | 16 | if dist <= tank: 17 | tank -= dist 18 | else: 19 | tank = 0 20 | res = ind+1 21 | 22 | q.put((petr, dist)) 23 | 24 | print(res) -------------------------------------------------------------------------------- /interview-preparation-kit/ctci-comparator-sorting.py: -------------------------------------------------------------------------------- 1 | from functools import cmp_to_key 2 | class Player: 3 | def __init__(self, name, score): 4 | self.name = name 5 | self.score = score 6 | 7 | #def __repr__(self): 8 | # return 9 | 10 | def comparator(a, b): 11 | if (a.score < b.score): 12 | return 1 13 | if (a.score > b.score): 14 | return -1 15 | if (a.name < b.name): 16 | return -1 17 | if (a.name > b.name): 18 | return 1 19 | return 0 -------------------------------------------------------------------------------- /interview-preparation-kit/ctci-is-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | """ Node is defined as 2 | class node: 3 | def __init__(self, data): 4 | self.data = data 5 | self.left = None 6 | self.right = None 7 | """ 8 | 9 | def checkNode(node, min, max): 10 | if node == None: 11 | return True 12 | if node.data <= min or node.data >= max: 13 | return False 14 | return checkNode(node.left, min, node.data) and checkNode(node.right, node.data, max) 15 | 16 | def checkBST(root): 17 | return checkNode(root, float('-inf'), float('inf')) 18 | -------------------------------------------------------------------------------- /interview-preparation-kit/recursive-digit-sum.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def _digitSum(number): 6 | if len(number) == 1: 7 | return int(number) 8 | else: 9 | temp = str(sum([int(x) for x in number])) 10 | return _digitSum(temp) 11 | 12 | def digitSum(number, k): 13 | temp = str(k*sum([int(x) for x in number])) 14 | return _digitSum(temp) 15 | 16 | 17 | if __name__ == "__main__": 18 | n, k = input().strip().split(' ') 19 | n, k = [str(n), int(k)] 20 | result = digitSum(n, k) 21 | print(result) 22 | -------------------------------------------------------------------------------- /algorithms part1/cut-the-sticks.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def cutTheSticks(arr): 6 | out = [] 7 | while arr: 8 | out.append(len(arr)) 9 | arr_min = min(arr) 10 | arr = list(map(lambda x: x - arr_min, arr)) 11 | arr = list(filter(lambda x: x > 0, arr)) 12 | 13 | 14 | return out 15 | 16 | 17 | if __name__ == "__main__": 18 | n = int(input().strip()) 19 | arr = list(map(int, input().strip().split(' '))) 20 | result = cutTheSticks(arr) 21 | print ("\n".join(map(str, result))) 22 | 23 | 24 | -------------------------------------------------------------------------------- /algorithms part2/grading.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def solve(grades): 6 | res = [] 7 | 8 | for el in grades: 9 | if el < 38: 10 | res.append(el) 11 | elif el%5 >= 3: 12 | res.append(el + 5-el%5) 13 | else: 14 | res.append(el) 15 | return res 16 | 17 | n = int(input().strip()) 18 | grades = [] 19 | grades_i = 0 20 | for grades_i in range(n): 21 | grades_t = int(input().strip()) 22 | grades.append(grades_t) 23 | result = solve(grades) 24 | print ("\n".join(map(str, result))) 25 | 26 | 27 | -------------------------------------------------------------------------------- /algorithms part2/mark-and-toys.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def maximumToys(prices, k): 6 | prices = sorted(prices) 7 | res = 0 8 | 9 | for el in prices: 10 | if k - el >= 0: 11 | k -= el 12 | res += 1 13 | else: 14 | break 15 | 16 | return res 17 | 18 | 19 | if __name__ == "__main__": 20 | n, k = input().strip().split(' ') 21 | n, k = [int(n), int(k)] 22 | prices = list(map(int, input().strip().split(' '))) 23 | result = maximumToys(prices, k) 24 | print(result) 25 | -------------------------------------------------------------------------------- /data-structures/and-xor-or.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | def solution(arr): 4 | res = 0 5 | stack = [] 6 | 7 | for el in arr: 8 | while stack: 9 | res = max(res, el^stack[-1]) 10 | 11 | if el < stack[-1]: 12 | stack.pop() 13 | else: 14 | break 15 | stack.append(el) 16 | 17 | return res 18 | 19 | if __name__ == "__main__": 20 | n = int(input().strip()) 21 | arr = [int(x) for x in input().strip().split()] 22 | print(solution(arr)) -------------------------------------------------------------------------------- /c/for-loop-in-c.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | 7 | 8 | int main() 9 | { 10 | int a, b; 11 | const char *numbers[9] = {"one", "two", "three", "four", "five", 12 | "six", "seven", "eight", "nine"}; 13 | scanf("%d\n%d", &a, &b); 14 | 15 | for (int i = a; i <= b; i++) { 16 | if ((i > 0) && (i < 10)) 17 | printf("%s\n", numbers[i-1]); 18 | else 19 | printf("%s\n", (i%2) ? "odd" : "even"); 20 | } 21 | 22 | return 0; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /c/frequency-of-digits-1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | int freq[10]; 8 | char string[1000]; 9 | 10 | scanf("%s", &string); 11 | 12 | for (int i = 0; i < 10; i++) 13 | freq[i] = 0; 14 | 15 | for (int i = 0; i < strlen(string); i++) { 16 | int pos = string[i] - '0'; 17 | if (pos >= 0 && pos < 10) 18 | freq[pos]++; 19 | } 20 | 21 | for (int i = 0; i < 10; i++) 22 | printf("%d ", freq[i]); 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /python part1/the-minion-game.py: -------------------------------------------------------------------------------- 1 | vowels = ['A', 'E', 'I', 'O', 'U'] 2 | 3 | def minion_game(string): 4 | score_kevin = 0 5 | score_stuart = 0 6 | 7 | for ind in range(len(string)): 8 | if string[ind] in vowels: 9 | score_kevin += len(string) - ind 10 | else: 11 | score_stuart += len(string) - ind 12 | 13 | if score_kevin > score_stuart: 14 | print("Kevin {}".format(score_kevin)) 15 | elif score_kevin < score_stuart: 16 | print("Stuart {}".format(score_stuart)) 17 | else: 18 | print("Draw") 19 | -------------------------------------------------------------------------------- /algorithms part1/utopian-tree.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | answers = [1] 6 | 7 | def gen_answers(): 8 | newlen = 1 9 | for i in range(61): 10 | if i % 2 == 1: 11 | newlen += 1 12 | else: 13 | newlen *= 2 14 | answers.append(newlen) 15 | 16 | 17 | def utopianTree(n): 18 | return answers[n] 19 | 20 | if __name__ == "__main__": 21 | t = int(input().strip()) 22 | gen_answers() 23 | for a0 in range(t): 24 | n = int(input().strip()) 25 | result = utopianTree(n) 26 | print(result) 27 | -------------------------------------------------------------------------------- /data-structures/binary-search-tree-lowest-common-ancestor.py: -------------------------------------------------------------------------------- 1 | """ 2 | Node is defined as 3 | self.left (the left child of the node) 4 | self.right (the right child of the node) 5 | self.data (the value of the node) 6 | """ 7 | 8 | def lca(root , v1 , v2): 9 | vals = sorted([v1, v2]) 10 | v1, v2 = vals[0], vals[1] 11 | node = root 12 | while True: 13 | if v1 < v2 < node.data: 14 | node = node.left 15 | if v1 > v2 > node.data: 16 | node = node.right 17 | if v1 <= node.data <= v2: 18 | break 19 | return node 20 | 21 | -------------------------------------------------------------------------------- /interview-preparation-kit/mark-and-toys.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def maximumToys(prices, k): 6 | prices = sorted(prices) 7 | res = 0 8 | 9 | for el in prices: 10 | if k - el >= 0: 11 | k -= el 12 | res += 1 13 | else: 14 | break 15 | 16 | return res 17 | 18 | 19 | if __name__ == "__main__": 20 | n, k = input().strip().split(' ') 21 | n, k = [int(n), int(k)] 22 | prices = list(map(int, input().strip().split(' '))) 23 | result = maximumToys(prices, k) 24 | print(result) 25 | -------------------------------------------------------------------------------- /interview-preparation-kit/ctci-bubble-sort.py: -------------------------------------------------------------------------------- 1 | n = int(input().strip()) 2 | a = list(map(int, input().strip().split(' '))) 3 | 4 | 5 | def bub_sort(arr, n): 6 | num_swaps = 0 7 | for i in range(n): 8 | for j in range(n-1): 9 | if arr[j] > a[j+1]: 10 | buff = arr[j+1] 11 | arr[j+1] = a[j] 12 | a[j] = buff 13 | num_swaps += 1 14 | print("Array is sorted in {} swaps.".format(num_swaps)) 15 | print("First Element: {}".format(arr[0])) 16 | print("Last Element: {}".format(arr[-1])) 17 | 18 | bub_sort(a, n) -------------------------------------------------------------------------------- /interview-preparation-kit/binary-search-tree-lowest-common-ancestor.py: -------------------------------------------------------------------------------- 1 | """ 2 | Node is defined as 3 | self.left (the left child of the node) 4 | self.right (the right child of the node) 5 | self.data (the value of the node) 6 | """ 7 | 8 | def lca(root , v1 , v2): 9 | vals = sorted([v1, v2]) 10 | v1, v2 = vals[0], vals[1] 11 | node = root 12 | while True: 13 | if v1 < v2 < node.data: 14 | node = node.left 15 | if v1 > v2 > node.data: 16 | node = node.right 17 | if v1 <= node.data <= v2: 18 | break 19 | return node 20 | 21 | -------------------------------------------------------------------------------- /python part2/py-collections-namedtuple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from collections import namedtuple 4 | 5 | if __name__ == "__main__": 6 | s_num = int(input().strip()) 7 | tuple_fields = input().strip().split() 8 | 9 | student = namedtuple('student', tuple_fields) 10 | library = [] 11 | res = 0 12 | 13 | for _ in range(s_num): 14 | st_info = input().strip().split() 15 | library.append(student(st_info[0], st_info[1], st_info[2], st_info[3])) 16 | 17 | for el in library: 18 | res += int(el.MARKS) 19 | 20 | print(res/s_num) -------------------------------------------------------------------------------- /interview-preparation-kit/ctci-recursive-staircase.py: -------------------------------------------------------------------------------- 1 | def staircase(n): 2 | if n == 0: 3 | return 0 4 | if n == 1: 5 | return 1 6 | if n == 2: 7 | return 2 8 | if n == 3: 9 | return 4 10 | 11 | return staircase(n-1) + staircase(n-2) + staircase(n-3) 12 | 13 | def staircase_lin(n): 14 | st1, st2, st3 = 1, 2, 4 15 | 16 | for _ in range(n-1): 17 | st1, st2, st3 = st2, st3, st1 + st2 + st3 18 | 19 | return st1 20 | 21 | s = int(input().strip()) 22 | for a0 in range(s): 23 | n = int(input().strip()) 24 | print(staircase_lin(n)) -------------------------------------------------------------------------------- /algorithms part2/diagonal-difference.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def diagonalDifference(a): 6 | # compute primary diagonal 7 | n = len(a) 8 | diag_pr = diag_sec = 0 9 | for i in range(n): 10 | diag_pr += a[i][i] 11 | diag_sec += a[n-i-1][i] 12 | 13 | return abs(diag_pr - diag_sec) 14 | 15 | if __name__ == "__main__": 16 | n = int(input().strip()) 17 | a = [] 18 | for a_i in range(n): 19 | a_t = [int(a_temp) for a_temp in input().strip().split(' ')] 20 | a.append(a_t) 21 | result = diagonalDifference(a) 22 | print(result) 23 | -------------------------------------------------------------------------------- /algorithms part2/fair-rations.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def check(array): 6 | return len(list(filter(lambda x: x%2 == 0, array))) == len(array) 7 | 8 | def fairRations(B): 9 | res = 0 10 | 11 | for ind in range(len(B)-1): 12 | if B[ind]%2 == 1: 13 | B[ind] += 1 14 | B[ind+1] += 1 15 | res += 2 16 | 17 | return res if check(B) else 'NO' 18 | 19 | if __name__ == "__main__": 20 | N = int(input().strip()) 21 | B = list(map(int, input().strip().split(' '))) 22 | result = fairRations(B) 23 | print(result) 24 | -------------------------------------------------------------------------------- /algorithms part1/cats-and-a-mouse.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def catAndMouse(x, y, z): 6 | cat_a = abs(x - z) 7 | cat_b = abs(y - z) 8 | 9 | if cat_a < cat_b: 10 | return "Cat A" 11 | elif cat_a > cat_b: 12 | return "Cat B" 13 | else: 14 | return "Mouse C" 15 | 16 | if __name__ == "__main__": 17 | q = int(input().strip()) 18 | for a0 in range(q): 19 | x, y, z = input().strip().split(' ') 20 | x, y, z = [int(x), int(y), int(z)] 21 | result = catAndMouse(x, y, z) 22 | print ("".join(map(str, result))) 23 | 24 | 25 | -------------------------------------------------------------------------------- /algorithms part2/strange-code.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import os 4 | import sys 5 | import math 6 | 7 | # 8 | # Complete the strangeCounter function below. 9 | # 10 | def strangeCounter(t): 11 | base = math.log2((t + 2)/3) 12 | val_top = 3*2**(math.floor(base)) 13 | print("base = {} base_t = {}".format(base, val_top)) 14 | 15 | return val_top - (t - (val_top-2)) 16 | 17 | if __name__ == '__main__': 18 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 19 | 20 | t = int(input()) 21 | 22 | result = strangeCounter(t) 23 | 24 | fptr.write(str(result) + '\n') 25 | 26 | fptr.close() 27 | -------------------------------------------------------------------------------- /data-structures/crush.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | n, m = input().strip().split(' ') 7 | n, m = [int(n), int(m)] 8 | array = [0] * (n+1) 9 | for a0 in range(m): 10 | a, b, k = input().strip().split(' ') 11 | a, b, k = [int(a), int(b), int(k)] 12 | 13 | array[a-1] += k 14 | if b+1 <= n: 15 | array[b] -= k 16 | 17 | res_max = 0 18 | res = 0 19 | for dif in array: 20 | res += dif 21 | res_max = max(res_max, res) 22 | 23 | print(res_max) 24 | 25 | 26 | -------------------------------------------------------------------------------- /data-structures/jim-and-the-skyscrapers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys 4 | 5 | def solution(arr): 6 | res = 0 7 | st = [] 8 | 9 | for ind in range(len(arr)): 10 | while st and st[-1][0] < arr[ind]: 11 | st.pop() 12 | if st and arr[ind] == st[-1][0]: 13 | res += st[-1][1] 14 | st[-1][1] += 1 15 | else: 16 | st.append([arr[ind], 1]) 17 | 18 | return 2*res 19 | 20 | if __name__ == "__main__": 21 | n = int(input().strip()) 22 | arr = [int(x) for x in input().strip().split()] 23 | print(solution(arr)) 24 | -------------------------------------------------------------------------------- /algorithms part2/halloween-sale.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | def how_many_games(p, d, m, s): 10 | res = 0 11 | 12 | while s > 0: 13 | res += 1 14 | s -= p 15 | p = max(p - d, m) 16 | 17 | if s != 0: 18 | res -= 1 19 | 20 | return res 21 | 22 | 23 | if __name__ == '__main__': 24 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 25 | p, d, m, s = [int(n) for n in input().split(" ")] 26 | 27 | answer = how_many_games(p, d, m, s) 28 | 29 | fptr.write(str(answer) + '\n') 30 | fptr.close() 31 | -------------------------------------------------------------------------------- /algorithms part2/making-anagrams.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from collections import Counter 5 | 6 | def makingAnagrams(s1, s2): 7 | res = 0 8 | 9 | cnt1 = Counter(s1) 10 | cnt2 = Counter(s2) 11 | cnt3 = {} 12 | 13 | for let, val in cnt1.items(): 14 | cnt3[let] = abs(val - cnt2[let]) 15 | for let, val in cnt2.items(): 16 | cnt3[let] = abs(val - cnt1[let]) 17 | 18 | for el in cnt3.values(): 19 | res += el 20 | 21 | return res 22 | 23 | 24 | s1 = input().strip() 25 | s2 = input().strip() 26 | result = makingAnagrams(s1, s2) 27 | print(result) 28 | -------------------------------------------------------------------------------- /algorithms part2/plus-minus.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def plusMinus(arr): 6 | arrlen = len(arr) 7 | positive = negative = zeros = 0 8 | 9 | for elem in arr: 10 | if elem > 0: 11 | positive += 1 12 | elif elem < 0: 13 | negative += 1 14 | else: 15 | zeros += 1 16 | 17 | print("{:.6f}\n{:.6f}\n{:.6f}".format(positive/arrlen, negative/arrlen, zeros/arrlen)) 18 | 19 | 20 | if __name__ == "__main__": 21 | n = int(input().strip()) 22 | arr = list(map(int, input().strip().split(' '))) 23 | plusMinus(arr) 24 | -------------------------------------------------------------------------------- /interview-preparation-kit/crush.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | n, m = input().strip().split(' ') 7 | n, m = [int(n), int(m)] 8 | array = [0] * (n+1) 9 | for a0 in range(m): 10 | a, b, k = input().strip().split(' ') 11 | a, b, k = [int(a), int(b), int(k)] 12 | 13 | array[a-1] += k 14 | if b+1 <= n: 15 | array[b] -= k 16 | 17 | res_max = 0 18 | res = 0 19 | for dif in array: 20 | res += dif 21 | res_max = max(res_max, res) 22 | 23 | print(res_max) 24 | 25 | 26 | -------------------------------------------------------------------------------- /interview-preparation-kit/ctci-linked-list-cycle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty. 3 | 4 | A Node is defined as: 5 | 6 | class Node(object): 7 | def __init__(self, data = None, next_node = None): 8 | self.data = data 9 | self.next = next_node 10 | """ 11 | 12 | 13 | def has_cycle(head): 14 | curr = head 15 | 16 | seen = set() 17 | 18 | while curr: 19 | if curr in seen: 20 | return True 21 | 22 | seen.add(curr) 23 | curr = curr.next 24 | return False 25 | -------------------------------------------------------------------------------- /python part2/py-collections-ordereddict.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from collections import OrderedDict 4 | 5 | if __name__ == "__main__": 6 | num = int(input().strip()) 7 | history = OrderedDict() 8 | 9 | for _ in range(num): 10 | get_log = input().strip().split() 11 | good = " ".join(get_log[:-1]) 12 | sold = int(get_log[-1]) 13 | if good not in history.keys(): 14 | history[good] = sold 15 | else: 16 | history[good] += sold 17 | 18 | 19 | for key in history.keys(): 20 | print("{} {}".format(key, history[key])) 21 | -------------------------------------------------------------------------------- /cpp/c-tutorial-for-loop.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | int start, end; 7 | const string Digits[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; 8 | cin >> start; 9 | cin >> end; 10 | 11 | for (int i = start; i <= end; i++) { 12 | if (i > 9) { 13 | if (i%2) 14 | cout << "odd" << endl; 15 | else 16 | cout << "even" << endl; 17 | continue; 18 | } 19 | cout << Digits[i] << endl; 20 | } 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /python part1/detect-html-tags-attributes-and-attribute-values.py: -------------------------------------------------------------------------------- 1 | from html.parser import HTMLParser 2 | 3 | class MyHTMLParser(HTMLParser): 4 | def handle_starttag(self, tag, attrs): 5 | print(tag) 6 | for at in attrs: 7 | print("-> {} > {}".format(at[0], at[1])) 8 | def handle_startendtag(self, tag, attrs): 9 | print(tag) 10 | for at in attrs: 11 | print("-> {} > {}".format(at[0], at[1])) 12 | 13 | html = "" 14 | for i in range(int(input())): 15 | html += input().rstrip() 16 | html += '\n' 17 | 18 | parser = MyHTMLParser() 19 | parser.feed(html) 20 | parser.close() 21 | -------------------------------------------------------------------------------- /data-structures/is-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | """ Node is defined as 2 | class node: 3 | def __init__(self, data): 4 | self.data = data 5 | self.left = None 6 | self.right = None 7 | """ 8 | def inOrder(root): 9 | if root is not None: 10 | out = [] 11 | out += inOrder(root.left) 12 | out.append(root.data) 13 | #print(root.data, end=' ') 14 | out += inOrder(root.right) 15 | return out 16 | else: 17 | return [] 18 | 19 | def check_binary_search_tree_(root): 20 | get_ordered = inOrder(root) 21 | return get_ordered == sorted(list(set(get_ordered))) 22 | 23 | -------------------------------------------------------------------------------- /algorithms part2/flatland-space-stations.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def flatlandSpaceStations(n, stations): 6 | stations = sorted(stations) 7 | res = stations[0] 8 | 9 | for ind in range(1, len(stations)): 10 | res = max(res, (stations[ind] - stations[ind-1])//2) 11 | 12 | res = max(res, n-1 - stations[-1]) 13 | 14 | return res 15 | 16 | 17 | 18 | if __name__ == "__main__": 19 | n, m = input().strip().split(' ') 20 | n, m = [int(n), int(m)] 21 | c = list(map(int, input().strip().split(' '))) 22 | result = flatlandSpaceStations(n, c) 23 | print(result) 24 | -------------------------------------------------------------------------------- /python part1/html-parser-part-2.py: -------------------------------------------------------------------------------- 1 | from html.parser import HTMLParser 2 | 3 | class MyHTMLParser(HTMLParser): 4 | def handle_comment(self, data): 5 | if data.count('\n') > 0: 6 | print(">>> Multi-line Comment") 7 | else: 8 | print(">>> Single-line Comment") 9 | print(data) 10 | def handle_data(self, data): 11 | if len(data) > 1: 12 | print(">>> Data") 13 | print(data) 14 | 15 | html = "" 16 | for i in range(int(input())): 17 | html += input().rstrip() 18 | html += '\n' 19 | 20 | parser = MyHTMLParser() 21 | parser.feed(html) 22 | parser.close() 23 | -------------------------------------------------------------------------------- /algorithms part2/hackerrank-in-a-string.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def hackerrankInString(s): 6 | hckr = list('hackerrank') 7 | index = 0 8 | res = '' 9 | 10 | for let in s: 11 | if index == len(hckr): 12 | break 13 | if let == hckr[index]: 14 | index += 1 15 | 16 | if index == len(hckr): 17 | res = 'YES' 18 | else: 19 | res = 'NO' 20 | return res 21 | 22 | if __name__ == "__main__": 23 | q = int(input().strip()) 24 | for a0 in range(q): 25 | s = input().strip() 26 | result = hackerrankInString(s) 27 | print(result) 28 | -------------------------------------------------------------------------------- /algorithms part2/quicksort1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def quickSort(arr): 6 | left = [] 7 | equal = [] 8 | right = [] 9 | pivot = arr[0] 10 | 11 | for el in arr: 12 | if el < pivot: 13 | left.append(el) 14 | elif el == pivot: 15 | equal.append(el) 16 | elif el > pivot: 17 | right.append(el) 18 | 19 | return left + equal + right 20 | 21 | if __name__ == "__main__": 22 | n = int(input().strip()) 23 | arr = list(map(int, input().strip().split(' '))) 24 | result = quickSort(arr) 25 | print (" ".join(map(str, result))) 26 | 27 | 28 | -------------------------------------------------------------------------------- /algorithms part2/sherlock-and-array.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def solve(arr): 6 | res = 'NO' 7 | right = sum(arr) 8 | left = 0 9 | 10 | for el in arr: 11 | right -= el 12 | 13 | #print("left = {} el = {} right = {}".format(left, el, right)) 14 | if right == left: 15 | res = 'YES' 16 | break 17 | 18 | left += el 19 | 20 | return res 21 | 22 | T = int(input().strip()) 23 | for a0 in range(T): 24 | n = int(input().strip()) 25 | a = list(map(int, input().strip().split(' '))) 26 | result = solve(a) 27 | print(result) 28 | -------------------------------------------------------------------------------- /algorithms part2/sherlock-and-the-beast.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def find_number(n): 6 | three = n//3 7 | 8 | while (n - 3*three)%5 != 0: 9 | #print("three = {} five = {}".format(three, (n - 3*three)//5)) 10 | three -= 1 11 | 12 | if three > 0: 13 | res = [5] * 3 * three 14 | res += [3] * (n - 3*three) 15 | elif three == 0 and n%5 == 0: 16 | res = [3] * n 17 | else: 18 | res = [-1] 19 | 20 | return res 21 | 22 | 23 | t = int(input().strip()) 24 | for a0 in range(t): 25 | n = int(input().strip()) 26 | print("".join(map(str, find_number(n)))) 27 | -------------------------------------------------------------------------------- /algorithms part1/breaking-best-and-worst-records.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def breakingRecords(score): 6 | arr_max = [score[0]] 7 | arr_min = [score[0]] 8 | 9 | for el in score[1:]: 10 | if el < arr_min[-1]: 11 | arr_min.append(el) 12 | if el > arr_max[-1]: 13 | arr_max.append(el) 14 | 15 | return str(len(arr_max)-1), str(len(arr_min)-1) 16 | 17 | 18 | if __name__ == "__main__": 19 | n = int(input().strip()) 20 | score = list(map(int, input().strip().split(' '))) 21 | result = breakingRecords(score) 22 | print (" ".join(map(str, result))) 23 | 24 | 25 | -------------------------------------------------------------------------------- /c/recursion-in-c.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int find_nth_term(int n, int a, int b, int c) { 7 | if (n == 1) 8 | return a; 9 | else if (n == 2) 10 | return b; 11 | else if (n == 3) 12 | return c; 13 | else 14 | return find_nth_term(n-1, a, b, c) + 15 | find_nth_term(n-2, a, b, c) + 16 | find_nth_term(n-3, a, b, c); 17 | } 18 | 19 | int main() { 20 | int n, a, b, c; 21 | 22 | scanf("%d %d %d %d", &n, &a, &b, &c); 23 | int ans = find_nth_term(n, a, b, c); 24 | 25 | printf("%d", ans); 26 | return 0; 27 | } -------------------------------------------------------------------------------- /cpp/vector-erase.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main() { 10 | int n, pos, right, left; 11 | cin >> n; 12 | vector vec(n); 13 | 14 | for (int i = 0; i < n; i++) 15 | cin >> vec[i]; 16 | 17 | cin >> pos; 18 | cin >> left >> right; 19 | vec.erase(vec.begin() + pos - 1); 20 | vec.erase(vec.begin() + left - 1, vec.begin() + right - 1); 21 | 22 | cout << vec.size() << endl; 23 | for (int i = 0; i < vec.size(); i++) 24 | cout << vec[i] << " "; 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /algorithms part1/counting-valleys.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def countingValleys(n, s): 6 | res = 0 7 | in_valley = 0 8 | curr = 0 9 | 10 | for step in s: 11 | if step == 'U': 12 | curr += 1 13 | else: 14 | curr -= 1 15 | 16 | if curr < 0 and in_valley == 0: 17 | in_valley = 1 18 | if in_valley == 1 and curr == 0: 19 | in_valley = 0 20 | res += 1 21 | 22 | return res 23 | 24 | if __name__ == "__main__": 25 | n = int(input().strip()) 26 | s = input().strip() 27 | result = countingValleys(n, s) 28 | print(result) 29 | -------------------------------------------------------------------------------- /algorithms part1/angry-children.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def angryChildren(k, arr): 6 | arr = sorted(arr) 7 | res = arr[-1] 8 | 9 | for ind in range(len(arr)-k+1): 10 | res = min(res, arr[ind+k-1] - arr[ind]) 11 | #print("ind = {} arr = {} res = {}".format(ind, arr[ind:ind+k], res)) 12 | 13 | return res 14 | 15 | 16 | if __name__ == "__main__": 17 | n = int(input().strip()) 18 | k = int(input().strip()) 19 | arr = [] 20 | arr_i = 0 21 | for arr_i in range(n): 22 | arr_t = int(input().strip()) 23 | arr.append(arr_t) 24 | result = angryChildren(k, arr) 25 | print(result) 26 | -------------------------------------------------------------------------------- /cpp/variable-sized-arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main() { 10 | int n, q; 11 | 12 | cin >> n >> q; 13 | 14 | vector> array(n); 15 | 16 | for (int i = 0; i < n; i++) { 17 | int k; 18 | cin >> k; 19 | 20 | array[i].resize(k); 21 | for (int j = 0; j < k; j++) 22 | cin >> array[i][j]; 23 | } 24 | 25 | for (int i = 0; i < q; i++) { 26 | int row, col; 27 | cin >> row >> col; 28 | cout << array[row][col] << endl; 29 | } 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /interview-preparation-kit/counting-valleys.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def countingValleys(n, s): 6 | res = 0 7 | in_valley = 0 8 | curr = 0 9 | 10 | for step in s: 11 | if step == 'U': 12 | curr += 1 13 | else: 14 | curr -= 1 15 | 16 | if curr < 0 and in_valley == 0: 17 | in_valley = 1 18 | if in_valley == 1 and curr == 0: 19 | in_valley = 0 20 | res += 1 21 | 22 | return res 23 | 24 | if __name__ == "__main__": 25 | n = int(input().strip()) 26 | s = input().strip() 27 | result = countingValleys(n, s) 28 | print(result) 29 | -------------------------------------------------------------------------------- /interview-preparation-kit/ctci-queue-using-two-stacks.py: -------------------------------------------------------------------------------- 1 | class MyQueue(object): 2 | def __init__(self): 3 | self.q = [] 4 | 5 | def peek(self): 6 | return self.q[0] 7 | 8 | def pop(self): 9 | self.q.pop(0) 10 | 11 | def put(self, value): 12 | self.q.append(value) 13 | 14 | 15 | queue = MyQueue() 16 | t = int(input()) 17 | for line in range(t): 18 | values = map(int, input().split()) 19 | values = list(values) 20 | if values[0] == 1: 21 | queue.put(values[1]) 22 | elif values[0] == 2: 23 | queue.pop() 24 | else: 25 | print(queue.peek()) 26 | 27 | -------------------------------------------------------------------------------- /algorithms part2/insertionsort1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def insertionSort1(n, arr): 6 | probe = arr[-1] 7 | 8 | for ind in range(len(arr)-2, -1, -1): 9 | if arr[ind] > probe: 10 | arr[ind+1] = arr[ind] 11 | print(" ".join(map(str, arr))) 12 | else: 13 | arr[ind+1] = probe 14 | print(" ".join(map(str, arr))) 15 | break 16 | if arr[0] > probe: 17 | arr[0] = probe 18 | print(" ".join(map(str, arr))) 19 | 20 | if __name__ == "__main__": 21 | n = int(input().strip()) 22 | arr = list(map(int, input().strip().split(' '))) 23 | insertionSort1(n, arr) 24 | -------------------------------------------------------------------------------- /algorithms part2/library-fine.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def libraryFine(d1, m1, y1, d2, m2, y2): 6 | fine = 0 7 | 8 | if y1 > y2: 9 | fine = 10000 10 | elif m1 > m2 and y1 == y2: 11 | fine = 500 * (m1 - m2) 12 | elif d1 > d2 and m1 == m2 and y1 == y2: 13 | fine = 15 * (d1 - d2) 14 | 15 | return fine 16 | 17 | if __name__ == "__main__": 18 | d1, m1, y1 = input().strip().split(' ') 19 | d1, m1, y1 = [int(d1), int(m1), int(y1)] 20 | d2, m2, y2 = input().strip().split(' ') 21 | d2, m2, y2 = [int(d2), int(m2), int(y2)] 22 | result = libraryFine(d1, m1, y1, d2, m2, y2) 23 | print(result) 24 | -------------------------------------------------------------------------------- /data-structures/detect-whether-a-linked-list-contains-a-cycle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty. 3 | 4 | A Node is defined as: 5 | 6 | class Node(object): 7 | def __init__(self, data = None, next_node = None): 8 | self.data = data 9 | self.next = next_node 10 | """ 11 | 12 | 13 | def has_cycle(head): 14 | cnt = 0 15 | node = head 16 | 17 | if head is None: 18 | return 0 19 | 20 | while node != None: 21 | node = node.next 22 | cnt += 1 23 | if cnt > 100: 24 | return 1 25 | 26 | return 0 27 | 28 | -------------------------------------------------------------------------------- /data-structures/maximum-element.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | stack = [] 5 | ops_cnt = int(input().strip()) 6 | max_elem = 0 7 | 8 | for _ in range(ops_cnt): 9 | args = list(map(int, input().strip().split())) 10 | 11 | if args[0] == 1: 12 | max_elem = max(max_elem, args[1]) 13 | stack.append(args[1]) 14 | if args[0] == 2: 15 | if stack.pop() == max_elem: 16 | if len(stack) > 0: 17 | max_elem = max(stack) 18 | else: 19 | max_elem = 0 20 | if args[0] == 3: 21 | print(max_elem) -------------------------------------------------------------------------------- /data-structures/2d-array.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | arr = [] 7 | for arr_i in range(6): 8 | arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')] 9 | arr.append(arr_t) 10 | 11 | 12 | best = 0 13 | for ind_i in range(6-2): 14 | for ind_j in range(6-2): 15 | temp = 0 16 | temp += arr[ind_i][ind_j] + arr[ind_i][ind_j+1] + arr[ind_i][ind_j+2] 17 | temp += arr[ind_i+1][ind_j+1] 18 | temp += arr[ind_i+2][ind_j] + arr[ind_i+2][ind_j+1] + arr[ind_i+2][ind_j+2] 19 | if ind_i == 0 and ind_j == 0: 20 | best = temp 21 | else: 22 | best = max(best, temp) 23 | 24 | print(best) -------------------------------------------------------------------------------- /interview-preparation-kit/angry-children.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def angryChildren(k, arr): 6 | arr = sorted(arr) 7 | res = arr[-1] 8 | 9 | for ind in range(len(arr)-k+1): 10 | res = min(res, arr[ind+k-1] - arr[ind]) 11 | #print("ind = {} arr = {} res = {}".format(ind, arr[ind:ind+k], res)) 12 | 13 | return res 14 | 15 | 16 | if __name__ == "__main__": 17 | n = int(input().strip()) 18 | k = int(input().strip()) 19 | arr = [] 20 | arr_i = 0 21 | for arr_i in range(n): 22 | arr_t = int(input().strip()) 23 | arr.append(arr_t) 24 | result = angryChildren(k, arr) 25 | print(result) 26 | -------------------------------------------------------------------------------- /data-structures/insert-a-node-at-the-head-of-a-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Insert Node at the begining of a linked list 3 | head input could be None as well for empty list 4 | Node is defined as 5 | 6 | class Node(object): 7 | 8 | def __init__(self, data=None, next_node=None): 9 | self.data = data 10 | self.next = next_node 11 | 12 | return back the head of the linked list in the below method. 13 | """ 14 | 15 | def Insert(head, data): 16 | if head is None: 17 | head = Node(data) 18 | return head 19 | else: 20 | buf = head 21 | 22 | head = Node(data) 23 | head.next = buf 24 | 25 | return head 26 | -------------------------------------------------------------------------------- /c/small-triangles-large-triangles.c: -------------------------------------------------------------------------------- 1 | double get_volume(triangle tr) { 2 | double p, a, b, c; 3 | a = (double) tr.a; 4 | b = (double) tr.b; 5 | c = (double) tr.c; 6 | p = (a + b + c)/2; 7 | 8 | /* don't return sqrt() as it doesn't change the order */ 9 | return p*(p - a)*(p - b)*(p - c); 10 | } 11 | 12 | int cmp_func(const void *a, const void *b) { 13 | triangle *ia = (triangle *) a; 14 | triangle *ib = (triangle *) b; 15 | 16 | return (int)(get_volume(*ia) - get_volume(*ib)); 17 | } 18 | 19 | void sort_by_area(triangle *tr, int n) { 20 | /** 21 | * Sort an array a of the length n 22 | */ 23 | qsort((void *) tr, n, sizeof(triangle), cmp_func); 24 | } -------------------------------------------------------------------------------- /cpp/c-tutorial-stringstream.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | vector parseInts(string str) { 7 | int n = str.size(); 8 | int i = 1; 9 | stringstream ss(str); 10 | vector out; 11 | while (ss) { 12 | char ch; 13 | int num; 14 | ss >> num; 15 | out.push_back(num); 16 | ss >> ch; 17 | } 18 | return out; 19 | } 20 | 21 | int main() { 22 | string str; 23 | cin >> str; 24 | vector integers = parseInts(str); 25 | for(int i = 0; i < integers.size(); i++) { 26 | cout << integers[i] << "\n"; 27 | } 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /data-structures/delete-a-node-from-a-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Delete Node at a given position in a linked list 3 | Node is defined as 4 | 5 | class Node(object): 6 | 7 | def __init__(self, data=None, next_node=None): 8 | self.data = data 9 | self.next = next_node 10 | 11 | return back the head of the linked list in the below method. 12 | """ 13 | 14 | def Delete(head, position): 15 | if position == 0: 16 | head = head.next 17 | else: 18 | node = head 19 | for _ in range(position-1): 20 | node = node.next 21 | 22 | node.next = node.next.next 23 | 24 | return head 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /interview-preparation-kit/2d-array.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | arr = [] 7 | for arr_i in range(6): 8 | arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')] 9 | arr.append(arr_t) 10 | 11 | 12 | best = 0 13 | for ind_i in range(6-2): 14 | for ind_j in range(6-2): 15 | temp = 0 16 | temp += arr[ind_i][ind_j] + arr[ind_i][ind_j+1] + arr[ind_i][ind_j+2] 17 | temp += arr[ind_i+1][ind_j+1] 18 | temp += arr[ind_i+2][ind_j] + arr[ind_i+2][ind_j+1] + arr[ind_i+2][ind_j+2] 19 | if ind_i == 0 and ind_j == 0: 20 | best = temp 21 | else: 22 | best = max(best, temp) 23 | 24 | print(best) -------------------------------------------------------------------------------- /data-structures/jesse-and-cookies.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import heapq as hq 4 | 5 | if __name__ == "__main__": 6 | n, k = map(int, input().strip().split(' ')) 7 | candies = list(map(int, input().strip().split(' '))) 8 | q = [] 9 | res = 0 10 | 11 | for el in candies: 12 | hq.heappush(q, el) 13 | 14 | while any(c < k for c in q) and len(q) > 1: 15 | last = hq.heappop(q) 16 | prelast = hq.heappop(q) 17 | 18 | new = last + 2*prelast 19 | 20 | hq.heappush(q, new) 21 | res += 1 22 | 23 | if all(c >= k for c in q): 24 | print(res) 25 | else: 26 | print(-1) 27 | -------------------------------------------------------------------------------- /data-structures/reverse-a-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reverse a linked list 3 | head could be None as well for empty list 4 | Node is defined as 5 | 6 | class Node(object): 7 | 8 | def __init__(self, data=None, next_node=None): 9 | self.data = data 10 | self.next = next_node 11 | 12 | return back the head of the linked list in the below method. 13 | """ 14 | 15 | def Reverse(head): 16 | prev = None 17 | node = head 18 | while node is not None: 19 | buf = node.next 20 | node.next = prev 21 | prev = node 22 | node = buf 23 | 24 | head = prev 25 | return head 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /algorithms part2/insertionsort2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def insertionSort1(start, arr): 6 | probe = arr[start] 7 | 8 | for ind in range(start-1, -1, -1): 9 | if arr[ind] > probe: 10 | arr[ind+1] = arr[ind] 11 | else: 12 | arr[ind+1] = probe 13 | break 14 | if arr[0] > probe: 15 | arr[0] = probe 16 | 17 | def insertionSort2(n, arr): 18 | for ind in range(1, len(arr)): 19 | insertionSort1(ind, arr) 20 | print(" ".join(map(str, arr))) 21 | 22 | if __name__ == "__main__": 23 | n = int(input().strip()) 24 | arr = list(map(int, input().strip().split(' '))) 25 | insertionSort2(n, arr) 26 | -------------------------------------------------------------------------------- /algorithms part2/nim-game-1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | from functools import reduce 9 | 10 | def nimGame(pile): 11 | res = reduce((lambda x, y: x ^ y), pile) 12 | 13 | if res == 0: 14 | return 'Second' 15 | else: 16 | return 'First' 17 | 18 | 19 | if __name__ == '__main__': 20 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 21 | 22 | g = int(input()) 23 | 24 | for g_itr in range(g): 25 | n = int(input()) 26 | 27 | pile = list(map(int, input().rstrip().split())) 28 | 29 | result = nimGame(pile) 30 | 31 | fptr.write(result + '\n') 32 | 33 | fptr.close() 34 | -------------------------------------------------------------------------------- /python part1/class-2-find-the-torsional-angle.py: -------------------------------------------------------------------------------- 1 | class Points(object): 2 | def __init__(self, x, y, z): 3 | self.x, self.y, self.z = x, y, z 4 | 5 | def __sub__(self, no): 6 | return Points(self.x - no.x, 7 | self.y - no.y, 8 | self.z - no.z) 9 | 10 | def dot(self, no): 11 | return self.x*no.x + self.y*no.y + self.z*no.z 12 | 13 | def cross(self, no): 14 | return Points(self.y*no.z - self.z*no.y, 15 | self.z*no.x - self.x*no.z, 16 | self.y*no.x - self.x*no.y) 17 | 18 | def absolute(self): 19 | return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5) 20 | -------------------------------------------------------------------------------- /python part2/py-collections-deque.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from collections import deque 4 | 5 | if __name__ == "__main__": 6 | num = int(input().strip()) 7 | deq = deque() 8 | 9 | for _ in range(num): 10 | args = input().strip().split() 11 | 12 | if args[0] == 'append': 13 | deq.append(args[1]) 14 | elif args[0] == 'appendleft': 15 | deq.appendleft(args[1]) 16 | elif args[0] == 'pop': 17 | deq.pop() 18 | elif args[0] == 'popleft': 19 | deq.popleft() 20 | 21 | out = [] 22 | for el in deq: 23 | out.append(el) 24 | 25 | print(" ".join(map(str, out))) -------------------------------------------------------------------------------- /algorithms part1/compare-the-triplets.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def solve(a0, a1, a2, b0, b1, b2): 6 | alice = bob = 0 7 | if a0 > b0: 8 | alice += 1 9 | elif a0 < b0: 10 | bob += 1 11 | if a1 > b1: 12 | alice += 1 13 | elif a1 < b1: 14 | bob += 1 15 | if a2 > b2: 16 | alice += 1 17 | elif a2 < b2: 18 | bob += 1 19 | return alice, bob 20 | 21 | a0, a1, a2 = input().strip().split(' ') 22 | a0, a1, a2 = [int(a0), int(a1), int(a2)] 23 | b0, b1, b2 = input().strip().split(' ') 24 | b0, b1, b2 = [int(b0), int(b1), int(b2)] 25 | result = solve(a0, a1, a2, b0, b1, b2) 26 | print (" ".join(map(str, result))) 27 | 28 | 29 | -------------------------------------------------------------------------------- /interview-preparation-kit/ctci-making-anagrams.py: -------------------------------------------------------------------------------- 1 | import math 2 | import string 3 | 4 | def number_needed(a, b): 5 | result = 0 6 | a_dict = dict.fromkeys(string.ascii_lowercase, 0) 7 | b_dict = dict.fromkeys(string.ascii_lowercase, 0) 8 | 9 | for a_symb in a: 10 | a_dict[a_symb] = a_dict[a_symb] + 1 11 | 12 | for b_symb in b: 13 | b_dict[b_symb] = b_dict[b_symb] + 1 14 | 15 | #print(a_dict) 16 | #print(b_dict) 17 | 18 | for key in string.ascii_lowercase: 19 | result += math.fabs(a_dict[key] - b_dict[key]) 20 | 21 | return int(result) 22 | 23 | a = input().strip() 24 | b = input().strip() 25 | 26 | print(number_needed(a, b)) 27 | -------------------------------------------------------------------------------- /python part1/merge-the-tools.py: -------------------------------------------------------------------------------- 1 | def merge_the_tools(string, k): 2 | block_cnt = len(string)//k 3 | output_t = [] 4 | output_u = [] 5 | 6 | #print("{}/{} = {}".format(len(string), k, block_len)) 7 | for ind in range(0, len(string) - k + 1, k): 8 | output_t.append(string[ind:ind + k]) 9 | 10 | for block in output_t: 11 | for char in block: 12 | char_count = block.count(char) 13 | if char_count > 1: 14 | block = block[::-1] 15 | block = block.replace(char, '', char_count - 1) 16 | block = block[::-1] 17 | output_u.append(block) 18 | 19 | print("\n".join(map(str, output_u))) -------------------------------------------------------------------------------- /algorithms part1/anagram.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from collections import Counter 5 | 6 | def anagram(s): 7 | if len(s)%2 == 1: 8 | return -1 9 | 10 | res = 0 11 | 12 | cnt1 = Counter(s[:len(s)//2]) 13 | cnt2 = Counter(s[len(s)//2:]) 14 | cnt3 = {} 15 | 16 | for let, val in cnt1.items(): 17 | cnt3[let] = abs(val - cnt2[let]) 18 | for let, val in cnt2.items(): 19 | cnt3[let] = abs(val - cnt1[let]) 20 | 21 | for el in cnt3.values(): 22 | res += el 23 | 24 | return res//2 25 | 26 | q = int(input().strip()) 27 | for a0 in range(q): 28 | s = input().strip() 29 | result = anagram(s) 30 | print(result) 31 | -------------------------------------------------------------------------------- /algorithms part2/reduced-string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys 4 | 5 | def super_reduced_string(s): 6 | if len(s) == 1: 7 | return s 8 | 9 | ind = 1 10 | while ind < len(s): 11 | #print("s[{}] = {} s = {}".format(ind, s[ind], s)) 12 | if s[ind] == s[ind-1]: 13 | if len(s) == 2: 14 | return 'Empty String' 15 | s = s[:ind-1] + s[ind+1:] 16 | ind = 1 17 | else: 18 | ind += 1 19 | 20 | if len(s) == 0: 21 | return 'Empty String' 22 | else: 23 | return s 24 | 25 | 26 | 27 | s = input().strip() 28 | result = super_reduced_string(s) 29 | print(result) 30 | -------------------------------------------------------------------------------- /algorithms part1/countingsort2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def countingSort(arr): 6 | cnt = [0] * (max(arr) + 1) 7 | output = [0] * (len(arr)) 8 | 9 | for el in arr: 10 | cnt[el] += 1 11 | 12 | total = 0 13 | for ind in range(len(cnt)): 14 | old = cnt[ind] 15 | cnt[ind] = total 16 | total += old 17 | 18 | for el in arr: 19 | output[cnt[el]] = el 20 | cnt[el] += 1 21 | 22 | return output 23 | 24 | if __name__ == "__main__": 25 | n = int(input().strip()) 26 | arr = list(map(int, input().strip().split(' '))) 27 | result = countingSort(arr) 28 | print (" ".join(map(str, result))) 29 | 30 | 31 | -------------------------------------------------------------------------------- /algorithms part1/acm-icpc-team.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def solution(): 6 | res = 0 7 | cnt = 0 8 | for ind in range(len(topic)-1): 9 | for jnd in range(ind+1, len(topic)): 10 | tmp = bin(int(topic[ind], 2) | (int(topic[jnd], 2))).count("1") 11 | if tmp > res: 12 | res = tmp 13 | cnt = 1 14 | elif tmp == res: 15 | cnt += 1 16 | 17 | return (res, cnt) 18 | 19 | 20 | n,m = input().strip().split(' ') 21 | n,m = [int(n),int(m)] 22 | topic = [] 23 | topic_i = 0 24 | for topic_i in range(n): 25 | topic_t = str(input().strip()) 26 | topic.append(topic_t) 27 | 28 | print("\n".join(map(str, solution()))) 29 | -------------------------------------------------------------------------------- /algorithms part2/funny-string.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | import string 5 | 6 | alpha = string.ascii_lowercase 7 | 8 | def funnyString(s): 9 | res = 'Funny' 10 | r = s[::-1] 11 | 12 | for ind in range(1, len(s)): 13 | #print("{} - {} ?= {} - {}".format(alpha.index(s[ind]), alpha.index(s[ind-1]), alpha.index(r[ind]), alpha.index(r[ind-1]))) 14 | if abs(alpha.index(s[ind]) - alpha.index(s[ind-1])) != abs(alpha.index(r[ind]) - alpha.index(r[ind-1])): 15 | res = 'Not Funny' 16 | break 17 | 18 | return res 19 | 20 | q = int(input().strip()) 21 | for a0 in range(q): 22 | s = input().strip() 23 | result = funnyString(s) 24 | print(result) 25 | -------------------------------------------------------------------------------- /algorithms part1/a-chessboard-game-1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the chessboardGame function below. 10 | def chessboardGame(x, y): 11 | x = x%4 12 | y = y%4 13 | 14 | if x in [1, 2] and y in [1,2]: 15 | return 'Second' 16 | else: 17 | return 'First' 18 | 19 | if __name__ == '__main__': 20 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 21 | 22 | t = int(input()) 23 | 24 | for t_itr in range(t): 25 | xy = input().split() 26 | 27 | x = int(xy[0]) 28 | y = int(xy[1]) 29 | 30 | result = chessboardGame(x, y) 31 | 32 | fptr.write(result + '\n') 33 | 34 | fptr.close() 35 | -------------------------------------------------------------------------------- /algorithms part1/absolute-permutation.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def max_permutation(n, k): 6 | #array = [x for x in range(1, n+1)] 7 | out = [] 8 | switch = k 9 | if k == 0: 10 | return [x for x in range(1, n+1)] 11 | 12 | if n % (2*k) != 0: 13 | return [-1] 14 | 15 | for pos in range(1, n + 1): 16 | out.append(pos + switch) 17 | 18 | if pos % k == 0: 19 | switch *= -1 20 | 21 | return out 22 | 23 | 24 | 25 | t = int(input().strip()) 26 | for a0 in range(t): 27 | n, k = input().strip().split(' ') 28 | n, k = [int(n),int(k)] 29 | 30 | print(" ".join(list(map(str, max_permutation(n, k))))) 31 | -------------------------------------------------------------------------------- /algorithms part1/counter-game.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # naive method 3 | 4 | import sys 5 | import math 6 | 7 | def get_mask(n): 8 | return 1 << math.floor(math.log(n,2)) 9 | 10 | def counter_game(n): 11 | winner = 0 12 | while n != 1: 13 | mask = get_mask(n) 14 | if mask == n: 15 | n = n/2 16 | else: 17 | n -= mask 18 | 19 | winner ^= 1 20 | 21 | 22 | if winner == 1: 23 | return "Louise" 24 | elif winner == 0: 25 | return "Richard" 26 | 27 | if __name__ == "__main__": 28 | t = int(input().strip()) 29 | for a0 in range(t): 30 | n = int(input().strip()) 31 | result = counter_game(n) 32 | print(result) 33 | -------------------------------------------------------------------------------- /data-structures/delete-duplicate-value-nodes-from-a-sorted-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Delete duplicate nodes 3 | head could be None as well for empty list 4 | Node is defined as 5 | 6 | class Node(object): 7 | 8 | def __init__(self, data=None, next_node=None): 9 | self.data = data 10 | self.next = next_node 11 | 12 | return back the head of the linked list in the below method. 13 | """ 14 | 15 | def RemoveDuplicates(head): 16 | node = head 17 | 18 | while node.next != None: 19 | if node.data == node.next.data: 20 | node.next = node.next.next 21 | continue 22 | node = node.next 23 | 24 | return head 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /python part1/html-parser-part-1.py: -------------------------------------------------------------------------------- 1 | import re 2 | from html.parser import HTMLParser 3 | 4 | class MyHTMLParser(HTMLParser): 5 | def handle_starttag(self, tag, attrs): 6 | print("Start".ljust(6) + ":", tag) 7 | for at in attrs: 8 | print("-> {} > {}".format(at[0], at[1])) 9 | def handle_endtag(self, tag): 10 | print("End".ljust(6) + ":", tag) 11 | def handle_startendtag(self, tag, attrs): 12 | print("Empty".ljust(6) + ":", tag) 13 | for at in attrs: 14 | print("-> {} > {}".format(at[0], at[1])) 15 | 16 | if __name__ == "__main__": 17 | parser = MyHTMLParser() 18 | n = int(input().strip()) 19 | for _ in range(n): 20 | line = input() 21 | parser.feed(line) -------------------------------------------------------------------------------- /python part2/python-lists.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | N = int(input()) 3 | outlist = [] 4 | for _ in range(N): 5 | args = input().strip().split(' ') 6 | cmd = args[0] 7 | if cmd == 'insert': 8 | outlist.insert(int(args[1]), int(args[2])) 9 | elif cmd == 'remove': 10 | outlist.remove(int(args[1])) 11 | elif cmd == 'append': 12 | outlist.append(int(args[1])) 13 | elif cmd == 'print': 14 | print(outlist) 15 | elif cmd == 'sort': 16 | outlist.sort() 17 | elif cmd == 'pop': 18 | outlist.pop() 19 | elif cmd == 'reverse': 20 | outlist.reverse() 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /data-structures/tree-level-order-traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Node is defined as 3 | self.left (the left child of the node) 4 | self.right (the right child of the node) 5 | self.data (the value of the node) 6 | """ 7 | 8 | def height(root): 9 | if root is not None: 10 | return max(1 + height(root.left), 1 + height(root.right)) 11 | else: 12 | return -1 13 | 14 | def _levelOrder(root, level): 15 | if root is not None: 16 | if level == 0: 17 | print root.data, 18 | else: 19 | _levelOrder(root.left, level - 1) 20 | _levelOrder(root.right, level - 1) 21 | 22 | 23 | def levelOrder(root): 24 | for level in range(height(root)+1): 25 | _levelOrder(root, level) 26 | 27 | -------------------------------------------------------------------------------- /data-structures/insert-a-node-at-the-tail-of-a-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Insert Node at the end of a linked list 3 | head pointer input could be None as well for empty list 4 | Node is defined as 5 | 6 | class Node(object): 7 | 8 | def __init__(self, data=None, next_node=None): 9 | self.data = data 10 | self.next = next_node 11 | 12 | return back the head of the linked list in the below method 13 | """ 14 | 15 | def Insert(head, data): 16 | node = head 17 | if head is None: 18 | head = Node(data) 19 | return head 20 | 21 | while node.next != None: 22 | node = node.next 23 | 24 | node.next = Node(data) 25 | 26 | return head 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /data-structures/reverse-a-doubly-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reverse a doubly linked list 3 | head could be None as well for empty list 4 | Node is defined as 5 | 6 | class Node(object): 7 | 8 | def __init__(self, data=None, next_node=None, prev_node = None): 9 | self.data = data 10 | self.next = next_node 11 | self.prev = prev_node 12 | 13 | return the head node of the updated list 14 | """ 15 | 16 | def Reverse(head): 17 | prev = None 18 | node = head 19 | 20 | while node is not None: 21 | buf = node.next 22 | node.next = prev 23 | prev = node 24 | node = buf 25 | 26 | head = prev 27 | return head 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /algorithms part1/caesar-cipher-1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | import string 5 | symbols_low = string.ascii_lowercase 6 | symbols_up = string.ascii_uppercase 7 | 8 | def caesarCipher(s, k): 9 | res = [] 10 | for c in s: 11 | if c.isupper(): 12 | res.append(symbols_up[(symbols_up.index(c)+k)%len(symbols_up)]) 13 | elif c.islower(): 14 | res.append(symbols_low[(symbols_low.index(c)+k)%len(symbols_low)]) 15 | else: 16 | res.append(c) 17 | 18 | return "".join(map(str, res)) 19 | 20 | 21 | if __name__ == "__main__": 22 | n = int(input().strip()) 23 | s = input().strip() 24 | k = int(input().strip()) 25 | result = caesarCipher(s, k) 26 | print(result) 27 | -------------------------------------------------------------------------------- /algorithms part2/jim-and-the-orders.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from bisect import insort 5 | from collections import defaultdict 6 | 7 | def jimOrders(orders): 8 | sequence = [] 9 | 10 | for ind, el in enumerate(orders, 1): 11 | time = sum(el) 12 | insort(sequence, (time, ind)) 13 | 14 | #print("seq: {}".format(sequence)) 15 | 16 | return list(map(lambda x: x[1], sequence)) 17 | 18 | if __name__ == "__main__": 19 | n = int(input().strip()) 20 | orders = [] 21 | for orders_i in range(n): 22 | orders_t = [int(orders_temp) for orders_temp in input().strip().split(' ')] 23 | orders.append(orders_t) 24 | result = jimOrders(orders) 25 | print (" ".join(map(str, result))) 26 | 27 | 28 | -------------------------------------------------------------------------------- /interview-preparation-kit/reverse-a-doubly-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reverse a doubly linked list 3 | head could be None as well for empty list 4 | Node is defined as 5 | 6 | class Node(object): 7 | 8 | def __init__(self, data=None, next_node=None, prev_node = None): 9 | self.data = data 10 | self.next = next_node 11 | self.prev = prev_node 12 | 13 | return the head node of the updated list 14 | """ 15 | 16 | def Reverse(head): 17 | prev = None 18 | node = head 19 | 20 | while node is not None: 21 | buf = node.next 22 | node.next = prev 23 | prev = node 24 | node = buf 25 | 26 | head = prev 27 | return head 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /data-structures/print-the-elements-of-a-linked-list-in-reverse.py: -------------------------------------------------------------------------------- 1 | """ 2 | Print elements of a linked list in reverse order as standard output 3 | head could be None as well for empty list 4 | Node is defined as 5 | 6 | class Node(object): 7 | 8 | def __init__(self, data=None, next_node=None): 9 | self.data = data 10 | self.next = next_node 11 | 12 | 13 | """ 14 | 15 | def ReversePrint(head): 16 | if head is None: 17 | return 18 | else: 19 | out = [] 20 | node = head 21 | 22 | while node != None: 23 | out.append(node.data) 24 | node = node.next 25 | 26 | print("\n".join(map(str, out[::-1]))) 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /algorithms part2/icecream-parlor.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def solve(arr, money): 6 | # find matched number 7 | cost_map = {} 8 | for i, cost in enumerate(arr): 9 | johnny = money - cost 10 | #print("cost = {} johny = {}".format(cost, johnny)) 11 | #print(cost_map.keys()) 12 | #print(cost_map) 13 | if johnny in cost_map.keys(): 14 | print("{} {}".format(cost_map[johnny]+1, i+1)) 15 | else: 16 | cost_map[cost] = i 17 | 18 | if __name__ == "__main__": 19 | t = int(input().strip()) 20 | for a0 in range(t): 21 | money = int(input().strip()) 22 | n = int(input().strip()) 23 | arr = list(map(int, input().strip().split(' '))) 24 | solve(arr, money) -------------------------------------------------------------------------------- /cpp/cpp-lower-bound.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main() { 10 | int n, q; 11 | cin >> n; 12 | vector v(n); 13 | 14 | for(int i = 0; i < n; i++) 15 | cin >> v[i]; 16 | sort(v.begin(), v.end()); 17 | 18 | cin >> q; 19 | for(int i = 0; i < q; i++) { 20 | vector::iterator low; 21 | int num; 22 | cin >> num; 23 | low = lower_bound(v.begin(), v.end(), num); 24 | if (v[low - v.begin()] == num) 25 | cout << "Yes " << (low - v.begin()+1) << endl; 26 | else 27 | cout << "No " << (low - v.begin()+1) << endl; 28 | } 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /algorithms part2/kangaroo.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def kangaroo(x1, v1, x2, v2): 6 | if x1 >= x2 and v1 > v2: 7 | return 'NO' 8 | elif x2 >= x1 and v2 > v1: 9 | return 'NO' 10 | elif (x1 > x2 or x2 > x1) and v1 == v2: 11 | return 'NO' 12 | else: 13 | pos1, pos2 = x1, x2 14 | dif_prev = dif = abs(pos1 - pos2) 15 | while dif_prev >= dif: 16 | if pos1 == pos2: 17 | return 'YES' 18 | pos1 += v1 19 | pos2 += v2 20 | dif_prev, dif = dif, abs(pos1 - pos2) 21 | return 'NO' 22 | 23 | x1, v1, x2, v2 = input().strip().split(' ') 24 | x1, v1, x2, v2 = [int(x1), int(v1), int(x2), int(v2)] 25 | result = kangaroo(x1, v1, x2, v2) 26 | print(result) 27 | -------------------------------------------------------------------------------- /algorithms part2/mini-max-sum.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # stupid O(n^2) algorithm 3 | 4 | import math 5 | import sys 6 | 7 | def miniMaxSum(arr): 8 | sum_min = math.inf 9 | sum_max = -math.inf 10 | sum_temp = 0 11 | 12 | for exclude in range(len(arr)): 13 | sum_temp = 0 14 | for ind, elem in enumerate(arr): 15 | if ind == exclude: 16 | continue 17 | sum_temp += elem 18 | if sum_temp < sum_min: 19 | sum_min = sum_temp 20 | if sum_temp > sum_max: 21 | sum_max = sum_temp 22 | 23 | print("{} {}".format(sum_min, sum_max)) 24 | return sum_min, sum_max 25 | 26 | if __name__ == "__main__": 27 | arr = list(map(int, input().strip().split(' '))) 28 | miniMaxSum(arr) 29 | -------------------------------------------------------------------------------- /algorithms part2/separate-the-numbers.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def validate(s, first): 6 | while s: 7 | if s.startswith(first): 8 | s = s[len(first):] 9 | first = str(int(first) + 1) 10 | else: 11 | return False 12 | return True 13 | 14 | def separateNumbers(s): 15 | if s[0] == '0' and len(s) > 1: 16 | return "NO" 17 | else: 18 | for ind in range(1, len(s)//2 + 1): 19 | first = s[:ind] 20 | if validate(str(s), first): 21 | return "YES " + first 22 | return "NO" 23 | 24 | 25 | if __name__ == "__main__": 26 | q = int(input().strip()) 27 | for a0 in range(q): 28 | s = input().strip() 29 | print(separateNumbers(s)) 30 | -------------------------------------------------------------------------------- /data-structures/largest-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def largestRectangle(h): 6 | res = 0 7 | 8 | for i in range(len(h)): 9 | length = 0 10 | for j in range(i, -1, -1): 11 | if h[j] >= h[i]: 12 | length += 1 13 | else: 14 | break 15 | 16 | for j in range(i+1, len(h)): 17 | if h[j] >= h[i]: 18 | length += 1 19 | else: 20 | break 21 | 22 | res = max(res, length*h[i]) 23 | 24 | return res 25 | 26 | if __name__ == "__main__": 27 | n = int(input().strip()) 28 | h = list(map(int, input().strip().split(' '))) 29 | result = largestRectangle(h) 30 | print(result) 31 | -------------------------------------------------------------------------------- /python part2/piling-up.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from collections import deque 4 | 5 | if __name__ == "__main__": 6 | t = int(input().strip()) 7 | 8 | for _ in range(t): 9 | num_cnt = int(input().strip()) 10 | deq = deque(list(map(int, input().strip().split(' ')))) 11 | 12 | prev = max(deq[0], deq[-1]) 13 | while deq: 14 | if prev >= deq[0] and prev >= deq[-1]: 15 | if deq[0] >= deq[-1]: 16 | prev = deq.popleft() 17 | else: 18 | prev = deq.pop() 19 | else: 20 | break 21 | 22 | if len(deq) == 0: 23 | print('Yes') 24 | else: 25 | print('No') 26 | 27 | -------------------------------------------------------------------------------- /interview-preparation-kit/new-year-chaos.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the minimumBribes function below. 10 | def minimumBribes(q): 11 | res = 0 12 | 13 | for ind in range(len(q)): 14 | if q[ind] - (1+ind) > 2: 15 | return "Too chaotic" 16 | 17 | for ind in range(len(q)): 18 | for jnd in range(max(0, q[ind]-2), ind): 19 | if (q[jnd] > q[ind]): 20 | res += 1 21 | 22 | return res 23 | 24 | 25 | if __name__ == '__main__': 26 | t = int(input()) 27 | 28 | for t_itr in range(t): 29 | n = int(input()) 30 | q = list(map(int, input().rstrip().split())) 31 | 32 | print(minimumBribes(q)) 33 | -------------------------------------------------------------------------------- /algorithms part2/pairs.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the pairs function below. 10 | def pairs(k, arr): 11 | res = 0 12 | memo = dict() 13 | 14 | for el in arr: 15 | if el-k in memo: 16 | res += 1 17 | 18 | if el+k in memo: 19 | res += 1 20 | 21 | memo[el] = True 22 | 23 | return res 24 | 25 | 26 | if __name__ == '__main__': 27 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 28 | 29 | nk = input().split() 30 | 31 | n = int(nk[0]) 32 | 33 | k = int(nk[1]) 34 | 35 | arr = list(map(int, input().rstrip().split())) 36 | 37 | result = pairs(k, arr) 38 | 39 | fptr.write(str(result) + '\n') 40 | 41 | fptr.close() 42 | -------------------------------------------------------------------------------- /interview-preparation-kit/greedy-florist.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the getMinimumCost function below. 10 | def getMinimumCost(k, flowers): 11 | res = 0 12 | cnt = 0 13 | 14 | flowers = sorted(flowers, key=lambda x: -x) 15 | 16 | for el in flowers: 17 | res += el * (1 + cnt//k) 18 | cnt += 1 19 | 20 | return res 21 | 22 | 23 | if __name__ == '__main__': 24 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 25 | 26 | nk = input().split() 27 | n = int(nk[0]) 28 | k = int(nk[1]) 29 | c = list(map(int, input().rstrip().split())) 30 | 31 | minimumCost = getMinimumCost(k, c) 32 | fptr.write(str(minimumCost) + '\n') 33 | fptr.close() 34 | -------------------------------------------------------------------------------- /interview-preparation-kit/largest-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def largestRectangle(h): 6 | res = 0 7 | 8 | for i in range(len(h)): 9 | length = 0 10 | for j in range(i, -1, -1): 11 | if h[j] >= h[i]: 12 | length += 1 13 | else: 14 | break 15 | 16 | for j in range(i+1, len(h)): 17 | if h[j] >= h[i]: 18 | length += 1 19 | else: 20 | break 21 | 22 | res = max(res, length*h[i]) 23 | 24 | return res 25 | 26 | if __name__ == "__main__": 27 | n = int(input().strip()) 28 | h = list(map(int, input().strip().split(' '))) 29 | result = largestRectangle(h) 30 | print(result) 31 | -------------------------------------------------------------------------------- /algorithms part2/poker-nim-1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | from functools import reduce 9 | 10 | # Complete the pokerNim function below. 11 | def pokerNim(k, c): 12 | res = reduce((lambda x, y: x ^ y), c) 13 | 14 | if res == 0: 15 | return 'Second' 16 | else: 17 | return 'First' 18 | 19 | if __name__ == '__main__': 20 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 21 | 22 | t = int(input()) 23 | 24 | for t_itr in range(t): 25 | nk = input().split() 26 | 27 | n = int(nk[0]) 28 | 29 | k = int(nk[1]) 30 | 31 | c = list(map(int, input().rstrip().split())) 32 | 33 | result = pokerNim(k, c) 34 | 35 | fptr.write(result + '\n') 36 | 37 | fptr.close() 38 | -------------------------------------------------------------------------------- /interview-preparation-kit/pairs.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the pairs function below. 10 | def pairs(k, arr): 11 | res = 0 12 | memo = dict() 13 | 14 | for el in arr: 15 | if el-k in memo: 16 | res += 1 17 | 18 | if el+k in memo: 19 | res += 1 20 | 21 | memo[el] = True 22 | 23 | return res 24 | 25 | 26 | if __name__ == '__main__': 27 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 28 | 29 | nk = input().split() 30 | 31 | n = int(nk[0]) 32 | 33 | k = int(nk[1]) 34 | 35 | arr = list(map(int, input().rstrip().split())) 36 | 37 | result = pairs(k, arr) 38 | 39 | fptr.write(str(result) + '\n') 40 | 41 | fptr.close() 42 | -------------------------------------------------------------------------------- /algorithms part2/palindrome-index.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from collections import Counter 5 | 6 | def is_palindrome(s): 7 | return s == s[::-1] 8 | 9 | def palindromeIndex(s): 10 | ret = -1 11 | lens = len(s) 12 | ind = 0 13 | 14 | if is_palindrome(s): 15 | return ret 16 | 17 | while ind < lens//2: 18 | if s[ind] != s[lens-ind-1]: 19 | if s[ind+1] == s[lens-ind-1] and s[ind+2] == s[lens-ind-2]: 20 | ret = ind 21 | break 22 | else: 23 | ret = lens-ind-1 24 | break 25 | ind += 1 26 | 27 | return ret 28 | 29 | 30 | q = int(input().strip()) 31 | for a0 in range(q): 32 | s = input().strip() 33 | result = palindromeIndex(s) 34 | print(result) 35 | -------------------------------------------------------------------------------- /algorithms part2/picking-numbers.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def pickingNumbers(arr): 6 | arr_s = sorted(arr) 7 | res = 1 8 | cur = 1 9 | diff = 0 10 | for ind in range(1, len(arr_s)): 11 | #print("arr[{}] - arr[{}] = {} - {} res = {} cur = {}".format(ind, ind - 1, arr_s[ind], arr_s[ind - 1], res, cur)) 12 | diff += arr_s[ind] - arr_s[ind - 1] 13 | if diff > 1: 14 | res = max(res, cur) 15 | cur = 1 16 | diff = 0 17 | else: 18 | cur += 1 19 | 20 | res = max(res, cur) 21 | 22 | return res 23 | 24 | 25 | if __name__ == "__main__": 26 | n = int(input().strip()) 27 | a = list(map(int, input().strip().split(' '))) 28 | result = pickingNumbers(a) 29 | print(result) 30 | -------------------------------------------------------------------------------- /data-structures/equal-stacks.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | n1,n2,n3 = input().strip().split(' ') 7 | n1,n2,n3 = [int(n1),int(n2),int(n3)] 8 | h1 = [int(h1_temp) for h1_temp in input().strip().split(' ')] 9 | h2 = [int(h2_temp) for h2_temp in input().strip().split(' ')] 10 | h3 = [int(h3_temp) for h3_temp in input().strip().split(' ')] 11 | stacks = [h1[::-1], h2[::-1], h3[::-1]] 12 | stack_sums = [sum(stacks[i]) for i in range(3)] 13 | 14 | while len({stack_sums[i] for i in range(3)}) > 1: 15 | tallest_stack = max(stack_sums) 16 | index = stack_sums.index(tallest_stack) 17 | removed = stacks[index].pop() 18 | stack_sums[index] -= removed 19 | 20 | print(min([sum(stacks[i]) for i in range(3)])) 21 | 22 | -------------------------------------------------------------------------------- /interview-preparation-kit/ctci-ice-cream-parlor.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def solve(arr, money): 6 | # find matched number 7 | cost_map = {} 8 | for i, cost in enumerate(arr): 9 | johnny = money - cost 10 | #print("cost = {} johny = {}".format(cost, johnny)) 11 | #print(cost_map.keys()) 12 | #print(cost_map) 13 | if johnny in cost_map.keys(): 14 | print("{} {}".format(cost_map[johnny]+1, i+1)) 15 | else: 16 | cost_map[cost] = i 17 | 18 | if __name__ == "__main__": 19 | t = int(input().strip()) 20 | for a0 in range(t): 21 | money = int(input().strip()) 22 | n = int(input().strip()) 23 | arr = list(map(int, input().strip().split(' '))) 24 | solve(arr, money) 25 | 26 | 27 | -------------------------------------------------------------------------------- /python part1/text-alignment.py: -------------------------------------------------------------------------------- 1 | #Replace all ______ with rjust, ljust or center. 2 | 3 | thickness = int(input()) #This must be an odd number 4 | c = 'H' 5 | 6 | #Top Cone 7 | for i in range(thickness): 8 | print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1)) 9 | 10 | #Top Pillars 11 | for i in range(thickness+1): 12 | print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) 13 | 14 | #Middle Belt 15 | for i in range((thickness+1)//2): 16 | print((c*thickness*5).center(thickness*6)) 17 | 18 | #Bottom Pillars 19 | for i in range(thickness+1): 20 | print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) 21 | 22 | #Bottom Cone 23 | for i in range(thickness): 24 | print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6)) 25 | -------------------------------------------------------------------------------- /algorithms part1/closest-numbers.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | def closestNumbers(arr): 7 | output = [] 8 | arr = sorted(arr) 9 | nowmin = 10**9 10 | 11 | for ind in range(1, len(arr)): 12 | diff = abs(arr[ind-1] - arr[ind]) 13 | 14 | if diff < nowmin: 15 | output = [(arr[ind-1], arr[ind])] 16 | nowmin = diff 17 | elif diff == nowmin: 18 | output.append((arr[ind-1], arr[ind])) 19 | 20 | flat_list = [item for sublist in output for item in sublist] 21 | 22 | return flat_list 23 | 24 | 25 | if __name__ == "__main__": 26 | n = int(input().strip()) 27 | arr = list(map(int, input().strip().split(' '))) 28 | result = closestNumbers(arr) 29 | print (" ".join(map(str, result))) 30 | 31 | 32 | -------------------------------------------------------------------------------- /cpp/cpp-sets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | 10 | int main() { 11 | int q; 12 | cin >> q; 13 | set s; 14 | 15 | for (int i = 0; i < q; i++) { 16 | int type, num; 17 | cin >> type >> num; 18 | 19 | switch(type) { 20 | case 1: 21 | s.insert(num); 22 | break; 23 | case 2: 24 | s.erase(num); 25 | break; 26 | case 3: 27 | if (s.find(num) == s.end()) 28 | cout << "No" << endl; 29 | else 30 | cout << "Yes" << endl; 31 | break; 32 | } 33 | } 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /data-structures/binary-search-tree-insertion.py: -------------------------------------------------------------------------------- 1 | """ 2 | Node is defined as 3 | self.left (the left child of the node) 4 | self.right (the right child of the node) 5 | self.data (the value of the node)""" 6 | 7 | def insert(root, val): 8 | if root is None: 9 | root = Node(data=val) 10 | return root 11 | 12 | current = root 13 | while True: 14 | if current.data > val: 15 | if current.left is not None: 16 | current = current.left 17 | else: 18 | current.left = Node(data=val) 19 | break 20 | else: 21 | if current.right is not None: 22 | current = current.right 23 | else: 24 | current.right = Node(data=val) 25 | break 26 | 27 | return root 28 | 29 | -------------------------------------------------------------------------------- /data-structures/get-the-value-of-the-node-at-a-specific-position-from-the-tail.py: -------------------------------------------------------------------------------- 1 | #Body 2 | """ 3 | Get Node data of the Nth Node from the end. 4 | head could be None as well for empty list 5 | Node is defined as 6 | 7 | class Node(object): 8 | 9 | def __init__(self, data=None, next_node=None): 10 | self.data = data 11 | self.next = next_node 12 | 13 | return back the node data of the linked list in the below method. 14 | """ 15 | 16 | def GetNode(head, position): 17 | node = head 18 | list_len = 0 19 | 20 | while node != None: 21 | node = node.next 22 | list_len += 1 23 | 24 | node = head 25 | for _ in range(list_len - position - 1): 26 | node = node.next 27 | 28 | return node.data 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /algorithms part2/misere-nim-1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | from functools import reduce 9 | 10 | def misereNim(pile): 11 | if set(pile) == {1}: 12 | if len(pile)%2 == 0: 13 | return 'First' 14 | else: 15 | return 'Second' 16 | 17 | res = reduce((lambda x, y: x ^ y), pile) 18 | if res == 0: 19 | return 'Second' 20 | else: 21 | return 'First' 22 | 23 | if __name__ == '__main__': 24 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 25 | 26 | t = int(input()) 27 | 28 | for t_itr in range(t): 29 | n = int(input()) 30 | 31 | s = list(map(int, input().rstrip().split())) 32 | 33 | result = misereNim(s) 34 | 35 | fptr.write(result + '\n') 36 | 37 | fptr.close() 38 | -------------------------------------------------------------------------------- /algorithms part1/bigger-is-greater.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from itertools import permutations 5 | 6 | def biggerIsGreater(w): 7 | arr = list(w) 8 | # Find non-increasing suffix 9 | i = len(arr) - 1 10 | while i > 0 and arr[i - 1] >= arr[i]: 11 | i -= 1 12 | if i <= 0: 13 | return 'no answer' 14 | 15 | # Find successor to pivot 16 | j = len(arr) - 1 17 | while arr[j] <= arr[i - 1]: 18 | j -= 1 19 | arr[i - 1], arr[j] = arr[j], arr[i - 1] 20 | 21 | # Reverse suffix 22 | arr[i : ] = arr[len(arr) - 1 : i - 1 : -1] 23 | 24 | return "".join(arr) 25 | 26 | 27 | if __name__ == "__main__": 28 | T = int(input().strip()) 29 | for a0 in range(T): 30 | w = input().strip() 31 | result = biggerIsGreater(w) 32 | print(result) 33 | -------------------------------------------------------------------------------- /algorithms part2/two-characters.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from itertools import combinations 5 | 6 | def validate(string): 7 | for ind in range(len(string)-1): 8 | if string[ind] == string[ind + 1]: 9 | return False 10 | return True 11 | 12 | def twoCharaters(string): 13 | str_set = set(list(string)) 14 | variants = combinations(str_set, 2) 15 | max_res = 0 16 | 17 | for comb in variants: 18 | t = [c for c in string if c == comb[0] or c == comb[1]] 19 | #print("comb = {} t = {}".format(comb, t)) 20 | if validate(t): 21 | max_res = max(max_res, len(t)) 22 | 23 | return max_res 24 | 25 | 26 | if __name__ == "__main__": 27 | l = int(input().strip()) 28 | s = input().strip() 29 | result = twoCharaters(s) 30 | print(result) 31 | -------------------------------------------------------------------------------- /interview-preparation-kit/ctci-ransom-note.py: -------------------------------------------------------------------------------- 1 | dict_mag = dict() 2 | dict_ran = dict() 3 | 4 | def ransom_note(magazine, ransom): 5 | for word in magazine: 6 | if word in dict_mag.keys(): 7 | dict_mag[word] += 1 8 | else: 9 | dict_mag[word] = 1 10 | 11 | for word in ransom: 12 | if word in dict_ran.keys(): 13 | dict_ran[word] += 1 14 | else: 15 | dict_ran[word] = 1 16 | 17 | for key in dict_ran.keys(): 18 | if dict_ran[key] > dict_mag[key]: 19 | return False 20 | return True 21 | 22 | m, n = map(int, input().strip().split(' ')) 23 | magazine = input().strip().split(' ') 24 | ransom = input().strip().split(' ') 25 | answer = ransom_note(magazine, ransom) 26 | if(answer): 27 | print("Yes") 28 | else: 29 | print("No") 30 | 31 | -------------------------------------------------------------------------------- /algorithms part1/circular-array-rotation.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def rightRotation(a, d): 6 | out = list(a) 7 | a_len = len(a) 8 | for ind, el in enumerate(a): 9 | out[(ind + d) % a_len] = el 10 | 11 | return out 12 | 13 | def circularArrayRotation(a, m): 14 | out = [] 15 | for pos in m: 16 | out.append(a[pos]) 17 | 18 | return out 19 | 20 | 21 | if __name__ == "__main__": 22 | n, k, q = input().strip().split(' ') 23 | n, k, q = [int(n), int(k), int(q)] 24 | a = list(map(int, input().strip().split(' '))) 25 | m = [] 26 | m_i = 0 27 | for m_i in range(q): 28 | m_t = int(input().strip()) 29 | m.append(m_t) 30 | a = rightRotation(a, k) 31 | result = circularArrayRotation(a, m) 32 | print ("\n".join(map(str, result))) 33 | 34 | 35 | -------------------------------------------------------------------------------- /algorithms part1/weighted-uniform-string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys 4 | import string 5 | 6 | symbols = string.ascii_lowercase 7 | 8 | def gen_uniforms(s): 9 | uniforms = {} 10 | 11 | mult = 1 12 | let_prev = '' 13 | for let in s: 14 | if let == let_prev: 15 | mult += 1 16 | else: 17 | mult = 1 18 | 19 | let_prev = let 20 | uniforms[((symbols.index(let) + 1)*mult)] = True 21 | 22 | return uniforms 23 | 24 | 25 | if __name__ == "__main__": 26 | s = input().strip() 27 | n = int(input().strip()) 28 | uniforms = gen_uniforms(s) 29 | 30 | for a0 in range(n): 31 | x = int(input().strip()) 32 | 33 | if x in uniforms: 34 | print("Yes") 35 | else: 36 | print("No") 37 | -------------------------------------------------------------------------------- /algorithms part1/xor-se.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def sequence(N): 6 | x = N % 8 7 | if x == 0 or x == 1: 8 | return N 9 | if x == 2 or x == 3: 10 | return 2 11 | if x == 4 or x == 5: 12 | return N+2 13 | if x == 6 or x == 7: 14 | return 0 15 | 16 | def solution(L, R): 17 | res = 0 18 | if (R - L) % 2 == 1: 19 | for ind in range(L+1, R+1, 2): 20 | res ^= ind 21 | else: 22 | for ind in range(L+1): 23 | res ^= ind 24 | for ind in range(L+2, R+1, 2): 25 | res ^= ind 26 | 27 | return res 28 | 29 | 30 | Q = int(input().strip()) 31 | for a0 in range(Q): 32 | L,R = input().strip().split(' ') 33 | L,R = [int(L),int(R)] 34 | #print(solution(L,R)) 35 | print(sequence(L-1)^sequence(R)) 36 | -------------------------------------------------------------------------------- /algorithms part2/missing-numbers.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from collections import Counter 5 | 6 | def missingNumbers(arr, brr): 7 | acnt = Counter(arr) 8 | bcnt = Counter(brr) 9 | 10 | for el in acnt.items(): 11 | #print("checking {}".format(el)) 12 | get = bcnt.get(el[0]) 13 | if get: 14 | bcnt[el[0]] -= el[1] 15 | 16 | bcnt = list(map(lambda x: x[0], (filter(lambda x: x[1] > 0, bcnt.items())))) 17 | bcnt = sorted(bcnt) 18 | 19 | return bcnt 20 | 21 | 22 | if __name__ == "__main__": 23 | n = int(input().strip()) 24 | arr = list(map(int, input().strip().split(' '))) 25 | m = int(input().strip()) 26 | brr = list(map(int, input().strip().split(' '))) 27 | result = missingNumbers(arr, brr) 28 | print (" ".join(map(str, result))) 29 | 30 | 31 | -------------------------------------------------------------------------------- /python part2/py-set-mutations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | n = int(input()) 5 | s = set(map(int, input().split())) 6 | num_cmds = int(input()) 7 | 8 | for _i in range(num_cmds): 9 | cmd = list(input().strip().split(' ')) 10 | if cmd[0] == 'intersection_update': 11 | get_set = set(map(int, input().split(' '))) 12 | s &= get_set 13 | elif cmd[0] == 'update': 14 | get_set = set(map(int, input().split(' '))) 15 | s |= get_set 16 | elif cmd[0] == 'difference_update': 17 | get_set = set(map(int, input().split(' '))) 18 | s -= get_set 19 | elif cmd[0] == 'symmetric_difference_update': 20 | get_set = set(map(int, input().split(' '))) 21 | s ^= get_set 22 | 23 | print(sum(s)) 24 | -------------------------------------------------------------------------------- /data-structures/down-to-zero-ii.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def generate_seive(): 6 | limit = pow(10, 6) + 1 7 | seive = [-1]* limit 8 | seive[0], seive[1], seive[2], seive[3] = 0, 1, 2, 3 9 | 10 | for iind in range(limit): 11 | if seive[iind] == -1 or seive[iind] > seive[iind-1] + 1: 12 | seive[iind] = seive[iind-1] + 1 13 | 14 | jind = 1 15 | while jind <= iind and jind * iind < limit: 16 | if seive[jind * iind] == -1 or seive[jind * iind] > seive[iind] + 1: 17 | seive[jind * iind] = seive[iind] + 1 18 | jind += 1 19 | 20 | return seive 21 | 22 | if __name__ == "__main__": 23 | Q = int(input().strip()) 24 | seive = generate_seive() 25 | for a0 in range(Q): 26 | N = int(input().strip()) 27 | print(seive[N]) 28 | -------------------------------------------------------------------------------- /algorithms part2/larrys-array.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def rotate(A, pos): 6 | A[pos], A[pos+1], A[pos+2] = A[pos+1], A[pos+2], A[pos] 7 | 8 | def larrysArray(A): 9 | for _ in range(len(A)): 10 | for ind in range(1, len(A) - 1): 11 | a, b, c = A[ind-1], A[ind], A[ind+1] 12 | #print("ind = {} A = {} B = {} C = {}".format(ind, a, b, c)) 13 | if a > b or c < a: 14 | #print("rotating 1") 15 | rotate(A, ind-1) 16 | 17 | if A == sorted(A): 18 | return 'YES' 19 | else: 20 | return 'NO' 21 | 22 | if __name__ == "__main__": 23 | t = int(input().strip()) 24 | for a0 in range(t): 25 | n = int(input().strip()) 26 | A = list(map(int, input().strip().split(' '))) 27 | result = larrysArray(A) 28 | print(result) 29 | -------------------------------------------------------------------------------- /algorithms part2/minimum-swaps-2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the minimumSwaps function below. 10 | def minimumSwaps(arr): 11 | res = 0 12 | ind = 0 13 | 14 | while ind < len(arr)-1: 15 | #print("ind = {} arr: {}".format(ind, arr)) 16 | if arr[ind] == ind + 1: 17 | ind += 1 18 | continue 19 | else: 20 | arr[arr[ind]-1], arr[ind] = arr[ind], arr[arr[ind]-1] 21 | res += 1 22 | 23 | return res 24 | 25 | if __name__ == '__main__': 26 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 27 | 28 | n = int(input()) 29 | 30 | arr = list(map(int, input().rstrip().split())) 31 | 32 | res = minimumSwaps(arr) 33 | 34 | fptr.write(str(res) + '\n') 35 | 36 | fptr.close() 37 | -------------------------------------------------------------------------------- /interview-preparation-kit/minimum-swaps-2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the minimumSwaps function below. 10 | def minimumSwaps(arr): 11 | res = 0 12 | ind = 0 13 | 14 | while ind < len(arr)-1: 15 | #print("ind = {} arr: {}".format(ind, arr)) 16 | if arr[ind] == ind + 1: 17 | ind += 1 18 | continue 19 | else: 20 | arr[arr[ind]-1], arr[ind] = arr[ind], arr[arr[ind]-1] 21 | res += 1 22 | 23 | return res 24 | 25 | if __name__ == '__main__': 26 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 27 | 28 | n = int(input()) 29 | 30 | arr = list(map(int, input().rstrip().split())) 31 | 32 | res = minimumSwaps(arr) 33 | 34 | fptr.write(str(res) + '\n') 35 | 36 | fptr.close() 37 | -------------------------------------------------------------------------------- /shell/fractal-trees-all.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | declare -A a 4 | 5 | # credits to https://github.com/MaskRay/HackerRank/blob/master/shell/fractal-trees-all.sh 6 | # d - depth 7 | # l = length 8 | # r = row 9 | # c = column 10 | 11 | f() { 12 | local d=$1 l=$2 r=$3 c=$4 13 | [[ $d -eq 0 ]] && return 14 | for ((i=l; i; i--)); do 15 | a[$((r-i)).$c]=1 16 | done 17 | ((r -= l)) 18 | for ((i=l; i; i--)); do 19 | a[$((r-i)).$((c-i))]=1 20 | a[$((r-i)).$((c+i))]=1 21 | done 22 | f $((d-1)) $((l/2)) $((r-l)) $((c-l)) 23 | f $((d-1)) $((l/2)) $((r-l)) $((c+l)) 24 | } 25 | read n 26 | f $n 16 63 49 27 | for ((i=0; i<63; i++)); do 28 | for ((j=0; j<100; j++)); do 29 | if [[ ${a[$i.$j]} ]]; then 30 | printf 1 31 | else 32 | printf _ 33 | fi 34 | done 35 | echo 36 | done -------------------------------------------------------------------------------- /algorithms part2/nimble-game-1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | from functools import reduce 9 | 10 | # Complete the nimbleGame function below. 11 | def nimbleGame(s): 12 | if len(s) > 1: 13 | res = 0 14 | for ind, el in enumerate(s): 15 | if el%2 == 1: 16 | res ^= ind 17 | else: 18 | return 'Second' 19 | 20 | if res == 0: 21 | return 'Second' 22 | else: 23 | return 'First' 24 | 25 | 26 | if __name__ == '__main__': 27 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 28 | 29 | t = int(input()) 30 | 31 | for t_itr in range(t): 32 | n = int(input()) 33 | 34 | s = list(map(int, input().rstrip().split())) 35 | 36 | result = nimbleGame(s) 37 | 38 | fptr.write(result + '\n') 39 | 40 | fptr.close() 41 | -------------------------------------------------------------------------------- /data-structures/insert-a-node-into-a-sorted-doubly-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Insert a node into a sorted doubly linked list 3 | head could be None as well for empty list 4 | Node is defined as 5 | 6 | class Node(object): 7 | 8 | def __init__(self, data=None, next_node=None, prev_node = None): 9 | self.data = data 10 | self.next = next_node 11 | self.prev = prev_node 12 | 13 | return the head node of the updated list 14 | """ 15 | 16 | def SortedInsert(head, data): 17 | if head == None: 18 | return Node(data=data, next_node=None, prev_node=None) 19 | 20 | node = head 21 | while node.next != None and node.next.data <= data: 22 | node = node.next 23 | 24 | node.next = Node(data=data, next_node=node.next, prev_node=node) 25 | 26 | return head 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /algorithms part1/apple-and-orange.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def appleAndOrange(s, t, a, b, apple, orange): 6 | count_app = 0 7 | count_org = 0 8 | for el in apple: 9 | if s <= el+a <= t: 10 | count_app += 1 11 | 12 | for el in orange: 13 | if s <= el+b <= t: 14 | count_org += 1 15 | 16 | return [ count_app, count_org ] 17 | 18 | if __name__ == "__main__": 19 | s, t = input().strip().split(' ') 20 | s, t = [int(s), int(t)] 21 | a, b = input().strip().split(' ') 22 | a, b = [int(a), int(b)] 23 | m, n = input().strip().split(' ') 24 | m, n = [int(m), int(n)] 25 | apple = list(map(int, input().strip().split(' '))) 26 | orange = list(map(int, input().strip().split(' '))) 27 | result = appleAndOrange(s, t, a, b, apple, orange) 28 | print ("\n".join(map(str, result))) 29 | 30 | 31 | -------------------------------------------------------------------------------- /data-structures/queries-with-fixed-length.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | if __name__ == "__main__": 4 | n, q = [int(x) for x in input().strip().split()] 5 | arr = [int(x) for x in input().strip().split()] 6 | 7 | for _ in range(q): 8 | d = int(input().strip()) 9 | maxes = [] 10 | was_first = False 11 | 12 | for i in range(n - d + 1): 13 | if i == 0 or was_first == True: 14 | #print(arr[i:i+d]) 15 | maxes.append(max(arr[i:i+d])) 16 | else: 17 | #print("max({}, {})".format(maxes[-1], arr[i+d-1])) 18 | maxes.append(max(maxes[-1], arr[i+d-1])) 19 | 20 | if maxes[-1] == arr[i]: 21 | was_first = True 22 | else: 23 | was_first = False 24 | 25 | print(min(maxes)) 26 | -------------------------------------------------------------------------------- /interview-preparation-kit/insert-a-node-into-a-sorted-doubly-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Insert a node into a sorted doubly linked list 3 | head could be None as well for empty list 4 | Node is defined as 5 | 6 | class Node(object): 7 | 8 | def __init__(self, data=None, next_node=None, prev_node = None): 9 | self.data = data 10 | self.next = next_node 11 | self.prev = prev_node 12 | 13 | return the head node of the updated list 14 | """ 15 | 16 | def SortedInsert(head, data): 17 | if head == None: 18 | return Node(data=data, next_node=None, prev_node=None) 19 | 20 | node = head 21 | while node.next != None and node.next.data <= data: 22 | node = node.next 23 | 24 | node.next = Node(data=data, next_node=node.next, prev_node=node) 25 | 26 | return head 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /data-structures/queue-using-two-stacks.py: -------------------------------------------------------------------------------- 1 | class MyQueue(object): 2 | def __init__(self): 3 | self.q1 = [] 4 | self.q2 = [] 5 | 6 | def peek(self): 7 | if not self.q2: 8 | while self.q1: 9 | self.q2.append(self.q1.pop()) 10 | 11 | return self.q2[-1] 12 | 13 | def pop(self): 14 | if not self.q2: 15 | while self.q1: 16 | self.q2.append(self.q1.pop()) 17 | 18 | return self.q2.pop() 19 | 20 | def put(self, value): 21 | self.q1.append(value) 22 | 23 | queue = MyQueue() 24 | t = int(input()) 25 | for line in range(t): 26 | values = map(int, input().split()) 27 | values = list(values) 28 | if values[0] == 1: 29 | queue.put(values[1]) 30 | elif values[0] == 2: 31 | queue.pop() 32 | else: 33 | print(queue.peek()) -------------------------------------------------------------------------------- /algorithms part1/beautiful-pairs.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | from collections import Counter 5 | 6 | def beautifulPairs(arr, brr): 7 | res = 0 8 | arr = sorted(arr) 9 | brr = sorted(brr) 10 | 11 | acnt = Counter(arr) 12 | bcnt = Counter(brr) 13 | 14 | spare = 0 15 | for el in acnt.items(): 16 | if el[0] in bcnt: 17 | get = bcnt[el[0]] 18 | res += min(el[1], get) 19 | else: 20 | spare += el[1] 21 | 22 | #print("res = {} spare = {}".format(res, spare)) 23 | 24 | if spare: 25 | res += 1 26 | else: 27 | res -= 1 28 | 29 | return res 30 | 31 | if __name__ == "__main__": 32 | n = int(input().strip()) 33 | A = list(map(int, input().strip().split(' '))) 34 | B = list(map(int, input().strip().split(' '))) 35 | result = beautifulPairs(A, B) 36 | print(result) 37 | -------------------------------------------------------------------------------- /c/dynamic-array-in-c.c: -------------------------------------------------------------------------------- 1 | int main() 2 | { 3 | int total_number_of_shelves; 4 | scanf("%d", &total_number_of_shelves); 5 | 6 | int total_number_of_queries; 7 | scanf("%d", &total_number_of_queries); 8 | 9 | total_number_of_books = (int *) malloc(total_number_of_shelves * sizeof(int)); 10 | total_number_of_pages = (int **) malloc(total_number_of_shelves * sizeof(int *)); 11 | 12 | while (total_number_of_queries--) { 13 | int type_of_query; 14 | scanf("%d", &type_of_query); 15 | 16 | if (type_of_query == 1) { 17 | int x, y; 18 | scanf("%d %d", &x, &y); 19 | total_number_of_books[x]++; 20 | total_number_of_pages[x] = (int *) realloc(total_number_of_pages[x], 21 | total_number_of_books[x] * sizeof(int)); 22 | total_number_of_pages[x][total_number_of_books[x]-1] = y; -------------------------------------------------------------------------------- /c/printing-pattern-2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define min(a, b) ((a) < (b) ? (a) : (b)) 7 | #define max(a, b) ((a) < (b) ? (b) : (a)) 8 | 9 | int main() 10 | { 11 | int n; 12 | scanf("%d", &n); 13 | 14 | for (int i = 0; i < 2*n - 1; i++) { 15 | int lead = 0; 16 | int lower_bound; 17 | 18 | if (i < n) 19 | lower_bound = n - i; 20 | else 21 | lower_bound = 2 + i%n; 22 | 23 | for (int j = 0; j < 2*n - 1; j++) { 24 | if (j < n-1) { 25 | printf("%d ", max(lower_bound, n - lead)); 26 | lead++; 27 | } 28 | else { 29 | printf("%d ", max(lower_bound, n - lead)); 30 | lead--; 31 | } 32 | } 33 | printf("\n"); 34 | } 35 | 36 | return 0; 37 | } --------------------------------------------------------------------------------