# 30 Days Of Code Hackerrank Solutions In Python

Looking for 30 days of code hackerrank solution in python then you are at the right place today in this tutorial I will share with you each 30 days of code hackerrank solution in python programming.

**Hackerrank **is a place for programmers and developers to learn programming and solve problems. It is one of the best platform to practice and learn as a new programmer.

30 days of code is a challenge created by Hackerrank for programmers, they have to solve each challenge daily till they complete 30 days.

You can use any programming language to complete these challenges. If you are using python you want the 30 days of code hackerrank solutions in python, then read till the end.

## 30 Days Of Code Hackerrank Solutions In Python

Before we go to the solutions, if you are a new programmer then you should definitely try to solve the hackerrank 30 days of code challenge by yourself, this will help you drastically improve your skills.

But if you get stuck to a problem can’t solve it then you can check the solutions for problems, so now let’s see the solutions of hackerrank 30 days of code in python.

### Hello World Day 0 Hackerrank solution in python

To complete this challenge, you must save a line of input from stdin to a variable, print Hello, World. on a single line, and finally print the value of your variable on a second line.

```
# Read a full line of input from stdin and save it to our dynamically typed variable, input_string.
input_string = input()
# Print a string literal saying "Hello, World." to stdout.
print('Hello, World.')
# TODO: Write a line of code here that prints the contents of input_string to stdout.
print(input_string)
```

### Datatypes Day 1 Hackerrank solution in python

Complete the code in the editor below. The variables i, d and s are already declared and initialized for you. You must:

1. Declare 3 variables: one of type int, one of type double, and one of type String.

2. Read 3 lines of input from stdin (according to the sequence given in the Input Format section below) and initialize your variables.

3. Use the + operator to perform the following operations:

a. Print the sum of i plus your int variable on a new line.

b. Print the sum of d plus your double variable to a scale of one decimal place on a new line.

c. Concatenate s with the string you read as input and print the result on a new line.

```
i = 4
d = 4.0
s = 'HackerRank '
# Declare second integer, double, and String variables.
a = int(input())
b = float(input())
c = str(input())
# Read and save an integer, double, and String to your variables.
# Print the sum of both integer variables on a new line.
print(i+a)
# Print the sum of the double variables on a new line.
print(d+b)
# Concatenate and print the String variables on a new line
print(s+c)
# The 's' variable above should be printed first.
```

### Operators Day 2 Hackerrank solution in python

Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal’s total cost.

Note: Be sure to use precise values for your calculations, or you may end up with an incorrectly rounded result!

```
#!/bin/python
import math
import os
import random
import re
import sys
# Complete the solve function below.
def solve(meal_cost, tip_percent, tax_percent):
# Write your calculation code here
tip = (tip_percent/100)* meal_cost # calculate tip
tax = (tax_percent/100)* meal_cost# caclulate tax
# cast the result of the rounding operation to an int and save it as total_cost
total_cost = round(meal_cost+tip+tax)
print(total_cost)
if __name__ == '__main__':
meal_cost = float(input())
tip_percent = int(input())
tax_percent = int(input())
solve(meal_cost, tip_percent, tax_percent)
```

### Conditional Statements Day 3 Hackerrank solution in python

Given an integer, n, perform the following conditional actions:

- If n is odd, print Weird
- If n is even and in the inclusive range of 2 to 5, print Not Weird
- If n is even and in the inclusive range of 6 to 20, print Weird
- If n is even and greater than 20, print Not Weird

Complete the stub code provided in your editor to print whether or not is weird.

```
import math
import os
import random
import re
import sys
if __name__ == '__main__':
N = int(input())
if N%2!=0:
print('Weird')
elif N%2==0 and N in range(1,6):
print('Not Weird')
elif N%2==0 and N in range(5,21):
print('Weird')
elif N%2==0 and N>20:
print('Not Weird')
```

### Class vs Instance Day 4 Hackerrank solution in python

Write a Person class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter. The constructor must assign initialAge to age after confirming the argument passed as initialAge is not negative;

If a negative argument is passed as initialAge, the constructor should set age to 0 and print Age is not valid, setting age to 0

