├── Important ├── CeaserCipher.py ├── FastestSumofN-Numbers.py ├── ParenthesisChecker.py ├── readaFile.py ├── GeneratorReturn.py ├── print_primeList.py ├── MinInList.py ├── repr_method.py ├── SimpleUnitTest.py ├── matrix-of-stars.py ├── Fibonacci_series.py ├── superUsage.py ├── find_substring.py ├── list.py ├── ReverseAString.py ├── StackToReverseAString.py ├── Questions.py ├── InsertionSort.py ├── HotPotato.py ├── highest_prod_list.py ├── super_example.py ├── hidden_properties.py ├── lookandsay1.py ├── highest_num_wihtout_maxFunc.py ├── firstRecurringChar.py ├── RearrangeAndCheckIfPalindrome.py ├── Iterator.py ├── dir_contents.py ├── accessSpecifier.py ├── kth_smallest_element.py ├── Permutations.py ├── BinarySearch.py ├── closure_example.py ├── ReturnFirstNonDupeItem.py ├── os_walk.py ├── contiguous_highest_sum.py ├── BaseConverter.py ├── CipherWord.py ├── DiffStrings.py ├── binarytoInteger.py ├── sort0-1-2.py ├── max_consective_1.py ├── ImplementQueue.py ├── FlattenListofLists.py ├── FizzBuzz.py ├── intToBinary.py ├── ImplementReverseStack.py ├── multipleinheritance.py ├── looksay.py ├── AllCombinations.py ├── ImplementingDequeue.py ├── Sum_of_2_int_in_array.py ├── ImplementStack.py ├── Transpose_matrix.py ├── class_methods_example.py ├── lowest_score_students.py ├── return_indices_of_substration.py ├── return_indices_of_sum.py ├── LinkedList_Node.py ├── average_score.py ├── peak_index_of_Mountain.py ├── PeakFinder-1D.py ├── RepeatingListofEvenNumbersFindTheOdd.py ├── MultipleLists.py ├── Rotate_string.py ├── DiffOfLists.py ├── Covert2Binary.py ├── meetingsInAllTimeZones.py ├── rotated_digits.py ├── AddDigitsTill-1.py ├── ArrayRotation.py ├── pattern.py ├── Palindrome.py ├── doorMat.py ├── LinkedList_Unordered.py ├── MergeSort.py ├── decorator_example2.py ├── birthday_candles.py ├── VowelReplace.py ├── longestSubstring.py ├── BubbleSort.py ├── RotateAList.py └── decorator_example.py ├── HackerRank ├── min_swaps.py ├── The_Coin_Change_Problem.py ├── Fibonacci_Modified.py ├── Equal.py ├── Sherlock_and_Cost.py ├── jumping_clouds.py ├── making_anagram_2_Strings.py ├── counting_valleys.py ├── hackerrank_in_string.py ├── pangram.py └── grading_students.py ├── bin ├── install.sh └── run.sh ├── DailyCoding ├── README.md ├── 10.py ├── 42.py ├── 101.py ├── 11.py ├── 1621.py ├── 49.py ├── 2.py ├── 1.py ├── 4.py ├── 1602.py ├── 29.py ├── 1601.py ├── 1573.py └── 1584.py ├── test ├── test_example.py ├── test_vowel_count.py ├── test_bin_tree_height.py ├── test_jump_game.py ├── test_top_frequent.py ├── test_find_odd_in_constant_space.py ├── test_two_sum_II.py ├── test_string_fill.py ├── test_linear_identification_of_sum_in_array.py ├── test_contiguous_highest_sum.py ├── test_CalculatePi.py ├── test_leetcode_number_of_1_bits.py ├── test_sum_root_to_leaf_numbers.py ├── test_binary_tree_right_side_view.py ├── test_array_plus_array.py ├── test_path_sum.py ├── test_7.py ├── test_fibonacci.py ├── test_matrix_operation.py ├── test_recursion_all_indices.py └── test_MergeSort.py ├── Exercism ├── hello-world │ └── hello_world.py ├── armstrong-numbers │ ├── armstrong_numbers.py │ └── README.md ├── acronym │ └── acronym.py ├── isogram │ └── isogram.py ├── pangram │ └── pangram.py ├── two-fer │ └── two_fer.py ├── perfect-numbers │ └── perfect_numbers.py ├── triangle │ └── triangle.py ├── all-your-base │ └── all_your_base.py ├── phone-number │ └── phone_number.py ├── word-count │ └── word_count.py └── palindrome-products │ └── palindrome_products.py ├── .gitignore ├── .travis.yml ├── LeetCode ├── 371.py ├── 5079.py ├── 5079-intersection-of-arrays.py ├── number_of_1_bits.py ├── 448.py ├── array_addition.py ├── Anagram.py ├── Find2intwithsum.py ├── 560.py ├── 5205.py ├── 5205-uniq-no-occurence.py ├── convert_to_lowercase.py ├── largest-sum-contiguous-subarray.py ├── 26.py ├── 5080.py ├── 5080-two-sum-bsts.py ├── 5.py ├── 581.py ├── jump_game.py ├── top_k_frequent.py ├── 217.py ├── 345.py ├── 169.py ├── buddystring.py ├── 94.py ├── two_sum_II.py ├── 784.py ├── 6.py ├── 724.py ├── 3.py ├── largest_number_at_least_twice_of_others.py ├── 541.py ├── 28.py ├── 58.py ├── 11.py ├── 104.py ├── binary_tree_right_side_view.py ├── self_dividing_numbers.py ├── 21.py ├── 7.py ├── 14.py ├── 122.py ├── 21_1.py ├── 27.py ├── 100.py ├── 121.py └── 61.py ├── Pipfile ├── Microsoft ├── Average_of_ASCII_values_of_characters_of_a_given_string.py └── Sum_of_cousins_of_a_given_node_in_a_Binary_Tree.py ├── requirements.txt ├── Hired └── debug1.py ├── CodeWars ├── ShortestWord.py ├── sort_the_odd.py ├── Unique_number.py ├── ArrayPlusArray.py ├── Tortoise_Racing.py ├── ModuletoAtoms.py ├── First_non_repeating_character.py └── take_a_ten_minute_walk.py ├── Company ├── implement_List.py ├── vowel_count.py ├── implement_Queue.py ├── string_fill.py ├── infinite_sequence.py ├── unique_username.py ├── search_strings_in_data.py ├── string_manipulation.py ├── collection_of_socks.py ├── fibonacci.py ├── find_average_in_a_matrix.py ├── matrixOperations.py ├── linear_identification_of_sum_in_array.py ├── find_max_difference.py ├── paranthesis_checker.py ├── hash_runners.py └── dups_in_json.py ├── GeeksforGeeks ├── Tower_of_Hanoi.py ├── kadanes_algorithm.py ├── roman_to_integer.py ├── recursion_all_indices.py ├── lenth_of_longest_contegeous_elements.py ├── pythagorean_triplet.py ├── reverse_string_with_special_char.py ├── smallest_subarray_with_greater_value.py ├── 1_N_queens.py └── longest_palindromic_substr.py ├── TreesAndGraphs ├── Depth-First-Search.py ├── bin_tree_height.py ├── Djikistra.py └── kruskall.py ├── PULL_REQUEST_TEMPLATE.md ├── Facebook └── all_wrong.py └── LICENSE /Important/CeaserCipher.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /HackerRank/min_swaps.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | 4 | """ -------------------------------------------------------------------------------- /bin/install.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | pipenv install pytest numpy -------------------------------------------------------------------------------- /bin/run.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | pipenv run pytest -vrfE -s -k test/ -------------------------------------------------------------------------------- /DailyCoding/README.md: -------------------------------------------------------------------------------- 1 | Coding challenges from https://www.dailycodingproblem.com/ -------------------------------------------------------------------------------- /test/test_example.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | def test_empty(): 4 | assert True -------------------------------------------------------------------------------- /Exercism/hello-world/hello_world.py: -------------------------------------------------------------------------------- 1 | def hello(): 2 | 3 | return 'Hello, World!' -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | __init* 3 | __pycache* 4 | .vscode* 5 | .DS_Store 6 | *BTC 7 | .pytest_cache -------------------------------------------------------------------------------- /Important/FastestSumofN-Numbers.py: -------------------------------------------------------------------------------- 1 | def SumOfN(n): 2 | return (n*(n+1)/2) 3 | 4 | print (SumOfN(10)) 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.7" 4 | install: 5 | - bin/install.sh 6 | script: 7 | - bin/run.sh -------------------------------------------------------------------------------- /Exercism/armstrong-numbers/armstrong_numbers.py: -------------------------------------------------------------------------------- 1 | def is_armstrong(number): 2 | return sum(int(ch) ** len(str(number)) for ch in str(number)) == number 3 | -------------------------------------------------------------------------------- /Important/ParenthesisChecker.py: -------------------------------------------------------------------------------- 1 | # implement a parenthesis checker 2 | 3 | def ParaChecker(symbolString): 4 | pass 5 | 6 | 7 | print(ParaChecker(input(""))) 8 | -------------------------------------------------------------------------------- /Important/readaFile.py: -------------------------------------------------------------------------------- 1 | 2 | path = '' 3 | 4 | total = 0 5 | with open(path) as f: 6 | lines = f.read() 7 | 8 | for line in lines: 9 | print(line) 10 | -------------------------------------------------------------------------------- /test/test_vowel_count.py: -------------------------------------------------------------------------------- 1 | from Company.vowel_count import count 2 | 3 | 4 | def test_count(): 5 | assert count('Alabama') == 4 6 | assert count('Caserta') == 3 7 | -------------------------------------------------------------------------------- /Important/GeneratorReturn.py: -------------------------------------------------------------------------------- 1 | # 0 1 8 27 64 2 | 3 | def gen(limit): 4 | for i in range(limit): 5 | yield i**3 6 | 7 | 8 | for f in gen(5): 9 | print(f) 10 | -------------------------------------------------------------------------------- /Important/print_primeList.py: -------------------------------------------------------------------------------- 1 | for n in range(1, 101): 2 | prime = True 3 | for i in range(2, n): 4 | if(n % 2 == 0): 5 | prime = False 6 | if prime: 7 | print(n) 8 | -------------------------------------------------------------------------------- /LeetCode/371.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getSum(self, a, b): 3 | """ 4 | :type a: int 5 | :type b: int 6 | :rtype: int 7 | """ 8 | return sum([a, b]) 9 | -------------------------------------------------------------------------------- /Exercism/acronym/acronym.py: -------------------------------------------------------------------------------- 1 | def abbreviate(words): 2 | special_seps = ["-"] 3 | for sep in special_seps: 4 | words = words.replace(sep, ' ') 5 | return ''.join(word[0].upper() for word in words.split()) 6 | -------------------------------------------------------------------------------- /Exercism/isogram/isogram.py: -------------------------------------------------------------------------------- 1 | def is_isogram(string): 2 | string = string.upper() 3 | for letter in string: 4 | if(letter.isalpha() and string.count(letter) > 1): 5 | return False 6 | return True -------------------------------------------------------------------------------- /test/test_bin_tree_height.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '../TreesAndGraphs/')) 4 | from bin_tree_height import unit_test 5 | 6 | def test_bin_tree_height(): 7 | unit_test() 8 | -------------------------------------------------------------------------------- /Exercism/pangram/pangram.py: -------------------------------------------------------------------------------- 1 | from string import ascii_lowercase 2 | 3 | 4 | def is_pangram(sentence): 5 | chars = set(ch for ch in sentence.lower() if ch in ascii_lowercase) 6 | return len(chars) == len(set(ascii_lowercase)) 7 | -------------------------------------------------------------------------------- /test/test_jump_game.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '..')) 4 | from LeetCode.jump_game import Solution 5 | 6 | def test_jump(): 7 | s = Solution() 8 | assert s.canJump([2,3,1,1,4]) == True -------------------------------------------------------------------------------- /Exercism/two-fer/two_fer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #encoding=utf8 3 | 4 | 5 | def two_fer(name=''): 6 | if name != '': 7 | f"One for {name}, one for me" 8 | else: 9 | f"One for you, one for me" 10 | -------------------------------------------------------------------------------- /test/test_top_frequent.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '..')) 4 | from LeetCode.top_k_frequent import Solution 5 | 6 | def test_topk(): 7 | s = Solution() 8 | assert s.topKFrequent([1,1,1,2,2,3],2) == [1,2] -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | url = "https://pypi.org/simple" 3 | verify_ssl = true 4 | name = "pypi" 5 | 6 | [packages] 7 | pytest = "*" 8 | numpy = "*" 9 | 10 | [dev-packages] 11 | 12 | [requires] 13 | python_version = "3.9" 14 | python_full_version = "3.9.18" 15 | -------------------------------------------------------------------------------- /test/test_find_odd_in_constant_space.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '..')) 4 | from Company.find_odd_in_constant_space import test_solution 5 | 6 | def test_find_odd_in_constant_space(): 7 | assert test_solution() 8 | 9 | -------------------------------------------------------------------------------- /test/test_two_sum_II.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '..')) 4 | from LeetCode.two_sum_II import twoSum 5 | 6 | def test_twoSum(): 7 | # check special cases 8 | assert twoSum([2, 7, 1, 15], 9) == [1, 2] 9 | 10 | -------------------------------------------------------------------------------- /Important/MinInList.py: -------------------------------------------------------------------------------- 1 | # Linear solution 2 | 3 | def findMin(lst): 4 | 5 | minInList = lst[0] 6 | 7 | for i in lst: 8 | if i < minInList: 9 | minInList = i 10 | 11 | return minInList 12 | 13 | 14 | print(findMin([5, 4, 3, 2, 1, 0])) 15 | -------------------------------------------------------------------------------- /Important/repr_method.py: -------------------------------------------------------------------------------- 1 | # printing objects/class 2 | 3 | class MyClass: 4 | 5 | def __init__(self, a, b): 6 | self.a = a 7 | self.b = b 8 | 9 | def __repr__(self): 10 | return "a: " + self.a + "b: " + self.b 11 | 12 | m = MyClass("hi", "there") 13 | print(m) -------------------------------------------------------------------------------- /test/test_string_fill.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '..')) 4 | from Company.string_fill import string_fill 5 | 6 | 7 | def test_string_fill(): 8 | assert string_fill("abc", 2) == "abc" 9 | assert string_fill("abc", 7) == " abc" 10 | 11 | -------------------------------------------------------------------------------- /LeetCode/5079.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: 3 | outList = [] 4 | for item in arr1: 5 | if item in arr2 and item in arr3: 6 | outList.append(item) 7 | return(outList) 8 | -------------------------------------------------------------------------------- /DailyCoding/10.py: -------------------------------------------------------------------------------- 1 | """ 2 | This problem was asked by Apple. 3 | 4 | Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds. 5 | 6 | """ 7 | 8 | import time 9 | def jobScheduler(f, n): 10 | time.sleep(n) 11 | f() 12 | 13 | 14 | jobScheduler(f, 1000) -------------------------------------------------------------------------------- /Important/SimpleUnitTest.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class TruthTest(unittest.TestCase): 4 | 5 | def test_assert_true(self): 6 | self.assertTrue(True) 7 | 8 | def test_assert_false(self): 9 | self.assertFalse(False) 10 | 11 | if __name__ == '__main__': 12 | unittest.main() 13 | -------------------------------------------------------------------------------- /LeetCode/5079-intersection-of-arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arraysIntersection(self, arr1: list[int], arr2: list[int], arr3: list[int]) -> list[int]: 3 | outList = [] 4 | for item in arr1: 5 | if item in arr2 and item in arr3: 6 | outList.append(item) 7 | return(outList) 8 | -------------------------------------------------------------------------------- /Microsoft/Average_of_ASCII_values_of_characters_of_a_given_string.py: -------------------------------------------------------------------------------- 1 | def averageValue(s): 2 | sum_char = 0 3 | for i in range(len(s)): 4 | sum_char += ord(s[i]) 5 | return sum_char // len(s) 6 | 7 | if __name__ == "__main__": 8 | 9 | s = input(); 10 | 11 | print(averageValue(s)) 12 | s1=input() 13 | -------------------------------------------------------------------------------- /test/test_linear_identification_of_sum_in_array.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '..')) 4 | from Company.linear_identification_of_sum_in_array import false_test, positive_test 5 | 6 | def test_linear_identification_of_sum_in_array(): 7 | assert false_test() 8 | assert positive_test() 9 | -------------------------------------------------------------------------------- /LeetCode/number_of_1_bits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hammingWeight(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | count = 0 8 | 9 | while n: 10 | count += n & 1 11 | n >>= 1 12 | 13 | return count 14 | -------------------------------------------------------------------------------- /Important/matrix-of-stars.py: -------------------------------------------------------------------------------- 1 | # given the number generate a 2 Dimentional matrix of '*' 2 | 3 | def matrix(n, c): 4 | 5 | for i in range(n): 6 | print(n * c) 7 | 8 | 9 | number = int(input("Enter the Dimension of the matrix: ")) 10 | character = input("Enter the character to make the matrix: ") 11 | matrix(number, character) 12 | -------------------------------------------------------------------------------- /test/test_contiguous_highest_sum.py: -------------------------------------------------------------------------------- 1 | import Important.contiguous_highest_sum as m 2 | 3 | def test_contigous_regular(): 4 | assert m.contiguous_pair([5,2,4,6,3,1]) == [4,6] 5 | 6 | def test_contigous_small(): 7 | assert m.contiguous_pair([5,2]) == [5,2] 8 | 9 | def test_contigous_empty(): 10 | assert m.contiguous_pair([]) == [] 11 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | -i https://pypi.org/simple 2 | exceptiongroup==1.2.0; python_version < '3.11' 3 | iniconfig==2.0.0; python_version >= '3.7' 4 | numpy==1.26.2; python_version >= '3.9' 5 | packaging==23.2; python_version >= '3.7' 6 | pluggy==1.3.0; python_version >= '3.8' 7 | pytest==7.4.3; python_version >= '3.7' 8 | tomli==2.0.1; python_version < '3.11' 9 | -------------------------------------------------------------------------------- /Exercism/perfect-numbers/perfect_numbers.py: -------------------------------------------------------------------------------- 1 | def classify(number): 2 | if number <= 0: 3 | raise ValueError("Bad number") 4 | sum_ = sum(i for i in range(1, number) if number % i == 0) 5 | if sum_ > number: 6 | return "abundant" 7 | elif sum_ < number: 8 | return "deficient" 9 | else: 10 | return "perfect" 11 | -------------------------------------------------------------------------------- /HackerRank/The_Coin_Change_Problem.py: -------------------------------------------------------------------------------- 1 | # Problem: https://www.hackerrank.com/challenges/coin-change/problem 2 | 3 | n, m = map(int, input().split()) 4 | coins = list(map(int, input().split())) 5 | 6 | ans = [1] + [0] * n 7 | 8 | for i in range(m): 9 | for j in range(coins[i], n + 1): 10 | ans[j] += ans[j - coins[i]] 11 | 12 | print(ans[-1]) 13 | -------------------------------------------------------------------------------- /HackerRank/Fibonacci_Modified.py: -------------------------------------------------------------------------------- 1 | # Problem: https://www.hackerrank.com/challenges/fibonacci-modified/problem 2 | 3 | n1, n2, n = map(int, input().split()) 4 | sequence = [n1, n2] 5 | 6 | if n <= 2: 7 | print(sequence[n-1]) 8 | else: 9 | for i in range(n-2): 10 | sequence.append(sequence[-2] + sequence[-1]**2) 11 | 12 | print(sequence[-1]) 13 | -------------------------------------------------------------------------------- /Important/Fibonacci_series.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Fibonacci series: 1 1 2 3 5 8 13 ... 3 | 4 | Write a function to spit out the nth Fibonacci number 5 | input: 6 | 5 7 | 8 | output: 9 | 5 10 | ''' 11 | 12 | 13 | def fib(limit): 14 | 15 | a, b = 0, 1 16 | for _ in range(limit): 17 | a, b = b, a+b 18 | 19 | return a 20 | 21 | 22 | print(fib(10)) 23 | -------------------------------------------------------------------------------- /Important/superUsage.py: -------------------------------------------------------------------------------- 1 | class Parent: 2 | def __init__(self, name): 3 | self.name = name 4 | 5 | class Child(Parent): 6 | def __init__(self, name, age): 7 | super(Child, self).__init__(name) 8 | self.age = age 9 | 10 | def display(self): 11 | print(self.name, self.age) 12 | 13 | obj = Child("child name", 6) 14 | obj.display() -------------------------------------------------------------------------------- /Important/find_substring.py: -------------------------------------------------------------------------------- 1 | 2 | def find_substring(s1, s2): 3 | 4 | l1=len(s1) 5 | l2=len(s2) 6 | count=0 7 | 8 | if s1==s2: 9 | return count+1 10 | else: 11 | for i in range(l1-l2+1): 12 | if s2 == s1[i:l2+i]: 13 | count+=1 14 | 15 | return count 16 | 17 | print (find_substring('abcdcdcd', 'cd')) 18 | -------------------------------------------------------------------------------- /Hired/debug1.py: -------------------------------------------------------------------------------- 1 | def solution(values, n , k) -> int: 2 | v1 = [x for x in values if x % k ==0] 3 | v1 = set(v1) 4 | v1 = sorted(v1, reverse=True) 5 | print(v1) 6 | count = 1 7 | for _ in v1: 8 | if count == k: 9 | return v1[count] 10 | count += 1 11 | 12 | values = [4,9,3,12,6,4,15] 13 | n = 4 14 | k = 3 15 | print(solution(values, n, k)) -------------------------------------------------------------------------------- /Important/list.py: -------------------------------------------------------------------------------- 1 | A0 = dict(zip(('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, 5, 6))) 2 | A1 = range(10) 3 | A2 = sorted([i for i in A1 if i in A0]) 4 | A3 = sorted([A0[s] for s in A0]) 5 | A4 = [i for i in A1 if i in A3] 6 | A5 = {i: i*i for i in A1} 7 | A6 = [[i, i*i] for i in A1] 8 | 9 | print(A0) 10 | print(A1) 11 | print(A2) 12 | print(A3) 13 | print(A4) 14 | print(A5) 15 | print(A6) 16 | -------------------------------------------------------------------------------- /test/test_CalculatePi.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '..')) 4 | from Important.CalculatePi import * 5 | 6 | PI = 3.141592653589793 # Close enough 7 | threshold = 0.01 8 | 9 | def test_calculate_pi(): 10 | pi_result = calculate_pi(iterations=100000) 11 | error = pi_result - PI 12 | 13 | assert abs(error) "))) 18 | -------------------------------------------------------------------------------- /test/test_leetcode_number_of_1_bits.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '..')) 4 | from LeetCode.number_of_1_bits import Solution 5 | 6 | def test_191(): 7 | s = Solution() 8 | # check special cases 9 | assert s.hammingWeight(0) == 0 10 | assert s.hammingWeight(0b00000000000000000000000000001011) == 3 11 | assert s.hammingWeight(0b11111111) == 8 12 | 13 | -------------------------------------------------------------------------------- /LeetCode/448.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findDisappearedNumbers(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | if len(nums) == 0: 8 | return nums 9 | mx = max(nums) 10 | mx = max(mx, len(nums)) 11 | nums = set(nums) 12 | return [c for c in [x for x in range(1, mx + 1)] if c not in nums] 13 | -------------------------------------------------------------------------------- /Important/Questions.py: -------------------------------------------------------------------------------- 1 | class Questions: 2 | text = None 3 | answer = None 4 | 5 | class Add(Questions): 6 | 7 | def __init__(self, num1, num2): 8 | self.text = '{} + {}'.format(num1, num2) 9 | self.answer = num1 + num2 10 | 11 | class Multiply(Questions): 12 | 13 | def __init__(self, num1, num2): 14 | self.text = '{} * {}'.format(num1, num2) 15 | self.answer = num1 * num2 -------------------------------------------------------------------------------- /Important/InsertionSort.py: -------------------------------------------------------------------------------- 1 | # do the insertion sort algorithm 2 | def insertionSort(A): 3 | 4 | for i in range(1, len(A)): 5 | currentVal = A[i] 6 | position = i 7 | 8 | while position > 0 and A[position-1] > currentVal: 9 | A[position] = A[position-1] 10 | position = position - 1 11 | 12 | A[position] = currentVal 13 | 14 | A = [54,26,93,17,77,31,44,55,20] 15 | insertionSort(A) 16 | print (A) -------------------------------------------------------------------------------- /Important/HotPotato.py: -------------------------------------------------------------------------------- 1 | from ImplementQueue import Queue 2 | 3 | 4 | def hotPotato(lst, num): 5 | 6 | queue = Queue() 7 | 8 | for item in lst: 9 | queue.enqueue(item) 10 | 11 | while queue.size() > 1: 12 | for i in range(num): 13 | queue.enqueue(queue.dequeue()) 14 | 15 | queue.dequeue() 16 | 17 | return queue.dequeue() 18 | 19 | 20 | lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 21 | print(hotPotato(lst, 7)) 22 | -------------------------------------------------------------------------------- /Important/highest_prod_list.py: -------------------------------------------------------------------------------- 1 | # You are given numbers. Store them in a list and find the second largest number. 2 | 3 | try: 4 | N = int(input()) 5 | except ValueError as va: 6 | print("expected an int:{}".format(va)) 7 | 8 | l = list(input().split()) 9 | 10 | new_l = [] 11 | for v in l: 12 | new_l.append(int(v)) 13 | 14 | max_val = max(new_l) 15 | 16 | while max_val in new_l: 17 | new_l.pop(new_l.index(max_val)) 18 | 19 | print(max(new_l)) 20 | -------------------------------------------------------------------------------- /Important/super_example.py: -------------------------------------------------------------------------------- 1 | # base class 2 | class Base(object): 3 | 4 | def __init__(self, x): 5 | self.x = x 6 | 7 | 8 | class Derived(Base): 9 | 10 | def __init__(self, x, y): 11 | # sending the x value up to base class 12 | super(Derived, self).__init__(x) 13 | self.y = y 14 | 15 | def printD(self): 16 | print(self.x + " " + self.y) 17 | 18 | 19 | d = Derived("hi", "there") 20 | d.printD() # prints => hi there 21 | -------------------------------------------------------------------------------- /Important/hidden_properties.py: -------------------------------------------------------------------------------- 1 | # define a regular class 2 | class Car: 3 | 4 | # hidden properties are defined between __? 5 | __hiddenProperty = "test" 6 | 7 | def __init__(self, model): 8 | self.model = model 9 | 10 | def model(self): 11 | print(self.model) 12 | 13 | mazda = Car("Mazda") 14 | print(mazda.model) 15 | # this will give u an error 16 | # print(mazda.__hiddenProperty) 17 | 18 | # can be read by below 19 | print(mazda._Car__hiddenProperty) -------------------------------------------------------------------------------- /CodeWars/ShortestWord.py: -------------------------------------------------------------------------------- 1 | """Simple, given a string of words, return the length of the shortest word(s). 2 | 3 | String will never be empty and you do not need to account for different data types.""" 4 | 5 | def find_short(s): 6 | s = s.split() 7 | shortestLength = len(s[0]) 8 | for item in s: 9 | if len(item) < shortestLength: 10 | shortestLength = len(item) 11 | return shortestLength 12 | 13 | print (find_short("Find shortest word in this dumbass string")) -------------------------------------------------------------------------------- /DailyCoding/42.py: -------------------------------------------------------------------------------- 1 | """ 2 | This problem was asked by Google. 3 | 4 | Given a list of integers S and a target number k, write a function that returns a subset of S that adds up to k. If such a subset cannot be made, then return null. 5 | 6 | Integers can appear more than once in the list. You may assume all numbers in the list are positive. 7 | 8 | For example, given S = [12, 1, 61, 5, 9, 2] and k = 24, return [12, 9, 2, 1] since it sums up to 24. 9 | 10 | """ 11 | 12 | def subArray(S, k): 13 | -------------------------------------------------------------------------------- /Company/implement_List.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class List(): 4 | 5 | def __init__(self): 6 | self._list = list() 7 | 8 | def __str__(self): 9 | return str(self._list) 10 | 11 | def addItem(self, item): 12 | if item not in self._list: 13 | self._list.append(item) 14 | 15 | def removeItem(self, item): 16 | self._list.remove(item) 17 | 18 | 19 | l = List() 20 | l.addItem('a') 21 | l.addItem('a') 22 | l.addItem('b') 23 | print(l) 24 | l.removeItem('b') 25 | print(l) 26 | -------------------------------------------------------------------------------- /Important/lookandsay1.py: -------------------------------------------------------------------------------- 1 | # ABBCD 2 | 3 | def lookandSay(look): 4 | 5 | say = '' 6 | for char in look: 7 | i = look.index(char) 8 | if i != look.index(look[-1]): 9 | nex = look[i+1] 10 | count = '1' 11 | 12 | if char == nex: 13 | count = int(count)+1 14 | continue 15 | else: 16 | say = str(count) + char 17 | 18 | print(say) 19 | 20 | 21 | lookandSay(input("Enter a string for LookandSay: ")) 22 | -------------------------------------------------------------------------------- /Important/highest_num_wihtout_maxFunc.py: -------------------------------------------------------------------------------- 1 | 2 | l = [1, 2, -1, 5, 8, 90, 2, 21, 32, 45] 3 | 4 | 5 | def highest_num(l): 6 | 7 | max_num = l[0] 8 | 9 | for num in l: 10 | if num > max_num: 11 | max_num = num 12 | 13 | return max_num 14 | 15 | 16 | def highest_num1(l): 17 | 18 | return sorted(l)[-1] 19 | 20 | 21 | def highest_num2(l): 22 | l.sort() 23 | return l[-1] 24 | 25 | 26 | print(highest_num(l)) 27 | 28 | print(highest_num1(l)) 29 | 30 | print(highest_num2(l)) 31 | -------------------------------------------------------------------------------- /Important/firstRecurringChar.py: -------------------------------------------------------------------------------- 1 | # return a first recurring char 2 | # Q: ABCDA 3 | # A: A 4 | 5 | def firstRecurring(str): 6 | 7 | if (len(str) == 0 or len(str) == 1): 8 | return str 9 | 10 | if (str.isdigit()): 11 | return '\0' 12 | 13 | dict = {} 14 | for ch in str: 15 | if ch in dict: 16 | return ch 17 | else: 18 | dict[ch] = 0 19 | 20 | return '\0' 21 | 22 | 23 | print(firstRecurring(input("enter the string to get first recurring char: "))) 24 | -------------------------------------------------------------------------------- /Company/vowel_count.py: -------------------------------------------------------------------------------- 1 | """ 2 | You get a string and need to return its number of vowels. 3 | For this test, we will only consider a, e, i, o and u as vowels. 4 | 5 | For example: 6 | 7 | Input: "Alabama" 8 | Output: 4 9 | 10 | Input: "Caserta" 11 | Output: 3 12 | 13 | """ 14 | 15 | 16 | #For Loop 17 | def count(input_string): 18 | num_vowels = 0 19 | vowels = ['a', 'e', 'i', 'o', 'u'] 20 | for letter in input_string.lower(): 21 | if letter in vowels: 22 | num_vowels += 1 23 | 24 | return num_vowels 25 | -------------------------------------------------------------------------------- /HackerRank/Equal.py: -------------------------------------------------------------------------------- 1 | # Problem: https://www.hackerrank.com/challenges/equal/problem 2 | 3 | target = [0, 1, 2] 4 | 5 | def solution(arr): 6 | min_arr = min(arr) 7 | results = [0] * len(target) 8 | 9 | for item in arr: 10 | for i in target: 11 | gap = item - min_arr + i 12 | results[i] += gap // 5 + (gap%5) // 2 + (gap%5)%2 13 | return min(results) 14 | 15 | 16 | for t in range(int(input())): 17 | input() 18 | items = list(map(int, input().split())) 19 | 20 | print(solution(items)) 21 | -------------------------------------------------------------------------------- /Important/RearrangeAndCheckIfPalindrome.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | 4 | def check_if_palindrome(s): 5 | 6 | result = False 7 | tup_list = [] 8 | for i in itertools.permutations(s, len(s)): 9 | tup_list.append(i) 10 | 11 | for tup in tup_list: 12 | if palindrome(tup): 13 | result = True 14 | break 15 | 16 | return result 17 | 18 | 19 | def palindrome(s): 20 | return s[:] == s[::-1] 21 | 22 | 23 | print(check_if_palindrome(input(('Enter a string to check if palindrome > ')))) 24 | -------------------------------------------------------------------------------- /test/test_sum_root_to_leaf_numbers.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '..')) 4 | from LeetCode.sum_root_to_leaf_numbers import Solution 5 | 6 | class TreeNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.left = None 10 | self.right = None 11 | 12 | def test_sum_root_to_leaf_numbers(): 13 | 14 | root = TreeNode(1) 15 | 16 | root.left = TreeNode(2) 17 | root.right = TreeNode(3) 18 | 19 | S = Solution() 20 | 21 | assert S.sumNumbers(root) == 25 22 | -------------------------------------------------------------------------------- /Company/implement_Queue.py: -------------------------------------------------------------------------------- 1 | class Queue(object): 2 | 3 | def __init__(self): 4 | self._list = list() 5 | 6 | def __str__(self): 7 | return str(self._list) 8 | 9 | def enqueue(self, item): 10 | self._list.append(item) 11 | 12 | def dequeue(self, item): 13 | if len(self._list) > 0: 14 | index = self._list.index(item) 15 | return self._list.pop(index) 16 | 17 | 18 | q = Queue() 19 | q.enqueue('a') 20 | q.enqueue('b') 21 | q.enqueue('c') 22 | print(q) 23 | q.dequeue('c') 24 | print(q) 25 | -------------------------------------------------------------------------------- /GeeksforGeeks/Tower_of_Hanoi.py: -------------------------------------------------------------------------------- 1 | # Recursive Python function to solve the tower of hanoi 2 | 3 | def TowerOfHanoi(n , source, destination, auxiliary): 4 | if n==1: 5 | print "Move disk 1 from source",source,"to destination",destination 6 | return 7 | TowerOfHanoi(n-1, source, auxiliary, destination) 8 | print "Move disk",n,"from source",source,"to destination",destination 9 | TowerOfHanoi(n-1, auxiliary, destination, source) 10 | 11 | # Driver code 12 | n = 4 13 | TowerOfHanoi(n,'A','B','C') 14 | # A, C, B are the name of rods 15 | 16 | 17 | -------------------------------------------------------------------------------- /HackerRank/Sherlock_and_Cost.py: -------------------------------------------------------------------------------- 1 | # Problem: https://www.hackerrank.com/challenges/sherlock-and-cost/problem 2 | 3 | test = int(input()) 4 | 5 | for i in range(test): 6 | n = int(input()) 7 | b = list(map(int, input().split())) 8 | 9 | dp = [[0], [0]] 10 | 11 | for i in range(1, len(b)): 12 | add_1 = max(dp[0][-1], dp[1][-1] + b[i - 1] - 1) 13 | add_max = max(dp[0][-1] + b[i] - 1, dp[1][-1] + abs(b[i] - b[i - 1])) 14 | dp[0].append(add_1) 15 | dp[1].append(add_max) 16 | 17 | print(max(dp[0][-1], dp[1][-1])) 18 | -------------------------------------------------------------------------------- /LeetCode/array_addition.py: -------------------------------------------------------------------------------- 1 | ''' 2 | given an integer array [1,2,3,9] add a carry to it so that it becomes [1,2,4,0] 3 | 4 | Input: 5 | [1,2,9,9] 6 | Output: 7 | [1,3,0,0] 8 | 9 | ''' 10 | 11 | def array_add(A): 12 | carry = 1 13 | new = [] 14 | for i in A[::-1]: 15 | add = i + carry 16 | if add != 10 : 17 | carry = 0 18 | new.append(add) 19 | else: 20 | new.append(0) 21 | 22 | if carry == 1: 23 | new.append(1) 24 | 25 | return new[::-1] 26 | 27 | print(array_add([1,9,9,9,9,9])) -------------------------------------------------------------------------------- /Important/Iterator.py: -------------------------------------------------------------------------------- 1 | class ArrayList: 2 | def __init__(self, nums) -> None: 3 | self.nums = nums 4 | 5 | def __iter__(self): 6 | self.pos = 0 7 | return self 8 | def __next__(self): 9 | if (self.pos < len(self.nums)): 10 | self.pos += 1 11 | return self.nums[self.pos - 1] 12 | else: 13 | raise StopIteration 14 | 15 | array_obj = ArrayList([1,2,3]) 16 | 17 | it = iter(array_obj) 18 | print(next(it)) # 1 19 | print(next(it)) # 2 20 | print(next(it)) # 3 21 | print(next(it)) # stopIteration exception 22 | -------------------------------------------------------------------------------- /Important/dir_contents.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | path = '/Users/aarakeri/PythonScripts/' 4 | 5 | total_files = [] 6 | 7 | 8 | def print_dir_contents(path): 9 | global total_files 10 | 11 | for child in os.listdir(path): 12 | childpath = os.path.join(path, child) 13 | 14 | if os.path.isdir(childpath): 15 | print_dir_contents(childpath) 16 | else: 17 | print(childpath) 18 | total_files.append(childpath) 19 | 20 | 21 | print_dir_contents(path) 22 | 23 | print("\n Total files in the path {} : {}\n".format(path, len(total_files))) 24 | -------------------------------------------------------------------------------- /LeetCode/Anagram.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function to check if two strings are anagrams of each other 3 | Anagram = 'abcd' is anagram of 'cdba' 4 | 5 | input: 6 | 'abcd' 7 | 'cdba' 8 | 9 | output: 10 | True 11 | 12 | ''' 13 | 14 | 15 | def is_Anagram(str1, str2): 16 | 17 | l1 = list(str1) 18 | l2 = list(str2) 19 | 20 | return sorted(l1) == sorted(l2) 21 | 22 | 23 | def is_Anagram2(str1, str2): 24 | return str1 == str2[::-1] 25 | 26 | 27 | a = input("Enter the first string: ") 28 | b = input("Enter the second string: ") 29 | print(is_Anagram(a, b)) 30 | print(is_Anagram2(a, b)) 31 | -------------------------------------------------------------------------------- /LeetCode/Find2intwithsum.py: -------------------------------------------------------------------------------- 1 | # Let A be an array of random integers and a given integer x. 2 | # Find all pairs of numbers from the array whose sum is equal to x. 3 | 4 | # import collections 5 | 6 | def find2ints(arr, x): 7 | 8 | #d = [0] * 10000 9 | d = {x-i: (i*0) for i in arr} 10 | 11 | new_l = [] 12 | for i in arr: 13 | temp = x - i 14 | 15 | if temp >= 0 and d[temp] == 1: 16 | new_l.append((temp, i)) 17 | 18 | d[i] = 1 19 | return new_l 20 | 21 | 22 | arr = [1, 2, 3, 4, 5, 6, 7, 7, 10] 23 | x = 10 24 | 25 | print(find2ints(arr, x)) 26 | -------------------------------------------------------------------------------- /LeetCode/560.py: -------------------------------------------------------------------------------- 1 | """ 2 | Subarray Sum Equals K 3 | 4 | Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 5 | 6 | Ex:1 7 | Input:nums = [1,1,1], k = 2 8 | Output: 2 9 | 10 | """ 11 | 12 | def subarraysum(nums, k): 13 | sums = {0:1} 14 | res = 0 15 | cur_sum = 0 16 | for n in nums: 17 | cur_sum += n 18 | res += sums.get(cur_sum - k, 0) # if it is not found return 0 19 | sums[cur_sum] = sums.get(cur_sum,0) + 1 20 | 21 | return res 22 | 23 | A = [1,2,3] 24 | k = 5 25 | print(subarraysum(A, k)) -------------------------------------------------------------------------------- /Important/accessSpecifier.py: -------------------------------------------------------------------------------- 1 | # to demonstrate access specifiers 2 | class Employee: 3 | 4 | # protected members 5 | _emp_name = None 6 | _age = None 7 | 8 | # private members 9 | __branch = None 10 | 11 | # constructor 12 | def __init__(self, emp_name, age, branch): 13 | self._emp_name = emp_name 14 | self._age = age 15 | self.__branch = branch 16 | 17 | #public member 18 | def display(self): 19 | print(self._emp_name +" "+self._age+" "+self.__branch) 20 | 21 | obj = Employee("employee name", "26", "main") 22 | obj.display() -------------------------------------------------------------------------------- /Important/kth_smallest_element.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an array of integers, and you have to find the k-th smallest number in the array. 3 | 4 | Input Format: 5 | 6 | The first line contains the value of K 7 | The second line contains a space separated list of integers 8 | 9 | 10 | Output Format: 11 | 12 | The only line contains the k-th smallest number in the array 13 | 14 | ''' 15 | 16 | k = int(input("Enter K: ")) 17 | print("Enter the array: ") 18 | arr = list(map(int, input().split(" "))) 19 | 20 | arrNew = sorted(arr) 21 | 22 | for i in range(1, k): 23 | del arrNew[0] 24 | print(arrNew[0]) 25 | -------------------------------------------------------------------------------- /Exercism/triangle/triangle.py: -------------------------------------------------------------------------------- 1 | def is_triangle(func): 2 | def wrapped(sides): 3 | if any(i <= 0 for i in sides): 4 | return False 5 | sum_ = sum(sides) 6 | if any(sides[i] > sum_ - sides[i] for i in range(3)): 7 | return False 8 | return func(sides) 9 | return wrapped 10 | 11 | 12 | @is_triangle 13 | def is_equilateral(sides): 14 | return len(set(sides)) == 1 15 | 16 | 17 | @is_triangle 18 | def is_isosceles(sides): 19 | return len(set(sides)) != 3 20 | 21 | 22 | @is_triangle 23 | def is_scalene(sides): 24 | return len(set(sides)) == 3 25 | -------------------------------------------------------------------------------- /Important/Permutations.py: -------------------------------------------------------------------------------- 1 | def permutations(lst): 2 | if len(lst) <= 1: 3 | return [lst] 4 | results = [] 5 | for i in range(len(lst)): 6 | for perm in permutations(lst[:i] + lst[i+1:]): 7 | results.append([lst[i]] + perm) 8 | return results 9 | 10 | # can also be done like this ;) 11 | # import itertools 12 | # def permutations(lst): 13 | # 14 | # results=[] 15 | # for i in itertools.permutations(lst, len(lst)): 16 | # results.append(list(i)) 17 | # 18 | # return results 19 | 20 | 21 | print(permutations([1, 2, 3])) 22 | 23 | print(permutations([1])) 24 | -------------------------------------------------------------------------------- /Important/BinarySearch.py: -------------------------------------------------------------------------------- 1 | # implement Binary Search 2 | 3 | def BinarySearch(alist, num): 4 | found = False 5 | first = 0 6 | last = len(alist) - 1 7 | 8 | while first <= last and not found: 9 | middle = (last + first)//2 10 | 11 | if alist[middle] == num: 12 | found = True 13 | elif alist[middle] < num: 14 | first = middle + 1 15 | else: 16 | last = middle - 1 17 | 18 | return found 19 | 20 | 21 | alist = [x for x in range(15)] 22 | num = int(input("enter the number you want to search > ")) 23 | print(BinarySearch(alist, num)) 24 | -------------------------------------------------------------------------------- /Important/closure_example.py: -------------------------------------------------------------------------------- 1 | # example of a nested function with out closure 2 | # outer func 3 | def outer_function(text): 4 | 5 | def inner_fuction(): 6 | print(text) 7 | 8 | inner_fuction() 9 | 10 | outer_function("Hi, from nested function without closure") 11 | 12 | # example of nested function with closure 13 | def outer_function1(text): 14 | 15 | def inner_function1(): 16 | print(text) 17 | 18 | return inner_function1 # notice the nested func being returned with out the paranthesis 19 | 20 | out_func = outer_function1("Hi, From nested function with Closure") 21 | out_func() -------------------------------------------------------------------------------- /Important/ReturnFirstNonDupeItem.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | 4 | def first_non_dup_item(string): 5 | 6 | d = collections.OrderedDict() 7 | 8 | for char in string.lower(): 9 | if char in d: 10 | d[char] += 1 11 | else: 12 | d[char] = 1 13 | 14 | while d > 0: 15 | # if you change the last=True , you will get the last dup item 16 | char, count = d.popitem(last=False) 17 | 18 | if count == 1: 19 | return char 20 | 21 | return None 22 | 23 | 24 | print(first_non_dup_item(input("Enter a string to return first Non Dupe item: "))) 25 | -------------------------------------------------------------------------------- /Important/os_walk.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function to search for a particular pattern of file in the 3 | current directory 4 | 5 | ''' 6 | 7 | 8 | import os 9 | 10 | 11 | def osWalkandFind(pat): 12 | 13 | pattern_lst = [] 14 | 15 | for dirpath, dirname, filenames in os.walk(os.getcwd()): 16 | for filename in filenames: 17 | if filename.endswith(pat): 18 | pattern_lst.append(os.path.join(dirpath, filename)) 19 | 20 | print("Files found of format({}): {}".format(pat, str(len(pattern_lst)))) 21 | 22 | 23 | osWalkandFind(input("\nEnter the pattern to search(ex: .txt, .py : ")) 24 | -------------------------------------------------------------------------------- /LeetCode/5205.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def uniqueOccurrences(self, arr): 3 | """ 4 | :type arr: List[int] 5 | :rtype: bool 6 | """ 7 | 8 | uniqList = list(set(arr)) 9 | countList = [] 10 | 11 | for x in uniqList: 12 | count = arr.count(x) 13 | if count not in countList: 14 | countList.append(count) 15 | 16 | uniqCount = list(set(countList)) 17 | 18 | if (len(uniqList) == len(uniqCount)): 19 | return True 20 | else: 21 | return False 22 | -------------------------------------------------------------------------------- /TreesAndGraphs/Depth-First-Search.py: -------------------------------------------------------------------------------- 1 | def procura(caminho, raiz, destino, pai, cont): 2 | if raiz == destino: 3 | print(cont) 4 | return 5 | for pivo in caminho[raiz]: 6 | if pivo != pai: 7 | procura(caminho, pivo, destino, raiz, cont + 1) 8 | entr1 = input().split() 9 | dist = (int(entr1[0])) 10 | caminho = {} 11 | for i in range(dist): 12 | caminho[i + 1] = [] 13 | for j in range(dist-1): 14 | entr2 = input().split() 15 | caminho[int(entr2[0])].append(int(entr2[1])) 16 | caminho[int(entr2[1])].append(int(entr2[0])) 17 | procura(caminho, int(entr1[1]), int(entr1[2]), None, 0) 18 | -------------------------------------------------------------------------------- /HackerRank/jumping_clouds.py: -------------------------------------------------------------------------------- 1 | Details of the challenge: https://www.hackerrank.com/challenges/jumping-on-the-clouds/ 2 | 3 | # Complete the jumpingOnClouds function below. 4 | def jumpingOnClouds(c): 5 | jumps = 0 6 | position = 0 7 | while position != len(c) - 1: 8 | if position != len(c) -2: 9 | if c[position + 2] is not 1: 10 | jumps += 1 11 | position += 2 12 | elif c[position + 1] is not 1: 13 | jumps += 1 14 | position += 1 15 | else: 16 | jumps += 1 17 | position += 1 18 | return jumps 19 | -------------------------------------------------------------------------------- /LeetCode/5205-uniq-no-occurence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def uniqueOccurrences(self, arr): 3 | """ 4 | :type arr: List[int] 5 | :rtype: bool 6 | """ 7 | 8 | uniqList = list(set(arr)) 9 | countList = [] 10 | 11 | for x in uniqList: 12 | count = arr.count(x) 13 | if count not in countList: 14 | countList.append(count) 15 | 16 | uniqCount = list(set(countList)) 17 | 18 | if (len(uniqList) == len(uniqCount)): 19 | return True 20 | else: 21 | return False 22 | -------------------------------------------------------------------------------- /Company/string_fill.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that receives string and number, 3 | and returns original string if number <= length of string, or 4 | string filled with spaces before original string with length = number 5 | 6 | Example 7 | >> string_fill("abc", 7) 8 | abc 9 | >> string_fill("abc", 2) 10 | abc 11 | """ 12 | 13 | def string_fill(original_str: str, number: int) -> str: 14 | if len(original_str) >= number: 15 | return original_str 16 | else: 17 | count_spaces = number - len(original_str) 18 | return " " * count_spaces + original_str 19 | 20 | 21 | #execute the function 22 | string_fill("abc", 7) 23 | -------------------------------------------------------------------------------- /DailyCoding/101.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Python | Check for URL in a String 3 | ''' 4 | 5 | # Python code to find the URL from an input string 6 | # Using the regular expression 7 | import re 8 | 9 | def Find(string): 10 | # findall() has been used 11 | # with valid conditions for urls in string 12 | url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+] 13 | |[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string) 14 | return url 15 | 16 | # Driver Code 17 | string = 'My Profile: https://auth.google.com.org 18 | / user / Chinmoy % 20Lenka / articles in 19 | the portal of http://www.geeksforgeeks.org/' 20 | print("Urls: ", Find(string)) -------------------------------------------------------------------------------- /Important/contiguous_highest_sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array as input, extract the pair of contiguous integers that have the highest sum of all pairs. Return the pair as an array. 3 | I = [5, 2, 4, 6, 3, 1] 4 | O = [4,6] 5 | 6 | """ 7 | 8 | def contiguous_pair(arr): 9 | if len(arr) == 2: 10 | return arr 11 | elif len(arr) < 2: 12 | return [] 13 | else: 14 | pair = [] 15 | highest = 0 16 | 17 | for i in range(len(arr)- 1): 18 | if highest < arr[i] + arr[i+1]: 19 | highest = arr[i] + arr[i+1] 20 | pair = [arr[i], arr[i+1]] 21 | 22 | return pair 23 | -------------------------------------------------------------------------------- /Exercism/all-your-base/all_your_base.py: -------------------------------------------------------------------------------- 1 | def rebase(input, digits, output_base): 2 | if input < 2 or output_base < 2: 3 | raise ValueError("invalid base") 4 | if any(d >= input or d < 0 for d in digits): 5 | raise ValueError("invalid digit") 6 | value = 0 7 | for i, digit in enumerate(digits): 8 | value += digit * input ** (len(digits) - i - 1) 9 | if not value: 10 | return [] 11 | rebased = [] 12 | while True: 13 | div, mod = divmod(value, output_base) 14 | rebased.append(mod) 15 | if div == 0: 16 | break 17 | value = div 18 | return list(reversed(rebased)) 19 | -------------------------------------------------------------------------------- /Exercism/phone-number/phone_number.py: -------------------------------------------------------------------------------- 1 | from string import digits 2 | 3 | 4 | class Phone(object): 5 | def __init__(self, phone_number): 6 | numbers = "".join(ch for ch in phone_number if ch in digits) 7 | if numbers.startswith("1"): 8 | numbers = numbers[1:] 9 | if len(numbers) != 10 or numbers[0] == "0" or numbers[3] in ["0", "1"]: 10 | raise ValueError("Invalid phone number") 11 | self.number = numbers 12 | 13 | @property 14 | def area_code(self): 15 | return self.number[:3] 16 | 17 | def pretty(self): 18 | return f"({self.number[:3]}) {self.number[3:6]}-{self.number[6:]}" 19 | -------------------------------------------------------------------------------- /Exercism/word-count/word_count.py: -------------------------------------------------------------------------------- 1 | from string import ascii_letters, punctuation 2 | 3 | 4 | def clean(word): 5 | start, end = 0, len(word) 6 | while start < len(word) and word[start] in punctuation: 7 | start += 1 8 | while end >= 0 and word[end-1] in punctuation: 9 | end -= 1 10 | if end > start: 11 | return word[start:end] 12 | 13 | def word_count(phrase): 14 | alternative_seps = [',', '_'] 15 | for sep in alternative_seps: 16 | phrase = phrase.replace(sep, " ") 17 | words = [clean(word) for word in phrase.lower().split() if clean(word)] 18 | return {word:words.count(word) for word in set(words)} 19 | -------------------------------------------------------------------------------- /Important/BaseConverter.py: -------------------------------------------------------------------------------- 1 | # implemeting a Base converter which takes in a int and the base to convert 2 | 3 | def BaseConverter(num, base): 4 | 5 | digits = "0123456789ABCDEF" 6 | stack = [] 7 | newString = "" 8 | 9 | while num > 0: 10 | rem = num % base 11 | stack.append(rem) 12 | num = num // base 13 | 14 | while len(stack) > 0: 15 | newString = newString + digits[stack.pop()] 16 | 17 | return newString 18 | 19 | 20 | print(BaseConverter(26, 2)) # binary conversion 21 | print(BaseConverter(26, 8)) # Octal 22 | print(BaseConverter(26, 16)) # Hexadecimal 23 | print(BaseConverter(26, 26)) # base of 26 24 | -------------------------------------------------------------------------------- /Important/CipherWord.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | def Cipher(string): 5 | 6 | if len(string) == 0: 7 | return "" 8 | if len(string) == 1: 9 | return random.choice([chr(i) for i in range(97, 123)]) 10 | 11 | c = 0 12 | new_string = [] 13 | while c < len(string): 14 | a = random.choice([chr(i) for i in range(97, 123)]) 15 | if string[c] == ' ': 16 | new_string.append(' ') 17 | c += 1 18 | elif a not in string: 19 | new_string.append(a) 20 | c += 1 21 | 22 | return ''.join(new_string) 23 | 24 | 25 | print(Cipher(input("Enter a string to be Ciphered: "))) 26 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | **IMPORTANT: Please do not create a Pull Request without an issue.** 2 | 3 | ### All Submissions: 4 | 5 | * [ ] I have read the CONTRIBUTING document. 6 | * [ ] My code is written in **Python3** and is ending with _.py_ 7 | * [ ] Have you checked to ensure there aren't other open [Pull Requests](../../../pulls) for the same update/change? 8 | * [ ] I have checked that my submission does pass the test on LeetCode.com 9 | * [ ] Does your filename follow the naming Conventions? 10 | * [ ] Have you linked your PR to an Issue? 11 | 12 | **Closing issues** 13 | 14 | Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes (if such). -------------------------------------------------------------------------------- /Important/DiffStrings.py: -------------------------------------------------------------------------------- 1 | # Given two strings s and t which consist of only lowercase letters. 2 | # 3 | # String t is generated by random shuffling string s and then add one more letter at a random position. 4 | # 5 | # Find the letter that was added in t. 6 | # 7 | # Example: 8 | # 9 | # Input: 10 | # s = "abcd" 11 | # t = "abcde" 12 | # 13 | # Output: 14 | # e 15 | # 16 | # Explanation: 17 | # 'e' is the letter that was added. 18 | 19 | # Solution using XOR 20 | 21 | def diff(s1, s2): 22 | 23 | ans = 0 24 | 25 | for i in s1+s2: 26 | ans ^= ord(i) 27 | 28 | return chr(ans) 29 | 30 | 31 | s1 = 'abcd' 32 | s2 = 'aecdb' 33 | 34 | print(diff(s1, s2)) 35 | -------------------------------------------------------------------------------- /Important/binarytoInteger.py: -------------------------------------------------------------------------------- 1 | # Q : create a func to create binary to integer 2 | # input : 1010 3 | # Output : 0*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 0 + 2 + 0 + 8 = 10 4 | 5 | def binary_to_integer(b): 6 | 7 | if not b.isdigit(): 8 | return "Not a binary" 9 | 10 | if int(b) == 0: 11 | return 0 12 | elif int(b) == 1: 13 | return 1 14 | else: 15 | a = list(b) 16 | f = 0 17 | i = 0 18 | while len(a) != 0: 19 | p = a.pop() 20 | f = f + int(p) * 2**i 21 | i = i + 1 22 | 23 | return f 24 | 25 | 26 | print(binary_to_integer(input("enter the binary digit to convert to integer: "))) 27 | -------------------------------------------------------------------------------- /Important/sort0-1-2.py: -------------------------------------------------------------------------------- 1 | # Question given an array of [0,1,0,2,0,1,0,2,0,1] sort it such that 0's are in the beginning, 1's in the middle and 2's at the end 2 | 3 | # input: [0,1,0,2,0,1,0,2,0,1] 4 | # output: [0,0,0,0,0,1,1,1,2,2] 5 | 6 | def sort_this(a): 7 | lo = 0 8 | hi = len(a) - 1 9 | mid = 0 10 | while mid <= hi: 11 | if a[mid] == 0: 12 | a[lo], a[mid] = a[mid], a[lo] 13 | lo = lo + 1 14 | mid = mid + 1 15 | elif a[mid] == 1: 16 | mid = mid + 1 17 | else: 18 | a[mid], a[hi] = a[hi], a[mid] 19 | hi = hi - 1 20 | return a 21 | 22 | print(sort_this([0,1,0,2,0,1,0,2,0,1])) -------------------------------------------------------------------------------- /HackerRank/making_anagram_2_Strings.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://www.hackerrank.com/challenges/making-anagrams/problem 3 | """ 4 | 5 | 6 | def makingAnagrams(s1, s2): 7 | if s1 == s2: 8 | return 0 9 | else: 10 | all = set(s1+s2) 11 | k1 = {i: s1.count(i) for i in all} 12 | k2 = {i: s2.count(i) for i in all} 13 | k3 = {} 14 | for i, v in k1.items(): 15 | diff = abs(k1[i]-k2[i]) 16 | k3[i] = diff 17 | 18 | count = sum(k3.values()) 19 | 20 | return count 21 | 22 | 23 | if __name__ == '__main__': 24 | 25 | s1 = input() 26 | 27 | s2 = input() 28 | 29 | result = makingAnagrams(s1, s2) 30 | print(result) 31 | -------------------------------------------------------------------------------- /GeeksforGeeks/kadanes_algorithm.py: -------------------------------------------------------------------------------- 1 | # Given an array arr of N integers 2 | # Find the contiguous sub-array with maximum sum 3 | 4 | def max_subarray_sum(arr): 5 | # if there is no positive element in the array 6 | if max(arr) < 0: 7 | return max(arr) 8 | 9 | mxm = max_end = 0 10 | length = len(arr) 11 | for i in range(length): 12 | max_end += arr[i] 13 | if mxm < max_end: 14 | mxm = max_end 15 | if max_end < 0: 16 | max_end = 0 17 | return mxm 18 | 19 | '''for _ in range(t): 20 | n = int(input()) 21 | a = list(map(int, input().split()))''' 22 | 23 | # a = [1, 2, 3, -2, 5] 24 | a = [-1, -2, -3, -4] 25 | print(max_subarray_sum(a)) 26 | -------------------------------------------------------------------------------- /DailyCoding/11.py: -------------------------------------------------------------------------------- 1 | """ 2 | This problem was asked by Twitter. 3 | 4 | Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix. 5 | 6 | For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal]. 7 | 8 | Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries. 9 | 10 | 11 | """ 12 | 13 | def autocomplete_bruteforce(words, s): 14 | result = [] 15 | for word in words: 16 | if s in word: 17 | result.append(word) 18 | 19 | return result 20 | 21 | 22 | print(autocomplete_bruteforce(['dog','deer','deal'], 'de')) -------------------------------------------------------------------------------- /Important/max_consective_1.py: -------------------------------------------------------------------------------- 1 | # Input: [1,1,0,1,1,1] 2 | # Output: 3 3 | # Explanation: The first two digits or the last three digits are consecutive 1s. 4 | # The maximum number of consecutive 1s is 3. 5 | 6 | class Solution(object): 7 | def findMaxConsecutiveOnes(self, nums): 8 | """ 9 | :type nums: List[int] 10 | :rtype: int 11 | """ 12 | count = 0 13 | ans = 0 14 | for num in nums: 15 | if num == 1: 16 | count += 1 17 | ans = max(ans, count) 18 | else: 19 | count = 0 20 | return ans 21 | 22 | 23 | l = Solution() 24 | print(l.findMaxConsecutiveOnes([1, 1, 1, 0, 1, 1, 1, 1])) 25 | -------------------------------------------------------------------------------- /Important/ImplementQueue.py: -------------------------------------------------------------------------------- 1 | #implement a Queue which works on FIFO principle 2 | 3 | class Queue(): 4 | 5 | def __init__(self): 6 | self.items = [] 7 | 8 | def isEmpty(self): 9 | return self.items == [] 10 | 11 | def size(self): 12 | return len(self.items) 13 | 14 | def enqueue(self, *args): 15 | for value in args: 16 | self.items.insert(0, value) 17 | 18 | def dequeue(self): 19 | return self.items.pop() 20 | 21 | 22 | q = Queue() 23 | 24 | q.enqueue(1) 25 | q.enqueue("test") 26 | q.enqueue(True) 27 | q.enqueue(1.5) 28 | q.enqueue(-1, 'test2', False) 29 | 30 | # print q.items 31 | # print q.size() 32 | # print q.dequeue() 33 | # print q.isEmpty() 34 | -------------------------------------------------------------------------------- /CodeWars/sort_the_odd.py: -------------------------------------------------------------------------------- 1 | """ 2 | URL: 3 | https://www.codewars.com/kata/578aa45ee9fd15ff4600090d 4 | 5 | DESCRIPTION: 6 | You have an array of numbers. 7 | Your task is to sort ascending odd numbers but even numbers must be on their places. 8 | 9 | Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it. 10 | 11 | Example 12 | sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] 13 | """ 14 | 15 | def sort_array(source_array): 16 | new_arr = [x for x in source_array if x % 2 == 1] 17 | new_arr.sort(reverse=True) 18 | for i, elem in enumerate(source_array): 19 | if elem % 2 == 1: 20 | source_array[i] = new_arr.pop() 21 | 22 | return source_array -------------------------------------------------------------------------------- /HackerRank/counting_valleys.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup 3 | 4 | """ 5 | 6 | 7 | # Complete the coutingValleys function below 8 | 9 | def countingValleys(n, s): 10 | valleys = 0 11 | level = 0 12 | 13 | for c in s: 14 | if c == 'D': 15 | level -= 1 16 | elif c == 'U': 17 | level += 1 18 | 19 | if level == 0: 20 | valleys += 1 21 | return valleys 22 | 23 | 24 | 25 | steps = 'UDDDUDUU' 26 | steps1 = 'DDUUUUDD' 27 | print(countingValleys(len(steps), steps)) 28 | print(countingValleys(len(steps1), steps1)) 29 | 30 | -------------------------------------------------------------------------------- /LeetCode/convert_to_lowercase.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. 3 | 4 | Note: do not use string functions 5 | 6 | Input: "Hello" 7 | Output: "hello" 8 | 9 | ''' 10 | 11 | 12 | class Solution(object): 13 | def toLowerCase(self, str): 14 | """ 15 | :type str: str 16 | :rtype: str 17 | """ 18 | new = '' 19 | for i in range(len(str)): 20 | if ord(str[i]) < 97 and ord(str[i]) > 64: 21 | new = new + chr(ord(str[i]) + 32) 22 | else: 23 | new = new + str[i] 24 | 25 | return new 26 | 27 | 28 | s = Solution() 29 | print(s.toLowerCase('HeLLo')) 30 | -------------------------------------------------------------------------------- /Company/infinite_sequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | Give an infinite sequence 0, -1, -1 , 0, 1, 1, 0, -1, -1, 0, 1, 1..... 3 | 4 | write a function which takes n1, n2 and num 5 | n1 and n2 are part of the sequence 6 | and num is the nth sequence integer in the infinite sequence 7 | 8 | Example: 9 | Input: -1, -1, 5 10 | Output: 1 11 | 12 | -1 occurs at position 1 13 | -1 occurs at position 2 14 | counting from -1, -1, 0 , 1, 1 <- 15 | returning the 5th element i.e 1 16 | 17 | 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, 1 18 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 19 | 20 | """ 21 | 22 | def sequence(n1, n2, num): 23 | 24 | seq = [0, -1, -1, 0, 1, 1] 25 | 26 | if num%3 == 0: 27 | return 0 28 | else: 29 | 30 | 31 | 32 | return -------------------------------------------------------------------------------- /HackerRank/hackerrank_in_string.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://www.hackerrank.com/challenges/hackerrank-in-a-string/problem 3 | """ 4 | 5 | 6 | def hackerrankInString(s): 7 | word = 'hackerrank' 8 | count = 0 9 | if word == s: 10 | return 'YES' 11 | if s == '' or len(s) < len(word) or len(s) > 10**4: 12 | return 'NO' 13 | else: 14 | for i, e in enumerate(word): 15 | index = s.find(e) 16 | if index == -1: 17 | return 'NO' 18 | else: 19 | s = s[index+1:] 20 | continue 21 | return 'YES' 22 | 23 | 24 | if __name__ == '__main__': 25 | 26 | s = input() 27 | 28 | result = hackerrankInString(s) 29 | print(result) 30 | -------------------------------------------------------------------------------- /CodeWars/Unique_number.py: -------------------------------------------------------------------------------- 1 | ###This one is from a problem I soved on codewars in my beginner level 2 | #Qustion 3 | '''There is an array with some numbers. All numbers are equal except for one. Try to find it! 4 | 5 | find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 6 | find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 7 | It’s guaranteed that array contains at least 3 numbers. 8 | 9 | The tests contain some very huge arrays, so think about performance. 10 | ''' 11 | 12 | #Solution 13 | 14 | def find_uniq(arr): 15 | if arr[0] != arr[1]: 16 | if arr[0] != arr[2]: 17 | return arr[0] 18 | else: 19 | return arr[1] 20 | else: 21 | for i in arr[2:]: 22 | if i != arr[0]: 23 | return i -------------------------------------------------------------------------------- /LeetCode/largest-sum-contiguous-subarray.py: -------------------------------------------------------------------------------- 1 | # find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum. 2 | 3 | # example: [-1, -2, 4, 3, 1, -1, -5] 4 | # ans: 2+4+3 = 9 5 | 6 | def largest_sum_of_sub_array(arr): 7 | 8 | max_so_far = 0 9 | max_ending_here = 0 10 | 11 | for num in arr: 12 | 13 | max_ending_here = max_ending_here + num 14 | 15 | if (max_ending_here < 0): 16 | max_ending_here = 0 17 | elif (max_so_far < max_ending_here): 18 | max_so_far = max_ending_here 19 | 20 | return max_so_far 21 | 22 | print (largest_sum_of_sub_array([-1,-2,4,3,1,-1,-5])) # 8 23 | 24 | print (largest_sum_of_sub_array([-1,-2,4,-1,3,-2,-4])) -------------------------------------------------------------------------------- /test/test_binary_tree_right_side_view.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '..')) 4 | from LeetCode.binary_tree_right_side_view import Solution 5 | 6 | class TreeNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.left = None 10 | self.right = None 11 | 12 | def test_binary_tree_right_side_view(): 13 | 14 | root = TreeNode(1) 15 | 16 | root.left = TreeNode(2) 17 | root.right = TreeNode(3) 18 | 19 | root.left.left = TreeNode(None) 20 | root.left.right = TreeNode(5) 21 | 22 | root.right.right = TreeNode(4) 23 | root.right.left = TreeNode(None) 24 | 25 | S = Solution() 26 | 27 | assert S.rightSideView(root) == [1, 3, 4] 28 | 29 | 30 | -------------------------------------------------------------------------------- /Important/FlattenListofLists.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function to flatten a list of lists 3 | 4 | input: 5 | [1,[2,3,4],[5,[6,7]]] 6 | 7 | output: 8 | [1,2,3,4,5,6,7] 9 | 10 | ''' 11 | 12 | 13 | # recursive function 14 | import itertools 15 | 16 | 17 | def flattenList(lst, f_lst=None): 18 | 19 | if f_lst is None: 20 | f_lst = [] 21 | 22 | for l in lst: 23 | if isinstance(l, list): 24 | flattenList(l, f_lst) 25 | else: 26 | f_lst.append(l) 27 | 28 | return f_lst 29 | 30 | 31 | # using itertools 32 | 33 | 34 | def flattenList1(lst): 35 | 36 | f_lst = list(itertools.chain.from_iterable(lst)) 37 | 38 | return f_lst 39 | 40 | 41 | print(flattenList([[1, 2, 3], [4, 5, 6], [7], [8, 9]])) 42 | -------------------------------------------------------------------------------- /Important/FizzBuzz.py: -------------------------------------------------------------------------------- 1 | """ 2 | input: 3 | n = 5 4 | Result: 5 | ['1', '2', 'Fizz', '4', 'Buzz'] 6 | 7 | """ 8 | 9 | class Solution(object): 10 | def fizzBuzz(self, n): 11 | """ 12 | :type n: int 13 | :rtype: List[str] 14 | """ 15 | if n ==0 or n ==1: 16 | return [str(n)] 17 | result = [] 18 | for i in range(1, n+1): 19 | if i%3== 0 and i%5==0: 20 | result.append("FizzBuzz") 21 | elif i%3 == 0: 22 | result.append('Fizz') 23 | elif i%5 == 0: 24 | result.append('Buzz') 25 | else: 26 | result.append(str(i)) 27 | return result 28 | 29 | s = Solution() 30 | print(s.fizzBuzz(15)) -------------------------------------------------------------------------------- /LeetCode/26.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. 3 | 4 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 5 | ''' 6 | 7 | 8 | class Solution: 9 | def removeDuplicates(self, nums: list[int]) -> int: 10 | di = {} 11 | x = 0 12 | while x < len(nums): 13 | # print(x) 14 | if nums[x] in di.keys(): 15 | nums.remove(nums[x]) 16 | x = x-1 17 | else: 18 | di[nums[x]] = 1 19 | x = x+1 20 | return len(nums) 21 | 22 | s = Solution() 23 | print(s.removeDuplicates([1,1,2])) -------------------------------------------------------------------------------- /test/test_array_plus_array.py: -------------------------------------------------------------------------------- 1 | """ 2 | Test cases for ArrayPlusArray.py found in the CodeWars folder. 3 | 4 | Answer by @mauricerivers 5 | """ 6 | 7 | # function to be tested 8 | def array_plus_array(arr1,arr2): 9 | # variable used to add the array membeers 10 | sum = 0 11 | 12 | # loop through arr1 and add each item to sum 13 | for item in arr1: 14 | sum += item 15 | 16 | # loop through arr2 and add each item to sum 17 | for item in arr2: 18 | sum += item 19 | 20 | return sum 21 | 22 | # function to test array_plus_array 23 | def test_array_plus_array(): 24 | assert array_plus_array([1, 2, 3], [4, 5, 6]) == 21, "Should be 21" 25 | assert array_plus_array([-1, -2, -3], [-4, -5, -6]) == -21, "Should be -21" 26 | -------------------------------------------------------------------------------- /DailyCoding/1621.py: -------------------------------------------------------------------------------- 1 | """ 2 | This problem was asked by Google. 3 | 4 | A regular number in mathematics is defined as one which evenly divides some power of 60. Equivalently, we can say that a regular number is one whose only prime divisors are 2, 3, and 5. 5 | 6 | These numbers have had many applications, from helping ancient Babylonians keep time to tuning instruments according to the diatonic scale. 7 | 8 | Given an integer N, write a program that returns, in order, the first N regular numbers. 9 | """ 10 | 11 | def regularNumbers(N): 12 | if N <= 0: 13 | return [] 14 | result = [1] 15 | for i in range(1, N): 16 | if i%2==0 and i%3==0 and i%5==0: 17 | result.append(i) 18 | 19 | return result 20 | 21 | print(regularNumbers(60)) -------------------------------------------------------------------------------- /Important/intToBinary.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function which takes 3 | i= integer 4 | s= index 5 | n= increment 6 | 7 | convert the integet i to binary and swap the 1/0 starting from index s 8 | and incrementing it to n 9 | 10 | ''' 11 | 12 | 13 | def IntToBin(i, s, n): 14 | 15 | i_binary = bin(i)[2:] 16 | 17 | i1 = i_binary[:s] 18 | i2 = i_binary[s:n+s] 19 | 20 | i_l = [] 21 | for c in i2: 22 | if c == '0': 23 | i_l.append('1') 24 | else: 25 | i_l.append('0') 26 | i_F = ''.join(i_l) 27 | 28 | i3 = i_binary[len(i1)+len(i2):] 29 | 30 | int_form = int((i1+i_F+i3), 2) 31 | 32 | print("Sent int: {}".format(i)) 33 | print("converted int: {}".format(int_form)) 34 | 35 | 36 | IntToBin(60, 3, 5) 37 | -------------------------------------------------------------------------------- /test/test_path_sum.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '..')) 4 | from LeetCode.path_sum import Solution 5 | 6 | class TreeNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.left = None 10 | self.right = None 11 | 12 | def test_path_sum(): 13 | 14 | root = TreeNode(5) 15 | 16 | root.left = TreeNode(4) 17 | root.right = TreeNode(8) 18 | 19 | root.left.left = TreeNode(11) 20 | 21 | root.right.right = TreeNode(13) 22 | root.right.left = TreeNode(4) 23 | 24 | root.left.left.left = TreeNode(7) 25 | root.left.left.right = TreeNode(2) 26 | 27 | root.right.left.right = TreeNode(1) 28 | 29 | S = Solution() 30 | 31 | assert S.hasPathSum(root, 22) == True 32 | 33 | -------------------------------------------------------------------------------- /DailyCoding/49.py: -------------------------------------------------------------------------------- 1 | """ 2 | This problem was asked by Amazon. 3 | 4 | Given an array of numbers, find the maximum sum of any contiguous subarray of the array. 5 | 6 | For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 42, 14, -5, and 86. 7 | 8 | Given the array [-5, -1, -8, -9], the maximum sum would be 0, since we would not take any elements. 9 | 10 | Do this in O(N) time. 11 | 12 | """ 13 | 14 | def findsum(A): 15 | result = sum(A) 16 | for i in range(len(A)): 17 | _sum = max([sum(A[:i]), sum(A[i:])]) 18 | if result < _sum: 19 | result = _sum 20 | 21 | return result if result > 0 else 0 22 | 23 | 24 | # A = [34, -50, 42, 14, -5, 86] 25 | A = [-5, -1, -8, -9] 26 | print(findsum(A)) 27 | -------------------------------------------------------------------------------- /Company/unique_username.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unique usernames 3 | You get an list of names and need to return a list of unique usernames. 4 | For a duplicate name, add the next integer after the name 5 | 6 | For example: 7 | 8 | Input 9 | ['Julie', 'Emma', 'Zoe', 'Liam', 'Emma'] 10 | Output 11 | ['Julie', 'Emma', 'Zoe', 'Liam', 'Emma1'] 12 | 13 | Input 14 | ['Julie', 'Zoe', 'Zoe', 'Liam', 'Emma', 'Zoe'] 15 | Output 16 | ['Julie', 'Zoe', 'Zoe1', 'Liam', 'Emma', 'Zoe2'] 17 | """ 18 | 19 | 20 | def users(names): 21 | usernames = [] 22 | for name in names[1:]: 23 | if name not in usernames: 24 | usernames.append(name) 25 | else: 26 | count = sum(name in user for user in usernames) 27 | usernames.append(name + str(count)) 28 | 29 | return usernames 30 | 31 | -------------------------------------------------------------------------------- /DailyCoding/2.py: -------------------------------------------------------------------------------- 1 | """ 2 | This problem was asked by Uber. 3 | 4 | Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. 5 | 6 | For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. 7 | 8 | """ 9 | from functools import reduce 10 | 11 | 12 | def brute_force(arr): 13 | new = [] 14 | # t = 1 15 | # for i in arr: 16 | # t *= i 17 | t = reduce((lambda x, y: x*y), arr) 18 | 19 | for i in arr: 20 | if i == 0: 21 | return [0]*len(arr) 22 | new.append(t/i) 23 | 24 | return new 25 | 26 | 27 | print(brute_force([2, 3, 1])) 28 | -------------------------------------------------------------------------------- /DailyCoding/1.py: -------------------------------------------------------------------------------- 1 | """ 2 | This problem was recently asked by Google. 3 | 4 | Given a list of numbers and a number k, return whether any two numbers from the list add up to k. 5 | 6 | For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. 7 | 8 | 9 | """ 10 | 11 | 12 | def sum_brute_force(arr, k): 13 | for i in range(len(arr) - 1): 14 | for j in range(i, len(arr)): 15 | if (arr[i] + arr[j] == k): 16 | return True 17 | 18 | return False 19 | 20 | 21 | def sum_improved(arr, k): 22 | s = set() 23 | for i in arr: 24 | if (k - i) in s: 25 | return True 26 | s.add(i) 27 | 28 | return False 29 | 30 | 31 | print(sum_brute_force([10, 9, 7, 8, 2, 0, -1], 17)) 32 | print(sum_improved([10, 9, 7, 8, 2, 0, -1], 17)) 33 | -------------------------------------------------------------------------------- /TreesAndGraphs/bin_tree_height.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # The riddle: 4 | # find the height (longest path from the root node) of a binary tree (not necessarily balanced). 5 | 6 | 7 | def depth(root): 8 | """ root is a tree node pointer that has access to left and right, 9 | returns the height of the tree + 1 """ 10 | if root is None: 11 | return 0 12 | return 1 + max(depth(root.l), depth(root.r)) 13 | 14 | def solution(root): 15 | return depth(root) - 1 16 | 17 | 18 | class T: 19 | def __init__(self, l=None, r=None): 20 | self.l = l 21 | self.r = r 22 | 23 | 24 | def unit_test(): 25 | assert solution(T(T(),T(T(), T()))) == 2 26 | assert solution(T(T(T(), T(T(None, T(T(),T())))), T(T()))) == 5 27 | 28 | if __name__ == '__main__': 29 | unit_test() 30 | -------------------------------------------------------------------------------- /HackerRank/pangram.py: -------------------------------------------------------------------------------- 1 | # Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.) 2 | 3 | # After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams. 4 | 5 | # Given a sentence , tell Roy if it is a pangram or not. 6 | 7 | import string 8 | s = input().lower() 9 | 10 | 11 | alphabets = [x for x in string.ascii_lowercase] 12 | 13 | result = [] 14 | for char in alphabets: 15 | if char in s: 16 | result.append(1) 17 | else: 18 | result.append(0) 19 | 20 | if 0 in result: 21 | print("not pangram") 22 | else: 23 | print("pangram") 24 | -------------------------------------------------------------------------------- /DailyCoding/4.py: -------------------------------------------------------------------------------- 1 | """ 2 | This problem was asked by Stripe. 3 | 4 | Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. 5 | 6 | For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. 7 | 8 | You can modify the input array in-place. 9 | 10 | 2,3,4,-1,1 => 2 11 | 1,2,3,0 => 3 12 | 13 | """ 14 | 15 | def func(arr): 16 | 17 | A = set(arr) 18 | A1 = set([i for i in range(min(A), max(A)+1)]) 19 | 20 | diff = A1.difference(A) 21 | if len(diff) == 0: 22 | return max(A)+1 23 | for i in diff: 24 | if i > 0: 25 | return i 26 | 27 | A = [3, 4, -1, 1] 28 | # A = [1, 2, 0] 29 | print(func(A)) -------------------------------------------------------------------------------- /Important/ImplementReverseStack.py: -------------------------------------------------------------------------------- 1 | # Implement a Reverse Stack in python 2 | 3 | class ReverseStack(): 4 | 5 | def __init__(self): 6 | self.items = list() 7 | 8 | def push(self, *args): 9 | for val in args: 10 | self.items.insert(0, val) 11 | 12 | def peek(self): 13 | return self.items[0] 14 | 15 | def pop(self): 16 | return self.items.pop(0) 17 | 18 | def isEmpty(self): 19 | if len(self.items) == 0: 20 | return True 21 | else: 22 | return False 23 | 24 | def size(self): 25 | return len(self.items) 26 | 27 | 28 | s = ReverseStack() 29 | 30 | s.push(1) 31 | s.push(2) 32 | s.push(3) 33 | s.push(4, 5) 34 | s.push('test') 35 | 36 | print(s.items) 37 | print(s.isEmpty()) 38 | print(s.peek()) 39 | print(s.size()) 40 | s.pop() 41 | print(s.items) 42 | -------------------------------------------------------------------------------- /Important/multipleinheritance.py: -------------------------------------------------------------------------------- 1 | # base class 2 | class Base1: 3 | 4 | def __init__(self): 5 | self.str1 = "string from base1" 6 | print("base1 class") 7 | 8 | 9 | class Base2: 10 | 11 | def __init__(self): 12 | self.str2 = "string from base2" 13 | print("base2 class") 14 | 15 | # Base1 and Base2 are being inherited by Deriver 16 | 17 | 18 | class Deriverd(Base1, Base2): 19 | 20 | def __init__(self): 21 | # calling initializers for both base classes 22 | Base1.__init__(self) 23 | Base2.__init__(self) 24 | print("Deriver class") 25 | 26 | def printStr(self): 27 | print(self.str1 + " " + self.str2) 28 | 29 | 30 | d = Deriverd() 31 | d.printStr() 32 | 33 | # prints => 34 | # base1 class 35 | # base2 class 36 | # Deriver class 37 | # string from base1 string from base2 38 | -------------------------------------------------------------------------------- /Important/looksay.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Function to look at the provided alphanumeric string and say it in order 3 | 4 | input: 5 | '1A2BBC' 6 | 7 | output: 8 | '111A122B1C' 9 | 10 | ''' 11 | 12 | 13 | def looksay(look): 14 | 15 | look = str(look) 16 | if len(look) == 0: 17 | return 'Empty string entered' 18 | else: 19 | prev = look[0] 20 | count = 1 21 | say = '' 22 | 23 | for char in look[1:]: 24 | if char == prev: 25 | count += 1 26 | continue 27 | say += str(count) + prev 28 | prev = char 29 | count = 1 30 | 31 | return say + str(count) + prev 32 | 33 | # change to ignore count == 1 and the prefix the numbers to the front 34 | 35 | 36 | # number will go here 37 | print(looksay(input("Enter a value which needs to be looked and said: "))) 38 | -------------------------------------------------------------------------------- /Important/AllCombinations.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | 4 | def CombinationOfWords(str): 5 | 6 | if len(str) == 1: 7 | return str 8 | 9 | str_list = [] 10 | for i in range(len(str)): 11 | ls = permutations(str, i) 12 | str_list.append(ls) 13 | i += 1 14 | 15 | new_list = [] 16 | for s in str_list: 17 | if isinstance(s, list): 18 | for item in s: 19 | new_list.append(''.join(item)) 20 | 21 | #new_list = set(new_list) 22 | 23 | return list(new_list) 24 | 25 | 26 | def permutations(str, i): 27 | 28 | perm_list = [] 29 | # i+1 since it needs to reach len of string 30 | for s in itertools.permutations(str, i+1): 31 | perm_list.append(list(s)) 32 | 33 | return perm_list 34 | 35 | 36 | print(CombinationOfWords(input('Enter a string to get all the combinations: '))) 37 | -------------------------------------------------------------------------------- /Important/ImplementingDequeue.py: -------------------------------------------------------------------------------- 1 | 2 | class Dequeue: 3 | """ 4 | class which creates a Deque object 5 | """ 6 | 7 | def __init__(self): 8 | self.items = list() 9 | 10 | def addRear(self, item): 11 | self.items.insert(0, item) 12 | 13 | def addFront(self, item): 14 | self.items.append(item) 15 | 16 | def isEmpty(self): 17 | return self.items == [] 18 | 19 | def removeFront(self): 20 | return self.items.pop() 21 | 22 | def removeRear(self): 23 | return self.items.pop(0) 24 | 25 | def size(self): 26 | return len(self.items) 27 | 28 | # d1 = Dequeue() 29 | # d2 = Dequeue() 30 | # s = input(">") 31 | # for ch in s: 32 | # d1.addFront(ch) 33 | 34 | # print d1.items 35 | 36 | # for ch in s: 37 | # d2.addRear(ch) 38 | 39 | # print d2.items 40 | 41 | # print d1.items == d2.items 42 | -------------------------------------------------------------------------------- /test/test_7.py: -------------------------------------------------------------------------------- 1 | """ 2 | Test cases for 7.py found in the LeetCode folder. 3 | Answer by @VGZELDA 4 | """ 5 | # function to be tested 6 | def reverse(x): 7 | x=int(x) 8 | if(x>=0): 9 | x=str(x) 10 | x=x[::-1] 11 | x=int(x) 12 | if(x<-1*(2**31))or(x>=2**31): 13 | return 0 14 | else: 15 | return x 16 | else: 17 | x=x*(-1) 18 | x=str(x) 19 | x=x[::-1] 20 | x=int(x) 21 | x=-1*x 22 | if(x<-1*(2147483648))or(x>=2147483648): 23 | return 0 24 | else: 25 | return x 26 | # function to test reverse 27 | def test_reverse(): 28 | assert reverse(123) == 321, "Should be 321" 29 | assert reverse(120) == 21, "Should be 21" 30 | test_reverse() 31 | print("Everything passed") 32 | -------------------------------------------------------------------------------- /Company/search_strings_in_data.py: -------------------------------------------------------------------------------- 1 | """ 2 | asked at Amazon 3 | 4 | Provided a large string, and an array of strings. return a dictonary with the number of times each string from the array appears in the large string 5 | 6 | # Input: S =>'this is a large string in a file' 7 | # Input: A => ['is', 'a'] 8 | # output => {'is': 2, 'a': 3} 9 | # explanation: 10 | # 'is' appears in 'this', 'is' == 2 11 | # 'a' appears in 'a', 'large', 'a' == 3 12 | 13 | """ 14 | 15 | 16 | def return_dict(S, A): 17 | 18 | result = {} 19 | # if inputs => [] 20 | if len(A) == 0: 21 | return {} 22 | 23 | for i in range(len(A)): 24 | result[A[i]] = 0 25 | 26 | if S.count(A[i]): 27 | result[A[i]] = S.count(A[i]) 28 | 29 | return result 30 | 31 | 32 | S = 'this is a large string in a file' 33 | A = ['is', 'a'] 34 | result = return_dict(S, A) 35 | print(result) 36 | -------------------------------------------------------------------------------- /LeetCode/5080.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSumBSTs(self, root1: TreeNode, root2: TreeNode, target: int) -> bool: 3 | flag = 0 4 | listTemp = [] 5 | def inOrderList(root) -> List[int]: 6 | if not root: 7 | return 8 | inOrderList(root.left) 9 | listTemp.append(root.val) 10 | inOrderList(root.right) 11 | return(listTemp) 12 | 13 | listTree1 = inOrderList(root1) 14 | listTemp = [] 15 | listTree2 = inOrderList(root2) 16 | 17 | for item1 in listTree1: 18 | for item2 in listTree2: 19 | result = item1 + item2 20 | if result == target: 21 | flag = 1 22 | break 23 | 24 | if flag == 0: 25 | return False 26 | else: 27 | return True 28 | 29 | -------------------------------------------------------------------------------- /Important/Sum_of_2_int_in_array.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | You are given an array of n integers and a number k. Determine whether there is 4 | a pair of elements in the array that sums to exactly k. For example, given the 5 | array [1, 3, 7] and k = 8, the answer is "yes", but given k = 6 the answer is 6 | "no." 7 | """ 8 | 9 | # time complexity O(n^2) 10 | def two_sum_brute(arr, target): 11 | 12 | for i in range(len(arr) - 1): 13 | for j in range(i, len(arr)): 14 | if (arr[i] + arr[j] == target): 15 | return True 16 | return False 17 | 18 | # time complexity O(n) 19 | def two_sum(arr, target): 20 | s = set() 21 | for n in arr: 22 | if (target - n) in s: 23 | return True 24 | s.add(n) 25 | return False 26 | 27 | print(two_sum_brute([1,2,3], 5)) 28 | print(two_sum_brute([1], 5)) 29 | print(two_sum([1,2,3], 5)) 30 | print(two_sum([1], 5)) -------------------------------------------------------------------------------- /Important/ImplementStack.py: -------------------------------------------------------------------------------- 1 | #Implement a Stack in python 2 | 3 | class Stack(): 4 | 5 | def __init__(self): 6 | self.items = list() 7 | 8 | def push(self,*args): 9 | for val in args: 10 | self.items.append(val) 11 | 12 | def peek(self): 13 | return self.items[-1] 14 | 15 | def pop(self): 16 | return self.items.pop() 17 | 18 | def isEmpty(self): 19 | if len(self.items)==0: 20 | return True 21 | else: 22 | return False 23 | 24 | def size(self): 25 | return len(self.items) 26 | 27 | def show(self): 28 | return (self.items) 29 | 30 | 31 | # s = Stack() 32 | 33 | # s.push(1) 34 | # s.push(2) 35 | # s.push(3) 36 | # s.push(4,5) 37 | # s.push('test') 38 | 39 | # print s.items 40 | # print s.isEmpty() 41 | # print s.peek() 42 | # print s.size() 43 | # s.pop() 44 | # print s.items 45 | 46 | -------------------------------------------------------------------------------- /LeetCode/5080-two-sum-bsts.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSumBSTs(self, root1: TreeNode, root2: TreeNode, target: int) -> bool: 3 | flag = 0 4 | listTemp = [] 5 | def inOrderList(root) -> List[int]: 6 | if not root: 7 | return 8 | inOrderList(root.left) 9 | listTemp.append(root.val) 10 | inOrderList(root.right) 11 | return(listTemp) 12 | 13 | listTree1 = inOrderList(root1) 14 | listTemp = [] 15 | listTree2 = inOrderList(root2) 16 | 17 | for item1 in listTree1: 18 | for item2 in listTree2: 19 | result = item1 + item2 20 | if result == target: 21 | flag = 1 22 | break 23 | 24 | if flag == 0: 25 | return False 26 | else: 27 | return True 28 | 29 | -------------------------------------------------------------------------------- /Company/string_manipulation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function to change every second word in a sentence to "Hello" 3 | 4 | Example 5 | sentence = Hey I love going to the park 6 | ==> Hey Hello love Hello to Hello park 7 | 8 | """ 9 | 10 | def sentenceReplace(sentence): 11 | #declaring a string to keep all the words after each loop and index as a counter 12 | new_sentence = "" 13 | index = 0 14 | #start looping through every word to check which are 'every second word in the sentence' 15 | for word in sentence.split(): 16 | if index % 2 == 1: 17 | new_sentence += " Hello " 18 | else: 19 | new_sentence += word 20 | index += 1 21 | #remove last space from sentence (as it is " Hello " being added each time) and print 22 | sentence = sentence[:-1] 23 | print(new_sentence) 24 | 25 | #execute the function 26 | sentenceReplace(input("Enter Your Sentence: ")) -------------------------------------------------------------------------------- /DailyCoding/1602.py: -------------------------------------------------------------------------------- 1 | """ 2 | This problem was asked by LinkedIn. 3 | 4 | You are given a string consisting of the letters x and y, such as xyxxxyxyy. In addition, you have an operation called flip, which changes a single x to y or vice versa. 5 | 6 | Determine how many times you would need to apply this operation to ensure that all x's come before all y's. In the preceding example, it suffices to flip the second and sixth characters, so you should return 2. 7 | 8 | """ 9 | 10 | def min_flips_to_order(s, type_flip): 11 | misplaced_y_count = 0 12 | flips_required = 0 13 | 14 | for char in s: 15 | if char == type_flip: 16 | flips_required += misplaced_y_count 17 | else: 18 | misplaced_y_count += 1 19 | 20 | return flips_required 21 | 22 | # Example usage: 23 | input_str = "xyxxxyxyy" 24 | result = min_flips_to_order(input_str, "x") 25 | print("Minimum flips required:", result) -------------------------------------------------------------------------------- /Important/Transpose_matrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a matrix A, return the transpose of A. 3 | 4 | The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. 5 | Example: 6 | Input: [[1,2,3],[4,5,6],[7,8,9]] 7 | Output: [[1,4,7],[2,5,8],[3,6,9]] 8 | 9 | """ 10 | 11 | class Solution(object): 12 | def transpose(self, A): 13 | """ 14 | :type A: List[List[int]] 15 | :rtype: List[List[int]] 16 | """ 17 | return zip(*A) 18 | 19 | def transpose2(self, A): 20 | n = len(A) 21 | l = len(A[0]) 22 | new = [[0]*n for i in range(l)] 23 | for i in range(n): 24 | for j in range(l): 25 | new[j][i] = A[i][j] 26 | 27 | return new 28 | 29 | s = Solution() 30 | print(s.transpose([[1,2,3],[4,5,6],[7,8,9]])) 31 | print(s.transpose2([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])) 32 | 33 | -------------------------------------------------------------------------------- /Important/class_methods_example.py: -------------------------------------------------------------------------------- 1 | # types of class methods 2 | class MyClass(object): 3 | 4 | # instance method has access to the instance of the object MyClass 5 | def method(self): 6 | return "instance method called ", self 7 | 8 | # class method has access to the class object MyClass and not the instance of MyClass 9 | @classmethod 10 | def classMethod(cls): 11 | return "class method called", cls 12 | 13 | # static method does not have access to either class Object MyClass or the instance of MyClass 14 | @staticmethod 15 | def staticMethod(): 16 | return "static method called" 17 | 18 | 19 | obj = MyClass() 20 | print(obj.method()) 21 | print(obj.classMethod()) 22 | print(obj.staticMethod()) 23 | # prints => 24 | # ('instance method called ', <__main__.MyClass object at 0x10586cb10>) 25 | # ('class method called', ) 26 | # static method called -------------------------------------------------------------------------------- /LeetCode/5.py: -------------------------------------------------------------------------------- 1 | """ 2 | Longest Palindromic Substring 3 | 4 | Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 5 | 6 | Example 1: 7 | 8 | Input: "babad" 9 | Output: "bab" 10 | Note: "aba" is also a valid answer. 11 | Example 2: 12 | 13 | Input: "cbbd" 14 | Output: "bb" 15 | 16 | """ 17 | 18 | 19 | class Solution(object): 20 | def isPalindrome(self, s): 21 | """ 22 | :type x: int 23 | :rtype: bool 24 | """ 25 | result = "" 26 | n = len(s) 27 | 28 | for i in range(n): 29 | for j in range(i + 1, n + 1): 30 | x = s[i:j] 31 | if x == x[::-1]: 32 | if len(x) > len(result): 33 | result = x 34 | return result 35 | 36 | 37 | S = Solution() 38 | print(S.isPalindrome("babad")) 39 | print(S.isPalindrome("cbbd")) 40 | -------------------------------------------------------------------------------- /DailyCoding/29.py: -------------------------------------------------------------------------------- 1 | """ 2 | This problem was asked by Amazon. 3 | 4 | Run-length encoding is a fast and simple method of encoding strings. 5 | The basic idea is to represent repeated successive characters as a single count and character. 6 | For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A". 7 | 8 | Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. 9 | You can assume the string to be decoded is valid. 10 | 11 | """ 12 | 13 | def encoding(s): 14 | 15 | prev = s[0] 16 | count = 1 17 | result = '' 18 | 19 | for char in s[1:]: 20 | if char == prev: 21 | count += 1 22 | continue 23 | 24 | result += str(count) + prev 25 | prev = char 26 | count = 1 27 | 28 | return result + str(count) + prev 29 | 30 | 31 | print(encoding('AAAABBBCCDAA')) -------------------------------------------------------------------------------- /Facebook/all_wrong.py: -------------------------------------------------------------------------------- 1 | """ 2 | There's a multiple-choice test with 3 | � 4 | N questions, numbered from 5 | 1 6 | 1 to 7 | � 8 | N. Each question has 9 | 2 10 | 2 answer options, labelled A and B. You know that the correct answer for the 11 | � 12 | ith question is the 13 | � 14 | ith character in the string 15 | � 16 | C, which is either "A" or "B", but you want to get a score of 17 | 0 18 | 0 on this test by answering every question incorrectly. 19 | Your task is to implement the function getWrongAnswers(N, C) which returns a string with 20 | � 21 | N characters, the 22 | � 23 | ith of which is the answer you should give for question 24 | � 25 | i in order to get it wrong (either "A" or "B"). 26 | 27 | """ 28 | 29 | def getWrongAnswers(N: int, C: str) -> str: 30 | # Write your code here 31 | result = '' 32 | for i in C: 33 | if i == 'A': 34 | result+='B' 35 | else: 36 | result+='A' 37 | return result -------------------------------------------------------------------------------- /Important/lowest_score_students.py: -------------------------------------------------------------------------------- 1 | try: 2 | N = int(input()) 3 | except ValueError as va: 4 | print("expected value is an int") 5 | 6 | student_l = [] 7 | while True: 8 | try: 9 | name = str(input()) 10 | except ValueError as va: 11 | print ("expected a string input") 12 | continue 13 | 14 | try: 15 | score = float(input()) 16 | except ValueError as va: 17 | print ("expected a int input") 18 | continue 19 | student_l.append([name, score]) 20 | 21 | if len(student_l) == N: 22 | break 23 | 24 | score_l = [] 25 | for score in student_l: 26 | score_l.append(score[-1]) 27 | 28 | m = min(score_l) 29 | while m in score_l: 30 | score_l.pop(score_l.index(m)) 31 | 32 | new_s = [] 33 | 34 | for val in student_l: 35 | if val[-1] == min(score_l): 36 | new_s.append(val[0]) 37 | 38 | new_s = sorted(new_s) 39 | for name in new_s: 40 | print (name) 41 | -------------------------------------------------------------------------------- /Important/return_indices_of_substration.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | Example: 7 | Given nums = [2, 7, 11, 15], target = 5, 8 | Because nums[0] + nums[1] = 7 - 2 = 5, 9 | return [0, 1]. 10 | 11 | Alteration of problem: https://leetcode.com/problems/two-sum/description/ 12 | """ 13 | 14 | class Solution(object): 15 | def twoSubstration(self, nums, target): 16 | """ 17 | :type nums: List[int] 18 | :type target: int 19 | :rtype: List[int] 20 | """ 21 | result = {} 22 | for i, e in enumerate(nums): 23 | if (target + e) in result: 24 | return [result[target + e], i] 25 | result[e] = i 26 | s = Solution() 27 | print(s.twoSubstration([2,7,11,15], 5)) -------------------------------------------------------------------------------- /Important/return_indices_of_sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | Example: 7 | Given nums = [2, 7, 11, 15], target = 9, 8 | Because nums[0] + nums[1] = 2 + 7 = 9, 9 | return [0, 1]. 10 | 11 | source: https://leetcode.com/problems/two-sum/description/ 12 | """ 13 | 14 | class Solution(object): 15 | def twoSum(self, nums, target): 16 | """ 17 | :type nums: List[int] 18 | :type target: int 19 | :rtype: List[int] 20 | """ 21 | result = {} 22 | for i, e in enumerate(nums): 23 | if (target - e) in result: 24 | return [result[target - e], i] 25 | result[e] = i 26 | 27 | s = Solution() 28 | print(s.twoSum([1,2,3,4], 7)) 29 | print(s.twoSum([4,4], 8)) 30 | -------------------------------------------------------------------------------- /Company/collection_of_socks.py: -------------------------------------------------------------------------------- 1 | """ 2 | If your sock drawer has 6 black socks, 4 brown socks, 8 white socks, and 2 tan socks, how many socks would you have to pull out in the dark to be sure you had a matching pair? 3 | 4 | """ 5 | 6 | # Data 7 | collection = { 8 | 'black': 6, 9 | 'brown': 4, 10 | 'white': 8, 11 | 'tan': 2 12 | } 13 | 14 | 15 | def choose_random(collection, picks=1): 16 | 17 | box_of_socks = [] 18 | for i in range(len(collection)): 19 | box_of_socks.append([str(collection.keys()[i])] 20 | * collection.values()[i]) 21 | 22 | choice = [] 23 | for color_box in box_of_socks: 24 | if len(color_box) > 0: 25 | pick = color_box.pop() 26 | if pick in choice: 27 | break 28 | else: 29 | choice.append(pick) 30 | 31 | return len(choice)+1 32 | 33 | 34 | print(choose_random(collection, picks=1)) 35 | -------------------------------------------------------------------------------- /Company/fibonacci.py: -------------------------------------------------------------------------------- 1 | """ 2 | The Fibonacci numbers, commonly denoted F(n) form a sequence, 3 | called the Fibonacci sequence, such that each number is the sum of the two preceding ones, 4 | starting from 0 and 1. That is, 5 | 6 | F(0) = 0, F(1) = 1 7 | F(N) = F(N - 1) + F(N - 2), for N > 1. 8 | 9 | Given N (N-th number in fibonacci sequence), calculate F(N). 10 | 11 | Input: 6 12 | Output: 8 13 | Explanation: F(6) = 0, 1, 1, 2, 3, 5, 8 14 | F(6) = F(5) + F(4) = 5 + 3 = 8. 15 | """ 16 | 17 | def fibonacci_recursive(N: int) -> int: 18 | if N <= 1: 19 | return N 20 | return fibonacci_recursive(N - 1) + fibonacci_recursive(N - 2) 21 | 22 | def fibonacci_iterative(N: int) -> int: 23 | a, b = 0, 1 24 | if N <= 1: 25 | return N 26 | for i in range(N): 27 | a, b = b, a + b 28 | return a 29 | 30 | if __name__=='__main__': 31 | print(fibonacci_recursive(10)) 32 | print(fibonacci_iterative(10)) 33 | -------------------------------------------------------------------------------- /CodeWars/ArrayPlusArray.py: -------------------------------------------------------------------------------- 1 | #!/usr/bir/#!/usr/bin/#!/usr/bin/env python 2 | """ 3 | PROBLEM: 4 | I'm new to coding and now I want to get the sum of two arrays 5 | ...actually the sum of all their elements. 6 | I'll appreciate for your help. 7 | P.S. Each array includes only integer numbers. Output is a number too. 8 | 9 | TEST: 10 | Some test cases can be found in the test folder 11 | 12 | Answer by @mauricerivers 13 | """ 14 | print("Code Wars - Array Plus Array!") 15 | 16 | # function defition 17 | def array_plus_array(arr1,arr2): 18 | # variable used to add the array membeers 19 | sum = 0 20 | 21 | # loop through arr1 and add each item to sum 22 | for item in arr1: 23 | sum += item 24 | 25 | # loop through arr2 and add each item to sum 26 | for item in arr2: 27 | sum += item 28 | 29 | return sum 30 | 31 | # simple terminal function call 32 | # should print 21 33 | print(array_plus_array([1, 2, 3], [4, 5, 6])) 34 | -------------------------------------------------------------------------------- /LeetCode/581.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shortest Unsorted Continuous Subarray 3 | 4 | Given an integer array, you need to find one continuous subarray that 5 | if you only sort this subarray in ascending order, 6 | then the whole array will be sorted in ascending order, too. 7 | 8 | You need to find the shortest such subarray and output its length. 9 | 10 | Example: 11 | Input: [2, 6, 4, 8, 10, 9, 15] 12 | Output: 5 13 | Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order 14 | to make the whole array sorted in ascending order. 15 | """ 16 | 17 | def findUnsortedSubarray(nums): 18 | 19 | temp = sorted(nums) 20 | l = 0 21 | r = len(nums) - 1 22 | 23 | while l < r: 24 | if nums[l] == temp[l]: 25 | l += 1 26 | elif nums[r] == temp[r]: 27 | r -= 1 28 | else: 29 | return r - l + 1 30 | 31 | if r == l: 32 | return 0 33 | 34 | 35 | A = [2, 2, 4, 8, 10, 9, 15] 36 | print(findUnsortedSubarray(A)) -------------------------------------------------------------------------------- /LeetCode/jump_game.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Determine if you are able to reach the last index. 7 | 8 | Input: nums = [2,3,1,1,4] 9 | Output: true 10 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 11 | 12 | ''' 13 | class Solution: 14 | def canJump(self, nums): 15 | """ 16 | : type nums: List[int] 17 | : rtype : bool 18 | 19 | """ 20 | s,k=1,len(nums) 21 | if k==1: 22 | return True 23 | for i in range(1,k): 24 | if nums[k-1-i]==0: 25 | s+=1 26 | elif nums[k-1-i]>=s: 27 | s=1 28 | else: 29 | s+=1 30 | if s==1: 31 | return True 32 | else: 33 | return False 34 | 35 | 36 | -------------------------------------------------------------------------------- /Important/LinkedList_Node.py: -------------------------------------------------------------------------------- 1 | # A single node of a linked list 2 | class Node: 3 | 4 | def __init__(self, data): 5 | self.data = data 6 | self.next = None 7 | 8 | def get_data(self): 9 | return self.data 10 | 11 | def set_data(self, new_data): 12 | self.data = new_data 13 | 14 | def get_next(self): 15 | return self.next 16 | 17 | def set_next(self, new_next): 18 | self.next = new_next 19 | 20 | class LinkedList: 21 | def __init__(self, head=None): 22 | self.head = head 23 | self.count = 0 24 | 25 | def insert(self, data): 26 | new_node = Node(data) 27 | if (self.head): 28 | current = self.head 29 | while (current.next): 30 | curret = current.get_next 31 | 32 | 33 | A = [1,2,3,4] 34 | 35 | N = Node(24) 36 | N.set_next(25) 37 | N.set_next(26) 38 | N.set_next(27) 39 | print(N.data) 40 | print(N.get_next()) 41 | print(N.get_next()) 42 | -------------------------------------------------------------------------------- /Important/average_score.py: -------------------------------------------------------------------------------- 1 | try: 2 | N = int(input()) 3 | except ValueError as va: 4 | print("Expected int input") 5 | 6 | names_list = [] 7 | while True: 8 | try: 9 | name_score = input().split() 10 | except ValueError as va: 11 | print("Expected string input") 12 | 13 | names_list.append(name_score) 14 | 15 | if len(names_list) == N: 16 | break 17 | 18 | names_only = [] 19 | 20 | for name in names_list: 21 | names_only.append(name[0]) 22 | 23 | 24 | while True: 25 | try: 26 | name = str(input()) 27 | except ValueError as va: 28 | print("Expected string input") 29 | 30 | if name in names_only: 31 | break 32 | 33 | avg_dict = {} 34 | for v in names_list: 35 | avg = (float(v[1])+float(v[2])+float(v[3]))/3 36 | 37 | avg_dict[v[0]] = '{:.2f}'.format(avg) 38 | 39 | print(avg_dict) 40 | exit() 41 | 42 | for k, v in avg_dict.iteritems(): 43 | if k == name: 44 | print(v) 45 | -------------------------------------------------------------------------------- /Important/peak_index_of_Mountain.py: -------------------------------------------------------------------------------- 1 | # Let's call an array A a mountain if the following properties hold: 2 | 3 | # A.length >= 3 4 | # There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 5 | # Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. 6 | 7 | 8 | 9 | class Solution(object): 10 | def peakIndexInMountainArray(self, A): 11 | """ 12 | :type A: List[int] 13 | :rtype: int 14 | """ 15 | peak = 0 16 | i = 0 17 | while (i+2 < len(A)): 18 | firstP = A[i] 19 | midP = A[i+1] 20 | lastP = A[i+2] 21 | 22 | if firstP < midP > lastP: 23 | peak = A.index(midP) 24 | 25 | i = i + 1 26 | 27 | return peak 28 | 29 | s = Solution() 30 | print(s.peakIndexInMountainArray([0,1,2,0])) -------------------------------------------------------------------------------- /Important/PeakFinder-1D.py: -------------------------------------------------------------------------------- 1 | # array = [1,2,3,6,3,4,5,6,7,8,4] 2 | 3 | def PeakFinder(a): 4 | 5 | L=len(a) 6 | m=L//2 7 | a1=[] 8 | 9 | #base case 10 | try: 11 | if a[m-1] < a[m] > a[m+1]: 12 | a1.append(a[m]) 13 | except IndexError: 14 | return [] 15 | 16 | 17 | checkLeft = a[m-1] > a[m] > a[m+1] 18 | checkRight = a[m-1] < a[m] < a[m+1] 19 | 20 | if checkLeft: 21 | return PeakFinder(a[:m]) 22 | elif checkRight: 23 | return PeakFinder(a[m:]) 24 | else: 25 | return a1 26 | 27 | 28 | 29 | def PeakFinder1(a): 30 | 31 | peak = 0 32 | i = 0 33 | while(i+2 < len(a)): 34 | firstP = a[i] 35 | midP = a[i+1] 36 | lastP = a[i+2] 37 | 38 | if firstP < midP > lastP: 39 | peak = midP 40 | i = i+1 41 | 42 | return [peak] 43 | 44 | 45 | a = [1,2,3,6,3,4,5,6,7,8,4] 46 | #a=[] 47 | print (PeakFinder(a)) 48 | print (PeakFinder1(a)) 49 | 50 | -------------------------------------------------------------------------------- /LeetCode/top_k_frequent.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-empty array of integers, return the k most frequent elements. 3 | 4 | Example 1: 5 | 6 | Input: nums = [1,1,1,2,2,3], k = 2 7 | Output: [1,2] 8 | Example 2: 9 | 10 | Input: nums = [1], k = 1 11 | Output: [1] 12 | 13 | ''' 14 | 15 | class Solution: 16 | 17 | def topKFrequent(self, nums, k): 18 | 19 | """ 20 | :type nums: List[int] 21 | :type k: int 22 | :rtype: List[int] 23 | """ 24 | 25 | m,v,ma={},[],0 26 | 27 | for i in nums: 28 | 29 | if i in m: 30 | m[i]+=1 31 | 32 | else: 33 | m[i]=1 34 | 35 | if m[i]>ma: 36 | ma=m[i] 37 | 38 | while k!=0: 39 | 40 | for i in m: 41 | 42 | if k==0: 43 | break 44 | 45 | if m[i]==ma: 46 | v.append(i) 47 | k-=1 48 | ma-=1 49 | return v -------------------------------------------------------------------------------- /GeeksforGeeks/roman_to_integer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Input: 3 | The first line of each test case contains the no of test cases T 4 | Then T test cases follow. Each test case contains a string s denoting the roman no 5 | 6 | Output: 7 | For each test case in a new line print the integer representation of roman number s 8 | ''' 9 | 10 | def roman_to_int(roman): 11 | value = { 12 | 'I': 1, 13 | 'V': 5, 14 | 'X': 10, 15 | 'L': 50, 16 | 'C': 100, 17 | 'D': 500, 18 | 'M': 1000 19 | } 20 | 21 | prev = 0 22 | ans = 0 23 | n = len(roman) 24 | for i in range(n-1, -1, -1): 25 | if value[roman[i]] >= prev: 26 | ans += value[roman[i]] 27 | else: 28 | ans -= value[roman[i]] 29 | 30 | prev = value[roman[i]] 31 | 32 | print(ans) 33 | '''for _ in range(int(input())): 34 | s = input() 35 | roman_to_int(s) 36 | ''' 37 | # s = 'V' 38 | # s = 'III' 39 | s = 'XIV' 40 | 41 | roman_to_int(s) 42 | -------------------------------------------------------------------------------- /LeetCode/217.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, find if the array contains any duplicates. 3 | 4 | Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 5 | 6 | Example 1: 7 | Input: [1,2,3,1] 8 | Output: true 9 | 10 | Example 2: 11 | Input: [1,2,3,4] 12 | Output: false 13 | 14 | Example 3: 15 | Input: [1,1,1,3,3,4,3,2,4,2] 16 | Output: true 17 | """ 18 | 19 | class Solution: 20 | def containsDuplicate(self, nums): 21 | """ 22 | :type nums: List[int] 23 | :rtype: bool 24 | """ 25 | seen = set() 26 | for num in nums: 27 | if num in seen: 28 | return True 29 | else: 30 | seen.add(num) 31 | return False 32 | 33 | s = Solution() 34 | 35 | assert s.containsDuplicate([1,2,3,1]) == True 36 | assert s.containsDuplicate([1,2,3,4]) == False 37 | assert s.containsDuplicate([1,1,1,3,3,4,3,2,4,2]) == True 38 | -------------------------------------------------------------------------------- /Important/RepeatingListofEvenNumbersFindTheOdd.py: -------------------------------------------------------------------------------- 1 | # Find from alist of numbers where each number is repeating 2 | # even number of times except one. Find that number ? 3 | # Input: 4 | # [1,1,2,2,3,4,4,5,6,5,6] 5 | # 6 | # Output: 7 | # 3 8 | from timeit import timeit as ti 9 | 10 | 11 | def RepeatingEvenList(aList): 12 | s = ti(number=10000) 13 | 14 | res = 0 15 | for i in aList: 16 | res ^= i 17 | 18 | e = ti(number=10000) 19 | 20 | return res, s-e 21 | 22 | 23 | def UsingDict(aList): 24 | 25 | s = ti(number=10000) 26 | 27 | #d={i: aList.count(i) for i in aList } 28 | 29 | d = {} 30 | 31 | for i in aList: 32 | if i in d: 33 | d[i] += 1 34 | else: 35 | d[i] = 1 36 | 37 | res = 0 38 | for k, v in d.items(): 39 | if v == 1: 40 | res = k 41 | 42 | e = ti(number=10000) 43 | 44 | return res, s-e 45 | 46 | 47 | a = [1, 1, 2, 2, 3, 4, 4, 5, 6, 5, 6] 48 | print(RepeatingEvenList(a)) 49 | print(UsingDict(a)) 50 | -------------------------------------------------------------------------------- /LeetCode/345.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reverse Vowels of a String 3 | 4 | Write a function that takes a string as input and reverse only the vowels of a string. 5 | 6 | Example1: 7 | Input: "hello" 8 | Output: "holle" 9 | 10 | Example2: 11 | Input: "leetcode" 12 | Output: "leotcede" 13 | 14 | """ 15 | 16 | class Solution: 17 | def reverseVowels(self, s): 18 | """ 19 | :type s: str 20 | :rtype: str 21 | """ 22 | s = list(s) 23 | n = len(s) 24 | l = 0 25 | r = len(s) - 1 26 | vowels = {'a':1, 'e':1, 'i':1, 'o':1, 'u':1, 'A':1, 'E':1, 'I':1, 'O':1, 'U':1} 27 | 28 | while l < r: 29 | if s[l] not in vowels: 30 | l += 1 31 | elif s[r] not in vowels: 32 | r -= 1 33 | else: 34 | s[l], s[r] = s[r], s[l] 35 | l += 1 36 | r -= 1 37 | 38 | return ''.join(s) 39 | 40 | s = Solution() 41 | S = 'hello' 42 | print(s.reverseVowels(S)) -------------------------------------------------------------------------------- /GeeksforGeeks/recursion_all_indices.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an array of distinct integers with size N and an integer X 4 | Display all the indices of the integer X in the array using RECURSION only 5 | If no X occurs in the array no output should be displayed 6 | Examples: 7 | Input: arr = {10, 12, 11, 12, 13, 12} ,X=12 8 | Output: 1 3 5 9 | Input: arr = {1, 2, 4, 3} ,X=9 10 | Output: No Output 11 | Input: arr= {8, 8, 8, 8, 8} ,X=8 12 | Output: 0 1 2 3 4 13 | 14 | """ 15 | def AllIndexesRecursive(input, x, start): 16 | if (start == len(input)): 17 | ans = [] 18 | return ans 19 | smallIndex = AllIndexesRecursive(input,x,start + 1) 20 | if (input[start] == x): 21 | myAns = [0 for i in range(len(smallIndex) + 1)] 22 | myAns[0] = start 23 | for i in range(len(smallIndex)): 24 | myAns[i + 1] = smallIndex[i] 25 | return myAns 26 | else: 27 | return smallIndex 28 | 29 | def AllIndexes(input, x): 30 | return AllIndexesRecursive(input, x, 0) 31 | -------------------------------------------------------------------------------- /Important/MultipleLists.py: -------------------------------------------------------------------------------- 1 | from timeit import timeit as ti 2 | 3 | 4 | def ltest1(): 5 | start = ti(number=1000) 6 | l = [] 7 | for i in range(1000): 8 | l = l+[i] 9 | end = ti(number=1000) 10 | 11 | return start-end 12 | 13 | 14 | def ltest2(): 15 | start = ti(number=1000) 16 | l = [] 17 | for i in range(1000): 18 | l.append(i) 19 | end = ti(number=1000) 20 | 21 | return start-end 22 | 23 | 24 | def ltest3(): 25 | start = ti(number=1000) 26 | l = [i for i in range(1000)] 27 | end = ti(number=1000) 28 | 29 | return start-end 30 | 31 | 32 | def ltest4(): 33 | start = ti(number=1000) 34 | l = list(range(1000)) 35 | end = ti(number=1000) 36 | 37 | return start-end 38 | 39 | 40 | print("concat : {} milliseconds".format(str(ltest1()))) 41 | print("append : {} milliseconds".format(str(ltest2()))) 42 | print("comprehension : {} milliseconds".format(str(ltest3()))) 43 | print("list range : {} milliseconds".format(str(ltest4()))) 44 | -------------------------------------------------------------------------------- /Important/Rotate_string.py: -------------------------------------------------------------------------------- 1 | ''' 2 | We are given two strings, A and B. 3 | 4 | A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', 5 | then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A. 6 | 7 | Example 1: 8 | Input: A = 'abcde', B = 'cdeab' 9 | Output: true 10 | 11 | Example 2: 12 | Input: A = 'abcde', B = 'abced' 13 | Output: false 14 | 15 | ''' 16 | 17 | class Solution(object): 18 | def rotateString(self, A, B): 19 | """ 20 | :type A: str 21 | :type B: str 22 | :rtype: bool 23 | """ 24 | if A == B == "": 25 | return True 26 | if len(A) != len(B): 27 | return False 28 | else: 29 | i = 0 30 | for i in range(len(A)): 31 | if A[i:]+A[:i] == B: 32 | return True 33 | return False 34 | 35 | s = Solution() 36 | print(s.rotateString('abcde', 'cdeab')) -------------------------------------------------------------------------------- /LeetCode/169.py: -------------------------------------------------------------------------------- 1 | """ 2 | 169. Majority Element 3 | Given an array nums of size n, return the majority element. 4 | The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. 5 | 6 | 7 | Example 1: 8 | Input: nums = [3,2,3] 9 | Output: 3 10 | 11 | Example 2: 12 | Input: nums = [2,2,1,1,1,2,2] 13 | Output: 2 14 | """ 15 | from typing import List 16 | 17 | def majorityElement(nums: List[int]) -> int: 18 | # len 19 | n = len(nums) 20 | # create an empty dict 21 | d = {} 22 | # majority value 23 | m = n/2 24 | # iterate over the nums 25 | for i in nums: 26 | if i in d.keys(): 27 | d[i]+=1 28 | else: 29 | d[i]=1 30 | 31 | # iterate over the dict 32 | for k,v in d.items(): 33 | if v > m: 34 | return k 35 | 36 | q1 = [3,2,3] 37 | q2 = [2,2,1,1,1,2,2] 38 | print(majorityElement(q1)) 39 | print(majorityElement(q2)) 40 | -------------------------------------------------------------------------------- /Company/find_average_in_a_matrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Provided a 2D n x n matrix, given two coordinates first and the last, return the average of cube 3 | 4 | Ex: 5 | Input: 6 | 3 => 3 x 3 matrix 7 | [[0,0], [0,1], [0,2] 8 | ,[1,0], [1,1], [1,2] 9 | ,[2,0], [2,1], [2,2]] 10 | 11 | coordinate => 4 => [1,1] 12 | coordinate => 6 => [2,2] 13 | 14 | result : 3 15 | average => ([1,1],[1,2],[2,1][2,2])/4 => 3 16 | 17 | 18 | """ 19 | 20 | 21 | def create_2d_matrix(n): 22 | result = [] 23 | 24 | for i in range(n): 25 | j = 0 26 | while j < n: 27 | result.append((i, j)) 28 | j += 1 29 | 30 | return result 31 | 32 | 33 | def find_average_2d_matrix(n, i1, i2): 34 | 35 | matrix = create_2d_matrix(n) 36 | 37 | result = [sum(i) for i in matrix] 38 | print(i1, i2) 39 | print(result) 40 | 41 | if i2 - i1 % n == 0: 42 | return 0 43 | if i1 < 0: 44 | return 0 45 | if i2 > len(matrix) - 1: 46 | return 0 47 | 48 | return (result[i2]) 49 | 50 | 51 | print(find_average_2d_matrix(4, 4, 8)) 52 | -------------------------------------------------------------------------------- /Company/matrixOperations.py: -------------------------------------------------------------------------------- 1 | 2 | class MatrixOperations: 3 | #Function which returns the transpose of given matrix A 4 | 5 | def transpose(self, A) : 6 | #T is used to store the transpose of A 7 | T = [[0, 0, 0], 8 | [0, 0, 0], 9 | [0, 0, 0]] 10 | 11 | # iterate through rows 12 | for i in range(len(A)): 13 | # iterate through columns 14 | for j in range(len(A[0])): 15 | T[j][i] = A[i][j] 16 | 17 | return T 18 | 19 | #Function for multiplication of given matrix A and its transpose T 20 | def mult(self, A,T) : 21 | 22 | result = [[0, 0, 0], 23 | [0, 0, 0], 24 | [0, 0, 0]] 25 | 26 | # iterating by row of A 27 | for i in range(len(A)): 28 | 29 | # iterating by coloum by T 30 | for j in range(len(T[0])): 31 | 32 | # iterating by rows of T 33 | for k in range(len(T)): 34 | result[i][j] += A[i][k] * T[k][j] 35 | 36 | return result -------------------------------------------------------------------------------- /Important/DiffOfLists.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def Difference(lst1, lst2): 5 | 6 | if lst1 == [] or lst2 == []: 7 | return [] 8 | else: 9 | diff1 = set(lst1).difference(set(lst2)) 10 | diff2 = set(lst2).difference(set(lst1)) 11 | 12 | union = diff1.union(diff2) 13 | 14 | return list(union) 15 | 16 | # lst1 = [1,2,3,4,5,6] 17 | # lst2 = [4,5,6,7,8,9] 18 | # #ans [1,2,3,7,8,9] 19 | 20 | # print Difference(lst1, lst2) 21 | 22 | 23 | class TestDifference(unittest.TestCase): 24 | 25 | def test_equalLength(self): 26 | lst1 = [1, 2, 3, 4, 5, 6] 27 | lst2 = [4, 5, 6, 7, 8, 9] 28 | self.assertEqual([1, 2, 3, 7, 8, 9], Difference(lst1, lst2)) 29 | 30 | def test_empty(self): 31 | lst1 = [] 32 | lst2 = [1, 2, 3] 33 | self.assertEqual([], Difference(lst1, lst2)) 34 | 35 | def test_single(self): 36 | lst1 = [1] 37 | lst2 = [2] 38 | self.assertEqual([1, 2], Difference(lst1, lst2)) 39 | 40 | 41 | if __name__ == '__main__': 42 | unittest.main(verbosity=2) 43 | -------------------------------------------------------------------------------- /test/test_fibonacci.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.join(sys.path[0], '..')) 4 | from Company.fibonacci import fibonacci_recursive, fibonacci_iterative 5 | 6 | def test_fibonacci_recursive(): 7 | # check special cases 8 | assert fibonacci_recursive(0) == 0 9 | assert fibonacci_recursive(1) == 1 10 | assert fibonacci_recursive(-1) == -1 11 | assert fibonacci_recursive(-10) == -10 12 | # check fibonacci sequence 13 | assert fibonacci_recursive(2) == 1 14 | assert fibonacci_recursive(5) == 5 15 | assert fibonacci_recursive(10) == 55 16 | assert fibonacci_recursive(20) == 6765 17 | 18 | def test_fibonacci_iterative(): 19 | # check special cases 20 | assert fibonacci_iterative(0) == 0 21 | assert fibonacci_iterative(1) == 1 22 | assert fibonacci_iterative(-1) == -1 23 | assert fibonacci_iterative(-10) == -10 24 | # check fibonacci sequence 25 | assert fibonacci_iterative(2) == 1 26 | assert fibonacci_iterative(5) == 5 27 | assert fibonacci_iterative(10) == 55 28 | assert fibonacci_iterative(20) == 6765 29 | -------------------------------------------------------------------------------- /LeetCode/buddystring.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B. 3 | Example 1: 4 | 5 | Input: A = "ab", B = "ba" 6 | Output: true 7 | Example 2: 8 | 9 | Input: A = "ab", B = "ab" 10 | Output: false 11 | Example 3: 12 | 13 | Input: A = "aa", B = "aa" 14 | Output: true 15 | Example 4: 16 | 17 | Input: A = "aaaaaaabc", B = "aaaaaaacb" 18 | Output: true 19 | Example 5: 20 | 21 | Input: A = "", B = "aa" 22 | Output: false 23 | 24 | ''' 25 | 26 | 27 | class Solution(object): 28 | def buddyStrings(self, A, B): 29 | """ 30 | :type A: str 31 | :type B: str 32 | :rtype: bool 33 | """ 34 | if len(A) != len(B): 35 | return False 36 | if A == B and len(set(A)) < len(A): 37 | return True 38 | diff = [(a, b) for a, b in zip(A, B) if a != b] 39 | return len(diff) == 2 and diff[0] == diff[1][::-1] 40 | 41 | 42 | s = Solution() 43 | A = input("enter string A: ") 44 | B = input("enter string B: ") 45 | print(s.buddyStrings(A, B)) 46 | -------------------------------------------------------------------------------- /CodeWars/Tortoise_Racing.py: -------------------------------------------------------------------------------- 1 | '''URL : https://www.codewars.com/kata/55e2adece53b4cdcb900006c ''' 2 | ''' 3 | Question 4 | 5 | Two tortoises named A and B must run a race. A starts with an average speed of 720 feet per hour. Young B knows she runs faster than A, and furthermore has not finished her cabbage. 6 | 7 | When she starts, at last, she can see that A has a 70 feet lead but B's speed is 850 feet per hour. How long will it take B to catch A? 8 | 9 | More generally: given two speeds v1 (A's speed, integer > 0) and v2 (B's speed, integer > 0) and a lead g (integer > 0) how long will it take B to catch A? 10 | 11 | The result will be an array [hour, min, sec] which is the time needed in hours, minutes and seconds (round down to the nearest second) or a string in some languages. 12 | 13 | If v1 >= v2 then return nil, nothing, null, None or {-1, -1, -1} for C++, C, Go, Nim, [] for Kotlin or "-1 -1 -1". 14 | ''' 15 | 16 | #ANSWER 17 | 18 | def race(v1, v2, g): 19 | if v1 >= v2: return None 20 | t = float(g)/(v2-v1)*3600 21 | mn, s = divmod(t, 60) 22 | h, mn = divmod(mn, 60) 23 | return [int(h), int(mn), int(s)] -------------------------------------------------------------------------------- /test/test_matrix_operation.py: -------------------------------------------------------------------------------- 1 | from Company.matrixOperations import MatrixOperations 2 | 3 | m = MatrixOperations() 4 | #Test to check the transpose of given matrix is correct 5 | def test_transpose(): 6 | transpose = m.transpose([[2, 5, 3], [4, 7, 6],[3, 8, 4]]) 7 | assert transpose == [[2, 4, 3], [5, 7, 8], [3, 6, 4]] 8 | 9 | #Test to check the transpose is 3X3 matrix 10 | def test_transpose_size(): 11 | transpose = m.transpose([[2, 5, 3], [4, 7, 6],[3, 8, 4]]) 12 | assert len(transpose) == 3 # row size 13 | assert len(transpose[0]) == 3 # column size 14 | 15 | #Test to check the multiplication of given matrix and its transpose is correct 16 | def test_mult(): 17 | mult = m.mult([[2, 5, 3], [4, 7, 6],[3, 8, 4]],[[2, 4, 3], [5, 7, 8], [3, 6, 4]]) 18 | assert mult == [[38, 61, 58], [61, 101, 92], [58, 92, 89]] 19 | 20 | #Test to check the multiplication of two matrices is 3X3 matrix. 21 | def test_mult_size(): 22 | mult = m.mult([[2, 5, 3], [4, 7, 6],[3, 8, 4]],[[2, 4, 3], [5, 7, 8], [3, 6, 4]]) 23 | assert len(mult) == 3 # row size 24 | assert len(mult[0]) == 3 # column size 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Aditya Arakeri 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LeetCode/94.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | ''' 5 | Given the root of a binary tree, return the inorder traversal of its nodes' values. 6 | 7 | Input: root = [1,null,2,3] 8 | Output: [1,3,2] 9 | Explanation: Iteration with stack 10 | 11 | ''' 12 | 13 | from typing import List 14 | # Definition for a binary tree node. 15 | class TreeNode: 16 | def __init__(self, val=0, left=None, right=None): 17 | self.val = val 18 | self.left = left 19 | self.right = right 20 | 21 | # Iteration-based solution 22 | class Solution: 23 | def inorderTraversal(self, root: TreeNode) -> List[int]: 24 | 25 | res = [] 26 | stk = [] 27 | 28 | while root or len(stk) != 0: 29 | while root is not None: 30 | stk.append(root) 31 | root = root.left 32 | 33 | root = stk[-1] 34 | res.append(root.val) 35 | stk.pop() 36 | root = root.right 37 | 38 | return res 39 | 40 | root = TreeNode(1, None, TreeNode(2, TreeNode(3))) 41 | s = Solution() 42 | print(s.inorderTraversal(root)) 43 | -------------------------------------------------------------------------------- /CodeWars/ModuletoAtoms.py: -------------------------------------------------------------------------------- 1 | """ 2 | For a given chemical formula represented by a string, count the number of atoms of each element contained in the molecule and return an object (associative array in PHP, Dictionary in C#, Map in Java). 3 | 4 | For example: 5 | water = 'H2O' 6 | breakdown -> H2O1 7 | parse_molecule(water) # return {H: 2, O: 1} 8 | 9 | magnesium_hydroxide = 'Mg(OH)2' 10 | breakdown -> Mg1O2H2 11 | parse_molecule(magnesium_hydroxide) # return {Mg: 1, O: 2, H: 2} 12 | 13 | var fremy_salt = 'K4[ON(SO3)2]2' 14 | breakdown -> K4O2N2(SO3)4 -> K4O2N2S4O12 15 | parse_molecule(fremySalt) # return {K: 4, O: 14, N: 2, S: 4} 16 | 17 | """ 18 | 19 | def parse_molecule(formula): 20 | 21 | word_stack = [] 22 | num_stack = [] 23 | formula = list(formula) 24 | brackets = {'}': '{', ']':'[', ')':'('} 25 | brackets1 = {'{': '}', '[':']', '(':')'} 26 | 27 | if not formula[-1].isdigit(): 28 | formula.append('1') 29 | print(formula) 30 | 31 | 32 | 33 | # for i in range(len(formula) - 1): 34 | 35 | 36 | 37 | print(parse_molecule('K4[ON(SO3)2]2')) 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /LeetCode/two_sum_II.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 3 | 4 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. 5 | 6 | Note: 7 | 8 | Your returned answers (both index1 and index2) are not zero-based. 9 | You may assume that each input would have exactly one solution and you may not use the same element twice. 10 | Example: 11 | 12 | Input: numbers = [2,7,11,15], target = 9 13 | Output: [1,2] 14 | Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. 15 | 16 | """ 17 | 18 | 19 | def twoSum(numbers, target): 20 | d = {} 21 | n = len(numbers) 22 | 23 | for i in range(n): 24 | d[numbers[i]] = i 25 | 26 | for i in range(n): 27 | diff = target - numbers[i] 28 | if(diff in d): 29 | x = i+1 30 | y = d[diff] + 1 31 | 32 | if(x 0: 16 | reminder = num % 2 17 | # push to stack 18 | stack.append(reminder) 19 | num = num // 2 20 | 21 | while len(stack) > 0: 22 | binary = binary + str(stack.pop()) 23 | 24 | return binary 25 | 26 | # print ConvertToBinary(int(input("Enter a number to be converted to Binary > "))) 27 | 28 | 29 | class Testconversion(unittest.TestCase): 30 | 31 | def test_zero(self): 32 | self.assertEquals(bin(0)[2:], ConvertToBinary(0)) 33 | 34 | def test_one(self): 35 | self.assertEquals(bin(1)[2:], ConvertToBinary(1)) 36 | 37 | def test_smallInt(self): 38 | self.assertEquals(bin(24)[2:], ConvertToBinary(24)) 39 | 40 | def test_LargeInt(self): 41 | self.assertEquals(bin(1000456)[2:], ConvertToBinary(1000456)) 42 | 43 | 44 | if __name__ == '__main__': 45 | unittest.main(verbosity=2) 46 | -------------------------------------------------------------------------------- /LeetCode/784.py: -------------------------------------------------------------------------------- 1 | """ 2 | 784. Letter Case Permutation 3 | 4 | Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. 5 | 6 | Examples: 7 | Input: S = "a1b2" 8 | Output: ["a1b2", "a1B2", "A1b2", "A1B2"] 9 | 10 | Input: S = "3z4" 11 | Output: ["3z4", "3Z4"] 12 | 13 | Input: S = "12345" 14 | Output: ["12345"] 15 | 16 | Input: S = "abc" 17 | Output: ["abc", "Abc", "aBc", "abC", "ABc", "AbC", "aBC", "ABC"] 18 | """ 19 | 20 | 21 | class Solution(object): 22 | def letterCasePerm(self, S): 23 | """ 24 | :type S: str 25 | :rtype: List[str] 26 | """ 27 | 28 | S = list(S) 29 | result = [''] 30 | while S: 31 | last = S.pop() 32 | if (last.isalpha()): 33 | result = [last.lower() + x for x in result] + \ 34 | [last.upper() + x for x in result] 35 | print(result) 36 | else: 37 | result = [last + x for x in result] 38 | print(result) 39 | 40 | return result 41 | 42 | 43 | s = Solution() 44 | print(s.letterCasePerm('1a2bc')) 45 | -------------------------------------------------------------------------------- /CodeWars/First_non_repeating_character.py: -------------------------------------------------------------------------------- 1 | def first_non_repeating_letter(string): 2 | """ 3 | This was created for Code Wars: 4 | https://www.codewars.com/kata/52bc74d4ac05d0945d00054e 5 | 6 | This function takes a string as an input. 7 | It will return the first character the does not repeat in the string. 8 | It is case insensitive 9 | """ 10 | 11 | #checks for empty string 12 | if string == "": 13 | return "" 14 | else: 15 | 16 | #creates list which will check if there is a repeated character 17 | list = [] 18 | 19 | #iterates through string to count how many times it appears 20 | #keeps track of occurences by adding counts to list 21 | for i in string: 22 | list.append(string.lower().count(i.lower())) 23 | if string.lower().count(i.lower()) > 1: 24 | pass 25 | else: 26 | return i 27 | #break so only first occurence is taken 28 | break 29 | 30 | #if no character occured only a single time, a blank string will be return 31 | if 1 not in list: 32 | return "" -------------------------------------------------------------------------------- /GeeksforGeeks/lenth_of_longest_contegeous_elements.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of distinct integers, 3 | find length of the longest subarray which contains numbers that can be arranged in a continuous sequence. 4 | 5 | 6 | Examples: 7 | 8 | Input: arr[] = {10, 12, 11}; 9 | Output: Length of the longest contiguous subarray is 3 10 | 11 | Input: arr[] = {14, 12, 11, 20}; 12 | Output: Length of the longest contiguous subarray is 2 13 | 14 | Input: arr[] = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45}; 15 | Output: Length of the longest contiguous subarray is 5 16 | """ 17 | 18 | def find_length(arr): 19 | 20 | arr.sort() 21 | n = len(arr) 22 | 23 | long_len = 1 24 | result = [] 25 | 26 | start = 0 27 | 28 | while start < n-1: 29 | 30 | if arr[start] == arr[start+1] - 1: 31 | long_len += 1 32 | else: 33 | result.append(long_len) 34 | long_len = 1 35 | start += 1 36 | 37 | result.append(long_len) 38 | 39 | if max(result) != 1: 40 | return max(result) 41 | else: 42 | return -1 43 | 44 | # A = [1, 56, 58, 57, 90, 92, 94, 93, 91, 45] 45 | # A = [10, 12, 11] 46 | A = [15, 13, 11, 20] 47 | print(find_length(A)) 48 | -------------------------------------------------------------------------------- /TreesAndGraphs/Djikistra.py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self): 3 | self.nodes = set() 4 | self.edges = defaultdict(list) 5 | self.distances = {} 6 | 7 | def add_node(self, value): 8 | self.nodes.add(value) 9 | 10 | def add_edge(self, from_node, to_node, distance): 11 | self.edges[from_node].append(to_node) 12 | self.edges[to_node].append(from_node) 13 | self.distances[(from_node, to_node)] = distance 14 | 15 | 16 | def dijsktra(graph, initial): 17 | visited = {initial: 0} 18 | path = {} 19 | 20 | nodes = set(graph.nodes) 21 | 22 | while nodes: 23 | min_node = None 24 | for node in nodes: 25 | if node in visited: 26 | if min_node is None: 27 | min_node = node 28 | elif visited[node] < visited[min_node]: 29 | min_node = node 30 | 31 | if min_node is None: 32 | break 33 | 34 | nodes.remove(min_node) 35 | current_weight = visited[min_node] 36 | 37 | for edge in graph.edges[min_node]: 38 | weight = current_weight + graph.distance[(min_node, edge)] 39 | if edge not in visited or weight < visited[edge]: 40 | visited[edge] = weight 41 | path[edge] = min_node 42 | 43 | return visited, path 44 | -------------------------------------------------------------------------------- /GeeksforGeeks/pythagorean_triplet.py: -------------------------------------------------------------------------------- 1 | '''Given an array arr of N integers 2 | write a function that 3 | returns true if there is a triplet (a, b, c) 4 | that satisfies a2 + b2 = c2 5 | otherwise false''' 6 | 7 | import math 8 | 9 | def checkTriplet(arr, n): 10 | mxm = 0 11 | 12 | # finding maximum element 13 | for element in arr: 14 | mxm = max(mxm, element) 15 | 16 | # hashing array 17 | hash = [0]*(mxm+1) 18 | 19 | for element in arr: 20 | hash[element] += 1 21 | 22 | for i in range(1, mxm+1): 23 | if hash[i] == 0: 24 | continue 25 | 26 | for j in range(1, mxm+1): 27 | if (i==j and hash[i]==1) or hash[j]==0: 28 | continue 29 | 30 | val = int(math.sqrt(i*i+j*j)) 31 | if val*val != (i*i+j*j): 32 | continue 33 | if val>mxm: 34 | continue 35 | if hash[val]: 36 | return True 37 | return False 38 | 39 | '''n = int(input()) 40 | a = list(map(int,input().split()))''' 41 | 42 | N = 5 43 | Arr = [3, 2, 4, 6, 5] 44 | 45 | # N = 3 46 | # Arr = [3, 8, 5] 47 | 48 | if checkTriplet(Arr, N): 49 | print("Yes") 50 | else: 51 | print("No") -------------------------------------------------------------------------------- /Important/meetingsInAllTimeZones.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | import pytz 3 | 4 | #all the timezones across the world 5 | OTHER_TIMEZONES = [ 6 | pytz.timezone('US/Eastern'), 7 | pytz.timezone('Pacific/Auckland'), 8 | pytz.timezone('Asia/Calcutta'), 9 | pytz.timezone('UTC'), 10 | pytz.timezone('Europe/Paris'), 11 | pytz.timezone('Africa/Khartoum'), 12 | ] 13 | 14 | #format string this is very useful format 15 | FMT = '%Y-%m-%d %H:%M:%S %Z%z' 16 | 17 | while True: 18 | user_input = input('\nWhen is your meeting? user format MM/DD/YYYY HH:MM : ') 19 | try: 20 | local_date = datetime.strptime(user_input, '%m/%d/%Y %H:%M') 21 | except ValueError: 22 | print("{} does not seem to be a valid input, please use a valid format of MM/DD/YYYY HH:MM".format(user_input)) 23 | else: 24 | local_date = pytz.timezone('US/Pacific').localize(local_date) 25 | utc_date = local_date.astimezone(pytz.utc) 26 | 27 | output = [] 28 | 29 | for timezone in OTHER_TIMEZONES: 30 | output.append(utc_date.astimezone(timezone)) 31 | 32 | for appointment in output: 33 | print(appointment.strftime(FMT)) 34 | break 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /CodeWars/take_a_ten_minute_walk.py: -------------------------------------------------------------------------------- 1 | """ 2 | URL: 3 | https://www.codewars.com/kata/54da539698b8a2ad76000228 4 | 5 | DESCRIPTION: 6 | You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, 7 | so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). 8 | You always walk only a single block in a direction and you know it takes you one minute to traverse one city block, 9 | so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. 10 | Return false otherwise. 11 | """ 12 | 13 | def isValidWalk(walk): 14 | if len(walk) != 10: 15 | return False 16 | 17 | d = { 18 | "n": 0, 19 | "s": 0, 20 | "e": 0, 21 | "w": 0 22 | } 23 | for elem in walk: 24 | if elem in d.keys(): 25 | d[elem] += 1 26 | 27 | return (d["n"] == d["s"]) and (d["e"] == d["w"]) -------------------------------------------------------------------------------- /LeetCode/6.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 3 | P A H N 4 | A P L S I I G 5 | Y I R 6 | And then read line by line: "PAHNAPLSIIGYIR" 7 | Write the code that will take a string and make this conversion given a number of rows: 8 | string convert(string s, int numRows); 9 | Example 1: 10 | Input: s = "PAYPALISHIRING", numRows = 3 11 | Output: "PAHNAPLSIIGYIR" 12 | Example 2: 13 | Input: s = "PAYPALISHIRING", numRows = 4 14 | Output: "PINALSIGYAHRPI" 15 | Explanation: 16 | P I N 17 | A L S I G 18 | Y A H R 19 | P I 20 | ''' 21 | 22 | 23 | class Solution: 24 | def convert(self, s: str, numRows: int) -> str: 25 | if numRows == 1: 26 | return s 27 | 28 | res = '' 29 | n = len(s) 30 | cycle_len = 2 * numRows - 2 31 | 32 | for i in range(numRows): 33 | j = 0 34 | while j + i < n: 35 | res += s[j + i] 36 | if i != 0 and i != numRows - 1 and j + cycle_len - i < n: 37 | res += s[j + cycle_len - i] 38 | j += cycle_len 39 | return res 40 | -------------------------------------------------------------------------------- /LeetCode/724.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find Pivot Index 3 | 4 | Given an array of integers nums, write a method that returns the "pivot" index of this array. 5 | 6 | We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index. 7 | 8 | If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index. 9 | 10 | 11 | Example: 12 | Input: 13 | nums = [1, 7, 3, 6, 5, 6] 14 | Output: 3 15 | Explanation: 16 | The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3. 17 | Also, 3 is the first index where this occurs. 18 | 19 | """ 20 | 21 | 22 | class Solution: 23 | def pivotIndex(self, nums): 24 | """ 25 | :type nums: List[int] 26 | :rtype: int 27 | """ 28 | 29 | total = sum(nums) 30 | sum_so_far = 0 31 | 32 | for i in range(len(nums)): 33 | if sum_so_far * 2 + nums[i] == total: 34 | return i 35 | else: 36 | sum_so_far += nums[i] 37 | 38 | return -1 39 | 40 | 41 | s = Solution() 42 | A = [1, 7, 3, 6, 5, 6] 43 | print(s.pivotIndex(A)) 44 | -------------------------------------------------------------------------------- /Company/find_max_difference.py: -------------------------------------------------------------------------------- 1 | """ 2 | Asked at box 3 | 4 | # Maximum difference between two elements such that larger element appears after the smaller number 5 | 6 | # Given an array arr[] of integers, find out the maximum difference between any two elements such that larger element appears after the smaller number. 7 | 8 | #Input : arr = {2, 3, 10, 6, 4, 8, 1} 9 | #Output : 8 10 | #Explanation : The maximum difference is between 10 and 2. 11 | 12 | """ 13 | 14 | def max_diff(arr): 15 | n = len(arr) 16 | if n == 0: 17 | return -1 18 | if n == 2 : 19 | if n[0] < n[1]: 20 | return n[1] - n[0] 21 | else: 22 | return -1 23 | else: 24 | result = [] 25 | for i in range(2, n): 26 | diff = 0 27 | _slice = arr[:i][:-1] # getting the slice of slice since we will only need the elements except the last element 28 | last = arr[:i][-1] 29 | 30 | if max(_slice) < last: 31 | diff = last - min(_slice) 32 | result.append(diff) 33 | 34 | if len(result) != 0: 35 | return max(result) 36 | else: 37 | return -1 38 | 39 | 40 | A = [2, 3, 10, 6, 4, 8, 1] 41 | print(max_diff(A)) -------------------------------------------------------------------------------- /Company/paranthesis_checker.py: -------------------------------------------------------------------------------- 1 | """ 2 | Check for Parenthesis in a given string 3 | 4 | Example: 5 | 1. 6 | Input: "abc{}abc" 7 | Output: True 8 | 9 | 2. 10 | Input: "{}" 11 | Output: True 12 | 13 | 3. 14 | Input: "{{}asd" 15 | Output: False 16 | 17 | """ 18 | 19 | def para_checker(S): 20 | 21 | Stack = [] 22 | para = {'{':0, '}':0} 23 | 24 | for i in S: 25 | if i == '{' or i == '}': 26 | Stack.append(i) 27 | if i=='{': 28 | para['{'] += 1 29 | if i=='}': 30 | para['}'] += 1 31 | 32 | return sum(para.values()) % 2 == 0 and Stack[0] == "{" 33 | 34 | # A = 'abc{}abc' 35 | # print(para_checker(A)) 36 | 37 | import unittest 38 | 39 | class TestPara(unittest.TestCase): 40 | 41 | def test_check_positive(self): 42 | self.assertTrue(para_checker('abc{}abc')) 43 | self.assertTrue(para_checker('{}')) 44 | self.assertTrue(para_checker('{{asdasd}}')) 45 | 46 | def test_check_negative(self): 47 | self.assertFalse(para_checker('abc{}}')) 48 | self.assertFalse(para_checker('}{')) 49 | self.assertFalse(para_checker('}}{{')) 50 | 51 | if __name__ == '__main__': 52 | unittest.main(verbosity=2) 53 | 54 | 55 | -------------------------------------------------------------------------------- /Important/rotated_digits.py: -------------------------------------------------------------------------------- 1 | ''' 2 | X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone. 3 | 4 | A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid. 5 | 6 | Now given a positive number N, how many numbers X from 1 to N are good? 7 | 8 | Example: 9 | Input: 10 10 | Output: 4 11 | Explanation: 12 | There are four good numbers in the range [1, 10] : 2, 5, 6, 9. 13 | Note that 1 and 10 are not good numbers, since they remain unchanged after rotating. 14 | ''' 15 | 16 | class Solution(object): 17 | def rotatedDigits(self, N): 18 | """ 19 | :type N: int 20 | :rtype: int 21 | """ 22 | count = 0 23 | for i in range(1, N+1): 24 | s = str(i) 25 | if '3' in s or '4' in s or '7' in s: 26 | continue 27 | elif '2' in s or '5' in s or '6' in s or '9' in s: 28 | count = count + 1 29 | 30 | return count 31 | 32 | s = Solution() 33 | print(s.rotatedDigits(10)) -------------------------------------------------------------------------------- /LeetCode/3.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3. Longest Substring Without Repeating Characters 3 | 4 | Given a string s, find the length of the longest 5 | substring 6 | without repeating characters. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: s = "abcabcbb" 13 | Output: 3 14 | Explanation: The answer is "abc", with the length of 3. 15 | Example 2: 16 | 17 | Input: s = "bbbbb" 18 | Output: 1 19 | Explanation: The answer is "b", with the length of 1. 20 | Example 3: 21 | 22 | Input: s = "pwwkew" 23 | Output: 3 24 | Explanation: The answer is "wke", with the length of 3. 25 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 26 | 27 | """ 28 | 29 | class Solution: 30 | def lengthOfLongestSubstring(self, s: str) -> int: 31 | char_set = set() 32 | l = 0 33 | res = 0 34 | 35 | for r in range(len(s)): 36 | while s[r] in char_set: 37 | char_set.remove(s[l]) 38 | l += 1 39 | char_set.add(s[r]) 40 | res = max(res, r - l + 1) 41 | 42 | return res 43 | 44 | S = Solution() 45 | q1 = "abcabcbb" 46 | q2 = "bbbbb" 47 | q3 = "pwwkew" 48 | 49 | print(S.lengthOfLongestSubstring(q1)) 50 | print(S.lengthOfLongestSubstring(q2)) 51 | print(S.lengthOfLongestSubstring(q3)) -------------------------------------------------------------------------------- /LeetCode/largest_number_at_least_twice_of_others.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In a given integer array nums, there is always exactly one largest element. 3 | 4 | Find whether the largest element in the array is at least twice as much as every other number in the array. 5 | 6 | If it is, return the index of the largest element, otherwise return -1. 7 | 8 | Example 1: 9 | 10 | Input: nums = [3, 6, 1, 0] 11 | Output: 1 12 | Explanation: 6 is the largest integer, and for every other number in the array x, 13 | 6 is more than twice as big as x. The index of value 6 is 1, so we return 1. 14 | 15 | Example 2: 16 | 17 | Input: nums = [1, 2, 3, 4] 18 | Output: -1 19 | Explanation: 4 isn't at least as big as twice the value of 3, so we return -1. 20 | ''' 21 | 22 | class Solution(object): 23 | def dominantIndex(self, nums): 24 | """ 25 | :type nums: List[int] 26 | :rtype: int 27 | """ 28 | max1 = 0 29 | for n in nums: 30 | if n > max1: 31 | max1 = n 32 | max2 = 0 33 | for n in nums: 34 | if n > max2 and n != max1: 35 | max2 = n 36 | 37 | if max1 >= 2 * max2: 38 | return nums.index(max1) 39 | else: 40 | return -1 41 | 42 | s = Solution() 43 | print(s.dominantIndex([1,3,6,0])) -------------------------------------------------------------------------------- /LeetCode/541.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. 3 | If there are less than k characters left, reverse all of them. 4 | If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original. 5 | 6 | Ex: 7 | Input: s = "abcdefg", k = 2 8 | Output: "bacdfeg" 9 | 10 | """ 11 | 12 | 13 | class Solution(object): 14 | def reverseStr(self, s, k): 15 | """ 16 | :type s: str 17 | :type k: int 18 | :rtype: str 19 | """ 20 | if len(s) == 1: 21 | return s 22 | if len(s) == k: 23 | return s[::-1] 24 | if len(s) == k + 1: 25 | return s[::-1]+s[-1] 26 | else: 27 | i = 0 28 | result = '' 29 | while (i+k < len(s)): 30 | temp = '' 31 | for n in range(i, k): 32 | temp = temp + s[n] 33 | 34 | result = result + temp[::-1] 35 | i = i + k 36 | 37 | return result 38 | 39 | 40 | s = Solution() 41 | input_string = input("string to reverse: ") 42 | integer = int(input("enter the integer: ")) 43 | print(s.reverseStr(input_string, integer)) 44 | -------------------------------------------------------------------------------- /Company/hash_runners.py: -------------------------------------------------------------------------------- 1 | ''' 2 | [Problem] 3 | Numerous local and international recreational runners were eager to take part in this year’s Zagreb Marathon! 4 | It is an already traditional race 42 125 meters long. 5 | A curious statistical info is that this year every single contestant managed to complete the race, except one. 6 | Since marathons are all about taking part, 7 | help the organizers figure out, based on the list of registered contestants and ranking list, 8 | the identity of the contestant that did not complete the race. 9 | 10 | [INPUT] 11 | The first line of input contains the integer N (1 6 N 6 105), the number of contestants. 12 | Each of the following N lines contains the names of registered contestants. 13 | The additional N−1 lines contain the names of contestants in the order which they completed the race. 14 | The contestants’ names will consist of at least one and at most twenty lowercase letters of the English alphabet. 15 | The contestants’ names won’t necessarily be unique. 16 | 17 | [OUTPUT] 18 | The first and only line of output must contain the name of the contestant who didn’t finish the race. 19 | ''' 20 | 21 | import collections 22 | 23 | 24 | def solution(participant, completion): 25 | answer = collections.Counter(participant) - collections.Counter(completion) 26 | return list(answer.keys())[0] -------------------------------------------------------------------------------- /Important/AddDigitsTill-1.py: -------------------------------------------------------------------------------- 1 | # Given a non-negative integer num, repeatedly add 2 | # all its digits until the result has only one digit. 3 | # 4 | # For example: 5 | # 6 | # Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. 7 | # Since 2 has only one digit, return it. 8 | 9 | # Recursive 10 | def addNum(n): 11 | 12 | s = str(n) 13 | if len(s) == 1: 14 | return n 15 | else: 16 | res = 0 17 | for i in s: 18 | res = res + int(i) 19 | 20 | return addNum(res) 21 | 22 | # Non Recursive 23 | 24 | 25 | def addNum2(n): 26 | 27 | s = str(n) 28 | res = 0 29 | while (len(s) > 1): 30 | 31 | for i in s: 32 | res = res + int(i) 33 | 34 | s = str(res) 35 | res = 0 36 | 37 | return s 38 | 39 | # the same problem for multiplying digits 40 | 41 | 42 | def multiplyNums(n): 43 | 44 | s = str(n) 45 | res = 1 46 | count = 0 47 | while len(s) > 1: 48 | for i in s: 49 | res = res * int(i) 50 | 51 | count += 1 52 | s = str(res) 53 | res = 1 54 | 55 | return count 56 | 57 | 58 | num = input("enter a number to add all digits > ") 59 | num1 = input("enter a number to add all digits > ") 60 | 61 | print(addNum(num)) 62 | print(addNum2(num1)) 63 | print(multiplyNums(num)) 64 | -------------------------------------------------------------------------------- /Important/ArrayRotation.py: -------------------------------------------------------------------------------- 1 | # Rotate the array Left and Right 2 | 3 | # rotate the array to left i.e move along in <---- 4 | def rotateLeft(array, rotations): 5 | 6 | # if array==[] or rotations==0: 7 | # return array 8 | # 9 | # return array[rotations:]+array[:rotations] 10 | 11 | # returning the array if the no of rotations is a multiple of len(array) 12 | if rotations % len(array) == 0: 13 | return array 14 | 15 | r_array = [0]*len(array) 16 | 17 | for i, e in enumerate(array): 18 | ind = (i-rotations) % len(array) 19 | r_array[ind] = e 20 | 21 | return r_array 22 | 23 | 24 | # rotate the array to right i.e move along in ----> 25 | def rotateRight(array, rotations): 26 | 27 | # returning the array if the no of rotations is a multiple of len(array) 28 | if rotations % len(array) == 0: 29 | return array 30 | 31 | r_array = [0]*len(array) 32 | 33 | for i, e in enumerate(array): 34 | ind = (i+rotations) % len(array) 35 | r_array[ind] = e 36 | 37 | return r_array 38 | 39 | 40 | array = map(int, input( 41 | 'enter the values of the array with a space in between > ').strip().split(' ')) 42 | rotations = int(input('enter the no of rotations > ').strip()) 43 | print(rotateLeft(array, rotations)) 44 | print(rotateRight(array, rotations)) 45 | -------------------------------------------------------------------------------- /HackerRank/grading_students.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://www.hackerrank.com/challenges/grading/problem 3 | 4 | """ 5 | #!/bin/python 6 | 7 | from __future__ import print_function 8 | 9 | import os 10 | import sys 11 | 12 | # 13 | # Complete the gradingStudents function below. 14 | # 15 | 16 | 17 | def gradingStudents(grades): 18 | # 19 | # Write your code here. 20 | # 21 | final = [] 22 | for grade in grades: 23 | if grade < 38: 24 | final.append(grade) 25 | else: 26 | if (grade % 5 == 0) and grade > 38: 27 | final.append(grade) 28 | else: 29 | comp = helper(grade) 30 | diff = comp - grade 31 | result = grade + diff 32 | if diff < 3: 33 | final.append(result) 34 | if diff >= 3: 35 | final.append(grade) 36 | 37 | return final 38 | 39 | 40 | def helper(grade): 41 | devisor = grade / 5 42 | devisor = devisor + 1 43 | result = devisor * 5 44 | return result 45 | 46 | 47 | if __name__ == '__main__': 48 | 49 | n = int(input()) 50 | 51 | grades = [] 52 | 53 | for _ in range(n): 54 | grades_item = int(input()) 55 | grades.append(grades_item) 56 | 57 | result = gradingStudents(grades) 58 | print(result) 59 | -------------------------------------------------------------------------------- /LeetCode/28.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement strStr() 3 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 4 | 5 | Example 1: 6 | Input: haystack = "hello", needle = "ll" 7 | Output: 2 8 | 9 | Example 2: 10 | Input: haystack = "aaaaa", needle = "bba" 11 | Output: -1 12 | 13 | Clarification: 14 | What should we return when needle is an empty string? This is a great question to ask during an interview. 15 | For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). 16 | """ 17 | 18 | #Actual Solution 19 | class Solution: 20 | # using .index 21 | def strStr(self, haystack: str, needle: str) -> int: 22 | try: 23 | return haystack.index(needle) 24 | except: 25 | return -1 26 | # using array slicing 27 | def strStr2(self, haystack: str, needle: str) -> int: 28 | if needle not in haystack: 29 | return -1 30 | else: 31 | nl = len(needle) 32 | hl = len(haystack) 33 | for i in range(hl - nl+1): 34 | if haystack[i: i+nl] == needle: 35 | return i 36 | #Demo 37 | s = Solution() 38 | 39 | #Read in two listnodes 40 | haystack = input() 41 | needle = input() 42 | print(s.strStr(haystack,needle)) 43 | -------------------------------------------------------------------------------- /LeetCode/58.py: -------------------------------------------------------------------------------- 1 | """ 2 | 58. Length of Last Word 3 | Solved 4 | Easy 5 | Topics 6 | Companies 7 | Given a string s consisting of words and spaces, return the length of the last word in the string. 8 | 9 | A word is a maximal 10 | substring 11 | consisting of non-space characters only. 12 | 13 | 14 | 15 | Example 1: 16 | 17 | Input: s = "Hello World" 18 | Output: 5 19 | Explanation: The last word is "World" with length 5. 20 | Example 2: 21 | 22 | Input: s = " fly me to the moon " 23 | Output: 4 24 | Explanation: The last word is "moon" with length 4. 25 | Example 3: 26 | 27 | Input: s = "luffy is still joyboy" 28 | Output: 6 29 | Explanation: The last word is "joyboy" with length 6. 30 | 31 | 32 | Constraints: 33 | 34 | 1 <= s.length <= 104 35 | s consists of only English letters and spaces ' '. 36 | There will be at least one word in s. 37 | """ 38 | 39 | class Solution: 40 | def lengthOfLastWord(self, s: str) -> int: 41 | sp = s.split(" ") 42 | # we need the last word so reverse the list 43 | for i in sp[::-1]: 44 | if i != "": 45 | return len(i) 46 | 47 | S = Solution() 48 | 49 | s1 = "Hello World" 50 | s2 = " fly me to the moon " 51 | s3 = "luffy is still joyboy" 52 | print(S.lengthOfLastWord(s1)) 53 | print(S.lengthOfLastWord(s2)) 54 | print(S.lengthOfLastWord(s3)) 55 | -------------------------------------------------------------------------------- /LeetCode/11.py: -------------------------------------------------------------------------------- 1 | """ 2 | 11. Container With Most Water 3 | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). 4 | 5 | Find two lines that together with the x-axis form a container, such that the container contains the most water. 6 | 7 | Return the maximum amount of water a container can store. 8 | 9 | Notice that you may not slant the container. 10 | 11 | Example 1: 12 | Input: height = [1,8,6,2,5,4,8,3,7] 13 | Output: 49 14 | Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 15 | 16 | Example 2: 17 | 18 | Input: height = [1,1] 19 | Output: 1 20 | """ 21 | from typing import List 22 | 23 | def maxArea(height: List[int]) -> int: 24 | if len(height) < 1: 25 | return 0 26 | l,r = 0, len(height) - 1 27 | max_area = 0 28 | 29 | while l < r: 30 | area = (r - l) * min(height[l], height[r]) 31 | max_area = max(area, max_area) 32 | 33 | if height[l] < height[r]: 34 | l += 1 35 | else: 36 | r -= 1 37 | 38 | return max_area 39 | 40 | q1 = [1,8,6,2,5,4,8,3,7] 41 | q2 = [1,1] 42 | q3 = [] 43 | print(maxArea(height=q1)) 44 | print(maxArea(height=q2)) 45 | print(maxArea(height=q3)) -------------------------------------------------------------------------------- /Important/pattern.py: -------------------------------------------------------------------------------- 1 | # given input: 3[d2[ca]] 2 | # output: dcacadcacadcaca 3 | 4 | # 3[d[caca]] d2[ca]d2[ca]d2[ca] 5 | # dcacadcacadcaca 6 | 7 | # stack 1 = [ 3, 2 ] 8 | # stack 2 = [ '[', 'd', '[', 'c', 'a' ] 9 | 10 | # import a predefined stack or create our own stack in here 11 | from ImplementStack import Stack 12 | 13 | def pattern_solve(inp): 14 | word_stack = Stack() 15 | num_stack = Stack() 16 | 17 | for char in inp: 18 | if (char != ']'): 19 | if(char.isalpha()): 20 | # print('alpha: {0}'.format(char)) 21 | word_stack.push(char) 22 | else: 23 | if(char.isdigit()): 24 | # print('number: {0}'.format(char)) 25 | num_stack.push(char) 26 | else: 27 | # print('not a num: {0}'.format(char)) 28 | word_stack.push(char) 29 | 30 | 31 | word_till_now = '' 32 | while(word_stack.isEmpty() == False): 33 | word = word_stack.pop() 34 | 35 | if(word != '['): 36 | word_till_now = word + word_till_now 37 | 38 | if(word == '['): 39 | num = num_stack.pop() 40 | 41 | word_till_now = word_till_now * int(num) 42 | 43 | 44 | return word_till_now 45 | # print(pattern_solve('3[d2[ca]]')) 46 | print(pattern_solve('5[d2[ca]]')) 47 | -------------------------------------------------------------------------------- /LeetCode/104.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root of a binary tree, return its maximum depth. 3 | 4 | A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 5 | 6 | Example 1: 7 | Input: root = [3,9,20,null,null,15,7] 8 | Output: 3 9 | 10 | Example 2: 11 | Input: root = [1,null,2] 12 | Output: 2 13 | """ 14 | from typing import Optional 15 | 16 | class TreeNode: 17 | def __init__(self, val=0, left=None, right=None): 18 | self.val = val 19 | self.left = left 20 | self.right = right 21 | 22 | class Solution: 23 | def max_depth(self, root: Optional(TreeNode)) -> int: 24 | # creating a stack with the root and the initial level depth 25 | stack = [[root, 1]] 26 | result = 0 27 | 28 | # while the stack exists 29 | while stack: 30 | # start popping the stack 31 | node, depth = stack.pop() 32 | 33 | if node: 34 | res = max(res, depth) 35 | # increasing the depth if we know node exists 36 | stack.append([node.left, depth + 1]) 37 | stack.append([node.right, depth + 1]) 38 | 39 | return result 40 | 41 | q1 = [3,9,20,None,None,15,7] 42 | s = Solution() 43 | node = TreeNode() 44 | node.val = 3 45 | node.left = 9 46 | node.right = 20 47 | 48 | -------------------------------------------------------------------------------- /DailyCoding/1601.py: -------------------------------------------------------------------------------- 1 | """ 2 | This question was asked by Apple. 3 | 4 | Given a binary tree, find a minimum path sum from root to a leaf. 5 | 6 | For example, the minimum path in this tree is [10, 5, 1, -1], which has sum 15. 7 | 8 | 10 9 | / \ 10 | 5 5 11 | \ \ 12 | 2 1 13 | / 14 | -1 15 | """ 16 | class TreeNode: 17 | def __init__(self, val): 18 | self.val = val 19 | self.left = None 20 | self.right = None 21 | 22 | def min_path_sum(root): 23 | def dfs(node, current_sum): 24 | nonlocal min_sum 25 | if not node: 26 | return 27 | 28 | current_sum += node.val 29 | 30 | if not node.left and not node.right: # If it's a leaf node 31 | min_sum = min(min_sum, current_sum) 32 | 33 | dfs(node.left, current_sum) 34 | dfs(node.right, current_sum) 35 | 36 | min_sum = float('inf') # Initialize with positive infinity 37 | dfs(root, 0) 38 | 39 | return min_sum if min_sum != float('inf') else 0 # Return 0 for an empty tree 40 | 41 | # Example usage: 42 | # Constructing the given tree 43 | root = TreeNode(10) 44 | root.left = TreeNode(5) 45 | root.right = TreeNode(5) 46 | root.left.right = TreeNode(2) 47 | root.right.right = TreeNode(1) 48 | root.right.right.left = TreeNode(-1) 49 | 50 | result = min_path_sum(root) 51 | print("Minimum path sum:", result) 52 | -------------------------------------------------------------------------------- /Important/Palindrome.py: -------------------------------------------------------------------------------- 1 | 2 | import unittest 3 | from Implementing_Dequeue import Dequeue 4 | 5 | 6 | def Palindrome(string): 7 | 8 | if string == '': 9 | return False 10 | 11 | if len(string) == 1: 12 | return True 13 | 14 | return string.lower() == string[::-1].lower() 15 | 16 | 17 | def Palindrome1(string): 18 | 19 | charDequeue = Dequeue() 20 | 21 | for ch in string: 22 | charDequeue.addFront(ch) 23 | 24 | stillEqual = True 25 | 26 | while charDequeue.size() > 1 and stillEqual: 27 | first = charDequeue.removeFront() 28 | last = charDequeue.removeRear() 29 | 30 | if first != last: 31 | stillEqual = False 32 | 33 | return stillEqual 34 | 35 | # print Palindrome1(input("Is this a Palindrome? : ")) 36 | 37 | 38 | class test_Palindrome(unittest.TestCase): 39 | 40 | def testPalindrome(self): 41 | self.assertEqual(Palindrome("radar"), True) 42 | 43 | def testPalindrome1(self): 44 | self.assertEqual(Palindrome1("radar"), True) 45 | 46 | 47 | if __name__ == '__main__': 48 | import timeit 49 | print(timeit.timeit("Palindrome('12321')", 50 | setup="from __main__ import Palindrome")) 51 | print(timeit.timeit("Palindrome1('radar')", 52 | setup="from __main__ import Palindrome1")) 53 | unittest.main(verbosity=2) 54 | -------------------------------------------------------------------------------- /GeeksforGeeks/reverse_string_with_special_char.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Reverse an array without affecting special characters 6 | Given a string, that contains special character together with alphabets (‘a’ to ‘z’ and ‘A’ to ‘Z’), reverse the string in a way that special characters are not affected. 7 | 8 | Examples: 9 | 10 | Input: str = "a,b$c" 11 | Output: str = "c,b$a" 12 | Note that $ and , are not moved anywhere. 13 | Only subsequence "abc" is reversed 14 | 15 | Input: str = "Ab,c,de!$" 16 | Output: str = "ed,c,bA!$" 17 | 18 | """ 19 | 20 | def reverse(s): 21 | # convert string to array 22 | s = list(s) 23 | # left index 24 | l = 0 25 | # right index 26 | r = len(s) - 1 27 | 28 | while l < r: 29 | if not isAlphabet(s[l]): 30 | l += 1 31 | elif not isAlphabet(s[r]): 32 | r -= 1 33 | else: 34 | s[l], s[r] = s[r], s[l] 35 | l += 1 36 | r -= 1 37 | 38 | return ''.join(s) 39 | 40 | # helper func 41 | def isAlphabet(x): 42 | return x.isalpha() 43 | 44 | # A = 'abc,$d' 45 | # print(reverse(A)) 46 | 47 | import unittest 48 | 49 | class Test(unittest.TestCase): 50 | def test_assert_true(self): 51 | self.assertEqual("i!!!h.g.f,e'd,cba", reverse("a!!!b.c.d,e'f,ghi") ) 52 | 53 | if __name__ == '__main__': 54 | unittest.main() -------------------------------------------------------------------------------- /GeeksforGeeks/smallest_subarray_with_greater_value.py: -------------------------------------------------------------------------------- 1 | """ 2 | Smallest subarray with sum greater than a given value 3 | Given an array of integers and a number x, 4 | find the smallest subarray with sum greater than the given value. 5 | 6 | 7 | Examples: 8 | arr[] = {1, 4, 45, 6, 0, 19} 9 | x = 51 10 | Output: 3 11 | Minimum length subarray is {4, 45, 6} 12 | 13 | arr[] = {1, 10, 5, 2, 7} 14 | x = 9 15 | Output: 1 16 | Minimum length subarray is {10} 17 | 18 | arr[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250} 19 | x = 280 20 | Output: 4 21 | Minimum length subarray is {100, 1, 0, 200} 22 | 23 | arr[] = {1, 2, 4} 24 | x = 8 25 | Output : Not Possible 26 | Whole array sum is smaller than 8. 27 | """ 28 | 29 | 30 | # arr -> provided array 31 | # n -> length of array 32 | # x -> provided integer 33 | def small_sub(arr, n, x): 34 | 35 | start = 0 36 | end = 0 37 | cur_sum = 0 38 | min_len = n + 1 39 | 40 | while (end < n): 41 | 42 | while (cur_sum <= x and end < n): 43 | cur_sum += arr[end] 44 | end += 1 45 | 46 | while (cur_sum > x and start < n): 47 | if (end - start < min_len): 48 | min_len = end - start 49 | 50 | cur_sum -= arr[start] 51 | start += 1 52 | 53 | return min_len 54 | 55 | 56 | arr = [1, 1, 1, 1, 2, 1,3] 57 | n = len(arr) 58 | x = 4 59 | print(small_sub(arr, n , x)) -------------------------------------------------------------------------------- /LeetCode/binary_tree_right_side_view.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 199. Binary Tree Right Side View 3 | Medium 4 | 5 | 1349 6 | 7 | 73 8 | 9 | Favorite 10 | 11 | Share 12 | Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. 13 | 14 | Example: 15 | 16 | Input: [1,2,3,null,5,null,4] 17 | Output: [1, 3, 4] 18 | Explanation: 19 | 20 | 1 <--- 21 | / \ 22 | 2 3 <--- 23 | \ \ 24 | 5 4 <--- 25 | 26 | ''' 27 | 28 | # Definition for a binary tree node. 29 | # class TreeNode(object): 30 | # def __init__(self, x): 31 | # self.val = x 32 | # self.left = None 33 | # self.right = None 34 | 35 | class Solution(object): 36 | 37 | def helper(self, root, level, max_level): 38 | 39 | if root is None: 40 | return 41 | 42 | if(max_level[0] < level): 43 | self.ans.append(root.val) 44 | max_level[0] = level 45 | 46 | self.helper(root.right, level+1, max_level) 47 | self.helper(root.left, level+1, max_level) 48 | 49 | def rightSideView(self, root): 50 | """ 51 | :type root: TreeNode 52 | :rtype: List[int] 53 | """ 54 | max_level = [0] 55 | self.ans = [] 56 | self.helper(root, 1, max_level) 57 | 58 | return(self.ans) -------------------------------------------------------------------------------- /LeetCode/self_dividing_numbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | A self-dividing number is a number that is divisible by every digit it contains. 3 | 4 | For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. 5 | 6 | Also, a self-dividing number is not allowed to contain the digit zero. 7 | 8 | Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. 9 | 10 | Example 1: 11 | Input: 12 | left = 1, right = 22 13 | Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] 14 | 15 | """ 16 | 17 | class Solution(object): 18 | def selfDividingNumbers(self, left, right): 19 | """ 20 | :type left: int 21 | :type right: int 22 | :rtype: List[int] 23 | """ 24 | 25 | result = [] 26 | for i in range(left, right+1): 27 | if i < 10: 28 | result.append(i) 29 | else: 30 | flag = True 31 | num = i 32 | while num > 0: 33 | rem = num % 10 34 | if not rem or i % rem: 35 | flag = False 36 | break 37 | num = num / 10 38 | if flag: 39 | result.append(i) 40 | 41 | return result 42 | 43 | s = Solution() 44 | print(s.selfDividingNumbers(1,22)) 45 | 46 | 47 | -------------------------------------------------------------------------------- /Exercism/armstrong-numbers/README.md: -------------------------------------------------------------------------------- 1 | # Armstrong Numbers 2 | 3 | An [Armstrong number](https://en.wikipedia.org/wiki/Narcissistic_number) is a number that is the sum of its own digits each raised to the power of the number of digits. 4 | 5 | For example: 6 | 7 | - 9 is an Armstrong number, because `9 = 9^1 = 9` 8 | - 10 is *not* an Armstrong number, because `10 != 1^2 + 0^2 = 2` 9 | - 153 is an Armstrong number, because: `153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153` 10 | - 154 is *not* an Armstrong number, because: `154 != 1^3 + 5^3 + 4^3 = 1 + 125 + 64 = 190` 11 | 12 | Write some code to determine whether a number is an Armstrong number. 13 | 14 | ## Submitting Exercises 15 | 16 | Note that, when trying to submit an exercise, make sure the solution is in the `exercism/python/` directory. 17 | 18 | For example, if you're submitting `bob.py` for the Bob exercise, the submit command would be something like `exercism submit /python/bob/bob.py`. 19 | 20 | For more detailed information about running tests, code style and linting, 21 | please see the [help page](http://exercism.io/languages/python). 22 | 23 | ## Source 24 | 25 | Wikipedia [https://en.wikipedia.org/wiki/Narcissistic_number](https://en.wikipedia.org/wiki/Narcissistic_number) 26 | 27 | ## Submitting Incomplete Solutions 28 | It's possible to submit an incomplete solution so you can see how others have completed the exercise. 29 | -------------------------------------------------------------------------------- /LeetCode/21.py: -------------------------------------------------------------------------------- 1 | """ 2 | Merge Two Sorted Lists 3 | Merge two sorted linked lists and return it as a new list. 4 | The new list should be made by splicing together the nodes of the first two lists. 5 | 6 | Example: 7 | Input: 1->2->4, 1->3->4 8 | Output: 1->1->2->3->4->4 9 | """ 10 | 11 | 12 | # Definition for singly-linked list. 13 | class ListNode: 14 | def __init__(self, x): 15 | self.val = x 16 | self.next = None 17 | 18 | #Actual Solution 19 | class Solution: 20 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 21 | if not l2: 22 | return l1 23 | elif not l1: 24 | return l2 25 | elif l1.val >= l2.val: 26 | l = ListNode(l2.val) 27 | l.next = self.mergeTwoLists(l1,l2.next) 28 | return l 29 | else: 30 | l = ListNode(l1.val) 31 | l.next = self.mergeTwoLists(l1.next,l2) 32 | return l 33 | #Demo 34 | s = Solution() 35 | 36 | #Read in two listnodes 37 | l1 = ListNode(0) 38 | temp = l1 39 | for i in input().split(" "): 40 | temp.next = ListNode(int(i)) 41 | temp = temp.next 42 | l1 = l1.next 43 | 44 | l2 = ListNode(0) 45 | temp = l2 46 | for i in input().split(" "): 47 | temp.next = ListNode(int(i)) 48 | temp = temp.next 49 | l2 = l2.next 50 | 51 | l3 = s.mergeTwoLists(l1,l2) 52 | while l3.val is not None: 53 | print(l3.val) 54 | l3 = l3.next 55 | -------------------------------------------------------------------------------- /Important/doorMat.py: -------------------------------------------------------------------------------- 1 | # Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications: 2 | 3 | # Mat size must be X. ( is an odd natural number, and is times .) 4 | # The design should have 'WELCOME' written in the center. 5 | # The design pattern should only use |, . and - characters. 6 | # Input Format 7 | 8 | # A single line containing the space separated values of and . 9 | 10 | # Constraints 11 | 12 | 13 | # Output Format 14 | 15 | # Output the design pattern. 16 | 17 | # Sample Input 18 | 19 | # 9 27 20 | # Sample Output 21 | 22 | # ------------.|.------------ 23 | # ---------.|..|..|.--------- 24 | # ------.|..|..|..|..|.------ 25 | # ---.|..|..|..|..|..|..|.--- 26 | # ----------WELCOME---------- 27 | # ---.|..|..|..|..|..|..|.--- 28 | # ------.|..|..|..|..|.------ 29 | # ---------.|..|..|.--------- 30 | # ------------.|.------------ 31 | 32 | try: 33 | # More than 6 lines of code will result in 0 score. Blank lines are not counted. 34 | N = int(input("Enter the No of rows you need in your Mat: \n").strip()) 35 | except: 36 | print("Did not enter a number for the number of rows") 37 | # no of coulmns calculated using N 38 | M = N*3 39 | for i in range(1, N, 2): 40 | print("{:-^{fill}}".format(".|." * i, fill=M)) 41 | print("{:-^{fill}}".format("WELCOME", fill=M)) 42 | for i in range(N-2, -1, -2): 43 | print("{:-^{fill}}".format(".|."*i, fill=M)) 44 | -------------------------------------------------------------------------------- /Important/LinkedList_Unordered.py: -------------------------------------------------------------------------------- 1 | from LinkedList_Node import Node 2 | 3 | class UnorderedList: 4 | 5 | def __init__(self): 6 | self.head = None 7 | 8 | def isEmpty(self): 9 | return self.head == None 10 | 11 | def add(self, item): 12 | temp = Node(item) 13 | temp.setNext(self.head) 14 | self.head = temp 15 | 16 | def size(self): 17 | current = self.head 18 | count = 0 19 | while current != None: 20 | count = count + 1 21 | current = current.getNext() 22 | 23 | return count 24 | 25 | def search(self, item): 26 | current = self.head 27 | found = False 28 | while current != None and not found: 29 | if current.getData() == item: 30 | found = True 31 | else: 32 | current = current.getNext() 33 | 34 | return found 35 | 36 | def remove(self, item): 37 | current = self.head 38 | previous = None 39 | found = False 40 | while not found: 41 | if current.getData() == item: 42 | found = True 43 | else: 44 | previous = current 45 | current = current.getNext() 46 | 47 | if previous == None: 48 | self.head = current.getNext() 49 | else: 50 | previous.setNext(current.getNext()) 51 | -------------------------------------------------------------------------------- /LeetCode/7.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a 32-bit signed integer, reverse digits of an integer. 3 | 4 | Example 1: 5 | 6 | Input: 123 7 | Output: 321 8 | Example 2: 9 | 10 | Input: -123 11 | Output: -321 12 | Example 3: 13 | 14 | Input: 120 15 | Output: 21 16 | """ 17 | 18 | 19 | class Solution(object): 20 | def matchChar(self, sc, pc): 21 | return sc == pc or pc == '.' 22 | 23 | def isEndOfStar(self, p): 24 | while p != '': 25 | if len(p) == 1 or len(p) > 1 and p[1] != '*': 26 | return False 27 | p = p[2:] 28 | return True 29 | 30 | def isMatch(self, s, p): 31 | if p == '': 32 | return s == '' 33 | 34 | if s == '': 35 | return self.isEndOfStar(p) 36 | 37 | if (len(p) > 1 and p[1] != '*') or len(p) == 1: 38 | # without * 39 | if not self.matchChar(s[0], p[0]): 40 | return False 41 | else: 42 | return self.isMatch(s[1:], p[1:]) 43 | 44 | else: 45 | # with * 46 | # try see x* is empty 47 | if self.isMatch(s[0:], p[2:]): 48 | return True 49 | 50 | while self.matchChar(s[0], p[0]): 51 | s = s[1:] 52 | 53 | if self.isMatch(s, p[2:]): 54 | return True 55 | 56 | if s == '': 57 | return self.isEndOfStar(p) 58 | return False 59 | -------------------------------------------------------------------------------- /GeeksforGeeks/1_N_queens.py: -------------------------------------------------------------------------------- 1 | # https://www.geeksforgeeks.org/n-queen-in-on-space/ 2 | 3 | # print the solutions for the queen to travel on chess board 4 | # also print the steps by count on the board 5 | # Contribution made by "gitkp" 6 | 7 | 8 | 9 | n = 8 10 | 11 | def issafe(n, x, y, sol): 12 | if (x >= 0 and x < n and y >= 0 and y < n and sol[x][y] == -1): 13 | return True 14 | return False 15 | 16 | def printsol(sol, n): 17 | for i in range(n): 18 | for j in range(n): 19 | print(sol[i][j], end=' ') 20 | print() 21 | 22 | def move1(n, x, y, steps, x_move, y_move, sol): 23 | if (steps == n * n): 24 | return True 25 | 26 | for i in range(n): 27 | nxtx = x + x_move[i] 28 | nxty = y + y_move[i] 29 | 30 | if (issafe(n, nxtx, nxty, sol)): 31 | sol[nxtx][nxty]= steps 32 | if (move1(n, nxtx, nxty, steps+1, x_move, y_move, sol)): 33 | return True 34 | 35 | sol[nxtx][nxty] = -1 36 | 37 | return False 38 | 39 | def solve(n): 40 | sol = [[-1 for _ in range(n)] for _ in range(n)] 41 | 42 | x_move = [1,2,2,1,-1,-2,-2,-1] 43 | y_move = [2,1,-1,-2,-2,-1,1,2] 44 | 45 | sol[0][0] = 0 46 | 47 | steps = 1 48 | if (not move1(n, 0, 0, steps, x_move, y_move, sol)): 49 | print("No solution") 50 | else: 51 | printsol(sol, n) 52 | 53 | if __name__ == "__main__": 54 | solve(n) 55 | 56 | -------------------------------------------------------------------------------- /Important/MergeSort.py: -------------------------------------------------------------------------------- 1 | # Merge sort is a recursive algorithm that continually splits a list in half. If the list is empty or has one item, 2 | # it is sorted by definition (the base case). If the list has more than one item, we split the list and recursively invoke 3 | # a merge sort on both halves. Once the two halves are sorted, the fundamental operation, called a merge, is performed. 4 | # Merging is the process of taking two smaller sorted lists and combining them together into a single, sorted, new list. 5 | 6 | def mergeSort(alist): 7 | print("Splitting ",alist) 8 | if len(alist)>1: 9 | mid = len(alist)//2 10 | lefthalf = alist[:mid] 11 | righthalf = alist[mid:] 12 | 13 | mergeSort(lefthalf) 14 | mergeSort(righthalf) 15 | 16 | i=0 17 | j=0 18 | k=0 19 | while i < len(lefthalf) and j < len(righthalf): 20 | if lefthalf[i] <= righthalf[j]: 21 | alist[k]=lefthalf[i] 22 | i=i+1 23 | else: 24 | alist[k]=righthalf[j] 25 | j=j+1 26 | k=k+1 27 | 28 | while i < len(lefthalf): 29 | alist[k]=lefthalf[i] 30 | i=i+1 31 | k=k+1 32 | 33 | while j < len(righthalf): 34 | alist[k]=righthalf[j] 35 | j=j+1 36 | k=k+1 37 | print("Merging ",alist) 38 | 39 | alist = [9,1,7,4,6] 40 | mergeSort(alist) 41 | print(alist) 42 | -------------------------------------------------------------------------------- /test/test_MergeSort.py: -------------------------------------------------------------------------------- 1 | # Merge sort is a recursive algorithm that continually splits a list in half. If the list is empty or has one item, 2 | # it is sorted by definition (the base case). If the list has more than one item, we split the list and recursively invoke 3 | # a merge sort on both halves. Once the two halves are sorted, the fundamental operation, called a merge, is performed. 4 | # Merging is the process of taking two smaller sorted lists and combining them together into a single, sorted, new list. 5 | 6 | def mergeSort(alist): 7 | print("Splitting ",alist) 8 | if len(alist)>1: 9 | mid = len(alist)//2 10 | lefthalf = alist[:mid] 11 | righthalf = alist[mid:] 12 | 13 | mergeSort(lefthalf) 14 | mergeSort(righthalf) 15 | 16 | i=0 17 | j=0 18 | k=0 19 | while i < len(lefthalf) and j < len(righthalf): 20 | if lefthalf[i] <= righthalf[j]: 21 | alist[k]=lefthalf[i] 22 | i=i+1 23 | else: 24 | alist[k]=righthalf[j] 25 | j=j+1 26 | k=k+1 27 | 28 | while i < len(lefthalf): 29 | alist[k]=lefthalf[i] 30 | i=i+1 31 | k=k+1 32 | 33 | while j < len(righthalf): 34 | alist[k]=righthalf[j] 35 | j=j+1 36 | k=k+1 37 | print("Merging ",alist) 38 | 39 | alist = [9,1,7,4,6] 40 | mergeSort(alist) 41 | print(alist) 42 | -------------------------------------------------------------------------------- /Company/dups_in_json.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a records 4 | records = [ 5 | { 6 | "metric": "count", 7 | "elephants": 8, 8 | },{ 9 | "name": "Mr Jones", 10 | "combomeal": 4, 11 | },{ 12 | "name": "Mr Jones", 13 | "combomeal": 4, 14 | },{ 15 | "name": "Mr Smith", 16 | "combomeal": 54, 17 | }] 18 | 19 | write a function to return the len of the records and no of duplicate objects => (4,1) 20 | 21 | Use cmp function for dictonoaries 22 | 23 | """ 24 | 25 | 26 | def find_duplicate(records): 27 | 28 | count = len(records) 29 | 30 | # duplicate = set([records.count(obj) for obj in records]) // old implementation 31 | duplicate = [cmp(vx, vy) for ix, vx in enumerate(records) 32 | for iy, vy in enumerate(records) if ix != iy and ix < iy] 33 | # OLD implementation 34 | # print duplicate.count(0) // 0 if objects are equal 35 | 36 | # dup_count = 0 37 | # for val in duplicate: 38 | # if val == 0: 39 | # dup_count += 1 40 | 41 | # return count, dup_count 42 | return count, duplicate.count(0) 43 | 44 | 45 | records = [ 46 | { 47 | "metric": "count", 48 | "elephants": 8, 49 | }, { 50 | "name": "Mr Jones", 51 | "combomeal": 4, 52 | }, { 53 | "name": "Mr Jones", 54 | "combomeal": 4, 55 | }, { 56 | "name": "Mr Smith", 57 | "combomeal": 54, 58 | }] 59 | 60 | print(find_duplicate(records)) 61 | -------------------------------------------------------------------------------- /GeeksforGeeks/longest_palindromic_substr.py: -------------------------------------------------------------------------------- 1 | '''Given a string S 2 | find the longest palindromic substring in S. 3 | Substring of string S: S[i....j] 4 | where 0 ≤ i ≤ j < len(S). 5 | Palindrome string: A string which reads the same backwards. 6 | More formally, S is palindrome if reverse(S) = S. 7 | Incase of conflict, return the substring which occurs first 8 | ( with the least starting index ). 9 | 10 | Required Time Complexity O(n2). ''' 11 | 12 | # function to find longest palindromic substring 13 | # dynamic approach 14 | 15 | 16 | def find_longst_pal_substr(string): 17 | maxLen = 1 18 | l = len(string) 19 | 20 | low = high = start = 0 21 | for i in range(1, l): 22 | low = i - 1 23 | high = i 24 | while low >= 0 and high < l and string[low] == string[high]: 25 | if high - low + 1 > maxLen: 26 | start = low 27 | maxLen = high - low + 1 28 | low -= 1 29 | high += 1 30 | low = i - 1 31 | high = i + 1 32 | while low >= 0 and high < l and string[low] == string[high]: 33 | if high - low + 1 > maxLen: 34 | start = low 35 | maxLen = high - low + 1 36 | low -= 1 37 | high += 1 38 | return string[start:start + maxLen] 39 | 40 | 41 | '''for _ in range(int(input())): 42 | s = input() 43 | print(find_longst_pal_substr(s)) ''' 44 | 45 | s = 'aaaabbaa' 46 | print(find_longst_pal_substr(s)) 47 | -------------------------------------------------------------------------------- /LeetCode/14.py: -------------------------------------------------------------------------------- 1 | """ 2 | Longest Common Prefix 3 | 4 | Write a function to find the longest common prefix string amongst an array of strings. 5 | 6 | If there is no common prefix, return an empty string "". 7 | 8 | Example 1: 9 | 10 | Input: ["flower","flow","flight"] 11 | Output: "fl" 12 | Example 2: 13 | 14 | Input: ["dog","racecar","car"] 15 | Output: "" 16 | Explanation: There is no common prefix among the input strings. 17 | 18 | """ 19 | 20 | 21 | class Solution(object): 22 | def longestCommonPrefix(self, strs): 23 | """ 24 | :type strs: List[str] 25 | :rtype: str 26 | """ 27 | prefix = '' 28 | i = 0 29 | while True: 30 | try: 31 | tmp = strs[0][i] 32 | for item in strs: 33 | if item[i] != tmp: 34 | return prefix 35 | except: 36 | return prefix 37 | prefix += tmp 38 | i += 1 39 | return prefix 40 | 41 | def longestCommonPrefix_use_zip(self, strs): 42 | """ 43 | :type strs: List[str] 44 | :rtype: str 45 | """ 46 | prefix = '' 47 | for _, item in enumerate(zip(*strs)): 48 | if len(set(item)) > 1: 49 | return prefix 50 | else: 51 | prefix += item[0] 52 | return prefix 53 | 54 | 55 | a = Solution().longestCommonPrefix_use_zip(["flower", "flow", "flight"]) 56 | print(a) 57 | -------------------------------------------------------------------------------- /LeetCode/122.py: -------------------------------------------------------------------------------- 1 | """ 2 | 122. Best Time to Buy and Sell Stock II 3 | 4 | You are given an integer array prices where prices[i] is the price of a given stock on the ith day. 5 | On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. 6 | Find and return the maximum profit you can achieve. 7 | 8 | Example 1: 9 | 10 | Input: prices = [7,1,5,3,6,4] 11 | Output: 7 12 | Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. 13 | Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. 14 | Total profit is 4 + 3 = 7. 15 | Example 2: 16 | 17 | Input: prices = [1,2,3,4,5] 18 | Output: 4 19 | Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. 20 | Total profit is 4. 21 | Example 3: 22 | 23 | Input: prices = [7,6,4,3,1] 24 | Output: 0 25 | Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. 26 | """ 27 | from typing import List 28 | 29 | def maxProfit(prices: List[int]) -> int: 30 | 31 | max_profit = 0 32 | for i in range(1, len(prices)): 33 | if prices[i] > prices[i-1]: 34 | max_profit += prices[i] - prices[i-1] 35 | 36 | return max_profit 37 | 38 | q1 = [7,1,5,3,6,4] 39 | q2 = [1,2,3,4,5] 40 | q3 = [7,6,4,3,1] 41 | print(maxProfit(q1)) 42 | print(maxProfit(q2)) 43 | print(maxProfit(q3)) 44 | -------------------------------------------------------------------------------- /Important/decorator_example2.py: -------------------------------------------------------------------------------- 1 | # decorator as a function 2 | # decorator to add functionality to func along with uneven arguments 3 | def decorator_function(original_function): 4 | def wrapper(*args, **kwargs): # adding *args **kwargs makes it take any no of arguments 5 | print("\nexecuting inside of Decorator Function: {}".format( 6 | original_function.__name__)) 7 | return original_function(*args, **kwargs) 8 | return wrapper 9 | 10 | 11 | @decorator_function 12 | def display(): 13 | print("Running this inside of a decorator") 14 | 15 | 16 | @decorator_function 17 | def display_info(name, age): 18 | print("Display_info ran with {} and {}".format(name, age)) 19 | 20 | 21 | display() 22 | display_info('John', 32) 23 | 24 | 25 | # decorator as a class 26 | # class decorator adds functionality to a func 27 | class Decorator_class(object): 28 | 29 | def __init__(self, original_function): 30 | self.original_function = original_function 31 | 32 | def __call__(self, *args, **kwargs): 33 | print("\nexecuting inside of Decorator Class: {}".format( 34 | self.original_function.__name__)) 35 | return self.original_function(*args, **kwargs) 36 | 37 | 38 | @Decorator_class 39 | def display(): 40 | print("Running this inside of a decorator") 41 | 42 | 43 | @Decorator_class 44 | def display_info(name, age): 45 | print("Display_info ran with {} and {}".format(name, age)) 46 | 47 | 48 | display() 49 | display_info('John', 32) 50 | -------------------------------------------------------------------------------- /Important/birthday_candles.py: -------------------------------------------------------------------------------- 1 | # Colleen is turning years old! She has candles of various heights on her cake, and candle has height . Because the taller candles tower over the shorter ones, Colleen can only blow out the tallest candles. 2 | 3 | # Given the for each individual candle, find and print the number of candles she can successfully blow out. 4 | 5 | # Input Format 6 | 7 | # The first line contains a single integer, , denoting the number of candles on the cake. 8 | # The second line contains space-separated integers, where each integer describes the height of candle . 9 | 10 | # Constraints 11 | 12 | # Output Format 13 | 14 | # Print the number of candles Colleen blows out on a new line. 15 | 16 | # Sample Input 0 17 | 18 | # 4 19 | # 3 2 1 3 20 | # Sample Output 0 21 | 22 | # 2 23 | # Explanation 0 24 | 25 | # We have one candle of height , one candle of height , and two candles of height . Colleen only blows out the tallest candles, meaning the candles where . Because there are such candles, we print on a new line. 26 | 27 | n = int(input().strip()) 28 | height = map(int, input().strip().split(' ')) 29 | 30 | 31 | def returnValue(arr): 32 | 33 | if len(arr) == 1: 34 | print ("1") 35 | else: 36 | d = {} 37 | for x in arr: 38 | if x in d: 39 | d[x] += 1 40 | else: 41 | d[x] = 1 42 | k_Array = sorted(d.keys()) 43 | max_val = k_Array[-1] 44 | 45 | print(d[max_val]) 46 | 47 | 48 | returnValue(height) 49 | -------------------------------------------------------------------------------- /Microsoft/Sum_of_cousins_of_a_given_node_in_a_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | class newNode: 2 | def __init__(self, data): 3 | self.data = data 4 | self.left = None 5 | self.right = None 6 | 7 | def findCousinSum( root, key): 8 | 9 | if (root == None): 10 | return -1 11 | 12 | if (root.data == key): 13 | return -1 14 | 15 | currSum = 0 16 | 17 | size = 0 18 | 19 | q = [] 20 | q.append(root) 21 | 22 | found = False 23 | 24 | while (len(q)): 25 | if (found == True): 26 | return currSum 27 | size = len(q) 28 | currSum = 0 29 | 30 | while (size): 31 | root = q[0] 32 | q.pop(0) 33 | if ((root.left and root.left.data == key) or 34 | (root.right and root.right.data == key)) : 35 | found = True 36 | else: 37 | if (root.left): 38 | currSum += root.left.data 39 | q.append(root.left) 40 | 41 | if (root.right) : 42 | currSum += root.right.data 43 | q.append(root.right) 44 | 45 | size -= 1 46 | return -1 47 | if __name__ == '__main__': 48 | root = newNode(1) 49 | root.left = newNode(3) 50 | root.right = newNode(7) 51 | root.left.left = newNode(6) 52 | root.left.right = newNode(5) 53 | root.left.right.left = newNode(10) 54 | root.right.left = newNode(4) 55 | root.right.right = newNode(13) 56 | root.right.left.left = newNode(17) 57 | root.right.left.right = newNode(15) 58 | 59 | print(findCousinSum(root, 13)) 60 | 61 | print(findCousinSum(root, 7)) 62 | 63 | s1=input() -------------------------------------------------------------------------------- /DailyCoding/1573.py: -------------------------------------------------------------------------------- 1 | """ 2 | This problem was asked by Sumo Logic. 3 | 4 | Given a array that's sorted but rotated at some unknown pivot, in which all elements are distinct, find a "peak" element in O(log N) time. 5 | 6 | An element is considered a peak if it is greater than both its left and right neighbors. It is guaranteed that the first and last elements are lower than all others. 7 | """ 8 | 9 | # O of N soln 10 | # def return_peak1(arr): 11 | # peak_array = [] 12 | # for i in range(len(arr)-1): 13 | # if arr[i-1] < arr[i] and arr[i] > arr[i+1]: 14 | # peak_array.append(arr[i]) 15 | # # return arr[i] 16 | # # else: 17 | # # return 0 18 | # return max(peak_array) 19 | 20 | # a1 = [1,2,3,4,5] 21 | # a2 = [1,2,3,5,3,6,2,1] 22 | # print(return_peak1(a1)) 23 | # print(return_peak1(a2)) 24 | 25 | # O of Log(N) soln 26 | def find_peak_element(nums): 27 | low, high = 0, len(nums) - 1 28 | 29 | while low < high: 30 | mid = (low + high) // 2 31 | 32 | # Check if mid is a peak 33 | if nums[mid] > nums[mid + 1]: 34 | high = mid # Search in the left half 35 | else: 36 | low = mid + 1 # Search in the right half 37 | 38 | return nums[low] 39 | 40 | # Example usage: 41 | rotated_array1 = [7, 9, 10, 2, 5, 6] 42 | rotated_array2 = [-7, -9, -10, -2, -5, -6] 43 | 44 | print("Peak element:", find_peak_element(rotated_array1)) 45 | print("Peak element:", find_peak_element(rotated_array2)) 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /Important/VowelReplace.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | write a func which replaces the vowels in a string and outputs the string 4 | 5 | input 6 | victor 7 | 8 | output 9 | voctir 10 | ''' 11 | 12 | 13 | def vowelReplace(str): 14 | l = list(str) 15 | vowel = ['a', 'e', 'i', 'o', 'u'] 16 | deque = [] 17 | newString = '' 18 | 19 | # edge case: 20 | if len(l) == 0: 21 | return "Empty" 22 | elif len(l) == 1: 23 | return str 24 | 25 | # everything else 26 | else: 27 | for char in l: 28 | if char in vowel: 29 | deque.append(char) 30 | len_d = len(deque) 31 | 32 | if len_d % 2 == 1: 33 | half = len_d/2 34 | middle = deque[len_d/2] 35 | deque = deque[:half] + deque[half+1:] 36 | else: 37 | middle = '' 38 | 39 | rearFlag = True 40 | while len(deque) > 0: 41 | for i in range(len(l)): 42 | if l[i] == middle: 43 | newString = newString + middle 44 | elif l[i] not in vowel: 45 | newString = newString + l[i] 46 | else: 47 | if rearFlag: 48 | newString = newString + deque.pop() 49 | rearFlag = False 50 | else: 51 | newString = newString + deque.pop(0) 52 | rearFlag = True 53 | 54 | return newString 55 | 56 | 57 | print(vowelReplace(input("Enter the string: "))) 58 | -------------------------------------------------------------------------------- /Important/longestSubstring.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, find the length of the longest substring without repeating characters. 3 | 4 | Examples: 5 | 6 | "abcabcbb" ->"abc" -> 3 7 | "bbbbb" ->"b" -> 1 8 | "pwwkew" ->"wke" ->3 9 | "pwke" is a subsequence and not a substring. 10 | 11 | """ 12 | 13 | # solution has a time complexity of O(n^2) 14 | def longest_substring_without_repeat_brute(string): 15 | maximum_length = 0 16 | for i in range(len(string)): 17 | maximum_length = max(maximum_length, helper(string, i)) 18 | return maximum_length 19 | 20 | def helper(string, start): 21 | seen = set() 22 | for i in range(start, len(string)): 23 | if string[i] not in seen: 24 | seen.add(string[i]) 25 | else: 26 | return i - start 27 | return len(string) - start 28 | 29 | # sliding window solution 30 | # time complexity is O(n) 31 | def longest_substring_without_repeat(string): 32 | seen = {} 33 | maximum_length = 0 34 | start = 0 35 | for end in range(len(string)): 36 | if string[end] in seen: 37 | start = max(start, seen[string[end]] + 1) 38 | seen[string[end]] = end 39 | maximum_length = max(maximum_length, end - start + 1) 40 | return maximum_length 41 | 42 | print(longest_substring_without_repeat_brute("abcabcbb") == 3) 43 | print(longest_substring_without_repeat_brute("bbbbb") == 1) 44 | print(longest_substring_without_repeat_brute("pwwkew") == 3) 45 | 46 | print(longest_substring_without_repeat("abcabcbb") == 3) 47 | print(longest_substring_without_repeat("bbbbb") == 1) 48 | print(longest_substring_without_repeat("pwwkew") == 3) -------------------------------------------------------------------------------- /Exercism/palindrome-products/palindrome_products.py: -------------------------------------------------------------------------------- 1 | def is_palindromic(number): 2 | return str(number) == "".join(reversed(str(number))) 3 | 4 | 5 | def find_factors(number, min_factor, max_factor): 6 | factors = [] 7 | for i in range(min_factor, max_factor+1): 8 | if number % i == 0 and max_factor >= number // i >= min_factor: 9 | factors.append((i, number // i)) 10 | return number, factors 11 | 12 | 13 | def largest_palindrome(max_factor, min_factor): 14 | all_numbers = set([]) 15 | for i in range(max_factor, min_factor + 1, -1): 16 | for j in range(max_factor, min_factor + 1, -1): 17 | product = i * j 18 | if is_palindromic(product): 19 | all_numbers.add(product) 20 | break 21 | if len(all_numbers) > 100: 22 | break 23 | if not all_numbers: 24 | raise ValueError("No palindromic number found.") 25 | return find_factors(max(all_numbers), min_factor, max_factor) 26 | 27 | 28 | def smallest_palindrome(max_factor, min_factor): 29 | all_numbers = set([]) 30 | for i in range(min_factor, max_factor + 1): 31 | for j in range(min_factor, max_factor + 1): 32 | product = i * j 33 | if is_palindromic(product): 34 | all_numbers.add(product) 35 | break 36 | if len(all_numbers) > 100: 37 | break 38 | if not all_numbers: 39 | raise ValueError("No palindromic number found.") 40 | return find_factors(min(all_numbers), min_factor, max_factor) 41 | -------------------------------------------------------------------------------- /Important/BubbleSort.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def BubbleSort(lst): 5 | 6 | for i in range(0, len(lst)-1): 7 | for j in range(i+1, len(lst)): 8 | if lst[i] > lst[j]: 9 | lst[i], lst[j] = lst[j], lst[i] 10 | 11 | return lst 12 | 13 | # print BubbleSort([1,5,4,3,6,7]) 14 | 15 | 16 | def BubbleSort1(lst): 17 | moreswaps = True 18 | 19 | while moreswaps: 20 | moreswaps = False 21 | for i in range(len(lst)-1): 22 | if lst[i] > lst[i+1]: 23 | moreswaps = True 24 | temp = lst[i] 25 | lst[i] = lst[i+1] 26 | lst[i+1] = temp 27 | 28 | return lst 29 | 30 | 31 | class Test(unittest.TestCase): 32 | 33 | def test_sortedequal(self): 34 | self.assertEqual([1, 2, 3, 4], BubbleSort([1, 2, 3, 4])) 35 | 36 | def test_Unsorterequal(self): 37 | self.assertEqual([1, 2, 3, 4], BubbleSort([4, 3, 2, 1])) 38 | 39 | def test_sortedequalLarge(self): 40 | self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 41 | BubbleSort([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) 42 | 43 | def test_UnsorterequalLarge(self): 44 | self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 45 | BubbleSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])) 46 | 47 | def test_empty(self): 48 | self.assertEqual([], BubbleSort([])) 49 | 50 | def test_single(self): 51 | self.assertEqual([1], BubbleSort([1])) 52 | 53 | 54 | if __name__ == '__main__': 55 | unittest.main(verbosity=2) 56 | -------------------------------------------------------------------------------- /LeetCode/21_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | 21. Merge Two Sorted Lists 3 | 4 | You are given the heads of two sorted linked lists list1 and list2. 5 | Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. 6 | Return the head of the merged linked list. 7 | Example 1: 8 | Input: list1 = [1,2,4], list2 = [1,3,4] 9 | Output: [1,1,2,3,4,4] 10 | 11 | Example 2: 12 | Input: list1 = [], list2 = [] 13 | Output: [] 14 | 15 | Example 3: 16 | Input: list1 = [], list2 = [0] 17 | Output: [0] 18 | 19 | traints: 20 | 21 | The number of nodes in both lists is in the range [0, 50]. 22 | -100 <= Node.val <= 100 23 | Both list1 and list2 are sorted in non-decreasing order. 24 | """ 25 | from typing import Optional 26 | # Definition for singly-linked list. 27 | class ListNode: 28 | def __init__(self, val=0, next=None): 29 | self.val = val 30 | self.next = next 31 | class Solution: 32 | def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: 33 | dummy = ListNode() 34 | tail = dummy 35 | 36 | while list1 and list2: 37 | if list1.val < list2.val: 38 | tail.next = list1 39 | list1 = list1.next 40 | else: 41 | tail.next = list2 42 | list2 = list2.next 43 | 44 | tail = tail.next 45 | 46 | if list1: 47 | tail.next = list1 48 | elif list2: 49 | tail.next = list2 50 | 51 | 52 | return dummy.next 53 | -------------------------------------------------------------------------------- /LeetCode/27.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val. 3 | 4 | Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things: 5 | 6 | Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums. 7 | Return k. 8 | Example 1: 9 | 10 | Input: nums = [3,2,2,3], val = 3 11 | Output: 2, nums = [2,2,_,_] 12 | Explanation: Your function should return k = 2, with the first two elements of nums being 2. 13 | It does not matter what you leave beyond the returned k (hence they are underscores). 14 | Example 2: 15 | 16 | Input: nums = [0,1,2,2,3,0,4,2], val = 2 17 | Output: 5, nums = [0,1,4,0,3,_,_,_] 18 | Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. 19 | Note that the five elements can be returned in any order. 20 | It does not matter what you leave beyond the returned k (hence they are underscores). 21 | 22 | """ 23 | from typing import List 24 | 25 | class Solution: 26 | def removeElement(self, nums: List[int], val: int) -> int: 27 | 28 | count = 0 29 | l = len(nums) 30 | for i in range(l): 31 | if nums[i] != val: 32 | nums[count] = nums[i] 33 | count += 1 34 | 35 | return count -------------------------------------------------------------------------------- /DailyCoding/1584.py: -------------------------------------------------------------------------------- 1 | """ 2 | This problem was asked by Uber. 3 | 4 | Implement a 2D iterator class. It will be initialized with an array of arrays, and should implement the following methods: 5 | 6 | next(): returns the next element in the array of arrays. If there are no more elements, raise an exception. 7 | has_next(): returns whether or not the iterator still has elements left. 8 | For example, given the input [[1, 2], [3], [], [4, 5, 6]], calling next() repeatedly should output 1, 2, 3, 4, 5, 6. 9 | 10 | """ 11 | 12 | class TwoDIterator: 13 | def __init__(self, arrays): 14 | self.arrays = arrays 15 | self.row = 0 16 | self.col = 0 17 | self.move_to_next_non_empty() 18 | 19 | def move_to_next_non_empty(self): 20 | while self.row < len(self.arrays) and self.col == len(self.arrays[self.row]): 21 | self.row += 1 22 | self.col = 0 23 | 24 | def next(self): 25 | if not self.has_next(): 26 | raise StopIteration("No more elements") 27 | 28 | result = self.arrays[self.row][self.col] 29 | self.col += 1 30 | self.move_to_next_non_empty() 31 | return result 32 | 33 | def has_next(self): 34 | return self.row < len(self.arrays) 35 | 36 | # class StopIteration(Exception): 37 | 38 | 39 | i = [[1, 2], [3], [], [4, 5, 6]] 40 | iterator = TwoDIterator(i) 41 | print(iterator.next()) 42 | print(iterator.next()) 43 | print(iterator.next()) 44 | print(iterator.next()) 45 | print(iterator.next()) 46 | print(iterator.next()) 47 | print(iterator.next()) # < raises exception 48 | 49 | -------------------------------------------------------------------------------- /LeetCode/100.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two binary trees, write a function to check if they are the same or not. 3 | 4 | Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 5 | 6 | Example 1: 7 | 8 | Input: 1 1 9 | / \ / \ 10 | 2 3 2 3 11 | 12 | [1,2,3], [1,2,3] 13 | 14 | Output: true 15 | Example 2: 16 | 17 | Input: 1 1 18 | / \ 19 | 2 2 20 | 21 | [1,2], [1,null,2] 22 | 23 | Output: false 24 | Example 3: 25 | 26 | Input: 1 1 27 | / \ / \ 28 | 2 1 1 2 29 | 30 | [1,2,1], [1,1,2] 31 | 32 | Output: false 33 | """ 34 | 35 | # Definition for a binary tree node. 36 | # class TreeNode(object): 37 | # def __init__(self, val=0, left=None, right=None): 38 | # self.val = val 39 | # self.left = left 40 | # self.right = right 41 | class Solution(object): 42 | def isSameTree(self, p, q): 43 | def checkTree(p, q): 44 | if p != None and q != None: 45 | if p.val != q.val: 46 | return False 47 | l = checkTree(p.left, q.left) 48 | r = checkTree(p.right, q.right) 49 | elif p == None and q == None: 50 | return True 51 | else: 52 | return False 53 | if l == True and r == True: 54 | return True 55 | else: 56 | return False 57 | 58 | return checkTree(p, q) 59 | -------------------------------------------------------------------------------- /TreesAndGraphs/kruskall.py: -------------------------------------------------------------------------------- 1 | #CONJUNTO 2 | 3 | class no: 4 | def __init__(self,lista_arestas,vertices): 5 | self.arestas = lista_arestas 6 | self.vertices = vertices 7 | class Grafo: 8 | def __init__(self, arestas, vertices): 9 | self.arestas = arestas 10 | self.vertices = vertices 11 | self.inicio = None 12 | def busca(self,Q,vertice): 13 | for i in Q: 14 | for elemento in i: 15 | if elemento == vertice: 16 | return i 17 | def uniao(self, Q, u, v): 18 | uniao1 = self.busca(Q,u) 19 | uniao2 = self.busca(Q,v) 20 | if len(uniao2)> 1: 21 | for i in uniao2: 22 | Q[Q.index(uniao1)].append(i) 23 | else: 24 | Q[Q.index(uniao1)].append(v) 25 | Q.pop(Q.index(uniao2)) 26 | return Q 27 | def linka(self): 28 | Q = [] 29 | for v in self.vertices: 30 | Q.append([v]) 31 | for edge in self.arestas: 32 | if self.busca(Q,edge[0]) != self.busca(Q,edge[1]): 33 | aux = self.uniao(Q,edge[0],edge[1]) 34 | Q = aux 35 | return len(Q) 36 | entr1 = input().split() 37 | n = int(entr1[0]) 38 | cont = 0 39 | aresta,vertice = [],[] 40 | for i in range(1, n+1): 41 | i = int(i) 42 | vertice.append(i) 43 | while cont int: 23 | # init left and right pointers 24 | l = 0 25 | r = 1 26 | # profit starts at 0 27 | max_profit = 0 28 | 29 | while r < len(prices): 30 | # regular check if profit 31 | if prices[l] < prices[r]: 32 | profit = prices[r] - prices[l] 33 | # get the max profit and store 34 | max_profit = max(max_profit, profit) 35 | else: 36 | # we found a price lower than previos low 37 | l = r 38 | # right moves as usual every iter 39 | r += 1 40 | 41 | return max_profit 42 | 43 | q1 = [7,1,5,3,6,4] 44 | q2 = [7,6,4,3,1] 45 | print(maxProfit(q1)) 46 | print(maxProfit(q2)) 47 | -------------------------------------------------------------------------------- /LeetCode/61.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a linked list, rotate the list to the right by k places, where k is non-negative. 3 | 4 | Example 1: 5 | 6 | Input: 1->2->3->4->5->NULL, k = 2 7 | Output: 4->5->1->2->3->NULL 8 | Explanation: 9 | rotate 1 steps to the right: 5->1->2->3->4->NULL 10 | rotate 2 steps to the right: 4->5->1->2->3->NULL 11 | Example 2: 12 | 13 | Input: 0->1->2->NULL, k = 4 14 | Output: 2->0->1->NULL 15 | Explanation: 16 | rotate 1 steps to the right: 2->0->1->NULL 17 | rotate 2 steps to the right: 1->2->0->NULL 18 | rotate 3 steps to the right: 0->1->2->NULL 19 | rotate 4 steps to the right: 2->0->1->NULL 20 | """ 21 | from types import ListNode 22 | # Definition for singly-linked list. 23 | # class ListNode: 24 | # def __init__(self, val=0, next=None): 25 | # self.val = val 26 | # self.next = next 27 | class Solution: 28 | def rotateRight(self, head: ListNode, k: int) -> ListNode: 29 | if not head or not k: 30 | return head 31 | 32 | # Find list length first 33 | length = 0 34 | node = head 35 | while node: 36 | last_node = node 37 | node = node.next 38 | length += 1 39 | 40 | rest = k % length 41 | if rest == 0: 42 | return head 43 | 44 | # Make it a ring 45 | last_node.next = head 46 | 47 | # Loop again to find the break point 48 | node = head 49 | for _ in range(length-rest): # This is reverse logic 50 | break_node = node 51 | node = node.next 52 | 53 | beginning_node = break_node.next 54 | break_node.next = None 55 | return beginning_node 56 | -------------------------------------------------------------------------------- /Important/decorator_example.py: -------------------------------------------------------------------------------- 1 | # 1 2 | # decorator function takes a function 3 | # returns a function 4 | def decorator1(function): 5 | 6 | # has a nested function 7 | def addWelcome(name): 8 | return "\nWelcome to " + function(name) 9 | 10 | # returns the nested function 11 | return addWelcome 12 | 13 | # decorator is appended above a regular function 14 | @decorator1 15 | def welcome(name): 16 | return name 17 | 18 | # using the welcom now 19 | 20 | print (welcome("decorator example")) 21 | # prints => Welcome to decorator example 22 | 23 | # 2 24 | # decorator to add data to func 25 | def decorator2(function): 26 | function.data = "\nattached data to function in decorator 2" 27 | return function 28 | 29 | @decorator2 30 | def addition(x, y): 31 | return x + y 32 | 33 | print(addition(2,3)) 34 | print(addition.data) 35 | # prints => 5 36 | # prints => attached data to function 37 | 38 | 39 | # decorator to conver to lowercase 40 | def lowercase_decorator(function): 41 | def wrapper(*args): 42 | new_args = [] 43 | for arg in args: 44 | new_args.append(arg.lower()) 45 | return function(*new_args) 46 | return wrapper 47 | 48 | # decorator to convert to Capitalize 49 | def capitalize_decorator(function): 50 | def wrapper(*args): 51 | new_args = [] 52 | for arg in args: 53 | new_args.append(arg.capitalize()) 54 | return function(*new_args) 55 | return wrapper 56 | 57 | 58 | @lowercase_decorator 59 | def hello(s): 60 | print(s) 61 | 62 | hello("Hello World") 63 | 64 | @capitalize_decorator 65 | def hello1(s): 66 | print(s) 67 | 68 | hello1("hello world") --------------------------------------------------------------------------------