PROBLEM stmt1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

HACKER RANK PYTHON BADGE

LINK : MADAN HS - madanhs_cse_rym1 | HackerRank .

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.

This platform provides recognized certifications about various topics.


PROBLEM 1 : Text wrapping using strings
You are given a string S and width W .
Your task is to wrap the string into a paragraph of width .

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

def wrap(string, max_width):


for i in range(0,len(string)+1,max_width):
result = string[i:i+max_width]
if len(result) == max_width:
print(result)
else:
return(result)

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.

NOTE: String letters are case-sensitive.

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

def count_substring(string, sub_string):


count=0
for i in range(0, len(string)-len(sub_string)+1):
if string[i] == sub_string[0]:
flag=1
for j in range (0, len(sub_string)):
if string[i+j] != sub_string[j]:
flag=0
break
if flag==1:
count += 1
return count

if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()

count = count_substring(string, sub_string)


print(count)
PROBLEM 3 : Mutations in string

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 first line contains a string, STRING

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'

5k position = 5, character = 'k'


Sample Output
abrackdabra
// CODE

def mutate_string(string, position, character):


n = list(string)
n[position] = character
string = "".join(n)
return string

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

# Complete the time_delta function below.


from datetime import datetime
def time_delta(t1, t2):
time_format = '%a %d %b %Y %H:%M:%S %z'
t1 = datetime.strptime(t1, time_format)
t2 = datetime.strptime(t2, time_format)
return str(int(abs((t1-t2).total_seconds())))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

t = int(input())

for t_itr in range(t):


t1 = input()

t2 = input()

delta = time_delta(t1, t2)

fptr.write(delta + '\n')

fptr.close()

PROBLEM 5 Merge the Tools

Consider the following: A string,s , of length where s is equals c1+c2+…+cn . An integer,k ,


where k is a factor of n .
We can split into substrings where each subtring, n/2 , consists of a contiguous block of characters
in . Then, use each to create string such that:
 The characters in are a subsequence of the characters in ti .

Sample Input
 AABCAAADA
 3

Sample Output
 AB
 CA
 AD

// CODE

def merge_the_tools(string, k):


# your code goes here
temp = []
len_temp = 0
for item in string:
len_temp += 1
if item not in temp:
temp.append(item)
if len_temp == k:
print (''.join(temp))
temp = []
len_temp = 0
if __name__ == '__main__':
string, k = input(), int(input())
merge_the_tools(string, k)
PROBLEM 6 : Set operations

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(' ')))

good = set(map(int, input().strip().split(' ')))


bad = set(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)

PROBLEM 8 : String Split and Join Method .

Task

You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.

Complete the split_and_join function in the editor below.


split_and_join has the following parameters:
 string line: a string of space-separated words.
 Input Format
The one line contains a string consisting of space separated words.
 Sample Input
 this is a string
 Sample Output
 this-is-a-string

//CODE

def split_and_join(line):

# write your code here

a = line.split(" ")

b = "-".join(a)

return(b)

if __name__ == '__main__':

line = input()

result = split_and_join(line)

print(result)

PROBLEM 8 Collections counter in python

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.

Your task is to compute how much money Raghu earned.

//CODE

# Enter your code here. Read input from STDIN. Print output to STDOUT

from collections import Counter

numShoes = int(input())

shoes = Counter(map(int, input().split()))


numCust = int(input())

income = 0

for i in range(numCust):

size, price = map(int, input().split())

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

You are given two sets, A and B.


Your job is to find whether set A is a subset of set B.

If set A is subset of set B, print True.


If set A is not a subset of set B, print False.

//CODE

# Enter your code here. Read input from STDIN. Print output to STDOUT

for i in range(int(input())):

a = int(input())

set_a = set(map(int, input().split()))

b = int(input())

set_b = set(map(int, input().split()))

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

PROBLEM 10 Inheritance in Python ( Complex Number )

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):

def __init__(self, real, imaginary):

self.real = real

self.imaginary = imaginary

def __add__(self, no):

return Complex((self.real+no.real), self.imaginary+no.imaginary)

def __sub__(self, no):

return Complex((self.real-no.real), (self.imaginary-no.imaginary))

def __mul__(self, no):

r = (self.real*no.real)-(self.imaginary*no.imaginary)

i = (self.real*no.imaginary+no.real*self.imaginary)

return Complex(r, i)

def __truediv__(self, no):

conjugate = Complex(no.real, (-no.imaginary))

num = self*conjugate

denom = no*conjugat
try:

return Complex((num.real/denom.real), (num.imaginary/denom.real))

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:

result = "%.2f+0.00i" % (self.real)

elif self.real == 0:

if self.imaginary >= 0:

result = "0.00+%.2fi" % (self.imaginary)

else:

result = "0.00-%.2fi" % (abs(self.imaginary))

elif self.imaginary > 0:

result = "%.2f+%.2fi" % (self.real, self.imaginary)

else:

result = "%.2f-%.2fi" % (self.real, abs(self.imaginary))

return result

if __name__ == '__main__':
c = map(float, input().split())

d = map(float, input().split())

x = Complex(*c)

y = Complex(*d)

print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n')

Sample Input

21

56

Sample Output

7.00+7.00i

-3.00-5.00i

PROBLEM 11 Map and Lambda Functions in Python

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

One line of input: an integer N.

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

Sample Output : [0, 1, 1, 8, 27] .

PROBLEM 12 Default arguments in Python

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:

def increment_by(n, increment=1)

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

def print_from_stream(n, stream=EvenStream()):

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

3,odd 2,even 3,odd 5

Sample Output 0

1,3,0,2,4,1,3,5,7,9.

PROBLEM 13 HTML Parser

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 :

You are given an HTML code snippet of N lines.


Your task is to print start tags, end tags and empty tags separately.

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

from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):

def handle_starttag(self, tag, attrs):

print ('Start :', tag)

for ele in attrs:

print ('->', ele[0], '>', ele[1])

def handle_endtag(self, tag):

print ('End :', tag)

def handle_startendtag(self, tag, attrs):

print ('Empty :', tag)

for ele in attrs:

print ('->', ele[0], '>', ele[1])

parser = MyHTMLParser()

for _ in range(int(input())):

parser.feed(input())

Sample Input
<html><head><title>HTML Parser - I</title></head>

<body data-modal-target class='1'><h1>HackerRank</h1><br /></body></html>

Sample Output

Start : html

Start : head

Start : title

End : title

End : head

Start : body

-> data-modal-target > None

-> class > 1

Start : h1

End : h1

Empty : br

End : body

End : html .

PROBLEM 14 Validating Email Address using filters .

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.

Constraints : Each line is a non-empty string.

//CODE

def fun(email):

try:

username, url = email.split('@')

website, extension = url.split('.')

except ValueError:

return False

if username.replace('-', '').replace('_', '').isalnum() is False:

return False

elif website.isalnum() is False:

return False

elif len(extension) > 3:

return False

else:

return True

def filter_mail(emails):

return list(filter(fun, 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

['brian-23@hackerrank.com', 'britts_54@hackerrank.com', 'lara@hackerrank.com'] .

PROBLEM 15 String Formatting.

Input Format

A single integer denoting n.

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:])

for i in range(1, number+1):

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

“ FULL STACK DEVELOPMENT ASSIGNMENT ”

BACHELOR OF ENGINEERING
IN
COMPUTER SCIENCE ENGINEERING

SUBMITED BY

MADAN H S

3VC21CS093

SUBMITED TO

Dr. Lingaraj K

Asst Professor. Dept of CSE.

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


RAO BAHADUR Y.MAHABALESHWARAPPA COLLEGE OF ENGINEERING
(AFFILIATED TO VISVESVARAYA TECHNOLOGICAL UNIVERSITY, BELAGAVI & APPROVED
BY AICTE & ACCREDITED BY NBA, NEW DELHI)
BALLARI - 583104, KARNATAKA
PROBLEM 16 WORD SCORE

In this challenge, the task is to debug the existing code to successfully execute all provided
test files.

Consider that vowels in the alphabet are a, e, i, o, u and y.

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):

return letter in ['a', 'e', 'i', 'o', 'u', 'y']

def is_vowel(letter):

return letter in ['a', 'e', 'i', 'o', 'u', 'y']

def score_words(words):

score = 0
for word in words:

num_vowels = 0

for letter in word:

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

PROBLEM 17 SUM and PRODUCT using numpy

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())

A = numpy.array([input().split() for _ in range(N)],int)

print(numpy.prod(numpy.sum(A, axis=0), axis=0))

Sample Input

22

12

34

Sample Output

24

PROBLEM 18 Validating UID using Regex

ABCXYZ company has up to 100 employees.


The company decides to create a unique identification number (UID) for each of its
employees.
The company has assigned you the task of validating all the randomly generated UIDs.

Input Format

The first line contains an integer T, the number of test cases.


The next T lines contains an employee’s UID.

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 not re.search(r'[^a-zA-Z0-9]', u)

assert not re.search(r'(.)\1', 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

from collections import defaultdict

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):

print(' '.join(d[input()]) or -1)

Sample Input Sample Output

35

----- -------- 124

52 group A size n = 5, group B size m = 2 35

a group A contains 'a', 'a', 'b', 'a', 'b'

a
PROBLEM 20 Incorrect Regex Expression

You are given a string S.


Your task is to find out whether S is a valid regex or not.

The first line contains integer T, the number of test cases.


The next T lines contains the string S.

//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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy