PROBLEM stmt1
PROBLEM stmt1
PROBLEM stmt1
Hacker Rank is a learning platform and coding editor , It contains various concepts of
Computer science and related topics. Here we can solve and practice various problems from
fundamental to advance topics and suitable badges are provided for each solution , it will
helps to recognize ourself.
Function Description
Complete the wrap function in the editor below.
wrap has the following parameters:
string string: a long string
int max_width: the width to wrap to
Returns
string: a single string with newline characters ('\n') where the breaks should be
Input Format
The first line contains a string,
The second line contains the width.
Sample Input 0
ABCDEFGHIJKLIMNOQRSTUVWXYZ
Sample Output 0
ABCD
EFGH
IJKL IMNO
QRST
UVWX YZ
// CODE
import textwrap
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
PROBLEM 2 Find a String
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.
Input Format
The first line of input contains the original string. The next line contains the substring.
Constraints
1<len(string)<200
Sample Input
ABCDCDC
CDC
Sample Output
2
// CODE
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
Task
Read a given string, change the character at a given index and then print the modified string.
Function Description
Complete the mutate_string function in the editor below.
mutate_string has the following parameters:
string string: the string to change
int position: the index to insert the character at
string character: the character to insert
Returns
string: the altered string
Input Format
The next line contains an integer Position, the index location and a string , charcter separated by a space.
Sample Input
STDIN Function
----- --------
abracadabra s = 'abracadabra'
if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)
print(s_new)
PROBLEM 4 : Time Delta using Math functions
Task
When users post an update on social media,such as a URL, image, status update etc., other users in their
network are able to view this new post on their news feed. Users can also see exactly when the post was
published, i.e, how many hours, minutes or seconds ago.
Since sometimes posts are published and viewed in different time zones, this can be confusing. You are
given two timestamps of one such post that a user can see on his newsfeed in the following format:
Day dd Mon yyyy hh:mm:ss +xxxx
Here +xxxx represents the time zone. Your task is to print the absolute difference (in seconds) between
them.
Input Format
The first line contains , T the number of testcases.
Each testcase contains 2 lines, representing time t1 and time t2.
Constraints
Input contains only valid timestamps.
Output Format
Print the absolute difference in seconds (t1-t2).
Sample Input 0
2
Sun 10 May 2015 13:54:36 -0700
Sun 10 May 2015 13:54:36 -0000
Sat 02 May 2015 19:54:36 +0530
Fri 01 May 2015 13:54:36 -0000
Sample Output 0
25200
88200
// CODE
import math
import os
import random
import re
import sys
t = int(input())
t2 = input()
fptr.write(delta + '\n')
fptr.close()
Sample Input
AABCAAADA
3
Sample Output
AB
CA
AD
// CODE
Task
There is an array of integers. There are also disjoint sets, and , each containing integers. You like all
the integers in set A and dislike all the integers in set B. Your initial happiness is . For each integer in the
array, if , you add 1 to your happiness. If , you add -1 to your happiness. Otherwise, your happiness does
not change. Output your final happiness at the end.
Note: Since and are sets, they have no repeated elements. However, the array might contain duplicate
elements.
Input Format
The first line contains integers n and m separated by a space.
The second line contains integers, the elements of the array.
The third and fourth lines contain integers, and , respectively.
Output Format
Output a single integer, your total happiness.
Sample Input :
32
153
31
57
Sample Output
1
//CODE
# Enter your code here. Read input from STDIN. Print output to STDOUT
# Enter your code here. Read input from STDIN. Print output to STDOUT
if __name__ == "__main__":
happiness = 0
n, m = map(int, input().strip().split(' '))
arr = list(map(int, input().strip().split(' ')))
for i in arr:
if i in good:
happiness += 1
elif i in bad:
happiness -= 1
print(happiness)
PROBLEM 7 : Minion Game
Task
Kevin and Stuart want to play the 'The Minion Game'
Game Rules
Both players are given the same string, S.
Both players have to make substrings using the letters of the string S .
Stuart has to make words starting with consonants.
Kevin has to make words starting with vowels.
The game ends when both players have made all possible substrings.
Scoring
A player gets +1 point for each occurrence of the substring in the string S
Example:
String S = BANANA
Kevin's vowel beginning word = ANA
Here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points.
Sample Input
BANANA
Sample Output
Stuart 12
//CODE
def minion_game(string):
# your code goes here
vowel = 'aeiou'.upper()
strl = len(string)
kevin = sum(strl-i for i in range(strl) if string[i] in vowel)
stuart = strl*(strl + 1)/2 - kevin
if kevin == stuart:
print ('Draw')
elif kevin > stuart:
print ('Kevin %d' % kevin)
else:
print ('Stuart %d' % stuart)
Task
You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.
//CODE
def split_and_join(line):
a = line.split(" ")
b = "-".join(a)
return(b)
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result)
Raghu is a shoe shop owner. His shop has X number of shoes.He has a list containing the
size of each shoe he has in his shop.There are N number of customers who are willing to
pay xi amount of money only if they get the shoe of their desired size.
//CODE
# Enter your code here. Read input from STDIN. Print output to STDOUT
numShoes = int(input())
income = 0
for i in range(numCust):
if shoes[size]:
income += price
shoes[size] -= 1
print(income)
Input
10
2 3 4 5 6 8 7 6 5 18
6 55
6 45
6 55
4 40
18 60
10 50
Sample Output
200
PROBLEM 9 Subset in Python
Task
//CODE
# Enter your code here. Read input from STDIN. Print output to STDOUT
for i in range(int(input())):
a = int(input())
b = int(input())
if len(set_a - set_b) == 0:
print("True")
else:
print("False")
Sample Input
12356
9
985632147
36541
1235689
982
Sample Output
True
False
False
Task
For this challenge, you are given two complex numbers, and you have to print the result of
their addition, subtraction, multiplication, division and modulus operations.
Input Format
One line of input: The real and imaginary part of a number separated by a space.
Output Format
For two complex numbers C and D, the output should be in the following sequence on
separate lines:
C+D
C–D
C*D
C/D
mod(C)
mod(D)
//CODE
import math
class Complex(object):
self.real = real
self.imaginary = imaginary
r = (self.real*no.real)-(self.imaginary*no.imaginary)
i = (self.real*no.imaginary+no.real*self.imaginary)
return Complex(r, i)
num = self*conjugate
denom = no*conjugat
try:
except Exception as e:
print(e)
def mod(self):
m = math.sqrt(self.real**2+self.imaginary**2)
return Complex(m, 0)
def __str__(self):
if self.imaginary == 0:
elif self.real == 0:
if self.imaginary >= 0:
else:
else:
return result
if __name__ == '__main__':
c = map(float, input().split())
d = map(float, input().split())
x = Complex(*c)
y = Complex(*d)
Sample Input
21
56
Sample Output
7.00+7.00i
-3.00-5.00i
You have to generate a list of the first N fibonacci numbers, 0 being the first number. Then,
apply the map function and a lambda expression to cube each fibonacci number and print the
list.
Input Format
Constraints
0 <= N <= 15
Output Format
A list on a single line containing the cubes of the first N fibonacci numbers.
//CODE
cube = lambda x: x ** 3
def fibonacci(n):
a, b, c = 0, 1, 1
for _ in range(n):
yield a
a, b = b, a + b
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n))))
Sample Input : 5
Task
we can assign a default value which is going to be used as the value of said argument if the
function is called without it. For example, consider the following increment function:
return n + increment
Input Format
The input is read by the provided locked code template. In the first line, there is a single
integer q denoting the number of queries. Each of the following q lines contains
a stream_name followed by integer n, and it corresponds to a single test for your function.
Constraints
1 <= q <= 100
1 <= n <= 10
Output Format
The output is produced by the provided and locked code template. For each of the
queries (stream_name, n), if the stream_name is even then print_from_stream(n) is called.
Otherwise, if the stream_name is odd, then print_from_stream(n, OddStream()) .
//CODE
class EvenStream(object):
def __init__(self):
self.current = 0
def get_next(self):
to_return = self.current
self.current += 2
return to_return
class OddStream(object):
def __init__(self):
self.current = 1
def get_next(self):
to_return = self.current
self.current += 2
return to_return
stream.__init__()
for _ in rage(n):
print(stream.get_next())
queries = int(input())
for _ in range(queries):
stream_name, n = input().split()
n = int(n)
if stream_name == "even":
print_from_stream(n)
else:
print_from_stream(n, OddStream())
Sample Input 0
Sample Output 0
1,3,0,2,4,1,3,5,7,9.
An HTMLParser instance is fed HTML data and calls handler methods when start tags, end
tags, text, comments, and other markup elements are encountered.
Task :
Input Format
The first line contains integer N, the number of lines in a HTML code snippet.
The next N lines contain HTML code.
Constraints : 0 < N < 100
Output Format
Print the HTML tags, attributes and attribute values in order of their occurrence from top to
bottom in the given snippet.
//CODE
# Enter your code here. Read input from STDIN. Print output to STDOUT
class MyHTMLParser(HTMLParser):
parser = MyHTMLParser()
for _ in range(int(input())):
parser.feed(input())
Sample Input
<html><head><title>HTML Parser - I</title></head>
Sample Output
Start : html
Start : head
Start : title
End : title
End : head
Start : body
Start : h1
End : h1
Empty : br
End : body
End : html .
Task :
You are given an integer N followed by N email addresses. Your task is to print a
list containing only valid email addresses in lexicographical order.
Input Format
The first line of input is the integer N, the number of email addresses. N lines follow, each
containing a string.
//CODE
def fun(email):
try:
except ValueError:
return False
return False
return False
return False
else:
return True
def filter_mail(emails):
if __name__ == '__main__':
n = int(input())
emails = []
for _ in range(n):
emails.append(input())
filtered_emails = filter_mail(emails)
filtered_emails.sort()
print(filtered_emails)
Sample Input
lara@hackerrank.com
brian-23@hackerrank.com
britts_54@hackerrank.com
Sample Output
Input Format
Constraints
1 <= n <= 99
Output Format
Print n lines where each line i (in the range 1 <= i <= n ) contains the respective decimal,
octal, capitalized hexadecimal, and binary values of i. Each printed value must be formatted
to the width of the binary value of n.
// CODE
def print_formatted(number):
width = len(bin(number)[2:])
deci = str(i)
octa = oct(i)[2:]
hexa = hex(i)[2:].upper()
bina = bin(i)[2:]
print(deci.rjust(width),octa.rjust(width),hexa.rjust(width),bina.rjust(width))
if __name__ == '__main__':
n = int(input())
print_formatted(n)
Sample Input
17
Sample Output
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
5 5 5 101
6 6 6 110
7 7 7 111
8 10 8 1000
9 11 9 1001
10 12 A 1010
11 13 B 1011
12 14 C 1100
13 15 D 1101
14 16 E 1110
15 17 F 1111
16 20 10 10000
17 21 11 10001
VISVESVARAYA TECHNOLOGICAL UNIVERSITY
BELAGAVI, KARNATAKA
BACHELOR OF ENGINEERING
IN
COMPUTER SCIENCE ENGINEERING
SUBMITED BY
MADAN H S
3VC21CS093
SUBMITED TO
Dr. Lingaraj K
In this challenge, the task is to debug the existing code to successfully execute all provided
test files.
Function score_words takes a list of lowercase words as an argument and returns a score as
follows:
The score of a single word is 2 if the word contains an even number of vowels. Otherwise,
the score of this word is 1. The score for the whole list of words is the sum of scores of all
words in the list.
Debug the given function score_words such that it returns a correct score.
Input Format
The input is read by the provided locked code template. In the first line, there is a single
integer n denoting the number of words. In the second line, there are n space-separated
lowercase words.
Constraints
1 <= n <= 20
Each word has at most 20 letters and all letters are English lowercase letters
Output Format
The output is produced by the provided and locked code template. It calls
function score_words with the list of words read from the input as the argument and prints the
returned score to the output.
//CODE
def is_vowel(letter):
def is_vowel(letter):
def score_words(words):
score = 0
for word in words:
num_vowels = 0
if is_vowel(letter):
num_vowels += 1
if num_vowels % 2 == 0:
score += 2
else:
score += 1
return score
n = int(input())
words = input().split()
print(score_words(words))
Sample Input 0
hacker book
Sample Output 0
Task
You are given a 2-D array with dimensions N X M.
Your task is to perform the sum tool over axis 0 and then find the product of that result.
//CODE
import numpy
N, M = map(int, input().split())
Sample Input
22
12
34
Sample Output
24
Input Format
Output Format
For each test case, print ‘Valid’ if the UID is valid. Otherwise, print ‘Invalid’, on separate
lines. Do not print the quotation marks.
//CODE
import re
for _ in range(int(input())):
u = ''.join(sorted(input()))
try:
assert re.search(r'[A-Z]{2}', u)
assert re.search(r'\d\d\d', u)
assert len(u) == 10
except:
print('Invalid')
else:
print('Valid')
Sample Input
B1CD102354
B1CDEF2354
Sample Output
Invalid
Valid
PROBLEM 19 Default Dictionary Tutoial
The defaultdict tool is a container in the collections class of Python. It’s similar to the usual
dictionary (dict) container, but the only difference is that a defaultdict will have
a default value if that key has not been set yet. If you didn’t use a defaultdict you’d have to
check to see if that key exists, and if it doesn’t, set it to what you want.
In this challenge, you will be given 2 integers, n and m. There are n words, which might
repeat, in word group A. There are m words belonging to word group B. For each m words,
check whether the word has appeared in group A or not. Print the indices of each occurrence
of m in group A. If it does not appear, print -1.
//CODE
d = defaultdict(list)
n, m = map(int, input().split())
for i in range(n):
d[input()].append(str(i + 1))
for j in range(m):
35
a
PROBLEM 20 Incorrect Regex Expression
//CODE
import re
T = int(input())
for _ in range(T):
try:
print(bool(re.compile(input())))
except:
print('False')
Sample Input
.*\+
.*+
Sample Output
True
False