```
class Person:
def __init__(self,initialAge):
# Add some more code to run some checks on initialAge
if initialAge < 0:
print("Age is not valid, setting age to 0.")
self.age = 0
def amIOld(self):
# Do some computations in here and print out the correct statement to the console
if age <13:
print("You are young.")
elif age >= 13 and age <18:
print("You are a teenager.")
else:
print('You are old.')
def yearPasses(self):
# Increment the age of the person in here
global age
age= age+1
t = int(input())
for i in range(0, t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print("")
```

### Loops Day 5 Hackerrank solution in python

Given an integer,n , print its first 10 multiples. Each multiple n x i (where 1<= i <= 10) should be printed on a new line in the form: n x i = result.

```
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
for i in range(1, 11):
print(n, 'x', i, '=', n*i)
```

### Review Day 6 Hackerrank solution in python

Given a string, S , of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail).

```
# Enter your code here. Read input from STDIN. Print output to STDOUT
t = int(input())
for i in range(t):
s = str(input())
print (s[::2], s[1::2])
```

### Arrays Day 7 Hackerrank solution in python

Given an array,A , of N integers, print A's elements in reverse order as a single line of space-separated numbers.

```
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
print (*arr[::-1], sep=' ')
```

### Dictionaries and Maps Day 8 Hackerrank solution in python

Given n names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for.

For each name queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for name is not found, print Not found instead.

```
n = int(input())
d = {}
for i in range(n):
x = input().split()
d[x[0]] = x[1]
while True:
try:
name = input()
if name in d:
print(name, "=", d[name], sep="")
else : print("Not found")
except: break
```

### Recursion Day 9 Hackerrank solution in python

Write a factorial function that takes a positive integer, N as a parameter and prints the result of N! (N factorial).

Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of 0.

```
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the factorial function below.
def factorial(n):
for i in range (1, n):
n= n*i
return n
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
result = factorial(n)
fptr.write(str(result) + '\n')
fptr.close()
```

### Binary Numbers Day 10 Hackerrank solution in python

Given a base-10 integer,n , convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's in n's binary representation.

```
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
numbers = str(bin(n)[2:]).split('0')
lenghts = [len(num) for num in numbers]
print(max(lenghts))
```

### 2D Arrays Day 11 Hackerrank solution in python

Given a 6x6 2D Array, A:

Calculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum.

```
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
arr = []
for _ in range(6):
tmp = [int(x) for x in str(input()).split(" ")]
arr.append(tmp)
maximum = -9 * 7
for i in range(6):
for j in range(6):
if j + 2 < 6 and i + 2 < 6:
result = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]
if result > maximum:
maximum = result
print(maximum)
```

### Inheritance Day 12 Hackerrank solution in python

You are given two classes, Person and Student, where Person is the base class and Student is the derived class. Completed code for Person and a declaration for Student are provided for you in the editor. Observe that Student inherits all the properties of Person.

```
class Person:
def __init__(self, firstName, lastName, idNumber):
self.firstName = firstName
self.lastName = lastName
self.idNumber = idNumber
def printPerson(self):
print("Name:", self.lastName + ",", self.firstName)
print("ID:", self.idNumber)
class Student(Person):
def __init__(self, firstName, lastName, idNumber, testScores):
super().__init__(firstName, lastName, idNumber)
self.testScores = testScores
def calculate(self):
total = 0
for testScore in self.testScores:
total += testScore
avg = total / len(self.testScores)
if 90 <= avg <= 100:
return 'O'
if 80 <= avg < 90:
return 'E'
if 70 <= avg < 80:
return 'A'
if 55 <= avg < 70:
return 'P'
if 40 <= avg < 55:
return 'D'
return 'T'
line = input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]
numScores = int(input()) # not needed for Python
scores = list( map(int, input().split()) )
s = Student(firstName, lastName, idNum, scores)
s.printPerson()
print("Grade:", s.calculate())
```

### Abstract Classes Day 13 Hackerrank solution in python

Given a Book class and a Solution class, write a MyBook class that does the following:

Inherits from Book

Has a parameterized constructor taking these parameters:

Implements the Book class' abstract display() method so it prints these lines

```
from abc import ABCMeta, abstractmethod
class Book(object, metaclass=ABCMeta):
def __init__(self,title,author):
self.title=title
self.author=author
@abstractmethod
def display(): pass
class MyBook(Book):
def __init__(self, title, author, price):
Book.__init__(self, title, author)
self.price = price
def display(self):
print('Title: ' + self.title)
print('Author: ' + self.author)
print('Price: ' + str(self.price))
title=input()
author=input()
price=int(input())
new_novel=MyBook(title,author,price)
new_novel.display()
```

