Last active
February 14, 2024 03:56
-
-
Save Br2850/2e9171968b255da411597fdf1c188113 to your computer and use it in GitHub Desktop.
Solutions for HackerRank 30 Day Challenge in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'Solutions for HackerRank 30 Day Challenge in Python.' | |
***Solution to Day 19 skipped, because Pyhton implementation was not available at the time of completion. | |
***Solution to Day 21 skipped, because Python implementation was not available at the time of completion. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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(str(input_string)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def Weird_Problem(): | |
integer = input() | |
double = input() | |
string_1 = input () | |
sum_int = int(integer) + i # new integer | |
double_d = float(double) + d # new double | |
sentence = s + '' + string_1 # new sentence | |
print('{0}\n{1:0.1f}\n{2}'.format(sum_int, double_d, sentence)) # prints all the statements on new lines | |
Weird_Problem() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def binary(n): | |
binary_string = '' # binary placeholder | |
while n >= 1: | |
remainder = n % 2 # looks for remainder of a base-10 number divided by base 2 | |
binary_string += str(remainder) # adds remainder i.e, 0 or 1 to binary string | |
n = n // 2 # decreases number by factor of 2 ignoring the remainder | |
return int(binary_string[-1::-1]) # returns binary string backwards, to match binary structure | |
def longest_consec_1(): | |
n = int(input().strip()) # input value | |
bin_number = str(binary(n)) # stores the binary of a number in a var | |
ones_list = bin_number.split('0') # splits binary by placement of zeros | |
print(len(max(ones_list))) # finds max number of list of 1s and returns length | |
longest_consec_1() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def hourglass(): | |
arr = [] # array placeholder | |
result = [] | |
for arr_i in range(6): # given values | |
arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')] # given values | |
arr.append(arr_t) # given array | |
for x in range(0, 4): # range for row of 16 hourglasses | |
for y in range(0, 4): # range for column of 16 houglasses | |
s = (arr[x][y] + arr[x][y+1] + arr[x][y+2] # 1st row of hourglass structure | |
+ arr[x+1][y+1] # 2nd row of hourglass | |
+ arr[x+2][y] + arr[x+2][y+1] + arr[x+2][y+2]) # 3rd row of hourglass | |
result.append(s) # appends sum to list | |
print(max(result)) # prints max value | |
hourglass() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, scores): | |
self.firstName = firstName | |
self.lastName = lastName | |
self.idNumber = idNumber | |
self.scores = scores | |
def calculate(self): | |
avg_score = sum(self.scores) / len(self.scores) | |
if avg_score >= 90 and avg_score <= 100: | |
return 'O' | |
elif avg_score >= 80 and avg_score < 90: | |
return 'E' | |
elif avg_score >= 70 and avg_score < 80: | |
return 'A' | |
elif avg_score >= 55 and avg_score < 70: | |
return 'P' | |
elif avg_score >= 40 and avg_score < 55: | |
return 'D' | |
else: | |
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()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
#Write MyBook class | |
class MyBook(Book): | |
def __init__(self, title, author, price): | |
self.title = title | |
self.author = author | |
self.price = price | |
def display(self): | |
print('Title: {0}'.format(self.title)) | |
print('Author: {0}'.format(self.author)) | |
print('Price: {0}'.format(self.price)) | |
title=input() | |
author=input() | |
price=int(input()) | |
new_novel=MyBook(title,author,price) | |
new_novel.display() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Difference: | |
def __init__(self, a): | |
self.__elements = a | |
self.maximumDifference = 0 # instance variable set intially at 0 | |
def computeDifference(self): # difference method | |
sorted_array = sorted(self.__elements) # sorts array | |
self.maximumDifference = abs(sorted_array[0] - sorted_array[len(sorted_array) - 1]) # finds absolute difference | |
return self.maximumDifference # returns absolute difference assigned in maximumDifference | |
# End of Difference class | |
_ = input() | |
a = [int(e) for e in input().split(' ')] | |
d = Difference(a) | |
d.computeDifference() | |
print(d.maximumDifference) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: # if empty link | |
self.head = Node(data) # head becomes Node trying to be inserted | |
else: # if link has length of at least 1 | |
current = self.head # pointer starts at head | |
while current.next: # infinite loop until false | |
current = current.next # pointer iterates through each node | |
current.next = Node(data) # assign null node to Node(data) trying to be inserted | |
return self.head | |
mylist= Solution() | |
T=int(input()) | |
head=None | |
for i in range(T): | |
data=int(input()) | |
head=mylist.insert(head,data) | |
mylist.display(head); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def string_to_int(): | |
S = input().strip() # takes input | |
try: # try block | |
print(int(S)) # prints string if it can be converted to an int | |
except: # error/except block | |
print('Bad String') # error message | |
string_to_int() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Calculator(object): | |
def power(self, n, p): # method | |
if n < 0 or p < 0: # exception cases | |
raise Exception('n and p should be non-negative') # Error message | |
else: | |
exponential = n ** p # exponential function | |
return exponential | |
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def __init__(self): | |
# empty instance variables | |
self.queue = [] #FIFO | |
self.stack = [] #LIFO | |
def pushCharacter(self, char): | |
new_char = self.stack.append(char) # adds character to stack | |
return new_char | |
def enqueueCharacter(self, char): | |
new_char = self.queue.append(char) # adds character to queue | |
return new_char | |
def popCharacter(self): | |
last_char = self.stack.pop(-1) # removes and returns last item in stack | |
return last_char | |
def dequeueCharacter(self): | |
first_char = self.queue.pop(0) # removes and returns first item in stack | |
return first_char | |
# 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.") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def meal_cost(): | |
meal = float(input()) # cost of meal before tax an tip | |
tip = float(input()) # percentage of tip | |
tax = float(input()) # percentage of tax | |
tip = tip / 100 # decimal of tip | |
tax = tax / 100 # decimal of tax | |
totalCost = meal + (meal * tip) + (meal * tax) # cost of meal including tax and tip | |
print('The total meal cost is {0} dollars.'.format(round(totalCost))) | |
meal_cost() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def bubble_sort(): | |
'''Runs in O(n^2) time.''' | |
n = int(input().strip()) | |
a = [int(a_temp) for a_temp in input().strip().split(' ')] | |
numSwaps = 0 # tracks number of swaps | |
for j in range(n): # for each index | |
for i in range(1, n): # runs n-1 seperate checks | |
if a[i] < a[i-1]: # if the left number is greater than the right number | |
a[i-1], a[i] = a[i], a[i-1] # transpose action | |
numSwaps += 1 # counts a swap | |
else: | |
None | |
print('Array is sorted in {0} swaps.'.format(numSwaps)) | |
print('First Element: {0}'.format(a[0])) | |
print('Last Element: {0}'.format(a[-1])) | |
bubble_sort() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 == None: # Base case | |
return -1 # num of nodes - 1 => edges | |
else: | |
return max(self.getHeight(root.left) + 1, self.getHeight(root.right) + 1) # add one recursive call | |
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 levelOrder(self, root): | |
queue = [] # empty queue FIFO | |
temp_node = root # assigns a temp value to the root node | |
queue.append(temp_node) # adds root to queue | |
while len(queue) > 0: | |
print(queue[0].data, end=" ") # takes first value in queue and prints its data | |
temp_node = queue.pop(0) # removes first value and assigns it to temp_node | |
if temp_node.left: # if left child exists | |
queue.append(temp_node.left) | |
if temp_node.right: # if right child exists | |
queue.append(temp_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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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): | |
if head: | |
current = head # pointer | |
while current.next: # while there is a next node | |
if current.data == current.next.data: # if current node and next node have the same data | |
current.next = current.next.next # next node becomes the node after itself | |
else: | |
current = current.next # current node becomes the next node | |
return head # returns head | |
else: | |
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def wacky_number(): | |
N = int(input().strip()) | |
if N % 2 == 0: # checks even condition | |
if N in list(range(2, 6)): # first condition | |
print('Not Weird') | |
elif N in list(range(6, 21)): # second condition | |
print('Weird') | |
else: | |
print('Not Weird') # greater than 20 | |
else: | |
print('Weird') # odd number | |
wacky_number() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person: | |
def __init__(self, age): | |
# Add some more code to run some checks on initialAge | |
self.age = age | |
self.initialAge = 0 | |
if self.age < 0: | |
self.age = self.initialAge | |
print('Age is not valid, setting age to 0.') | |
else: | |
self.initialAge = self.age | |
def amIOld(self): | |
# Do some computations in here and print out the correct statement to the console | |
if self.age < 13: | |
print('You are young.') | |
elif self.age >= 13 and self.age < 18: | |
print('You are a teenager.') | |
else: | |
print('You are old.') | |
def yearPasses(self): | |
# Increment the age of the person in here | |
self.age += 1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def multiples(): | |
N = int(input().strip()) | |
for number in range(1, 11): | |
print('{0} x {1} = {2}'.format(N, number, N*number)) | |
multiples() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def mixed_word(word): | |
even_word = word[::2] # appends every 2 indicies starting at index 0 | |
odd_word = word[1::2] # appends every 2 inidicies starting at index 1 | |
return'{0} {1}'.format(even_word, odd_word) # joins individual word structures and then prints in correct format | |
def full_input(): | |
for i in range(int(input().strip())): # creates number of iterations based on input | |
print(mixed_word(input().strip())) # calls mixed_words for each input and then prints | |
full_input() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def array_reverse1(): | |
n = int(input().strip()) | |
arr = [str(arr_temp) for arr_temp in input().strip().split(' ')] # changed int variable to str an created a list | |
print(' '.join(arr[::-1])) # joins list in reverse and inserts a space after each number | |
array_reverse1() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def phone_book(): | |
number_of_people = int(input()) # takes initial input of number of entries | |
phonebook = {} # dict placeholder | |
for i in range(number_of_people): # iterates n number of times | |
name, number = input().split(' ') # assigns name and number | |
phonebook[name] = number # appends to dictionary | |
while True: # infinite loop | |
try: | |
lookup = input() # asks for input if any | |
if lookup in phonebook: # searches dictionary | |
print('{0}={1}'.format(lookup,phonebook[lookup])) # if in dictionary, prints name and number | |
else: | |
print('Not found') # if not in dictionary, prints desired message | |
except: # if no input is found, breaks the infinite loop | |
break | |
phone_book() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def factorial(N): | |
N = int(N) | |
if N == 1: # Base Case | |
return 1 | |
else: # Recursive Case | |
return N * factorial(N - 1) # Takes parameter and multiples by recursive function | |
print(factorial(int(input()))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment