Home / Development / Software Development / Python / HackerRank Challenges
HackerRank Python Challenges
In this article I show how I solved HackerRank Python challenges. The main purpose of the content is to present my acquired experiences primarily for learning purposes.
Other categories:
Introduction
Basic Data Types
Strings
Sets
Itertools
Collections
Built-Ins
Numpy
Others
Strings
sWAP cASE
Task:
You are given a string and your task is to swap cases.
In other words, convert all lowercase letters to uppercase letters and vice versa.
Solution:
def swap_case(s): new_str = '' for i in s: new_char = '' if i.isupper(): new_char = i.lower() elif i.islower(): new_char = i.upper() else: new_char = i new_str += new_char return new_str if __name__ == '__main__': s = input() result = swap_case(s) print(result)
String Split and Join
Task:
In Python, a string can be split on a delimiter.
You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.
Solution:
def split_and_join(line): return line.replace(' ', '-') if __name__ == '__main__': line = input() result = split_and_join(line) print(result)
What's Your Name?
Task:
You are given the firstname and lastname of a person on two different lines.
Your task is to read them and print the following:
"Hello firstname lastname! You just delved into python."
Solution:
def print_full_name(first, last): print("Hello " + first + " " + last + "! You just delved into python.") if __name__ == '__main__': first_name = input() last_name = input() print_full_name(first_name, last_name)
Mutations
Task:
We have seen that lists are mutable (they can be changed), and tuples are immutable (they cannot be changed).
Let's try to understand this with an example.
You are given an immutable string, and you want to make changes to it.
Read a given string, change the character at a given index and then print the modified string.
Solution:
def mutate_string(string, position, character): return string[:position] + character + string[position + 1:] if __name__ == '__main__': s = input() i, c = input().split() s_new = mutate_string(s, int(i), c) print(s_new)
Find a string
Task:
In this challenge, the user enters a string and a substring.
You have to print the number of times that the substring occurs in the given string.
String traversal will take place from left to right, not from right to left.
Solution:
def count_substring(string, sub_string): count = 0 for i in range(0, len(string)): if string[i:len(sub_string) + i] == sub_string: count += 1 return count if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
String Validators
Task:
You are given a string S.
Your task is to find out if the string S contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters.
Solution:
s = input() #In the first line, print True if has any alphanumeric characters. Otherwise, print False. found = False for i in s: if i.isalnum(): found = True break print(found) #In the second line, print True if has any alphabetical characters. Otherwise, print False. found = False for i in s: if i.isalpha(): found = True break print(found) #In the third line, print True if has any digits. Otherwise, print False. found = False for i in s: if i.isdigit(): found = True break print(found) #In the fourth line, print True if has any lowercase characters. Otherwise, print False. found = False for i in s: if i.islower(): found = True break print(found) #In the fifth line, print True if has any uppercase characters. Otherwise, print False. found = False for i in s: if i.isupper(): found = True break print(found)
Text Alignment
Task:
You are given a partial code that is used for generating the HackerRank Logo of variable thickness.
Your task is to replace the blank (______) with rjust, ljust or center.
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
Task:
You are given a string S and width w.
Your task is to wrap the string into a paragraph of width w.
Solution:
import textwrap def wrap(string, max_width): i = 0 new_str = '' while i < len(string): new_str += string[i:i + max_width] + '\n' i += max_width return new_str if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)
String Formatting
Task:
Given an integer, n, print the following values for each integer i from 1 to n:
- Decimal
- Octal
- Hexadecimal (capitalized)
- Binary
Function Description
Complete the print_formatted function in the editor below.
print_formatted has the following parameters:
int number: the maximum value to print
Prints
The four values must be printed on a single line in the order specified above for each i from 1 to number. Each value should be space-padded to match the width of the binary value of number and the values should be separated by a single space.
Solution:
def print_formatted(number): format_dec = '{:>'+str(len(str(int(bin(number)[2:]))))+'}' format_bin = '{:>'+str(len(str(int(bin(number)[2:])))+1)+'}' for i in range(1, number + 1): print(format_dec.format(str(i)) + format_bin.format(str(oct(i)[2:])) + format_bin.format(str(hex(i)[2:]).upper()) + format_bin.format(str(bin(i)[2:]))) if __name__ == '__main__': n = int(input()) print_formatted(n)
Capitalize!
Task:
You are asked to ensure that the first and last names of people begin with a capital letter in their passports.
For example, alison heck should be capitalised correctly as Alison Heck.
Given a full name, your task is to capitalize the name appropriately.
Solution:
#!/bin/python3 import math import os import random import re import sys # Complete the solve function below. def solve(s): new_s = '' previous_letter_space = False for i in range(len(s)): if i == 0: new_s += s[i].capitalize() else: if s[i] == ' ': previous_letter_space = True new_s += s[i] else: if previous_letter_space and s[i] != ' ': new_s += s[i].capitalize() previous_letter_space = False else: new_s += s[i] return new_s if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = solve(s) fptr.write(result + '\n') fptr.close()