### Scope Day 14 Hackerrank solution in python

Complete the Difference class by writing the following:

A class constructor that takes an array of integers as a parameter and saves it to the elements instance variable.

A computeDifference method that finds the maximum absolute difference between any 2 numbers in N and stores it in the maximumDifference instance variable.

```
class Difference:
def __init__(self, a):
self.__elements = a
def computeDifference(self):
sorted_elements = sorted(self.__elements)
self.maximumDifference = abs(sorted_elements[-1] - sorted_elements[0])
# End of Difference class
_ = input()
a = [int(e) for e in input().split(' ')]
d = Difference(a)
d.computeDifference()
print(d.maximumDifference)
```

### Linked List Day 15 Hackerrank solution in python

Complete the insert function in your editor so that it creates a new Node (pass data as the Node constructor argument) and inserts it at the tail of the linked list referenced by the head parameter. Once the new node is added, return the reference to the head node.

Python Linked List, HackerRank

```
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
def insert(self,head,data):
if (head == None):
head = Node(data)
elif (head.next == None):
head.next = Node(data)
else:
self.insert(head.next, data)
return head
mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
mylist.display(head);
```

### Exceptions Day 16 Hackerrank solution in python

Read a string, S, and print its integer value; if S cannot be converted to an integer, print Bad String.

```
#!/bin/python3
import sys
S = input().strip()
try:
print (int(S))
except ValueError:
print ("Bad String")
```

### More Exceptions Day 17 Hackerrank solution in python

Write a Calculator class with a single method: int power(int,int). The power method takes two integers, n and p, as parameters and returns the integer result of n^p. If either n or p is negative, then the method must throw an exception with the message: n and p should be non-negative

```
#Write your code here
class e(Exception):
"n and p should be non-negative"
class Calculator():
def power(self, n, p):
try:
if n | p < 0:
raise e
else:
return (n ** p)
except e:
return ("n and p should be non-negative")
myCalculator=Calculator()
T=int(input())
for i in range(T):
n,p = map(int, input().split())
try:
ans=myCalculator.power(n,p)
print(ans)
except Exception as e:
print(e)
```

### Queues and Stacks Day 18 Hackerrank solution in python

Write the following declarations and implementations:

- Two instance variables: one for your stack, and one for your queue.
- A void pushCharacter(char ch) method that pushes a character onto a stack.
- A void enqueueCharacter(char ch) method that enqueues a character in the queue instance variable.
- A char popCharacter() method that pops and returns the character at the top of the stack instance variable.

```
import sys
class Solution:
def __init__(self):
self.mystack = list()
self.myqueue = list()
return(None)
def pushCharacter(self, char):
self.mystack.append(char)
def popCharacter(self):
return(self.mystack.pop(-1))
def enqueueCharacter(self, char):
self.myqueue.append(char)
def dequeueCharacter(self):
return(self.myqueue.pop(0))
# read the string s
s=input()
#Create the Solution class object
obj=Solution()
l=len(s)
# push/enqueue all the characters of string s to stack
for i in range(l):
obj.pushCharacter(s[i])
obj.enqueueCharacter(s[i])
isPalindrome=True
'''
pop the top character from stack
dequeue the first character from queue
compare both the characters
'''
for i in range(l // 2):
if obj.popCharacter()!=obj.dequeueCharacter():
isPalindrome=False
break
#finally print whether string s is palindrome or not.
if isPalindrome:
print("The word, "+s+", is a palindrome.")
else:
print("The word, "+s+", is not a palindrome.")
```

### Interfaces Day 19 Hackerrank solution in python

The AdvancedArithmetic interface and the method declaration for the abstract divisorSum(n) method are provided for you in the editor below.

Complete the implementation of Calculator class, which implements the AdvancedArithmetic interface. The implementation for the divisorSum(n) method must return the sum of all divisors of n.

```
class AdvancedArithmetic(object):
def divisorSum(n):
raise NotImplementedError
class Calculator(AdvancedArithmetic):
def divisorSum(self, n):
#pass
x = []
for i in range(1, n+1):
if n % i == 0:
x.append(i)
else:
pass
return sum(x)
n = int(input())
my_calculator = Calculator()
s = my_calculator.divisorSum(n)
print("I implemented: " + type(my_calculator).__bases__[0].__name__)
print(s)
```

