├── CodingBlocks └── Challenges-Basics │ ├── Boston_Number.java │ ├── LCM_assignment.java │ ├── OddEvenPlaceSum.java │ ├── PrimeNumber.java │ ├── PrimePrint.java │ ├── ReverseNumber.java │ ├── SimpleInput.java │ ├── gcd.java │ ├── gcd_assignment.java │ ├── oddEven.java │ ├── primeFactors.java │ ├── testing.java │ └── whileExperiment.java ├── Data structure ├── Deque Implementation.py ├── Hash table.py ├── Linked List │ ├── Cycle Check 2.py │ ├── Cycle Check.py │ ├── Doubly Linked List.py │ ├── Linked List Reversal.py │ ├── LinkedList Nth to Last Node.py │ ├── Nth to last node 2.py │ └── Singly Linked List.py ├── Queue to Stack.py ├── Searching techniques │ ├── Binary Search.py │ ├── Recursive Binary search.py │ ├── Sequential Search.py │ └── Sequential search ordered.py ├── Sorting Algorithms │ ├── Bubble Sort.py │ ├── Bubble sort1.py │ ├── Insertion Sort.py │ ├── Merge sort.py │ ├── Quick Sort.py │ └── Selection sort.py ├── Stack Implementation.py └── Tree │ ├── Nodes and References.py │ └── Tree representation.py ├── LICENSE ├── Logical problems ├── Balanced Paranthesis.py ├── Bridgelabz interview │ ├── Bridgelabz 4.py │ ├── bridgelabz 1.py │ ├── bridgelabz 2.py │ ├── bridgelabz 3.py │ ├── bridgelabz 4a.py │ └── permutations.py ├── Day-1.ipynb ├── Find Missing Element.py ├── FizzBuzz_hackerearth.py ├── Longest Continuous Sum.py ├── Pair Sum.py ├── Rotate Array.py ├── anagram.py ├── rotate pdf.py ├── sum digits.py └── word split.py ├── README.md ├── Recursion ├── Change coin problem optimised.py ├── Coin Change Problem.py ├── Fibonacci series.py ├── Memoization factorial.py ├── Permutation string.py ├── Recursion Cumulative SUM.py ├── Recursion factorial.py ├── memoization.py ├── reverse string.py └── sum of digits.py └── Udacity Data Structure and Algorithms Nanodegree └── Introduction ├── AssertionExample.py ├── Efficiency.ipynb ├── FindNextDay.py ├── Friend_Birthday.py ├── Unscramble computer science problems.ipynb ├── calls.csv ├── courses_udacity.py ├── daysBetweenDates.py ├── daysBetweenDatesFinal.py ├── generator_example.py ├── smallest_positive.py ├── sudoko_check.py └── texts.csv /CodingBlocks/Challenges-Basics/Boston_Number.java: -------------------------------------------------------------------------------- 1 | package Lecture2; 2 | 3 | import java.util.Scanner; 4 | import java.lang.Math; 5 | 6 | public class Boston_Number { 7 | public static void main(String args[]) { 8 | 9 | Scanner sc = new Scanner(System.in); 10 | 11 | boolean bostonNum = false; 12 | int num = sc.nextInt(); 13 | int numSum = sumOfDigits(num); 14 | 15 | int primeFactorsum = primeFactorFinder(num); 16 | 17 | if (numSum == primeFactorsum) { 18 | bostonNum = true; 19 | } 20 | 21 | if (bostonNum) { 22 | System.out.println("1"); 23 | } else { 24 | System.out.println("0"); 25 | 26 | } 27 | 28 | } 29 | 30 | public static int sumOfDigits(int n) { 31 | int nsum = 0; 32 | 33 | while (n != 0) { 34 | nsum += n % 10; 35 | n = n / 10; 36 | } 37 | 38 | return nsum; 39 | } 40 | 41 | 42 | public static int primeFactorFinder(int n) { 43 | 44 | int factorSum = 0; 45 | 46 | while (n % 2 == 0) { 47 | factorSum += 2; 48 | n = n / 2; 49 | } 50 | 51 | for (int i = 3; i <= n/2; i = i + 2) { 52 | 53 | while (n % i == 0) { 54 | factorSum = factorSum + sumOfDigits(i); 55 | n = n / i; 56 | } 57 | } 58 | 59 | if (n > 2) { 60 | factorSum = factorSum + sumOfDigits(n); 61 | } 62 | 63 | return factorSum; 64 | 65 | } 66 | } -------------------------------------------------------------------------------- /CodingBlocks/Challenges-Basics/LCM_assignment.java: -------------------------------------------------------------------------------- 1 | package Lecture2; 2 | 3 | import java.util.Scanner; 4 | 5 | public class LCM_assignment { 6 | 7 | public static void main(String args[]) { 8 | 9 | Scanner sc = new Scanner(System.in); 10 | long n1 = sc.nextLong(); 11 | long n2 = sc.nextLong(); 12 | 13 | long gcd = compute_gcd(n1, n2); 14 | 15 | long lcm = (n1 * n2) / gcd; 16 | 17 | System.out.println(lcm); 18 | 19 | } 20 | 21 | public static long compute_gcd(long n1, long n2) { 22 | 23 | long divisor = 0, dividend = 0, rem = 0; 24 | 25 | if (n1 < n2) { 26 | divisor = n1; 27 | dividend = n2; 28 | } else { 29 | divisor = n2; 30 | dividend = n1; 31 | } 32 | 33 | while (dividend % divisor != 0) { 34 | rem = dividend % divisor; 35 | dividend = divisor; 36 | divisor = rem; 37 | } 38 | 39 | return divisor; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /CodingBlocks/Challenges-Basics/OddEvenPlaceSum.java: -------------------------------------------------------------------------------- 1 | package Lecture2; 2 | import java.util.Scanner; 3 | 4 | public class OddEvenPlaceSum { 5 | public static void main(String args[]) { 6 | 7 | Scanner sc = new Scanner(System.in); 8 | long n = sc.nextLong(); 9 | 10 | int oddSum = 0; 11 | int evenSum = 0; 12 | int length = 0; 13 | 14 | String numStr = Long.toString(n); 15 | 16 | while (n!=0){ 17 | n = n/10; 18 | length++; 19 | } 20 | System.out.println("length "+length); 21 | for (int i=0;i0){ 20 | System.out.println(num); 21 | } 22 | else{ 23 | return; 24 | } 25 | } 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /CodingBlocks/Challenges-Basics/gcd.java: -------------------------------------------------------------------------------- 1 | package Lecture2; 2 | 3 | import java.util.Scanner; 4 | 5 | public class gcd { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | Scanner s=new Scanner(System.in); 10 | 11 | int a=s.nextInt(); 12 | int b=s.nextInt(); 13 | 14 | int dividend=0,divisor=0; 15 | if(a>b) { 16 | dividend=a; 17 | divisor=b; 18 | }else { 19 | dividend=b; 20 | divisor=a; 21 | } 22 | 23 | while(dividend%divisor!=0) { 24 | int rem=dividend%divisor; 25 | dividend=divisor; 26 | divisor=rem; 27 | } 28 | 29 | System.out.println(divisor); 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /CodingBlocks/Challenges-Basics/gcd_assignment.java: -------------------------------------------------------------------------------- 1 | package Lecture2; 2 | 3 | import java.util.Scanner; 4 | 5 | public class gcd_assignment { 6 | 7 | 8 | 9 | public static void main(String args[]) { 10 | 11 | Scanner sc = new Scanner(System.in); 12 | long n1 = sc.nextLong(); 13 | long n2 = sc.nextLong(); 14 | 15 | long divisor = 0; 16 | long dividend = 0; 17 | long rem = 0; 18 | 19 | if (n1 < n2){ 20 | divisor = n1; 21 | dividend = n2; 22 | }else{ 23 | divisor = n2; 24 | dividend = n1; 25 | } 26 | 27 | while (dividend % divisor != 0){ 28 | rem = dividend % divisor; 29 | dividend = divisor; 30 | divisor = rem; 31 | } 32 | System.out.println(divisor); 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /CodingBlocks/Challenges-Basics/oddEven.java: -------------------------------------------------------------------------------- 1 | package Lecture2; 2 | 3 | // Take N as input. Print the sum of its odd placed digits and sum of its even placed digits. 4 | //Constraints 5 | //0 < N <= 1000000000 6 | 7 | import java.util.Scanner; 8 | 9 | public class oddEven { 10 | 11 | public static void main(String args[]) { 12 | 13 | Scanner sc = new Scanner(System.in); 14 | 15 | long n = sc.nextLong(); 16 | long temp = n; 17 | int evenSum = 0; 18 | int oddSum = 0; 19 | int count = 1; 20 | long rem=0; 21 | 22 | while (n!=0){ 23 | if (count %2 != 0){ 24 | rem = n%10; 25 | oddSum += rem; 26 | count++; 27 | n = n/10; 28 | } 29 | else{ 30 | rem = n%10; 31 | evenSum += rem; 32 | count++; 33 | n = n/10; 34 | } 35 | } 36 | 37 | System.out.println(oddSum); 38 | System.out.println(evenSum); 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /CodingBlocks/Challenges-Basics/primeFactors.java: -------------------------------------------------------------------------------- 1 | package Lecture2; 2 | 3 | import java.lang.Math; 4 | 5 | public class primeFactors { 6 | 7 | public static void main(String[] args) { 8 | 9 | int n = 85; 10 | int sum = 0; 11 | 12 | while (n % 2 == 0) { 13 | System.out.println(2); 14 | sum += 2; 15 | n = n / 2; 16 | } 17 | 18 | for (int i=3; i<=Math.sqrt(n);i=i+2){ 19 | while (n%i == 0){ 20 | System.out.println(i); 21 | sum += i; 22 | n = n/i; 23 | } 24 | } 25 | 26 | if (n>2){ 27 | System.out.println(n); 28 | sum += n; 29 | } 30 | System.out.println("sum of all prime factors is: "+sum); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /CodingBlocks/Challenges-Basics/testing.java: -------------------------------------------------------------------------------- 1 | package Lecture2; 2 | 3 | //testing scope of variables 4 | 5 | public class testing { 6 | 7 | public static void main(String[] args) { 8 | int n = 10; 9 | int x = check(n); 10 | System.out.println(n+" "+ x); 11 | } 12 | public static int check(int n){ 13 | n = n+10; 14 | return n; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /CodingBlocks/Challenges-Basics/whileExperiment.java: -------------------------------------------------------------------------------- 1 | package Lecture2; 2 | 3 | import java.util.Scanner; 4 | 5 | public class whileExperiment { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | Scanner sc = new Scanner(System.in); 10 | int i=0; 11 | while(true){ 12 | int n = sc.nextInt(); 13 | System.out.println(i+" "+n); 14 | i++; 15 | if (n==4){ 16 | return; 17 | } 18 | } 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Data structure/Deque Implementation.py: -------------------------------------------------------------------------------- 1 | class Dequeue(object): 2 | 3 | def __init__(self): 4 | self.lst = [] 5 | 6 | def is_empty(self): 7 | return self.lst == [] 8 | 9 | def get_size(self): 10 | return len(self.lst) 11 | 12 | def push_front(self, item): 13 | self.lst.append(item) 14 | 15 | def push_rear(self, item): 16 | self.lst.insert(0, item) 17 | 18 | def pop_front(self): 19 | if self.is_empty(): 20 | return 'nothing to pop' 21 | return self.lst.pop(-1) 22 | 23 | def pop_rear(self): 24 | if self.is_empty(): 25 | return 'nothing to pop' 26 | return self.lst.pop(0) 27 | 28 | def display(self): 29 | print(*self.lst) 30 | 31 | 32 | deq = Dequeue() 33 | # print(deq.get_size()) 34 | # print(deq.is_empty()) 35 | # print(deq.display()) 36 | # print(deq.pop_front()) 37 | # print(deq.pop_rear()) 38 | # deq.push_front([1,2]) 39 | # deq.display() -------------------------------------------------------------------------------- /Data structure/Hash table.py: -------------------------------------------------------------------------------- 1 | class HashTable(object): 2 | 3 | def __init__(self, size): 4 | self.size = size 5 | self.slots = [None] * self.size 6 | self.data = [None] * self.size 7 | 8 | def put(self, key, data): 9 | 10 | hash_value = self.hashfunction(key, len(self.slots)) 11 | if self.slots[hash_value] is None: 12 | self.slots[hash_value] = key 13 | self.data[hash_value] = data 14 | else: 15 | if self.slots[hash_value] == key: 16 | self.data[hash_value] = data 17 | 18 | else: 19 | nextslot = self.rehash(hash_value, len(self.slots)) 20 | 21 | while self.slots[nextslot] is not None and self.slots[nextslot] != key: 22 | nextslot = self.rehash(nextslot, len(self.slots)) 23 | 24 | if self.slots[nextslot] is None: 25 | self.slots[nextslot] = key 26 | self.data[nextslot] = data 27 | else: 28 | self.data[nextslot] = data 29 | 30 | 31 | def hashfunction(self, key, size): 32 | return key % size 33 | 34 | def rehash(self, oldhash, size): 35 | return (oldhash+1) % size 36 | 37 | def get(self, key): 38 | startslot = self.hashfunction(key,len(self.slots)) 39 | data = None 40 | stop = False 41 | found = False 42 | position = startslot 43 | 44 | while self.slots[position] is not None and not found and not stop: 45 | if self.slots[position] == key: 46 | found = True 47 | data = self.data[position] 48 | else: 49 | position = self.rehash(position, len(self.slots)) 50 | if position == startslot: 51 | stop = True 52 | return data 53 | 54 | def __getitem__(self, item): 55 | return self.get(item) 56 | 57 | def __setitem__(self, key, value): 58 | self.put(key, value) 59 | 60 | 61 | my_table = HashTable(5) 62 | my_table[1] = 'one' 63 | my_table[2] = 'two' 64 | my_table[3] = 'three' 65 | 66 | print(my_table[1]) -------------------------------------------------------------------------------- /Data structure/Linked List/Cycle Check 2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Followed pattern: PEP8, python3 3 | @aurthor: Nirmal Silwal 4 | @github: https://github.com/NirmalSilwal 5 | @linkedln: https://www.linkedin.com/in/nirmal-silwal-827341139/ 6 | @twitter: https://twitter.com/silwal_nirmal 7 | """ 8 | 9 | 10 | class Node(object): 11 | 12 | def __init__(self, data): 13 | self.data = data 14 | self.next = None 15 | 16 | 17 | def check_cycle(node): 18 | marker1 = node 19 | marker2 = node 20 | while marker2 is not None and marker2.next is not None: 21 | marker1 = marker1.next 22 | marker2 = marker2.next.next 23 | 24 | if marker2 == marker1: 25 | return True 26 | 27 | return False 28 | 29 | 30 | # adding nodes in linked list 31 | first_node = Node(1) 32 | second_node = Node(2) 33 | third_node = Node(3) 34 | 35 | # forming singly linked list 36 | first_node.next = second_node 37 | second_node.next = third_node 38 | 39 | # adding nodes in new linked list 40 | node1 = Node(10) 41 | node2 = Node(20) 42 | node3 = Node(30) 43 | node4 = Node(40) 44 | node5 = Node(50) 45 | 46 | # forming cycled linked list 47 | node1.next = node2 48 | node2.next = node3 49 | node3.next = node4 50 | node4.next = node5 51 | node5.next = node1 52 | 53 | # testing 54 | print(f'cycle present: {check_cycle(node1)}') 55 | print(f'cycle present: {check_cycle(first_node)}') 56 | -------------------------------------------------------------------------------- /Data structure/Linked List/Cycle Check.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | 3 | def __init__(self,data): 4 | self.data = data 5 | self.next = None 6 | 7 | 8 | def singly_linked_list_cycle_check(node): 9 | while node.next is not None: 10 | node = node.next 11 | if node.next == node1: 12 | return True 13 | 14 | return False 15 | 16 | 17 | node1 = Node(1) 18 | node2 = Node(2) 19 | node3 = Node(3) 20 | 21 | node1.next = node2 22 | node2.next = node3 23 | 24 | #making circulaly linked list for checking cycle 25 | node3.next = node1 26 | 27 | is_cycle = singly_linked_list_cycle_check(node1) 28 | print(f'cycle present in this linked list: {is_cycle}') -------------------------------------------------------------------------------- /Data structure/Linked List/Doubly Linked List.py: -------------------------------------------------------------------------------- 1 | class DoublyLinkedListNode(object): 2 | 3 | def __init__(self, data): 4 | self.data = data 5 | self.next = None 6 | self.prev = None 7 | 8 | 9 | doubly_node1 = DoublyLinkedListNode(10) 10 | doubly_node2 = DoublyLinkedListNode(20) 11 | doubly_node3 = DoublyLinkedListNode(30) 12 | doubly_node4 = DoublyLinkedListNode(40) 13 | 14 | doubly_node1.next = doubly_node2 15 | doubly_node2.prev = doubly_node1 16 | doubly_node2.next = doubly_node3 17 | doubly_node3.prev = doubly_node2 18 | doubly_node3.next = doubly_node4 19 | doubly_node4.prev = doubly_node3 20 | 21 | print(doubly_node2.prev.data) 22 | print(doubly_node2.next.data) 23 | print(doubly_node2.data) 24 | print(doubly_node4.next) 25 | print(doubly_node1.prev) 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Data structure/Linked List/Linked List Reversal.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | 3 | def __init__(self,data): 4 | self.data = data 5 | self.next = None 6 | 7 | 8 | def display_next(node): 9 | while node.next is not None: 10 | print(node.next.data) 11 | node = node.next 12 | else: 13 | print(node.next) 14 | 15 | 16 | def reverse_list(head): 17 | current_node = head 18 | prev_node = None 19 | next_node = None 20 | 21 | while current_node: 22 | next_node = current_node.next 23 | current_node.next = prev_node 24 | prev_node = current_node 25 | current_node = next_node 26 | 27 | return prev_node 28 | 29 | 30 | node1 = Node(1) 31 | node2 = Node(2) 32 | node3 = Node(3) 33 | node4 = Node(4) 34 | 35 | node1.next = node2 36 | node2.next = node3 37 | node3.next = node4 38 | 39 | print('before reversal') 40 | display_next(node1) 41 | 42 | print('after reversal') 43 | display_next(reverse_list(node1)) 44 | -------------------------------------------------------------------------------- /Data structure/Linked List/LinkedList Nth to Last Node.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | 3 | def __init__(self,data): 4 | self.data = data 5 | self.next = None 6 | 7 | 8 | def nth_to_last_node(head, n_before): 9 | start_node = head 10 | counter = 0 11 | while head.next is not None: 12 | head = head.next 13 | counter += 1 14 | else: 15 | # tail = head 16 | counter += 1 17 | 18 | if n_before > counter: 19 | return 'invalid position' 20 | 21 | for node_position in range(counter - n_before): 22 | start_node = start_node.next 23 | 24 | return start_node 25 | 26 | 27 | node1 = Node(100) 28 | node2 = Node(200) 29 | node3 = Node(300) 30 | node4 = Node(400) 31 | node5 = Node(500) 32 | 33 | node1.next = node2 34 | node2.next = node3 35 | node3.next = node4 36 | node4.next = node5 37 | 38 | result = nth_to_last_node(node1, 2) 39 | try: 40 | print(result.data) 41 | except Exception: 42 | print(result) -------------------------------------------------------------------------------- /Data structure/Linked List/Nth to last node 2.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | 3 | def __init__(self,data): 4 | self.data = data 5 | self.next = None 6 | 7 | 8 | def nth_to_last_node(head, n_before): 9 | left_pointer = head 10 | right_pointer = head 11 | 12 | # moving right_pointer to 'n_before' position ahead of head/start node 13 | for i in range(n_before-1): 14 | if not right_pointer.next: 15 | raise LookupError('Error: n is larger than the linked list') 16 | 17 | right_pointer = right_pointer.next 18 | 19 | # while right_pointer.next is not None: # below line and this line is same 20 | 21 | while right_pointer.next: 22 | left_pointer = left_pointer.next 23 | right_pointer = right_pointer.next 24 | 25 | return left_pointer 26 | 27 | 28 | node1 = Node(100) 29 | node2 = Node(200) 30 | node3 = Node(300) 31 | node4 = Node(400) 32 | node5 = Node(500) 33 | 34 | node1.next = node2 35 | node2.next = node3 36 | node3.next = node4 37 | node4.next = node5 38 | 39 | result = nth_to_last_node(node1, 2) 40 | try: 41 | print(result.data) 42 | except Exception: 43 | print(result) -------------------------------------------------------------------------------- /Data structure/Linked List/Singly Linked List.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | 3 | def __init__(self, data): 4 | self.data = data 5 | self.nextnode = None 6 | 7 | 8 | a = Node(1) 9 | b = Node(2) 10 | c = Node(3) 11 | 12 | a.nextnode = b 13 | b.nextnode = c 14 | 15 | print(a.data,b.data,c.data) 16 | print(a.nextnode,b.nextnode,c.nextnode) 17 | print(a.nextnode.data) 18 | 19 | ''' 20 | NOTE: 21 | ===== 22 | PROS: Linked List has constant time O(1) Insertion and Deletions in any position. While array takes O(n). 23 | Flexibility in dynamic memory allocation. 24 | 25 | CONS: No random access of elements is allowed like in Array. Takes O(k) time to access kth element. You have to 26 | traverse from head/start node till you reach kth element, so no random access allowed in Linked List. 27 | 28 | Thus depending upon the use case, you will be choosing Array or Linked List. If you are looking for fast and 29 | random access, then go with Array, else Linked list is the better option. 30 | ''' -------------------------------------------------------------------------------- /Data structure/Queue to Stack.py: -------------------------------------------------------------------------------- 1 | class Queue2Stack(object): 2 | 3 | def __init__(self): 4 | self.stack1 = [] 5 | self.stack2 = [] 6 | 7 | def enqueue(self, item): 8 | self.stack1.append(item) 9 | 10 | def dequeue(self): 11 | for i in range(len(self.stack1)): 12 | self.stack2.append(self.stack1.pop()) 13 | 14 | return self.stack2.pop() 15 | 16 | 17 | q2stack = Queue2Stack() 18 | 19 | for i in range(1,6): 20 | q2stack.enqueue(i) 21 | 22 | for i in range(5): 23 | print(q2stack.dequeue()) -------------------------------------------------------------------------------- /Data structure/Searching techniques/Binary Search.py: -------------------------------------------------------------------------------- 1 | def binary_search(arr, element): 2 | 3 | first = 0 4 | last = len(arr)-1 5 | found = False 6 | 7 | while first < last and not found: 8 | 9 | mid_index = (first+last) // 2 10 | 11 | if arr[mid_index] == element: 12 | found = True 13 | else: 14 | if element < arr[mid_index]: 15 | last = mid_index - 1 16 | else: 17 | first = mid_index + 1 18 | 19 | return found 20 | 21 | 22 | lst = [1,2,3,4,5,6,7] 23 | print(binary_search(lst, 2)) 24 | print(binary_search(lst, 10)) -------------------------------------------------------------------------------- /Data structure/Searching techniques/Recursive Binary search.py: -------------------------------------------------------------------------------- 1 | def rec_bin_search(arr, element): 2 | 3 | if len(arr) == 0: 4 | return False 5 | else: 6 | mid = len(arr) // 2 7 | 8 | if arr[mid] == element: 9 | return True 10 | else: 11 | if element < arr[mid]: 12 | return rec_bin_search(arr[:mid], element) 13 | else: 14 | return rec_bin_search(arr[mid+1:], element) 15 | 16 | 17 | lst = [1,2,3,4,5,6,7] 18 | print(rec_bin_search(lst, 2)) 19 | print(rec_bin_search(lst, 10)) -------------------------------------------------------------------------------- /Data structure/Searching techniques/Sequential Search.py: -------------------------------------------------------------------------------- 1 | def seq_search(lst, element): 2 | pos = 0 3 | found = False 4 | 5 | while pos < len(lst) and not found: 6 | 7 | if lst[pos] == element: 8 | found = True 9 | else: 10 | pos += 1 11 | 12 | return found 13 | 14 | 15 | arr = [1,2,3,4,5,56] 16 | 17 | print(seq_search(arr,3)) 18 | print(seq_search(arr,56)) 19 | print(seq_search(arr,1)) 20 | print(seq_search(arr,6)) -------------------------------------------------------------------------------- /Data structure/Searching techniques/Sequential search ordered.py: -------------------------------------------------------------------------------- 1 | def ordered_seq_search(lst, item): 2 | """ 3 | Input array must be sorted 4 | """ 5 | pos = 0 6 | found = False 7 | stopped = False 8 | 9 | while pos < len(lst) and not found and not stopped: 10 | 11 | if lst[pos] == item: 12 | found = True 13 | return found 14 | else: 15 | if lst[pos] > item: 16 | stopped = True 17 | return found 18 | else: 19 | pos += 1 20 | print(lst[pos]) 21 | return found 22 | 23 | 24 | arr = [1,2,3,50,56,65] 25 | 26 | print(ordered_seq_search(arr,4)) 27 | # note here that last 2 elements are not even checked 28 | 29 | # print(ordered_seq_search(arr,56)) 30 | # print(ordered_seq_search(arr,1)) 31 | # print(ordered_seq_search(arr,6)) 32 | -------------------------------------------------------------------------------- /Data structure/Sorting Algorithms/Bubble Sort.py: -------------------------------------------------------------------------------- 1 | def bubble_sort(lst): 2 | length = len(lst) 3 | for pass_index in range(length-1): 4 | for check_element in range(length - pass_index - 1): 5 | if lst[check_element] > lst[check_element+1]: 6 | #swap them 7 | lst[check_element], lst[check_element+1] = lst[check_element+1], lst[check_element] 8 | 9 | return lst 10 | 11 | 12 | # lst = [5,1,4,2,8] 13 | lst = [64, 34, 25, 12, 22, 11, 90] 14 | # lst = [4,6,73,2,7,9,0,23,6,8,2] 15 | sorted_list = bubble_sort(lst) 16 | print(sorted_list) -------------------------------------------------------------------------------- /Data structure/Sorting Algorithms/Bubble sort1.py: -------------------------------------------------------------------------------- 1 | def bubble_sort(lst): 2 | for passes in range(len(lst)-1, 0, -1): 3 | for check in range(passes): 4 | if lst[check] > lst[check+1]: 5 | lst[check], lst[check+1] = lst[check+1], lst[check] 6 | 7 | return lst 8 | 9 | 10 | lst = [1,24,4,5,6,7] 11 | print(bubble_sort(lst)) -------------------------------------------------------------------------------- /Data structure/Sorting Algorithms/Insertion Sort.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(lst): 2 | 3 | for passes in range(1, len(lst)): # n-1 passes 4 | current_val = lst[passes] 5 | pos = passes 6 | 7 | while pos > 0 and lst[pos-1] > current_val: 8 | lst[pos] = lst[pos-1] 9 | pos = pos-1 10 | 11 | lst[pos] = current_val 12 | 13 | return lst 14 | 15 | 16 | arr = [2, 4, 42, 6, 22, 7] 17 | print(insertion_sort(arr)) 18 | -------------------------------------------------------------------------------- /Data structure/Sorting Algorithms/Merge sort.py: -------------------------------------------------------------------------------- 1 | def merge_sort(arr): 2 | 3 | if len(arr) > 1: 4 | mid = len(arr)//2 5 | left_half = arr[:mid] 6 | right_half = arr[mid:] 7 | 8 | merge_sort(left_half) 9 | merge_sort(right_half) 10 | 11 | i = 0 12 | j = 0 13 | k = 0 14 | 15 | while i < len(left_half) and j < len(right_half): 16 | 17 | if left_half[i] < right_half[j]: 18 | arr[k] = left_half[i] 19 | i += 1 20 | else: 21 | arr[k] = right_half[j] 22 | j += 1 23 | 24 | k += 1 25 | 26 | while i < len(left_half): 27 | arr[k] = left_half[i] 28 | i += 1 29 | k += 1 30 | 31 | while j < len(right_half): 32 | arr[k] = right_half[j] 33 | j += 1 34 | k += 1 35 | 36 | print(arr) 37 | return arr 38 | 39 | 40 | lst = [11, 3, 2, 5, 77, 4, 8, 0] 41 | print('original array is: ',lst) 42 | print('sorted array: ',merge_sort(lst)) 43 | -------------------------------------------------------------------------------- /Data structure/Sorting Algorithms/Quick Sort.py: -------------------------------------------------------------------------------- 1 | def quick_sort(arr): 2 | 3 | return quick_sort_help(arr, 0, len(arr)-1) 4 | 5 | 6 | def quick_sort_help(arr, first, last): 7 | 8 | if first < last: 9 | split_point = partition(arr, first, last) 10 | 11 | quick_sort_help(arr, first, split_point-1) 12 | quick_sort_help(arr, split_point+1, last) 13 | 14 | return arr 15 | 16 | 17 | def partition(arr, first, last): 18 | 19 | pivot = arr[first] 20 | 21 | left_mark = first+1 22 | right_mark = last 23 | 24 | done = False 25 | 26 | while not done: 27 | 28 | while left_mark <= right_mark and arr[left_mark] <= pivot: 29 | left_mark += 1 30 | 31 | while right_mark >= left_mark and arr[right_mark] >= pivot: 32 | right_mark -= 1 33 | 34 | if right_mark < left_mark: 35 | done = True 36 | else: 37 | arr[left_mark], arr[right_mark] = arr[right_mark], arr[left_mark] 38 | 39 | arr[first], arr[right_mark] = arr[right_mark], arr[first] 40 | # temp = arr[first] 41 | # arr[first] = arr[right_mark] 42 | # arr[right_mark] = temp 43 | 44 | return right_mark 45 | 46 | 47 | lst = [11, 3, 2, 5, 77, 4, 8, 0] 48 | print('original array: ', lst) 49 | print('sorted array: ', quick_sort(lst)) 50 | -------------------------------------------------------------------------------- /Data structure/Sorting Algorithms/Selection sort.py: -------------------------------------------------------------------------------- 1 | def selection_sort(lst): 2 | 3 | for passes in range(len(lst)-1, 0, -1): # requires n-1 passes 4 | 5 | max_position = 0 6 | 7 | for loc in range(1, passes+1): 8 | # selecting position of highest element 9 | 10 | if lst[loc] > lst[max_position]: 11 | max_position = loc 12 | 13 | lst[passes], lst[max_position] = lst[max_position], lst[passes] 14 | 15 | return lst 16 | 17 | 18 | arr = [21, 2, 45.2, 3, 65, 6] 19 | print(selection_sort(arr)) 20 | -------------------------------------------------------------------------------- /Data structure/Stack Implementation.py: -------------------------------------------------------------------------------- 1 | class Stack(object): 2 | 3 | def __init__(self): 4 | self.lst = [] 5 | 6 | def is_empty(self): 7 | return self.lst == [] 8 | 9 | def get_size(self): 10 | return len(self.lst) 11 | 12 | def push(self, item): 13 | self.lst.append(item) 14 | 15 | def pop(self): 16 | if self.is_empty(): 17 | return 'stack underflow' 18 | return self.lst.pop() 19 | 20 | def display(self): 21 | print(*self.lst) 22 | 23 | 24 | stack = Stack() 25 | # print(stack.is_empty()) 26 | # print(stack.get_size()) 27 | # print(stack.pop()) 28 | stack.push(1) 29 | stack.push(2) 30 | stack.push(3) 31 | # print(stack.get_size()) 32 | print(stack.pop()) 33 | print(stack.display()) 34 | print(stack.pop()) 35 | print(stack.display()) -------------------------------------------------------------------------------- /Data structure/Tree/Nodes and References.py: -------------------------------------------------------------------------------- 1 | class BinaryTree(object): 2 | 3 | def __init__(self, root_element): 4 | self.key = root_element 5 | self.leftChild = None 6 | self.rightChild = None 7 | 8 | def insert_left(self, new_node): 9 | if self.leftChild is None: 10 | self.leftChild = BinaryTree(new_node) 11 | else: 12 | subtree = BinaryTree(new_node) 13 | subtree.leftChild = self.leftChild 14 | self.leftChild = subtree 15 | 16 | def insert_right(self, new_node): 17 | if self.rightChild is None: 18 | self.rightChild = BinaryTree(new_node) 19 | else: 20 | subtree = BinaryTree(new_node) 21 | subtree.rightChild = self.rightChild 22 | self.rightChild = subtree 23 | 24 | def get_right_child(self): 25 | return self.rightChild 26 | 27 | def get_left_child(self): 28 | return self.leftChild 29 | 30 | def get_root_value(self): 31 | return self.key 32 | 33 | def set_root_value(self, value): 34 | self.key = value 35 | 36 | 37 | my_tree = BinaryTree('a') 38 | print(my_tree.get_root_value()) 39 | 40 | print(my_tree.get_right_child()) 41 | 42 | my_tree.insert_left('b') 43 | print(my_tree.get_left_child()) 44 | print(my_tree.get_left_child().get_root_value()) 45 | 46 | my_tree.insert_right('c') 47 | print(my_tree.get_right_child()) 48 | print(my_tree.get_right_child().get_root_value()) 49 | 50 | -------------------------------------------------------------------------------- /Data structure/Tree/Tree representation.py: -------------------------------------------------------------------------------- 1 | def binary_tree(root): 2 | return [root, [], []] 3 | 4 | 5 | def insert_left(root, new_branch): 6 | left = root.pop(1) 7 | 8 | if len(left) > 1: 9 | root.insert(1, [new_branch, left, [] ]) 10 | else: 11 | root.insert(1,[new_branch, [], []]) 12 | 13 | return root 14 | 15 | 16 | def insert_right(root, new_branch): 17 | right = root.pop(2) 18 | 19 | if len(right) > 1: 20 | root.insert(2, [new_branch, [], right]) 21 | else: 22 | root.insert(2, [new_branch, [], []]) 23 | 24 | return root 25 | 26 | 27 | def get_root_value(root): 28 | return root[0] 29 | 30 | 31 | def set_root_value(root,new_val): 32 | root[0] = new_val 33 | 34 | 35 | def get_left_child(root): 36 | return root[1] 37 | 38 | 39 | def get_right_child(root): 40 | return root[2] 41 | 42 | 43 | root_node = binary_tree('a') 44 | print('root node: ',root_node) 45 | 46 | insert_left(root_node,'b') 47 | print('left branch: ',get_left_child(root_node)) 48 | 49 | insert_right(root_node, 'c') 50 | print('right branch: ',get_right_child(root_node)) 51 | 52 | insert_right(root_node, 'd') 53 | print('right branch: ',get_right_child(root_node)) 54 | 55 | print('tree looks like: ',binary_tree(root_node)) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Nirmal Silwal 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 | -------------------------------------------------------------------------------- /Logical problems/Balanced Paranthesis.py: -------------------------------------------------------------------------------- 1 | def check_paranthesis_balancing(paran_str, open, close, d): 2 | stack = [] 3 | #Edge cases 4 | if len(paran_str) == 0: 5 | return 'no string provided to check paranthesis matching' 6 | 7 | elif len(paran_str) == 1: 8 | return 'paranthesis not balanced' 9 | 10 | elif len(paran_str)%2 != 0: 11 | return 'paranthesis not balanced' 12 | 13 | elif len(paran_str) > 1: 14 | for index, paranthesis in enumerate(paran_str): 15 | 16 | if paranthesis in open: 17 | stack.append(paranthesis) 18 | 19 | if paranthesis in close: 20 | #another tricky edge case 21 | if index == 0 or len(stack) == 0: 22 | return 'oye, paranthesis not balanced' 23 | 24 | elif d[paranthesis] == stack[-1]: 25 | stack.pop() 26 | continue 27 | 28 | else: 29 | stack.append(paranthesis) 30 | 31 | return 'balanced' if stack == [] else 'not balanced' 32 | 33 | 34 | 35 | paran_str = "{()}[]" 36 | #'{[()()]}((' 37 | 38 | d = { '}':'{', 39 | ']':'[', 40 | ')':'(' 41 | } 42 | open = d.values() 43 | close = d.keys() 44 | 45 | print(check_paranthesis_balancing(paran_str, open, close, d)) -------------------------------------------------------------------------------- /Logical problems/Bridgelabz interview/Bridgelabz 4.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | 3 | def __init__(self, data): 4 | self.data = data 5 | self.next = None 6 | 7 | 8 | def traverse_list(head): 9 | while head.next is not None: 10 | print(head.data) 11 | head = head.next 12 | 13 | print(head.data) 14 | 15 | 16 | def reverse_list(head): 17 | 18 | # edge case 19 | if head.next is None or head is None: 20 | return head 21 | 22 | arr_data = [] 23 | cursor = head 24 | while cursor.next is not None: 25 | arr_data.append(cursor.data) 26 | cursor = cursor.next 27 | 28 | arr_data.append(cursor.data) 29 | 30 | index = len(arr_data)-1 31 | 32 | while head.next is not None: 33 | head.data = arr_data[index] 34 | print(head.data) 35 | index -= 1 36 | head = head.next 37 | else: 38 | head.data = arr_data[index] 39 | print(head.data) 40 | 41 | 42 | first_node = Node(1) 43 | second_node = Node(2) 44 | third_node = Node(3) 45 | fourth_node = Node(4) 46 | 47 | # linking the nodes to make singly linked list 48 | 49 | first_node.next = second_node 50 | second_node.next = third_node 51 | third_node.next = fourth_node 52 | 53 | traverse_list(first_node) 54 | 55 | print('after reversing the list: ') 56 | 57 | reverse_list(first_node) 58 | -------------------------------------------------------------------------------- /Logical problems/Bridgelabz interview/bridgelabz 1.py: -------------------------------------------------------------------------------- 1 | user_name = input('enter your name: ') 2 | 3 | while len(user_name) < 3: 4 | print('please enter at least 3 character! ') 5 | user_name = input('enter your name: ') 6 | else: 7 | template = f'Hello {user_name}, How are you?' 8 | 9 | print(template) 10 | -------------------------------------------------------------------------------- /Logical problems/Bridgelabz interview/bridgelabz 2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Stopwatch program 3 | """ 4 | 5 | import time 6 | 7 | start_click = time.time() 8 | 9 | tmp = 0 10 | for i in range(400000): 11 | """ 12 | just to demonstrate how much time has elapsed running this loop 13 | """ 14 | tmp += i 15 | 16 | end_click = time.time() 17 | 18 | total = (end_click - start_click)*1000 19 | print(f'time elapsed: {total} milliseconds') -------------------------------------------------------------------------------- /Logical problems/Bridgelabz interview/bridgelabz 3.py: -------------------------------------------------------------------------------- 1 | my_string = input('enter any string: ') 2 | 3 | 4 | def is_palindrome(word): 5 | return word == word[::-1] 6 | 7 | 8 | def find_permutations(sen): 9 | result = [] 10 | 11 | if len(sen) == 1: 12 | result = [sen] 13 | else: 14 | for i, letter in enumerate(sen): 15 | 16 | for permute in find_permutations(sen[:i] + sen[i+1:]): 17 | 18 | result.append(letter + permute) 19 | 20 | return result 21 | 22 | 23 | def is_possible(word): 24 | # let's make the permutation of given string and check till any combination satisfies or all finishes 25 | permutation = find_permutations(word) 26 | 27 | counter = 0 28 | 29 | while counter < len(permutation): 30 | 31 | if is_palindrome(permutation[counter]): 32 | return True 33 | 34 | counter += 1 35 | else: 36 | return False 37 | 38 | 39 | if __name__ == "__main__": 40 | if is_possible(my_string): 41 | print(f'palindrome possible for given string: {my_string}') 42 | else: 43 | print('palindrome not possible') 44 | -------------------------------------------------------------------------------- /Logical problems/Bridgelabz interview/bridgelabz 4a.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | 3 | def __init__(self, data): 4 | self.data = data 5 | self.next = None 6 | 7 | 8 | def traverse_list(head): 9 | while head.next is not None: 10 | print(head.data) 11 | head = head.next 12 | 13 | print(head.data) 14 | 15 | 16 | def reverse_me(head): 17 | p1 = head 18 | p2 = head.next 19 | 20 | p1.next = None 21 | while p2 is not None: 22 | temp = p2 23 | p2 = p2.next 24 | 25 | temp.next = p1 26 | p1 = temp 27 | 28 | return p1 29 | 30 | 31 | first_node = Node(1) 32 | second_node = Node(2) 33 | third_node = Node(3) 34 | fourth_node = Node(4) 35 | 36 | # linking the nodes to make singly linked list 37 | 38 | first_node.next = second_node 39 | second_node.next = third_node 40 | third_node.next = fourth_node 41 | 42 | rev = reverse_me(first_node) 43 | traverse_list(rev) -------------------------------------------------------------------------------- /Logical problems/Bridgelabz interview/permutations.py: -------------------------------------------------------------------------------- 1 | def permutation(sen): 2 | 3 | result = [] 4 | 5 | if len(sen) == 1: 6 | result = [sen] 7 | else: 8 | for i, letter in enumerate(sen): 9 | 10 | before_letter = sen[:i] 11 | after_letter = sen[i+1:] 12 | 13 | print(f'current letter {letter} and index {i} ') 14 | 15 | for permute in permutation(before_letter + after_letter): 16 | 17 | print('permute here: ', permute) 18 | 19 | result.append(letter+permute) 20 | 21 | print('result till now: ',result) 22 | 23 | return result 24 | 25 | 26 | print('=========================== OUTPUT ========================================') 27 | output = permutation('abc') 28 | print(output) 29 | -------------------------------------------------------------------------------- /Logical problems/Day-1.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 2, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "data": { 10 | "text/plain": [ 11 | "'HELLO'" 12 | ] 13 | }, 14 | "execution_count": 2, 15 | "metadata": {}, 16 | "output_type": "execute_result" 17 | } 18 | ], 19 | "source": [ 20 | "s = 'hello'\n", 21 | "s.upper()" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": 3, 27 | "metadata": {}, 28 | "outputs": [ 29 | { 30 | "data": { 31 | "text/plain": [ 32 | "'hello'" 33 | ] 34 | }, 35 | "execution_count": 3, 36 | "metadata": {}, 37 | "output_type": "execute_result" 38 | } 39 | ], 40 | "source": [ 41 | "s.lower()" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": 8, 47 | "metadata": {}, 48 | "outputs": [ 49 | { 50 | "name": "stdout", 51 | "output_type": "stream", 52 | "text": [ 53 | "('singleton',)\n" 54 | ] 55 | } 56 | ], 57 | "source": [ 58 | "a='singleton',\n", 59 | "print(a)" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": 1, 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "def solution(num1,num2):\n", 69 | " return num1+num2" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": 5, 75 | "metadata": {}, 76 | "outputs": [ 77 | { 78 | "name": "stdout", 79 | "output_type": "stream", 80 | "text": [ 81 | "Collecting nose\n", 82 | " Downloading https://files.pythonhosted.org/packages/15/d8/dd071918c040f50fa1cf80da16423af51ff8ce4a0f2399b7bf8de45ac3d9/nose-1.3.7-py3-none-any.whl (154kB)\n", 83 | "Installing collected packages: nose\n", 84 | "Successfully installed nose-1.3.7\n" 85 | ] 86 | } 87 | ], 88 | "source": [ 89 | "# !pip install nose" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": 6, 95 | "metadata": {}, 96 | "outputs": [ 97 | { 98 | "name": "stdout", 99 | "output_type": "stream", 100 | "text": [ 101 | "ALL TEST CASES PASSED\n" 102 | ] 103 | } 104 | ], 105 | "source": [ 106 | "from nose.tools import assert_equal\n", 107 | "\n", 108 | "class SolutionTest(object):\n", 109 | " \n", 110 | " def test(self,sol):\n", 111 | " assert_equal(sol(2,2),4)\n", 112 | " assert_equal(sol(1,2),3)\n", 113 | " \n", 114 | " print('ALL TEST CASES PASSED')\n", 115 | " \n", 116 | "obj = SolutionTest()\n", 117 | "obj.test(solution)" 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": 19, 123 | "metadata": {}, 124 | "outputs": [ 125 | { 126 | "data": { 127 | "text/plain": [ 128 | "55" 129 | ] 130 | }, 131 | "execution_count": 19, 132 | "metadata": {}, 133 | "output_type": "execute_result" 134 | } 135 | ], 136 | "source": [ 137 | "def sum1(n):\n", 138 | " final_sum=0\n", 139 | " \n", 140 | " for i in range(1,n+1):\n", 141 | " final_sum += i\n", 142 | " \n", 143 | " return final_sum\n", 144 | "\n", 145 | "sum1(10)" 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": 22, 151 | "metadata": {}, 152 | "outputs": [ 153 | { 154 | "data": { 155 | "text/plain": [ 156 | "55" 157 | ] 158 | }, 159 | "execution_count": 22, 160 | "metadata": {}, 161 | "output_type": "execute_result" 162 | } 163 | ], 164 | "source": [ 165 | "def sum2(n):\n", 166 | " return (n*(n+1))//2\n", 167 | "\n", 168 | "sum2(10)" 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": 23, 174 | "metadata": {}, 175 | "outputs": [ 176 | { 177 | "name": "stdout", 178 | "output_type": "stream", 179 | "text": [ 180 | "7.24 µs ± 925 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n" 181 | ] 182 | } 183 | ], 184 | "source": [ 185 | "%timeit sum1(100)" 186 | ] 187 | }, 188 | { 189 | "cell_type": "code", 190 | "execution_count": 24, 191 | "metadata": {}, 192 | "outputs": [ 193 | { 194 | "name": "stdout", 195 | "output_type": "stream", 196 | "text": [ 197 | "273 ns ± 31.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n" 198 | ] 199 | } 200 | ], 201 | "source": [ 202 | "%timeit sum2(100)" 203 | ] 204 | }, 205 | { 206 | "cell_type": "code", 207 | "execution_count": null, 208 | "metadata": {}, 209 | "outputs": [], 210 | "source": [] 211 | } 212 | ], 213 | "metadata": { 214 | "kernelspec": { 215 | "display_name": "Python 3", 216 | "language": "python", 217 | "name": "python3" 218 | }, 219 | "language_info": { 220 | "codemirror_mode": { 221 | "name": "ipython", 222 | "version": 3 223 | }, 224 | "file_extension": ".py", 225 | "mimetype": "text/x-python", 226 | "name": "python", 227 | "nbconvert_exporter": "python", 228 | "pygments_lexer": "ipython3", 229 | "version": "3.6.9" 230 | } 231 | }, 232 | "nbformat": 4, 233 | "nbformat_minor": 2 234 | } 235 | -------------------------------------------------------------------------------- /Logical problems/Find Missing Element.py: -------------------------------------------------------------------------------- 1 | def find_missing(arr1, arr2): 2 | miss = [] 3 | for i in arr1: 4 | if i not in arr2: 5 | miss.append(i) 6 | 7 | return miss 8 | 9 | 10 | ##ANOTHER APPROACH 11 | 12 | def finder(arr1,arr2): 13 | arr1.sort() 14 | arr2.sort() 15 | 16 | for num1, num2 in zip(arr1, arr2): 17 | if num1 != num2: 18 | return num1 19 | 20 | return arr1[-1] 21 | 22 | ### 23 | 24 | 25 | ##ANOTHER APPROACH using XOR trick for optimal solution 26 | 27 | def finder2(arr1,arr2): 28 | result = 0 29 | for item in arr1+arr2: 30 | result ^= item 31 | 32 | return result 33 | 34 | ### 35 | 36 | 37 | arr1 = [1,2,3,4] 38 | arr2 = [3,1,4] 39 | 40 | # missing = find_missing(arr1, arr2) 41 | # print(f'missing element is: {missing}') 42 | # print('missing element is',*missing) 43 | 44 | # print(finder(arr1, arr2)) 45 | 46 | print(finder2(arr1,arr2)) -------------------------------------------------------------------------------- /Logical problems/FizzBuzz_hackerearth.py: -------------------------------------------------------------------------------- 1 | # Write a program which iterates the integers from 1 to 50. For multiples of three print "Fizz" instead of the 2 | # number and for the multiples of five print "Buzz". For numbers which are multiples of both three 3 | # and five print "FizzBuzz". 4 | 5 | testcases = int(input()) 6 | if 1 <= testcases <= 10: 7 | lst = list(map (int, input().split())) 8 | 9 | for N in lst: 10 | for displayCount in range(1,N+1): 11 | if displayCount % 3 == 0 and displayCount % 5 == 0: 12 | print('FizzBuzz') 13 | elif displayCount % 3 == 0: 14 | print('Fizz') 15 | elif displayCount % 5 == 0: 16 | print('Buzz') 17 | else: 18 | print(displayCount) 19 | -------------------------------------------------------------------------------- /Logical problems/Longest Continuous Sum.py: -------------------------------------------------------------------------------- 1 | def largest_continuous_sum(lst): 2 | 3 | max_list = [] 4 | 5 | for i in range(len(lst)): 6 | consecutive_sum = [] 7 | total = lst[i] 8 | for next_element in lst[i+1:]: 9 | total = total + next_element 10 | consecutive_sum.append(total) 11 | 12 | max_list.append(max(consecutive_sum)) 13 | 14 | return max(max_list) 15 | 16 | 17 | 18 | arr = [1,2,-1,3,4,10,10,-10,-1] 19 | 20 | print(largest_continuous_sum(arr)) -------------------------------------------------------------------------------- /Logical problems/Pair Sum.py: -------------------------------------------------------------------------------- 1 | def pair_sum(lst, total): 2 | item_pairs=[] 3 | for i in range(len(lst)): 4 | for j in lst[i+1:]: 5 | if lst[i] + j == total: 6 | item_pairs.append([lst[i],j]) 7 | 8 | unique_pairs = [] 9 | for pair in item_pairs: 10 | if pair not in unique_pairs: 11 | unique_pairs.append(pair) 12 | 13 | return unique_pairs 14 | 15 | 16 | lst = [1,2,3,2,4,0,2] 17 | total = 4 18 | result = pair_sum(lst, total) 19 | print(f'given input list is : {lst}') 20 | print(f'Total unique pairs with sum {total} is {len(result)}') 21 | print(f'unique pairs are : {result}') -------------------------------------------------------------------------------- /Logical problems/Rotate Array.py: -------------------------------------------------------------------------------- 1 | def rotate_arr(lst, how_much): 2 | tmp = lst[:how_much] 3 | new_lst = lst[how_much:] 4 | new_lst.extend(tmp) 5 | 6 | return new_lst 7 | 8 | ##ANOTHER APPROACH 9 | 10 | def left_shift(lst): 11 | tmp = lst[0] 12 | for i in range(len(lst)-1): 13 | lst[i] = lst[i + 1] 14 | 15 | lst[-1] = tmp 16 | 17 | return lst 18 | 19 | def rotate_by_shifting(lst, how_much): 20 | result = lst 21 | for rotation in range(how_much): 22 | result = left_shift(result) 23 | 24 | return result 25 | 26 | #### 27 | 28 | lst = [1,2,3,4,5,6,7] 29 | how_much = 2 30 | result = rotate_by_shifting(lst,how_much) 31 | print(result) -------------------------------------------------------------------------------- /Logical problems/anagram.py: -------------------------------------------------------------------------------- 1 | def anagram_check1(sen1, sen2): 2 | sen1 = sen1.replace(' ','').lower() 3 | sen2 = sen2.replace(' ','').lower() 4 | 5 | return 'anagram' if sorted(sen1) == sorted(sen2) else 'not anagram' 6 | 7 | 8 | def anagram_check2(sen1, sen2): 9 | sen1 = sen1.replace(' ','').lower() 10 | sen2 = sen2.replace(' ','').lower() 11 | dic = {} 12 | for character in sen1: 13 | if character in dic: 14 | dic[character] += 1 15 | else: 16 | dic[character] = 1 17 | 18 | for character in sen2: 19 | if character in dic: 20 | dic[character] -= 1 21 | else: 22 | dic[character] = 1 23 | 24 | for key in dic: 25 | if dic[key]>0: 26 | return 'not anagram' 27 | return 'anagram' 28 | 29 | print(anagram_check2('dogfx`','ogd')) 30 | -------------------------------------------------------------------------------- /Logical problems/rotate pdf.py: -------------------------------------------------------------------------------- 1 | from PyPDF2 import PdfFileReader, PdfFileWriter 2 | 3 | output_dir = 'rotated\\' 4 | file_name = 'DAA 5.pdf' 5 | 6 | pdf_in = open('inputs\\'+file_name, 'rb') 7 | 8 | pdf_reader = PdfFileReader(pdf_in) 9 | pdf_writer = PdfFileWriter() 10 | 11 | for page_num in range(pdf_reader.numPages): 12 | page = pdf_reader.getPage(page_num) 13 | page.rotateCounterClockwise(180) 14 | pdf_writer.addPage(page) 15 | 16 | pdf_out = open(output_dir + file_name, 'wb') 17 | pdf_writer.write(pdf_out) 18 | 19 | pdf_out.close() 20 | pdf_in.close() 21 | -------------------------------------------------------------------------------- /Logical problems/sum digits.py: -------------------------------------------------------------------------------- 1 | def sum_digits_of_integer(num): 2 | """ 3 | For example: if n = 4321, return 4+3+2+1 4 | """ 5 | 6 | total = 0 7 | while num != 0: 8 | last_digit = num % 10 9 | total += last_digit 10 | num //= 10 11 | 12 | return total 13 | 14 | 15 | print(sum_digits_of_integer(4321)) 16 | 17 | -------------------------------------------------------------------------------- /Logical problems/word split.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function called word_split() which takes in a string phrase and a set list_of_words. 3 | The function will then determine if it is possible to split the string in a way in which words 4 | can be made from the list of words. You can assume the phrase will only contain words found in the 5 | dictionary if it is completely splittable. 6 | """ 7 | 8 | 9 | def word_split(phrase, list_of_words): 10 | 11 | if len(list_of_words) == len(set(list_of_words)): 12 | dic = {word:1 for word in list_of_words} 13 | 14 | else: 15 | dic = {} 16 | # if any duplicates in list_of_words 17 | for words in list_of_words: 18 | if words not in dic.keys(): 19 | dic[words] = 1 20 | else: 21 | dic[words] += 1 22 | 23 | result = [] 24 | for keys in dic.keys(): 25 | if keys in phrase: 26 | result.append(keys) 27 | 28 | result_str = ''.join(result) 29 | 30 | if len(result_str) == len(phrase): 31 | return result 32 | else: 33 | return [] 34 | 35 | 36 | print(word_split('themanran', ['the','ran','man'])) 37 | print(word_split('ilovedogsJohn',['i','am','a','dogs','lover','a','love','John'])) 38 | print(word_split('themanran',['clown','ran','man'])) 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Problem-Solving 2 | 3 | :dart: I have prepared this repository during my coding ***interview preparation***. Basically I have implemented various logical problems in **Python**. 4 | 5 | :gem: Various **Data Structures implementation along with the interview problem** associated with the topics are solved. 6 | 7 | :pencil2: Filename is self explanatory for those directly wanting to jump over the interview problem. 8 | 9 | :point_right: *Also you will find my solutions easy to understand due to standard naming convention.* 10 | 11 | :gem: **CodingBlocks** folder has all the assignment and practice coursework while taking *Data Structure using Java* course. 12 | 13 | -------------------------------------------------------------------------------- /Recursion/Change coin problem optimised.py: -------------------------------------------------------------------------------- 1 | # using recursion 2 | def coin_recursion(target, coins): 3 | 4 | min_coins = target # just setting some default value 5 | 6 | if target in coins: 7 | return 1 8 | 9 | for money in [c for c in coins if c <= target]: 10 | 11 | num_coins = 1 + coin_recursion(target-money, coins) 12 | 13 | if num_coins < min_coins: 14 | min_coins = num_coins 15 | 16 | return min_coins 17 | 18 | 19 | # DYNAMIC APPROACH USING MEMOIZATION 20 | 21 | def dynamic_coin_rec(target, coins, cache_results): 22 | 23 | min_coins = target 24 | 25 | if target in coins: 26 | # saving for future uses in same value of target, faster access with cost of storage 27 | cache_results[target] = 1 28 | return 1 29 | 30 | elif cache_results[target] > 0: 31 | return cache_results[target] 32 | 33 | else: 34 | for money in [c for c in coins if c <= target]: 35 | 36 | num_coins = 1 + dynamic_coin_rec(target-money, coins, cache_results) 37 | 38 | if num_coins < min_coins: 39 | min_coins = num_coins 40 | 41 | cache_results[target] = min_coins 42 | 43 | return min_coins 44 | 45 | 46 | print(coin_recursion(3,[1,5,10])) 47 | 48 | target = 60 49 | cache = [0]*(target+1) 50 | print(dynamic_coin_rec(target,[1,5,10,25],cache)) 51 | -------------------------------------------------------------------------------- /Recursion/Coin Change Problem.py: -------------------------------------------------------------------------------- 1 | def rec_coin(target, coins): 2 | 3 | min_coins = target 4 | 5 | if target in coins: 6 | return 1 7 | 8 | for chutta in [paisa for paisa in coins if paisa <= target]: 9 | 10 | num_coins = 1 + rec_coin(target-chutta, coins) 11 | 12 | if num_coins < min_coins: 13 | min_coins = num_coins 14 | 15 | return min_coins 16 | 17 | 18 | all_coins = [1,5,10] 19 | total = 15 20 | print(rec_coin(total, all_coins)) 21 | 22 | ''' 23 | OUTPUT: 2 indicates we need minimum of 2 coins change to make total of 15 from given changes of coin 24 | 5+10=15 so len(5,10) is 2 25 | ''' -------------------------------------------------------------------------------- /Recursion/Fibonacci series.py: -------------------------------------------------------------------------------- 1 | # iteratively 2 | def fibonacci_iter(n): 3 | a, b = 0, 1 4 | for i in range(n): 5 | a, b = b, a+b 6 | 7 | return a 8 | 9 | 10 | # using recursion 11 | def fibonacci_recur(n): 12 | # base case 13 | if n == 0 or n == 1: 14 | return n 15 | 16 | return fibonacci_recur(n-1)+fibonacci_recur(n-2) 17 | 18 | 19 | # using Memoization 20 | n = 10 21 | cache = [None]*(n+1) 22 | 23 | 24 | def fibonacci_dynamic(n): 25 | # base case 26 | if n == 0 or n == 1: 27 | return n 28 | 29 | # check cache 30 | if cache[n] is not None: 31 | return cache[n] 32 | 33 | # keep setting cache 34 | cache[n] = fibonacci_dynamic(n-1) + fibonacci_dynamic(n-2) 35 | 36 | return cache[n] 37 | 38 | 39 | print(fibonacci_iter(n)) 40 | print(fibonacci_recur(n)) 41 | print(fibonacci_dynamic(n)) 42 | -------------------------------------------------------------------------------- /Recursion/Memoization factorial.py: -------------------------------------------------------------------------------- 1 | class Memoize(object): 2 | 3 | def __init__(self, func): 4 | self.func = func 5 | self.memo = {} 6 | 7 | def __call__(self, *args): 8 | if args not in self.memo: 9 | self.memo[args] = self.func(*args) 10 | 11 | return self.memo[args] 12 | 13 | 14 | def factorial(num): 15 | if num < 2: 16 | return 1 17 | 18 | return num * factorial(num - 1) 19 | 20 | 21 | fact = Memoize(factorial) 22 | print(fact(4)) 23 | -------------------------------------------------------------------------------- /Recursion/Permutation string.py: -------------------------------------------------------------------------------- 1 | def permutation(sen): 2 | result = [] 3 | # base case 4 | if len(sen) == 1: 5 | result = [sen] 6 | else: 7 | for index, letter in enumerate(sen): 8 | 9 | for perm in permutation(sen[:index] + sen[index+1:]): 10 | 11 | result.append(letter + perm) 12 | 13 | return result 14 | 15 | 16 | per_str = 'abc' 17 | output = permutation(per_str) 18 | # print(output) 19 | -------------------------------------------------------------------------------- /Recursion/Recursion Cumulative SUM.py: -------------------------------------------------------------------------------- 1 | def rec_sum(num): 2 | while num > 0: 3 | return num + (0 if rec_sum(num-1) is None else rec_sum(num-1)) 4 | 5 | 6 | # Another way of solving 7 | def rec_sum2(num): 8 | if num == 0: 9 | return 0 10 | elif num < 0: 11 | return 'not for negative numbers' 12 | else: 13 | return num + rec_sum2(num-1) 14 | 15 | 16 | # Another way of solving 17 | def rec_sum3(num): 18 | if num == 0: 19 | return 0 20 | else: 21 | return num + rec_sum3(num-1) 22 | 23 | 24 | print(rec_sum(4)) 25 | print(rec_sum2(4)) 26 | print(rec_sum3(4)) 27 | 28 | 29 | ''' 30 | Finding the cumulative sum of given number 31 | For example, if n=4 , return 4+3+2+1+0, which is 10. 32 | ''' -------------------------------------------------------------------------------- /Recursion/Recursion factorial.py: -------------------------------------------------------------------------------- 1 | def factorial(num): 2 | if num == 0: 3 | return 1 4 | else: 5 | return num * factorial(num-1) 6 | 7 | 8 | print(factorial(5)) 9 | -------------------------------------------------------------------------------- /Recursion/memoization.py: -------------------------------------------------------------------------------- 1 | # storing known results in cache 2 | factorial_memo = {} 3 | 4 | 5 | def factorial(n): 6 | if n < 2: 7 | return 1 8 | 9 | if n not in factorial_memo: 10 | factorial_memo[n] = n * factorial(n-1) 11 | 12 | return factorial_memo[n] 13 | 14 | 15 | print(factorial_memo) 16 | print(factorial(5)) 17 | print(factorial_memo) 18 | print(factorial(4)) 19 | print(factorial_memo) 20 | print(factorial(7)) 21 | print(factorial_memo) 22 | 23 | -------------------------------------------------------------------------------- /Recursion/reverse string.py: -------------------------------------------------------------------------------- 1 | # 1st approach: python trick 2 | def reverse1(sen): 3 | return sen[::-1] 4 | 5 | 6 | # 2nd approach: using recursion 7 | def reverse_recursion(sen): 8 | # base case 9 | if len(sen) == 1: 10 | return sen 11 | 12 | # recursive case 13 | return reverse_recursion(sen[1:]) + sen[0] 14 | 15 | 16 | # 3rd approach: using stack 17 | def reverse2(sen): 18 | 19 | stack = [char for char in sen] 20 | reversed_stack = [stack.pop() for _ in range(len(stack))] 21 | 22 | return ''.join(reversed_stack) 23 | 24 | 25 | # 4th approach: using stack long way 26 | def reverse3(sen): 27 | stack = [] 28 | for character in sen: 29 | stack.append(character) 30 | 31 | reversed_stack = [] 32 | for i in range(len(stack)): 33 | reversed_stack.append(stack.pop()) 34 | 35 | return ''.join(reversed_stack) 36 | 37 | 38 | my_string = 'hello world' 39 | 40 | print(reverse1(my_string)) 41 | print(reverse2(my_string)) 42 | print(reverse3(my_string)) 43 | 44 | print('using recursion:', reverse_recursion(my_string)) -------------------------------------------------------------------------------- /Recursion/sum of digits.py: -------------------------------------------------------------------------------- 1 | def sum_digits(num): 2 | if len(str(num)) == 1: 3 | return num 4 | else: 5 | return num % 10 + sum_digits(num // 10) 6 | 7 | 8 | print(sum_digits(4321)) 9 | -------------------------------------------------------------------------------- /Udacity Data Structure and Algorithms Nanodegree/Introduction/AssertionExample.py: -------------------------------------------------------------------------------- 1 | 2 | # Program defensively: 3 | # 4 | # What do you do if your input is invalid? For example what should 5 | # happen when date 1 is not before date 2? 6 | # 7 | # Add an assertion to the code for daysBetweenDates to give 8 | # an assertion failure when the inputs are invalid. This should 9 | # occur when the first date is not before the second date. 10 | # 11 | 12 | def nextDay(year, month, day): 13 | """Simple version: assume every month has 30 days""" 14 | if day < 30: 15 | return year, month, day + 1 16 | else: 17 | if month == 12: 18 | return year + 1, 1, 1 19 | else: 20 | return year, month + 1, 1 21 | 22 | 23 | def dateIsBefore(year1, month1, day1, year2, month2, day2): 24 | """Returns True if year1-month1-day1 is before 25 | year2-month2-day2. Otherwise, returns False.""" 26 | if year1 < year2: 27 | return True 28 | if year1 == year2: 29 | if month1 < month2: 30 | return True 31 | if month1 == month2: 32 | return day1 < day2 33 | return False 34 | 35 | 36 | def daysBetweenDates(year1, month1, day1, year2, month2, day2): 37 | """Returns the number of days between year1/month1/day1 38 | and year2/month2/day2. Assumes inputs are valid dates 39 | in Gregorian calendar.""" 40 | # program defensively! Add an assertion if the input is not valid! 41 | assert not dateIsBefore(year2, month2, day2, year1, month1, day1) 42 | days = 0 43 | while dateIsBefore(year1, month1, day1, year2, month2, day2): 44 | year1, month1, day1 = nextDay(year1, month1, day1) 45 | days += 1 46 | return days 47 | 48 | 49 | def test(): 50 | test_cases = [((2012, 9, 30, 2012, 10, 30), 30), 51 | ((2012, 1, 1, 2013, 1, 1), 360), 52 | ((2012, 9, 1, 2012, 9, 4), 3), 53 | ((2013, 1, 1, 1999, 12, 31), "AssertionError")] 54 | 55 | for (args, answer) in test_cases: 56 | try: 57 | result = daysBetweenDates(*args) 58 | if result == answer and answer != "AssertionError": 59 | print("Test case passed!") 60 | 61 | else: 62 | print("Test with data:", args, "failed") 63 | 64 | except AssertionError: 65 | if answer == "AssertionError": 66 | print("Nice job! Test case {0} correctly raises AssertionError!\n".format(args)) 67 | else: 68 | print("Check your work! Test case {0} should not raise AssertionError!\n".format(args)) 69 | 70 | 71 | test() -------------------------------------------------------------------------------- /Udacity Data Structure and Algorithms Nanodegree/Introduction/Efficiency.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Big O Notation" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "One of the main goals of this lesson is to help you develop your ability to look at some code and identify its time complexity—and then describe this time complexity using Big O notation.\n", 15 | "\n", 16 | "We will use this graph as a referece and reminder of the importance of the run time of an algorithm. We have the number of inputs (n) on the X axis and the the number of operations required (N) on the Y axis.\n", 17 | "\n", 18 | "\"Drawing\"\n", 19 | "\n", 20 | "[\"Comparison of computational complexity\"](https://commons.wikimedia.org/wiki/File:Comparison_computational_complexity.svg) by Cmglee. Used under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/deed.en)." 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "#### Quadratic Example" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 1, 33 | "metadata": {}, 34 | "outputs": [ 35 | { 36 | "name": "stdout", 37 | "output_type": "stream", 38 | "text": [ 39 | "Items: 1, 1\n", 40 | "Items: 1, 2\n", 41 | "Items: 1, 3\n", 42 | "Items: 1, 4\n", 43 | "Items: 2, 1\n", 44 | "Items: 2, 2\n", 45 | "Items: 2, 3\n", 46 | "Items: 2, 4\n", 47 | "Items: 3, 1\n", 48 | "Items: 3, 2\n", 49 | "Items: 3, 3\n", 50 | "Items: 3, 4\n", 51 | "Items: 4, 1\n", 52 | "Items: 4, 2\n", 53 | "Items: 4, 3\n", 54 | "Items: 4, 4\n", 55 | "CPU times: user 3 µs, sys: 0 ns, total: 3 µs\n", 56 | "Wall time: 7.15 µs\n" 57 | ] 58 | } 59 | ], 60 | "source": [ 61 | "# O(n^2)\n", 62 | "\n", 63 | "def Quad_Example(our_list):\n", 64 | " for first_loop_item in our_list:\n", 65 | " for second_loop_item in our_list:\n", 66 | " print (\"Items: {}, {}\".format(first_loop_item,second_loop_item))\n", 67 | " \n", 68 | " \n", 69 | "Quad_Example([1,2,3,4])\n", 70 | "\n", 71 | "%time" 72 | ] 73 | }, 74 | { 75 | "cell_type": "markdown", 76 | "metadata": {}, 77 | "source": [ 78 | "#### Log Linear Example " 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 4, 84 | "metadata": {}, 85 | "outputs": [ 86 | { 87 | "name": "stdout", 88 | "output_type": "stream", 89 | "text": [ 90 | "[0, 4, 4, 11, 12, 23, 35, 56, 65, 65, 84, 90]\n", 91 | "CPU times: user 4 µs, sys: 1 µs, total: 5 µs\n", 92 | "Wall time: 6.68 µs\n" 93 | ] 94 | } 95 | ], 96 | "source": [ 97 | "# O(nlogn)\n", 98 | "\n", 99 | "# Don't worry about how this algorithm works, we will cover it later in the course!\n", 100 | "\n", 101 | "def Log_Linear_Example(our_list):\n", 102 | " \n", 103 | " if len(our_list) < 2:\n", 104 | " return our_list\n", 105 | " \n", 106 | " else:\n", 107 | " mid = len(our_list)//2\n", 108 | " left = our_list[:mid]\n", 109 | " right = our_list[mid:]\n", 110 | "\n", 111 | " Log_Linear_Example(left)\n", 112 | " Log_Linear_Example(right)\n", 113 | "\n", 114 | " i = 0\n", 115 | " j = 0\n", 116 | " k = 0\n", 117 | "\n", 118 | " while i < len(left) and j < len(right):\n", 119 | " if left[i] < right[j]:\n", 120 | " our_list[k]=left[i]\n", 121 | " i+=1\n", 122 | " else:\n", 123 | " our_list[k]=right[j]\n", 124 | " j+=1\n", 125 | " k+=1\n", 126 | "\n", 127 | " while i < len(left):\n", 128 | " our_list[k]=left[i]\n", 129 | " i+=1\n", 130 | " k+=1\n", 131 | "\n", 132 | " while j < len(right):\n", 133 | " our_list[k]=right[j]\n", 134 | " j+=1\n", 135 | " k+=1\n", 136 | " \n", 137 | " return our_list\n", 138 | "\n", 139 | "x=Log_Linear_Example([56,23,11,90,65,4,35,65,84,12,4,0])\n", 140 | "print(x)\n", 141 | "\n", 142 | "\n", 143 | "%time" 144 | ] 145 | }, 146 | { 147 | "cell_type": "markdown", 148 | "metadata": {}, 149 | "source": [ 150 | "#### Linear Example" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": 1, 156 | "metadata": {}, 157 | "outputs": [ 158 | { 159 | "name": "stdout", 160 | "output_type": "stream", 161 | "text": [ 162 | "Item: 1\n", 163 | "Item: 2\n", 164 | "Item: 3\n", 165 | "Item: 4\n", 166 | "CPU times: user 3 µs, sys: 0 ns, total: 3 µs\n", 167 | "Wall time: 6.2 µs\n" 168 | ] 169 | } 170 | ], 171 | "source": [ 172 | "# O(n)\n", 173 | "\n", 174 | "def Linear_Example(our_list):\n", 175 | " for item in our_list:\n", 176 | " print (\"Item: {}\".format(item))\n", 177 | "\n", 178 | "Linear_Example([1,2,3,4])\n", 179 | "\n", 180 | "%time" 181 | ] 182 | }, 183 | { 184 | "cell_type": "markdown", 185 | "metadata": {}, 186 | "source": [ 187 | "#### Logarithmic Example" 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": 3, 193 | "metadata": {}, 194 | "outputs": [ 195 | { 196 | "name": "stdout", 197 | "output_type": "stream", 198 | "text": [ 199 | "514229\n", 200 | "CPU times: user 3 µs, sys: 1 µs, total: 4 µs\n", 201 | "Wall time: 5.72 µs\n" 202 | ] 203 | } 204 | ], 205 | "source": [ 206 | "# O(logn)\n", 207 | "\n", 208 | "def Logarithmic_Example(number):\n", 209 | " if number == 0: \n", 210 | " return 0\n", 211 | " \n", 212 | " elif number == 1: \n", 213 | " return 1\n", 214 | " \n", 215 | " else: \n", 216 | " return Logarithmic_Example(number-1)+Logarithmic_Example(number-2)\n", 217 | "\n", 218 | " \n", 219 | "print(Logarithmic_Example(29))\n", 220 | "\n", 221 | "%time" 222 | ] 223 | }, 224 | { 225 | "cell_type": "markdown", 226 | "metadata": {}, 227 | "source": [ 228 | "#### Constant Example" 229 | ] 230 | }, 231 | { 232 | "cell_type": "code", 233 | "execution_count": 5, 234 | "metadata": {}, 235 | "outputs": [ 236 | { 237 | "name": "stdout", 238 | "output_type": "stream", 239 | "text": [ 240 | "CPU times: user 3 µs, sys: 1 µs, total: 4 µs\n", 241 | "Wall time: 6.2 µs\n" 242 | ] 243 | } 244 | ], 245 | "source": [ 246 | "# O(1)\n", 247 | "\n", 248 | "def Constant_Example(our_list):\n", 249 | " return our_list.pop()\n", 250 | "\n", 251 | "Constant_Example([1,2,3,4])\n", 252 | "\n", 253 | "%time" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": null, 259 | "metadata": {}, 260 | "outputs": [], 261 | "source": [] 262 | } 263 | ], 264 | "metadata": { 265 | "kernelspec": { 266 | "display_name": "Python 3", 267 | "language": "python", 268 | "name": "python3" 269 | }, 270 | "language_info": { 271 | "codemirror_mode": { 272 | "name": "ipython", 273 | "version": 3 274 | }, 275 | "file_extension": ".py", 276 | "mimetype": "text/x-python", 277 | "name": "python", 278 | "nbconvert_exporter": "python", 279 | "pygments_lexer": "ipython3", 280 | "version": "3.6.3" 281 | }, 282 | "widgets": { 283 | "state": {}, 284 | "version": "1.1.2" 285 | } 286 | }, 287 | "nbformat": 4, 288 | "nbformat_minor": 2 289 | } 290 | -------------------------------------------------------------------------------- /Udacity Data Structure and Algorithms Nanodegree/Introduction/FindNextDay.py: -------------------------------------------------------------------------------- 1 | ### 2 | ### Define a simple nextDay procedure, that assumes 3 | ### every month has 30 days. 4 | ### 5 | ### For example: 6 | ### nextDay(1999, 12, 30) => (2000, 1, 1) 7 | ### nextDay(2013, 1, 30) => (2013, 2, 1) 8 | ### nextDay(2012, 12, 30) => (2013, 1, 1) (even though December really has 31 days) 9 | ### 10 | 11 | 12 | def next_day2(year, month, day): 13 | """Simple version: assume every month has 30 days""" 14 | if day < 30: 15 | return year, month, day + 1 16 | else: 17 | if month == 12: 18 | return year + 1, 1, 1 19 | else: 20 | return year, month + 1, 1 21 | 22 | 23 | def next_day(year, month, day): 24 | """ 25 | Returns the year, month, day of the next day. 26 | Simple version: assume every month has 30 days. 27 | """ 28 | # YOUR CODE HERE 29 | if month == 12: 30 | if day == 30: 31 | day = 1 32 | year += 1 33 | month = 1 34 | else: 35 | day += 1 36 | 37 | else: 38 | if day == 30: 39 | month += 1 40 | day = 1 41 | 42 | else: 43 | day += 1 44 | 45 | return year, month, day 46 | 47 | 48 | y, m, d = next_day(2012, 12, 1) 49 | print(y, m, d) 50 | -------------------------------------------------------------------------------- /Udacity Data Structure and Algorithms Nanodegree/Introduction/Friend_Birthday.py: -------------------------------------------------------------------------------- 1 | class Person: 2 | def __init__(self, name, age, month): 3 | self.name = name 4 | self.age = age 5 | self.birthday_month = month 6 | 7 | def birthday(self): 8 | self.age += 1 9 | 10 | 11 | def create_person_objects(names, ages, months): 12 | my_data = zip(names, ages, months) 13 | person_objects = [] 14 | for item in my_data: 15 | person_objects.append(Person(*item)) 16 | 17 | return person_objects 18 | 19 | 20 | def get_april_birthdays(people): 21 | # TODO: 22 | # Increment "age" for all people with birthdays in April. 23 | # Return a dictionary "april_birthdays" with the names of 24 | # all people with April birthdays as keys, and their updated ages 25 | # as values. See the test below for an example expected output. 26 | april_birthdays = {} 27 | 28 | for individual in people: 29 | if individual.birthday_month == 'April': 30 | individual.age += 1 31 | april_birthdays[individual.name] = individual.age 32 | 33 | # TODO: Modify the return statement 34 | return april_birthdays 35 | 36 | 37 | def get_most_common_month(people): 38 | # TODO: 39 | # Use the "months" dictionary to record counts of birthday months 40 | # for persons in the "people" data. 41 | # Return the month with the largest number of birthdays. 42 | months = {'January': 0, 'February': 0, 'March': 0, 'April': 0, 'May': 0, 43 | 'June': 0, 'July': 0, 'August': 0, 'September': 0, 'October': 0, 44 | 'November': 0, 'December': 0} 45 | 46 | for individual in people: 47 | months[individual.birthday_month] += 1 48 | 49 | maximum = 0 50 | result = '' 51 | for month, count in months.items(): 52 | if count > maximum: 53 | maximum = count 54 | result = month 55 | # TODO: Modify the return statement. 56 | return result 57 | 58 | 59 | def test(): 60 | # Here is the data for the test. Assume there is a single most common month. 61 | names = ['Howard', 'Richard', 'Jules', 'Trula', 'Michael', 'Elizabeth', 'Richard', 'Shirley', 'Mark', 'Brianna', 62 | 'Kenneth', 'Gwen', 'William', 'Rosa', 'Denver', 'Shelly', 'Sammy', 'Maryann', 'Kathleen', 'Andrew', 63 | 'Joseph', 'Kathleen', 'Lisa', 'Viola', 'George', 'Bonnie', 'Robert', 'William', 'Sabrina', 'John', 64 | 'Robert', 'Gil', 'Calvin', 'Robert', 'Dusty', 'Dario', 'Joeann', 'Terry', 'Alan', 'Rosa', 'Jeane', 'James', 65 | 'Rachel', 'Tu', 'Chelsea', 'Andrea', 'Ernest', 'Erica', 'Priscilla', 'Carol', 'Michael', 'Dale', 'Arthur', 66 | 'Helen', 'James', 'Donna', 'Patricia', 'Betty', 'Patricia', 'Mollie', 'Nicole', 'Ernest', 'Wendy', 67 | 'Graciela', 'Teresa', 'Nicole', 'Trang', 'Caleb', 'Robert', 'Paul', 'Nieves', 'Arleen', 'Milton', 'James', 68 | 'Lawrence', 'Edward', 'Susan', 'Patricia', 'Tana', 'Jessica', 'Suzanne', 'Darren', 'Arthur', 'Holly', 69 | 'Mary', 'Randal', 'John', 'Laura', 'Betty', 'Chelsea', 'Margaret', 'Angel', 'Jeffrey', 'Mary', 'Donald', 70 | 'David', 'Roger', 'Evan', 'Danny', 'William'] 71 | 72 | ages = [17, 58, 79, 8, 10, 57, 4, 98, 19, 47, 81, 68, 48, 13, 39, 21, 98, 51, 49, 12, 24, 78, 36, 59, 3, 87, 94, 85, 73 | 43, 69, 15, 52, 57, 36, 52, 5, 52, 5, 33, 10, 71, 28, 70, 9, 25, 28, 76, 71, 22, 35, 35, 100, 9, 95, 69, 52, 74 | 66, 91, 39, 84, 65, 29, 20, 98, 30, 83, 30, 15, 88, 89, 24, 98, 62, 94, 86, 63, 34, 23, 23, 19, 10, 80, 88, 75 | 67, 17, 91, 85, 97, 29, 7, 34, 38, 92, 29, 14, 52, 94, 62, 70, 22] 76 | 77 | months = ['January', 'March', 'January', 'October', 'April', 'February', 'August', 'January', 'June', 'August', 78 | 'February', 'May', 'March', 'June', 'February', 'August', 'June', 'March', 'August', 'April', 'April', 79 | 'June', 'April', 'June', 'February', 'September', 'March', 'July', 'September', 'December', 'June', 80 | 'June', 'August', 'November', 'April', 'November', 'August', 'June', 'January', 'August', 'May', 'March', 81 | 'March', 'March', 'May', 'September', 'August', 'April', 'February', 'April', 'May', 'March', 'March', 82 | 'January', 'August', 'October', 'February', 'November', 'August', 'June', 'September', 'September', 83 | 'January', 'September', 'July', 'July', 'December', 'June', 'April', 'February', 'August', 'September', 84 | 'August', 'February', 'April', 'July', 'May', 'November', 'December', 'February', 'August', 'August', 85 | 'September', 'December', 'February', 'March', 'June', 'December', 'February', 'May', 'April', 'July', 86 | 'March', 'June', 'December', 'March', 'July', 'May', 'September', 'November'] 87 | 88 | people = create_person_objects(names, ages, months) 89 | 90 | # Calls to the two functions you have completed. 91 | print(get_april_birthdays(people)) 92 | print(get_most_common_month(people)) 93 | 94 | 95 | test() 96 | # Expected result: 97 | # {'Michael': 11, 'Erica': 72, 'Carol': 36, 'Lisa': 37, 'Lawrence': 87, 'Joseph': 25, 'Margaret': 35, 98 | # 'Andrew': 13, 'Dusty': 53, 'Robert': 89} 99 | # August 100 | -------------------------------------------------------------------------------- /Udacity Data Structure and Algorithms Nanodegree/Introduction/Unscramble computer science problems.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## TASK 0" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [ 15 | { 16 | "data": { 17 | "text/plain": [ 18 | "'\\nTASK 0:\\nWhat is the first record of texts and what is the last record of calls?\\nPrint messages:\\n\"First record of texts, texts at time