Hacker Rank - Python Strings
Python Version 3
Problems
- sWAP cASE
- String Split and Join
- What’s Your Name?
- Mutations
- Find a string
- String Validators
- Text Alignment
- Text Wrap
- Designer Door Mat
- String Formatting
- Alphabet Rangoli
- Capitalize
- The Minion Game
- Merge the Tools!
sWAP cASE
Problem -> URL
Difficulty Level: Easy
Pseudocode:
- Read input from user.
- Validate user input, constraints
0 < len(s) <= 100
.- Create a variable result.
- Iterate through each character in string and cast lower case characters into upper case and vise versa.
Solution:
def is_valid_input(input_string): if(len(input_string) > 0 and len(input_string) <= 1000): return True return False def swap_case(s): result = "" if(is_valid_input(s)): for c in s: result += c.upper() if c.islower() else c.lower() return result if __name__ == '__main__': s = input() result = swap_case(s) print(result)
String Split and Join
Problem -> URL
Difficulty Level: Easy
Pseudocode:
- Read input from user.
- Split the string by ‘ ‘.
- Join the list of string by ‘-‘.
Solution:
def split_and_join(line): split_string = line.split(" ") return "-".join(split_string) if __name__ == '__main__': line = input() result = split_and_join(line) print(result)
What’s Your Name?
Problem -> URL
Difficulty Level: Easy
Pseudocode:
- Read input from user.
- Print the required string.
Solution:
# # Complete the 'print_full_name' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING first # 2. STRING last # def print_full_name(first, last): print("Hello {} {}! You just delved into python.".format(first, last)) if __name__ == '__main__': first_name = input() last_name = input() print_full_name(first_name, last_name)
Mutations
Problem -> URL
Difficulty Level: Easy
Pseudocode:
- Read input from user.
- Since strings are immutable, cast string to list.
- Update the character at given index.
- Cast list back to string and return.
Solution:
def mutate_string(string, position, character): str_as_list = list(string) str_as_list[position] = character return "".join(str_as_list) if __name__ == '__main__': s = input() i, c = input().split() s_new = mutate_string(s, int(i), c) print(s_new)
Find a string
Problem -> URL
Difficulty Level: Easy
Pseudocode:
- Read input from user.
- Validate user input, constraints
1 <= len(string) <= 200
.- Instantiate a counter.
- Iterate thru the each character and form the substring from given string of length same as substring length.
- If Substring from string and given substring matches increase the counter by 1.
- Return the counter.
Solution:
def is_valid_input(string): if(len(string) >= 1 and len(string) <= 200): return True return False def count_substring(string, sub_string): str_len = len(string) substr_len = len(sub_string) count = 0 if(is_valid_input(string)): for i in range(0, str_len): if(not(i + substr_len > str_len)): count += 1 if(string[i:i+substr_len] == sub_string) else 0 return count if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
String Validators
Problem -> URL
Difficulty Level: Easy
Pseudocode:
- Read input from user.
- Validate user input, constraints
1 < len(string) < 1000
.- Instantiate variables for alnum, alpha, digit, lower and upper with default value.
- Iterate thru the each character and if the variables are not updated then update the variables. Eg. if we find any alphanumeric then we will update alnum = True.
- Print the variables in the required order.
Solution:
def is_valid_input(string): if(len(string) > 0 and len(string) < 1000): return True return False def solution(string): alnum = False alpha = False digit = False lower = False upper = False if(is_valid_input(string)): for c in string: if(not(alnum)): alnum = c.isalnum() if(not(alpha)): alpha = c.isalpha() if(not(digit)): digit = c.isdigit() if(not(lower)): lower = c.islower() if(not(upper)): upper = c.isupper() if(all([alnum, alpha, digit, lower, upper])): break print(alnum) print(alpha) print(digit) print(lower) print(upper) if __name__ == '__main__': s = input() solution(s)
Text Alignment
Problem -> URL
Difficulty Level: Easy
Pseudocode:
- Read input from user.
- Our task is to replace the blank (__) with rjust, ljust or center.
- Print the requried string pattern.
Solution:
#Replace all ______ with rjust, ljust or center. thickness = int(input()) #This must be an odd number c = 'H' #Top Cone for i in range(thickness): print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1)) #Top Pillars for i in range(thickness+1): print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) #Middle Belt for i in range((thickness+1)//2): print((c*thickness*5).center(thickness*6)) #Bottom Pillars for i in range(thickness+1): print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) #Bottom Cone for i in range(thickness): print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6))
Text Wrap
Problem -> URL
Difficulty Level: Easy
Pseudocode:
- Read input from user.
- Validate user input, constraints
0 < len(string) < 1000
and0 < max_width < len(string)
.- Instantiate a empty string variable.
- Iterate through the index and append the character to the string variable and if index + 1 is divisible by max_width then append ‘\n’ character to string variable
- Print the string variable.
Solution:
import textwrap def is_valid_input(string, max_width): if((len(string) > 0 and len(string) < 1000) and (max_width > 0 and max_width < len(string))): return True return False def wrap(string, max_width): result = "" if(is_valid_input(string, max_width)): for i in range(0, len(string)): result += string[i] if((i + 1) % max_width == 0): result += "\n" return result if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)
Designer Door Mat
Problem -> URL
Difficulty Level: Easy
Pseudocode:
- Read input from user.
- Validate user input, constraints
5 < N < 101
and15 < M < 303
.- Calculate mid_index for N, and form the required pattern for ‘WELCOME’.
- Calculate the width of pattern for each rows above mid_index and print the string.
- Calculate the width of pattern for each rows below mid_index and print the string.
Solution:
from math import ceil def is_valid_input(N, M): if((N > 5 and N < 101) and (M > 15 and M < 303)): return True return False def solution(N, M): mid_index = ceil(N / 2) if(is_valid_input(N, M)): for i in range(0, N): if(i + 1 < N/2): centre_pattern = ".|." * ((i * 2) + 1) edge_pattern = "-" * ((M - len(centre_pattern)) // 2) print(edge_pattern + centre_pattern + edge_pattern) elif (i + 1 == mid_index): print("-" * ((M - 7)//2) + "WELCOME" + "-" * ((M - 7)//2)) else: centre_pattern = ".|." * (((N - i - 1) * 2 ) + 1) edge_pattern = "-" * ((M - len(centre_pattern)) // 2) print(edge_pattern + centre_pattern + edge_pattern) if __name__ == '__main__': user_input = input().split(" ") N = int(user_input[0]) M = int(user_input[1]) solution(N, M)
String Formatting
Problem -> URL
Difficulty Level: Easy
Pseudocode:
- Read input from user.
- Validate user input, constraints
0 <= number <= 100
.- Calculate the maximum width from the max number’s binary string.
- For each number in range of 1 to number,
- Extract decimal, octal, hexa and binary number.
- Form the final string with required width and space.
- Print the pattern string.
Solution:
def is_valid_input(number): if(number >= 1 and number <= 100): return True return False def print_formatted(number): # your code goes here if(is_valid_input(number)): max_width = len(str(bin(number))[2:]) for i in range(0, number): decimal = str(i + 1) octal = str(oct(i + 1))[2:] hexa = str(hex(i + 1))[2:].upper() binary = str(bin(i + 1))[2:] pattern_string = decimal.rjust(max_width) + " " + octal.rjust(max_width) + " " + hexa.rjust(max_width) + " " + binary.rjust(max_width) + " " print(pattern_string) if __name__ == '__main__': n = int(input()) print_formatted(n)
Alphabet Rangoli
Problem -> URL
Difficulty Level: Easy
Pseudocode:
- Read input from user.
- Validate user input, constraints
0 < size < 27
.- Calculate the number of rows and columns. To do this, we need to understand how pattern was created by investigating given examples.
- Generate list of required alphabets in reverse order. e.g. For size = 3, we will have [‘c’, ‘b’, ‘a’].
- For each row,
- First, form the charater string, e.g. ‘c-b-a-b-c’.
- Calculate the width and fill the outer edges.
- Concatenate all together.
- Print the pattern string.
Solution:
def is_valid_input(size): if(size > 0 and size < 27): return True return False def print_rangoli(size): if(is_valid_input(size)): row_length = (size * 2) - 1 column_length = row_length + (size - 1) * 2 alphabets = [chr(i) for i in range(97, 97 + size)][::-1] for i in range(0, row_length): pattern_string = "" if(i <= row_length//2): characters = alphabets[:i+1] + alphabets[:i][::-1] characters_string = "-".join(characters) width = (column_length - len(characters_string)) // 2 width_string = "-" * width pattern_string = width_string + characters_string + width_string else: characters = alphabets[:row_length - i - 1] + alphabets[:row_length - i][::-1] characters_string = "-".join(characters) width = (column_length - len(characters_string)) // 2 width_string = "-" * width pattern_string = width_string + characters_string + width_string print(pattern_string) if __name__ == '__main__': n = int(input()) print_rangoli(n)
Capitalize!
Problem -> URL
Difficulty Level: Easy
Pseudocode:
- Read input from user.
- Validate user input, constraints
0 < len(string) < 1000
.- Instantiate a new empty string variable.
- Split the input string by ‘ ‘.
- Iterate through each word, captialize the word and append to the string variable.
- Print the string variable.
Solution:
#!/bin/python3 import math import os import random import re import sys def is_valid_input(s): if(len(s) > 0 and len(s) < 1000): return True return False # Complete the solve function below. def solve(s): name = "" for word in s.split(" "): if name == "": name += word.capitalize() else: name += " " + word.capitalize() return name if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = solve(s) fptr.write(result + '\n') fptr.close()
The Minion Game
Problem -> URL
Difficulty Level: Medium
Pseudocode:
- Read input from user.
- Validate user input, constraints
0 < len(string) <= 10 ^ 6
.- Instantiate a set with vowels.
- Instantiate counters to count scores for kevin and staurt.
Mathematical Solution
- We know that we should count based on the starting letter in the word, so we don’t need to generate all possible substrings.
- Instead, we will count all the possible word that we can make out of each letter in the word.
e.g. BANANA
B, BA, BAN, BANA, BANAN, BANANA (6)
A, AN, ANA, ANAN, ANANA (5)
N, NA, NAN, NANA (4)
A, AN, ANA (3)
N, NA (2)
A (1)
- From above we can clearly understand that number of words that can be formed starting with character at index
i
will belen(string) - i
- We will iterate through each index in the string and check if the character is in vowels, If yes, we will increase the counter for kevin and if no, we will increase the counter for staurt.
- Finally, Print the maximum score and if scores are equal then print
Draw
.Solution:
def is_valid_input(n): if(n > 0 and n <= 10 ** 6): return True return False vowels = set(['A', 'E', 'I', 'O', 'U']) # Generating Word using substring method # This solution will fail with time limit exceed def minion_game_words(string): # your code goes here n = len(string) if(is_valid_input(n)): stuart_score = 0 kevin_score = 0 for i in range(0, n): for j in range(i, n): word = string[i:j+1] if (word[0] in vowels): kevin_score +=1 else: stuart_score += 1 if stuart_score > kevin_score: print("Stuart {}".format(stuart_score)) elif stuart_score == kevin_score: print("Draw") else: print("Kevin {}".format(kevin_score)) # Mathematical Solution def minion_game(string): # your code goes here n = len(string) if(is_valid_input(n)): stuart_score = 0 kevin_score = 0 for i in range(0, n): if string[i] in vowels: kevin_score += n - i else: stuart_score += n - i if stuart_score > kevin_score: print("Stuart {}".format(stuart_score)) elif stuart_score == kevin_score: print("Draw") else: print("Kevin {}".format(kevin_score)) if __name__ == '__main__': s = input() minion_game(s)
Merge the Tools!
Problem -> URL
Difficulty Level: Medium
Pseudocode:
- Read input from user.
- Validate user input, constraints
1 <= len(string) <= 10 ^ 4
and1 <= k <= n
.- For each substring of k length,
- Instantiate a empty set and a empty string variable.
- For character not in set add the character to set and string, by doing this way we will only have distinct character appended to string variable in same order.
- By end of each iteration, clear the set and print the string variable.
Solution:
def is_valid_input(n, k): if((n >= 1 and n <= 10 ** 4) and (k >= 1 and k <= n)): return True return False def merge_the_tools(string, k): n = len(string) if(is_valid_input(n, k)): for i in range(0, n, k): char_set = set() dist_char_string = "" for j in range(i, i + k): if string[j] not in char_set: dist_char_string += string[j] char_set.add(string[j]) char_set.clear() print(dist_char_string) if __name__ == '__main__': string, k = input(), int(input()) merge_the_tools(string, k)