### Sorting Day 20 Hackerrank solution in python

Given an array, a, of size n distinct elements, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following 3 lines:

```
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
numSwaps = 0
for i in range(n):
currentSwaps = 0
for j in range(n-1):
if a[j] > a[j+1]:
tmp = a[j]
a[j] = a[j+1]
a[j+1] = tmp
numSwaps += 1
currentSwaps += 1
if currentSwaps == 0:
break
print('Array is sorted in ' + str(numSwaps) + ' swaps.')
print('First Element: ' + str(a[0]))
print('Last Element: ' + str(a[n-1]))
```

### Generics Day 21 Hackerrank solution in python

Write a single generic function named *printArray*; this function must take an array of generic elements as a parameter (the exception to this is C++, which takes a *vector*). The locked *Solution* class in your editor tests your function.

**Note:** You must use generics to solve this challenge. *Do not* write overloaded functions.

```
from typing import TypeVar
Element = TypeVar("Element")
def printArray(array: [Element]):
for element in array:
print(element)
vInt = [1, 2, 3]
vString = ["Hello", "World"]
printArray(vInt)
printArray(vString)
```

### Binary Search Trees Day 22 Hackerrank solution in python

The height of a binary search tree is the number of edges between the tree's root and its furthest leaf. You are given a pointer, root, pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of the binary search tree.

```
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
def getHeight(self,root):
if root:
leftDepth = self.getHeight(root.left)
rightDepth = self.getHeight(root.right)
if leftDepth > rightDepth:
return leftDepth + 1
else:
return rightDepth + 1
else:
return -1
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
height=myTree.getHeight(root)
print(height)
```

### BST Level Order Traversel Day 23 Hackerrank solution in python

A level-order traversal, also known as a breadth-first search, visits each level of a tree's nodes from left to right, top to bottom. You are given a pointer, root, pointing to the root of a binary search tree. Complete the levelOrder function provided in your editor so that it prints the level-order traversal of the binary search tree.

```
import sys
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
from collections import deque
def levelOrder(self,root):
queue = self.deque([root]) if root else self.deque()
while queue:
node = queue.popleft()
print(node.data, end=' ')
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
myTree.levelOrder(root)
```

### More Linked Lists Day 24 Hackerrank solution in python

A Node class is provided for you in the editor. A Node object has an integer data field, data, and a Node instance pointer, next, pointing to another node (i.e.: the next node in a list).

A removeDuplicates function is declared in your editor, which takes a pointer to the head node of a linked list as a parameter. Complete removeDuplicates so that it deletes any duplicate nodes from the list and returns the head of the updated list.

Note: The head+ pointer may be null, indicating that the list is empty. Be sure to reset your next pointer when performing deletions to avoid breaking the list.

```
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def insert(self,head,data):
p = Node(data)
if head==None:
head=p
elif head.next==None:
head.next=p
else:
start=head
while(start.next!=None):
start=start.next
start.next=p
return head
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
def removeDuplicates(self,head):
#Write your code here
node = head
while node:
if node.next:
if node.data == node.next.data:
node.next = node.next.next
continue
node = node.next
return head
mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
head=mylist.removeDuplicates(head)
mylist.display(head);
```

### Time and Complexity Day 25 Hackerrank solution in python

A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Given a number, n, determine and print whether it's Prime or Not prime.

```
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import count, islice
n = int(input())
for i in range(n):
x, prime = int(input()), True
sq = int(x**0.5)-1
if x<2: prime = False
else:
for num in islice(count(2), sq):
if not x%num:
prime = False
print("Prime") if prime else print("Not prime")
```

### Nested Logic Day 26 Hackerrank solution in python

Your local library needs your help! Given the expected and actual return dates for a library book, create a program that calculates the fine (if any). The fee structure is as follows:

- If the book is returned on or before the expected return date, no fine will be charged (i.e. fine=0) .
- If the book is returned after the expected return day but still within the same calendar month and year as the expected return date, fine= 15 Hackos x number of days late.
- If the book is returned after the expected return month but still within the same calendar year as the expected return date, the fine= 500Hackos x number of days late.
- If the book is returned after the calendar year in which it was expected, there is a fixed fine of 10000 Hackos.

```
returned_date = list(map(int,input().split(' ')))
expected_date = list(map(int,input().split(' ')))
fine = 0
if returned_date[2] > expected_date[2]:
fine = 10000
elif returned_date[2] == expected_date[2]:
if returned_date[1] > expected_date[1]:
fine = (returned_date[1] - expected_date[1])*500
elif returned_date[1] == expected_date[1]:
if returned_date[0] > expected_date[0]:
fine = (returned_date[0] - expected_date[0])*15
print(fine)
```

### Testing Day 27 Hackerrank solution in python

This problem is all about unit testing.

Your company needs a function that meets the following requirements:

For a given array of n integers, the function returns the index of the element with the minimum value in the array. If there is more than one element with the minimum value, the returned index should be the smallest one.

If an empty array is passed to the function, it should raise an Exception.

Note: The arrays are indexed from 0.

```
def minimum_index(seq):
if len(seq) == 0:
raise ValueError("Cannot get the minimum value index from an empty sequence")
min_idx = 0
for i in range(1, len(seq)):
if seq[i] < seq[min_idx]:
min_idx = i
return min_idx
class TestDataEmptyArray():
@staticmethod
def get_array():
return list()
class TestDataUniqueValues():
@staticmethod
def get_array():
return [5, 2, 8, 3, 1, -6, 9]
@staticmethod
def get_expected_result():
return 5
class TestDataExactlyTwoDifferentMinimums():
@staticmethod
def get_array():
return [5, 2, 8, 3, 1, -6, 9, -6, 10]
@staticmethod
def get_expected_result():
return 5
def TestWithEmptyArray():
try:
seq = TestDataEmptyArray.get_array()
result = minimum_index(seq)
except ValueError as e:
pass
else:
assert False
def TestWithUniqueValues():
seq = TestDataUniqueValues.get_array()
assert len(seq) >= 2
assert len(list(set(seq))) == len(seq)
expected_result = TestDataUniqueValues.get_expected_result()
result = minimum_index(seq)
assert result == expected_result
def TestiWithExactyTwoDifferentMinimums():
seq = TestDataExactlyTwoDifferentMinimums.get_array()
assert len(seq) >= 2
tmp = sorted(seq)
assert tmp[0] == tmp[1] and (len(tmp) == 2 or tmp[1] < tmp[2])
expected_result = TestDataExactlyTwoDifferentMinimums.get_expected_result()
result = minimum_index(seq)
assert result == expected_result
TestWithEmptyArray()
TestWithUniqueValues()
TestiWithExactyTwoDifferentMinimums()
print("OK")
```

### Regex Day 28 Hackerrank solution in python

Consider a database table, Emails, which has the attributes First Name and Email ID. Given N rows of data simulating the Emails table, print an alphabetically-ordered list of people whose email address ends in @gmail.com.

```
#!/bin/python3
import re
if __name__ == '__main__':
N = int(input())
pattern = r"@gmail\.com$"
regex = re.compile(pattern)
firstNames = []
for N_itr in range(N):
firstNameEmailID = input().split()
firstName = firstNameEmailID[0]
emailID = firstNameEmailID[1]
if regex.search(emailID):
firstNames.append(firstName)
firstNames.sort()
for name in firstNames:
print(name)
```

### Bitwise Day 29 Hackerrank solution in python

Given set S={1, 2, 3,..., N}. Find two integers, A and B (where A

```
#!/bin/python3
import math
import os
import random
import re
import sys
T = int(input().strip())
for _ in range(T):
n , k = map(int , input().split())
print(k-1 if ((k-1) | k) <= n else k-2)
```

These were all the 30 days of code hackerrank solutions in python I hope you found all the solutions and you completed the challenge. If you want to test any of the above code you can do that quickly by using **an online python compiler**.

## Summary

So this was the complete solutions for the 30 days of code challenge by hackerrank don't copy and paste the solutions directly try to solve them first.

Here are more python guides that might interest you:

**What will be the output of the following python code MCQ.****Best python learning apps free 2022.****Top Regex Interview Questions 2022 for freshers.**

I hope you found this tutorial helpful and what you were looking for and do share this guide with anyone who needs it and also join our **Telegram channel** for more solutions like this.

Thanks for reading, have a nice day 🙂