├── 0-HelloWorld.py ├── 1-Data Types.py ├── 10-Binary.py ├── 11-2D Arrays.py ├── 12-Inheritance.py ├── 13-Abstract_Classes.py ├── 14-Scope.py ├── 15-LinkedList.py ├── 16-Exceptions.py ├── 17-MoreExceptions.py ├── 18-Queues-Stacks.py ├── 19-Interfaces.py ├── 2-Operators.py ├── 20-SortingProblem.py ├── 22-BST.py ├── 23-BST_Level_Order_Traversal.py ├── 24-MoreLinkedList.py ├── 25-Runtimes.py ├── 26-NestedLogic.py ├── 27-Testing.py ├── 28-RegEx_Patterns_and_Databases.py ├── 29-Bitwise_AND ├── 3-Intro to conditional statements.py ├── 4-Class vs Instance.py ├── 5-Loops.py ├── 6-Let's Review.py ├── 8-DictionariesAndMap.py ├── 9-Recursion.py └── README.md /0-HelloWorld.py: -------------------------------------------------------------------------------- 1 | # Read a full line of input from stdin and save it to our dynamically typed variable, input_string. 2 | input_string = input() 3 | 4 | # Print a string literal saying "Hello, World." to stdout. 5 | print('Hello, World.') 6 | 7 | # Write a line of code here that prints the contents of input_string to stdout. 8 | print(input_string) 9 | -------------------------------------------------------------------------------- /1-Data Types.py: -------------------------------------------------------------------------------- 1 | i = 4 2 | d = 4.0 3 | s = 'HackerRank ' 4 | 5 | # Declare second integer, double, and String variables. 6 | i2 = None 7 | d2 = None 8 | s2 = None 9 | 10 | # Read and save an integer, double, and String to your variables. 11 | i2 = int(input()) 12 | d2 = float(input()) 13 | s2 = str(input()) 14 | 15 | # Print the sum of both integer variables on a new line. 16 | print(i + i2) 17 | 18 | # Print the sum of the double variables on a new line. 19 | print(d + d2) 20 | 21 | # Concatenate and print the String variables on a new line 22 | # The 's' variable above should be printed first. 23 | print(s + s2 24 | -------------------------------------------------------------------------------- /10-Binary.py: -------------------------------------------------------------------------------- 1 | num = int(input()) 2 | #Every odd values, Increment 1 3 | result = 0 4 | maximum = 0 5 | 6 | while num > 0: 7 | if num % 2 == 1: 8 | result += 1 9 | if result > maximum: 10 | maximum = result 11 | 12 | else: 13 | result = 0 14 | num //= 2 15 | print(maximum) 16 | 17 | -------------------------------------------------------------------------------- /11-2D Arrays.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | if __name__ == '__main__': 10 | arr = [] 11 | max = -99 12 | for _ in range(6): 13 | arr.append(list(map(int, input().rstrip().split()))) 14 | 15 | for i in range(6): 16 | for j in range(6): 17 | if ((i + 2 < 6) and (j + 2 < 6)): 18 | temp = arr[i][j] + arr[i + 2][j] + arr[i][j + 1] + arr[i + 1][j + 1] + arr[i + 2][j + 1] + arr[i][ 19 | j + 2] + arr[i + 2][j + 2] 20 | if (temp > max): 21 | max = temp 22 | 23 | print(max) 24 | -------------------------------------------------------------------------------- /12-Inheritance.py: -------------------------------------------------------------------------------- 1 | class Student(Person): 2 | # Class Constructor 3 | # 4 | # Parameters: 5 | # firstName - A string denoting the Person's first name. 6 | # lastName - A string denoting the Person's last name. 7 | # id - An integer denoting the Person's ID number. 8 | # scores - An array of integers denoting the Person's test scores. 9 | # 10 | # Write your constructor here 11 | 12 | def __init__(self, firstName, lastName, idNumber, scores): 13 | super().__init__(firstName, lastName, idNumber) 14 | self.scores = scores 15 | 16 | def calculate(self): 17 | summation = 0 18 | size = len(self.scores) 19 | for i in self.scores: 20 | summation += i 21 | grade = summation / size 22 | 23 | if (grade >= 90 and grade <= 100): 24 | grade = "O" 25 | elif (grade >= 80 and grade < 90): 26 | grade = "E" 27 | elif (grade >= 70 and grade < 80): 28 | grade = "A" 29 | elif (grade >= 55 and grade < 70): 30 | grade = "P" 31 | elif (grade >= 40 and grade < 50): 32 | grade = "D" 33 | else: 34 | grade = "T" 35 | return grade 36 | -------------------------------------------------------------------------------- /13-Abstract_Classes.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | 3 | class Book(object, metaclass=ABCMeta): 4 | def __init__(self,title,author): 5 | self.title=title 6 | self.author=author 7 | @abstractmethod 8 | def display(): pass 9 | 10 | #Write MyBook class 11 | class MyBook(Book): 12 | def __init__(self, title, author, price): 13 | super().__init__(title, author) 14 | self.price = price 15 | 16 | def display(self): 17 | print("Title: " + title) 18 | print("Author: " + author) 19 | print("Price: " + str(price)) -------------------------------------------------------------------------------- /14-Scope.py: -------------------------------------------------------------------------------- 1 | class Difference: 2 | def __init__(self, a): 3 | self.__elements = a 4 | self.maximumDifference = None 5 | 6 | def computeDifference(self): 7 | lengthElem = len(self.__elements) 8 | max = 0 9 | for i in range(lengthElem): 10 | for j in range(lengthElem): 11 | value = abs(self.__elements[i] - self.__elements[j]) 12 | if (max < value): 13 | max = value 14 | self.maximumDifference = max 15 | 16 | _ = input() 17 | a = [int(e) for e in input().split(' ')] 18 | 19 | d = Difference(a) 20 | d.computeDifference() 21 | 22 | print(d.maximumDifference) -------------------------------------------------------------------------------- /15-LinkedList.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self,data): 3 | self.data = data 4 | self.next = None 5 | class Solution: 6 | def display(self,head): 7 | current = head 8 | while current: 9 | print(current.data,end=' ') 10 | current = current.next 11 | def insert(self,head,data): 12 | nodeData = Node(data) 13 | if head is None: 14 | head = nodeData 15 | else: 16 | current = head 17 | while current.next: 18 | current = current.next 19 | current.next = nodeData 20 | return head 21 | 22 | mylist= Solution() 23 | T=int(input()) 24 | head=None 25 | for i in range(T): 26 | data=int(input()) 27 | head=mylist.insert(head,data) 28 | mylist.display(head); -------------------------------------------------------------------------------- /16-Exceptions.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | S = input().strip() 7 | try: 8 | k = int(S) 9 | print(S) 10 | except BaseException as error: 11 | print("Bad String") -------------------------------------------------------------------------------- /17-MoreExceptions.py: -------------------------------------------------------------------------------- 1 | #Write your code here 2 | class Calculator: 3 | def power(self,n, p): 4 | if(n < 0 or p < 0): 5 | raise Exception("n and p should be non-negative") 6 | else: 7 | return pow(n,p) 8 | 9 | myCalculator=Calculator() 10 | T=int(input()) 11 | for i in range(T): 12 | n,p = map(int, input().split()) 13 | try: 14 | ans=myCalculator.power(n,p) 15 | print(ans) 16 | except Exception as e: 17 | print(e) -------------------------------------------------------------------------------- /18-Queues-Stacks.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.stack = [] 4 | self.queue = [] 5 | # Write your code here 6 | def pushCharacter(self, s): 7 | self.stack.append(s) 8 | def enqueueCharacter(self, s): 9 | self.queue.append(s) 10 | def popCharacter(self): 11 | return self.stack.pop() 12 | def dequeueCharacter(self): 13 | c = self.queue[0] 14 | self.queue.remove(c) 15 | return c 16 | 17 | 18 | # read the string s 19 | s = input() 20 | # Create the Solution class object 21 | obj = Solution() 22 | 23 | l = len(s) 24 | # push/enqueue all the characters of string s to stack 25 | for i in range(l): 26 | obj.pushCharacter(s[i]) 27 | obj.enqueueCharacter(s[i]) 28 | 29 | isPalindrome = True 30 | ''' 31 | pop the top character from stack 32 | dequeue the first character from queue 33 | compare both the characters 34 | ''' 35 | for i in range(l // 2): 36 | if obj.popCharacter() != obj.dequeueCharacter(): 37 | isPalindrome = False 38 | break 39 | # finally print whether string s is palindrome or not. 40 | if isPalindrome: 41 | print("The word, " + s + ", is a palindrome.") 42 | else: 43 | print("The word, " + s + ", is not a palindrome.") -------------------------------------------------------------------------------- /19-Interfaces.py: -------------------------------------------------------------------------------- 1 | class Calculator(AdvancedArithmetic): 2 | def divisorSum(self, n): 3 | val = 0 4 | for i in range(1,n+1): 5 | if(n % i == 0): 6 | val += i 7 | return val 8 | 9 | n = int(input()) 10 | my_calculator = Calculator() 11 | s = my_calculator.divisorSum(n) 12 | print("I implemented: " + type(my_calculator).__bases__[0].__name__) 13 | print(s) -------------------------------------------------------------------------------- /2-Operators.py: -------------------------------------------------------------------------------- 1 | def get_total_cost_of_meal(): 2 | # original meal price 3 | meal_cost = float(input()) 4 | # tip percentage 5 | tip_percent = int(input()) 6 | # tax percentage 7 | tax_percent = int(input()) 8 | 9 | # Write your calculation code here 10 | tip = # calculate tip 11 | tax = # caclulate tax 12 | 13 | # cast the result of the rounding operation to an int and save it as total_cost 14 | total_cost = int(round("""write your total cost calculation here""")) 15 | 16 | return str(total_cost) 17 | 18 | # Print your result 19 | print("The total meal cost is " + get_total_cost_of_meal() + " dollars.") 20 | -------------------------------------------------------------------------------- /20-SortingProblem.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | n = int(input().strip()) 6 | a = list(map(int, input().strip().split(' '))) ## puts the line of string in a list 7 | # Write Your Code Here 8 | numSwaps = 0 9 | for i in range(n): 10 | for j in range(n-1): 11 | if(a[j] > a[j+1]): 12 | numSwaps+=1 13 | a[j], a[j+1] = a[j+1], a[j] 14 | if(numSwaps is 0): 15 | break 16 | print("Array is sorted in " + str(numSwaps) + " swaps.") 17 | print("First Element: " + str(a[0])) 18 | print("Last Element: " + str(a[n-1])) -------------------------------------------------------------------------------- /22-BST.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self,data): 3 | self.right=self.left=None 4 | self.data = data 5 | class Solution: 6 | def insert(self,root,data): 7 | if root==None: 8 | return Node(data) 9 | else: 10 | if data<=root.data: 11 | cur=self.insert(root.left,data) 12 | root.left=cur 13 | else: 14 | cur=self.insert(root.right,data) 15 | root.right=cur 16 | return root 17 | 18 | def getHeight(self,root): 19 | if root is None: 20 | return -1 21 | else: 22 | return 1 + max(self.getHeight(root.left), self.getHeight(root.right)) 23 | 24 | 25 | 26 | 27 | T=int(input()) 28 | myTree=Solution() 29 | root=None 30 | for i in range(T): 31 | data=int(input()) 32 | root=myTree.insert(root,data) 33 | height=myTree.getHeight(root) 34 | print(height) -------------------------------------------------------------------------------- /23-BST_Level_Order_Traversal.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class Node: 4 | def __init__(self,data): 5 | self.right=self.left=None 6 | self.data = data 7 | class Solution: 8 | def insert(self,root,data): 9 | if root==None: 10 | return Node(data) 11 | else: 12 | if data<=root.data: 13 | cur=self.insert(root.left,data) 14 | root.left=cur 15 | else: 16 | cur=self.insert(root.right,data) 17 | root.right=cur 18 | return root 19 | 20 | def levelOrder(self, root): 21 | Q = [] 22 | if (root.data is not None): 23 | Q.append(root) 24 | answer = "" 25 | while (Q): 26 | current = Q[0] 27 | answer = answer + str(current.data) + " " 28 | if current.left is not None: 29 | Q.append(current.left) 30 | if current.right is not None: 31 | Q.append(current.right) 32 | Q.pop(0) 33 | print(answer) 34 | 35 | T=int(input()) 36 | myTree=Solution() 37 | root=None 38 | for i in range(T): 39 | data=int(input()) 40 | root=myTree.insert(root,data) 41 | myTree.levelOrder(root) -------------------------------------------------------------------------------- /24-MoreLinkedList.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self,data): 3 | self.data = data 4 | self.next = None 5 | class Solution: 6 | def insert(self,head,data): 7 | p = Node(data) 8 | if head==None: 9 | head=p 10 | elif head.next==None: 11 | head.next=p 12 | else: 13 | start=head 14 | while(start.next!=None): 15 | start=start.next 16 | start.next=p 17 | return head 18 | def display(self,head): 19 | current = head 20 | while current: 21 | print(current.data,end=' ') 22 | current = current.next 23 | 24 | def removeDuplicates(self, head): 25 | current = head 26 | while current is not None and current.next is not None: 27 | currData = current.data 28 | currNext = current.next 29 | if currData is currNext.data: 30 | current.next = current.next.next 31 | current = current.next 32 | return head 33 | 34 | mylist= Solution() 35 | T=int(input()) 36 | head=None 37 | for i in range(T): 38 | data=int(input()) 39 | head=mylist.insert(head,data) 40 | head=mylist.removeDuplicates(head) 41 | mylist.display(head); -------------------------------------------------------------------------------- /25-Runtimes.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | from sys import stdin 3 | 4 | 5 | def checkPrime(n): 6 | for i in range(2, int(sqrt(n))+1): 7 | if n % i is 0: 8 | return False 9 | return True 10 | 11 | 12 | n = int(input()) 13 | for line in stdin: 14 | val = int(line) 15 | if (val >= 2 and checkPrime(val)): 16 | print("Prime") 17 | else: 18 | print("Not prime") -------------------------------------------------------------------------------- /26-NestedLogic.py: -------------------------------------------------------------------------------- 1 | actual = input() 2 | actual = list(map(int, actual.split(" "))) 3 | 4 | expected = input() 5 | expected = list(map(int, expected.split(" "))) 6 | 7 | actualDate = actual[0] 8 | actualMonth = actual[1] 9 | actualYear = actual[2] 10 | 11 | expectedDate = expected[0] 12 | expectedMonth = expected[1] 13 | expectedYear = expected[2] 14 | 15 | fine = 0 16 | 17 | if actualYear > expectedYear: 18 | fine = 10000 19 | elif actualYear == expectedYear: #Same calender year 20 | if actualMonth > expectedMonth: #checking months 21 | fine = 500 * (actualMonth - expectedMonth) 22 | elif actualMonth == expectedMonth: #check dates now 23 | if actualDate > expectedDate: 24 | fine = 15 * (actualDate - expectedDate) 25 | print(fine) 26 | -------------------------------------------------------------------------------- /27-Testing.py: -------------------------------------------------------------------------------- 1 | 2 | def minimum_index(seq): 3 | if len(seq) == 0: 4 | raise ValueError("Cannot get the minimum value index from an empty sequence") 5 | min_idx = 0 6 | for i in range(1, len(seq)): 7 | if seq[i] < seq[min_idx]: 8 | min_idx = i 9 | return min_idx 10 | 11 | 12 | class TestDataEmptyArray(object): 13 | 14 | @staticmethod 15 | def get_array(): 16 | return [] 17 | # complete this function 18 | 19 | class TestDataUniqueValues(object): 20 | data = [] 21 | for i in range(5): 22 | data.append(i) 23 | data[::-1] 24 | @staticmethod 25 | def get_array(): 26 | return TestDataUniqueValues.data 27 | @staticmethod 28 | def get_expected_result(): 29 | data = TestDataUniqueValues.get_array() 30 | return data.index(min(data)) 31 | # complete this function 32 | 33 | class TestDataExactlyTwoDifferentMinimums(object): 34 | data = [] 35 | for i in range(5): 36 | data.append(i) 37 | data[::-1] 38 | data.insert(0,0) 39 | 40 | @staticmethod 41 | def get_array(): 42 | return TestDataExactlyTwoDifferentMinimums.data 43 | @staticmethod 44 | def get_expected_result(): 45 | data = TestDataExactlyTwoDifferentMinimums.get_array() 46 | return data.index(min(data)) 47 | # complete this function 48 | def TestWithEmptyArray(): 49 | try: 50 | seq = TestDataEmptyArray.get_array() 51 | result = minimum_index(seq) 52 | except ValueError as e: 53 | pass 54 | else: 55 | assert False 56 | 57 | 58 | def TestWithUniqueValues(): 59 | seq = TestDataUniqueValues.get_array() 60 | assert len(seq) >= 2 61 | 62 | assert len(list(set(seq))) == len(seq) 63 | 64 | expected_result = TestDataUniqueValues.get_expected_result() 65 | result = minimum_index(seq) 66 | assert result == expected_result 67 | 68 | 69 | def TestiWithExactyTwoDifferentMinimums(): 70 | seq = TestDataExactlyTwoDifferentMinimums.get_array() 71 | assert len(seq) >= 2 72 | tmp = sorted(seq) 73 | assert tmp[0] == tmp[1] and (len(tmp) == 2 or tmp[1] < tmp[2]) 74 | 75 | expected_result = TestDataExactlyTwoDifferentMinimums.get_expected_result() 76 | result = minimum_index(seq) 77 | assert result == expected_result 78 | 79 | TestWithEmptyArray() 80 | TestWithUniqueValues() 81 | TestiWithExactyTwoDifferentMinimums() 82 | print("OK") 83 | -------------------------------------------------------------------------------- /28-RegEx_Patterns_and_Databases.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | 10 | 11 | if __name__ == '__main__': 12 | N = int(input()) 13 | validNamesList = [] 14 | for N_itr in range(N): 15 | firstNameEmailID = input().split() 16 | firstName = firstNameEmailID[0] 17 | emailID = firstNameEmailID[1] 18 | if emailID.find("@gmail.com") != -1: #gmail email found 19 | validNamesList.append(firstName) 20 | for i in sorted(validNamesList): 21 | print(i) 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /29-Bitwise_AND: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | 10 | 11 | if __name__ == '__main__': 12 | T = int(input()) 13 | 14 | for i in range(T): 15 | tmp = str(input()).split() 16 | N = int(tmp[0]) 17 | K = int(tmp[1]) 18 | 19 | maximum = 0 20 | 21 | for j in range(1, N): 22 | for k in range(j + 1, N + 1): 23 | h = j & k 24 | if K > h > maximum: 25 | maximum = h 26 | 27 | print(maximum) 28 | -------------------------------------------------------------------------------- /3-Intro to conditional statements.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | 3 | if N % 2 != 0: 4 | print("Weird") 5 | else: 6 | if N <= 5: 7 | print("Not Weird") 8 | elif N <= 20: 9 | print("Weird") 10 | else: 11 | print("Not Weird") 12 | -------------------------------------------------------------------------------- /4-Class vs Instance.py: -------------------------------------------------------------------------------- 1 | class Person: 2 | def __init__(self, initialAge): 3 | if initialAge > 0: 4 | self.age = initialAge 5 | else: 6 | print("Age is not valid, setting age to 0.") 7 | self.age = 0 8 | 9 | def amIOld(self): 10 | if self.age < 13: 11 | print("You are young.") 12 | elif self.age < 18: 13 | print("You are a teenager.") 14 | else: 15 | print("You are old.") 16 | 17 | def yearPasses(self): 18 | self.age += 1 19 | 20 | 21 | t = int(input()) 22 | for i in range(0, t): 23 | age = int(input()) 24 | p = Person(age) 25 | p.amIOld() 26 | for j in range(0, 3): 27 | p.yearPasses() 28 | p.amIOld() 29 | print("") 30 | -------------------------------------------------------------------------------- /5-Loops.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | import sys 3 | n = int(input().strip()) 4 | for i in range(1, 11): ##Loops from 1 to 10 5 | answer = i * n 6 | print(str(n) + " x " + str(i) + " = " + str(answer)) 7 | ##+ " x " + i + " = " + (N*i)) 8 | -------------------------------------------------------------------------------- /6-Let's Review.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | 3 | for i in range(0, N): 4 | 5 | string = input() 6 | 7 | for j in range(0, len(string)): 8 | if j % 2 == 0: 9 | print(string[j], end='') 10 | 11 | print(" ", end='') 12 | 13 | for j in range(0, len(string)): 14 | if j % 2 != 0: 15 | print(string[j], end='') 16 | 17 | print("") 18 | -------------------------------------------------------------------------------- /8-DictionariesAndMap.py: -------------------------------------------------------------------------------- 1 | phonebook = {} 2 | num = int(input()) 3 | for i in range(0, num): 4 | entry = str(input()).split(" ") 5 | name = entry[0] 6 | number = int(entry[1]) 7 | phonebook[name] = number 8 | 9 | for i in range(0, num): 10 | name = input() 11 | if name in phonebook: 12 | print(name + "=" + str(phonebook[name])) 13 | else: 14 | print("Not found") -------------------------------------------------------------------------------- /9-Recursion.py: -------------------------------------------------------------------------------- 1 | import math 2 | import os 3 | import random 4 | import re 5 | import sys 6 | 7 | # Complete the factorial function below. 8 | def factorial(n): 9 | if(n == 1): 10 | return 1 11 | else: 12 | return n * factorial(n-1) 13 | 14 | if __name__ == '__main__': 15 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 16 | 17 | n = int(input()) 18 | 19 | result = factorial(n) 20 | 21 | fptr.write(str(result) + '\n') 22 | 23 | fptr.close() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 30-Days-of-Code-by-HackerRank-Solutions-in-Python 2 | Solutions for 30 Days of Code by HackerRank in python language 3 | --------------------------------------------------------------------------------