My goal is to commit to 2 challenges a day for this 30 day HackerRank python challenge, while simultaneously studying for OSCP and doing boxes (Target : 1hr per day)
Day 6 : Lets Review
So this challenge mainly reviews knowledge of strings, loops and accessing indexes
Task
Given a string, , of length that is indexed from to , print its even-indexed and odd-indexed characters as 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
# First input is number of test cases, T
T = int(input())
#Now iterate exactly T times for per input string S
for i in range (0,T):
#take twice input string
S=input()
# Now this is the function for slicing indexes of even + odd
print(S[0::2] + " " + S[1::2])
# first [0::2] takes index zero of string S then jumps by twos to the end and so on..
Day 7 : Arrays
Task
Given an array, , of integers, print 's elements in reverse order as a single line of space-separated numbers.
Example
A = [1,2,3,4]
Print 4 3 2 1. Each integer is separated by one space.
Solution 1 - use slicing with negative step then join
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
#to reverse theres a few ways, one is to call from -1 steps (the last element to first)
x = arr[::-1]
# this gives us an array of reverse n [2, 3, 4, 1]
y=' '.join(str(e) for e in x)
#must use str to convert int (you cannot join int)
print(y)
# the above returns the array reversed, now to convert to string with spaces
Solution 2 - for loop
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
empty=[]
# loop from 0 to len -1 size of list
for i in range(0,len(arr)):
#append item at -1 to list
#basically u wanna count -1, -2, -3 ...
#so if i start from 0, 1 > apply algo such that 0, 1 turns to -1, -2
empty.append(arr[-(i+1)])
print(' '.join(str(e) for e in empty))
Day 8 : Dictionaries & Key-value map
Task
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 is not found, print Not found instead.
The criteria was for the phone book to be of: Dictionary, Map or HashMap data structure
Input format:
3 #cater dictionary length to n provided
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry #these queries can go unlimited
Solution
Used first to map to dictionary structure, next perform while True if loop for input in dict (is the name query a key in the dictionary?)
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
# only takes first line, number of dict items = 3
# PART 1: CREATE DICT
dict={}
for x in range(0,int(n)):
s = input()
# s now reads the dict items names and num
y=s.split(" ")
#multiple duo arrays with [name1, num1] and so on
dict[y[0]]=y[1]
#print(dict) #now we have a dict of the names and nums linked ready
#PART 2: QUERIES HANDLING
while True:
try:
inp=input()
if inp in dict: #if names queries are keys in dict
print(inp + "=" + dict[inp])
else:
print("Not found")
except EOFError:
break
Tip: items() method for looping through dictionaries
dict = {...}
for key, value in dict.items():
print(key, value)
Recap: Looping over a list and appending filtered values (To filter out only numbers)
import math
raw_data = [1,2,3, "nan"]
filtered_data = []
for value in raw_data:
#use math.isnan(<insert to be filtered>)
if !math.isnan(value):
filtered_data.append(value)
Day 9 : Recursion & Factorial of Number
#!/bin/python3
import math
import os
import random
import re
import sys
#main
def factorial(n):
# intialise
result = 1
for i in range(2,n+1):
result = result*i
#input 3 = 3*2*1 (we exclude 2 to cut process time)
return result
#the below is provided to process input
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
result = factorial(n)
fptr.write(str(result) + '\n')
fptr.close()
Day 10 : Converting Base10 to Base2
Given a base10 number, convert to base2 and find the maximum number of consecutive ones '1'.
Plan 1:
counter of current no. of consecutive 1 (if current counter > maximum counter, set it to maximum counter value)
counter of maximum consecutive 1
once hit zero, reset counter to zero
#!/bin/python3
import sys
n = int(input().strip())
# first intialize counters
current_consecutive_ones=0
max_consecutive_ones=0
while n>0:
remainder = n%2
if remainder == 1:
current_consecutive_ones += 1 #now to let max_consecutive catchup to current counter
if current_consecutive_ones > max_consecutive_ones:
current_consecutive_ones == max_consecutive_ones
else: #remainder ==0 (cant be anything except 0 or 1 when divided by 2
current_consecutive_ones = 0 #reset to zero
n = n//2
#// is floor division, 9//2 = 4
print(max_consecutive_ones)
num = int(input())
convert = bin(num) # binary numbers 1 or 0
current = 0
maximum = 0
for i in convert:
if i =='1':
current +=1
else:
current = 0 # reset to zero
maximum_count = max(maximum, current)
print(max(maximum,current))
Plan 4: Use append the remainders to a list, count number of 1s
if __name__ == '__main__':
n = int(input())
rmd = []
while n > 0:
rm = n % 2
n = n//2
rmd.append(rm)
count,result = 0,0 # intialise
for i in range(0,len(rmd)): #iterate thru list for ones
if rmd[i] == 0:
count = 0
else:
count +=1
result = max(result,count)
print(result)