Q1 Hello World: You Do Not Need To Read Any Input in This Challenge. Print To Stdout
Q1 Hello World: You Do Not Need To Read Any Input in This Challenge. Print To Stdout
Q1 Hello World: You Do Not Need To Read Any Input in This Challenge. Print To Stdout
Q1 Hello World
Input Format
You do not need to read any input in this challenge.
Output Format
Print Hello, World! to stdout.
Sample Output 0
Hello, World!
CODE
print("Hello, World!")
2 .If-else
Given an integer,n , perform the following conditional actions:
● If n is odd, print Weird
● If n is even and in the inclusive range of 2 to 5, print Not Weird
● If n is even and in the inclusive range of 6 to 20, print Weird
● If n is even and greater than 20, print Not Weird
Input Format
A single line containing a positive integer, n.
Constraints
● 1<= n<= 100
Output Format
Print Weird if the number is weird. Otherwise, print Not Weird.
Sample Input 0
3
Sample Output 0
Weird
Explanation 0
n=3
n is odd and odd numbers are weird, so print Weird.
CODE
if __name__ == '__main__':
n = int(input().strip())
if n%2 == 1:
print("Weird")
else:
if n>=2 and n<=5:
print("Not Weird")
elif n>=6 and n<=20:
print("Weird")
else:
print("Not Weird")
3. Arithmetic Operators
The provided code stub reads two integers from STDIN, a and b. Add code to
print three lines where:
1. The first line contains the sum of the two numbers.
2. The second line contains the difference of the two numbers (first -
second).
3. The third line contains the product of the two numbers.
Print the following:
8
-2
15
Input Format
The first line contains the first integer,a.
The second line contains the second integer,b.
Output Format
Print the three lines as explained above.
Sample Input 0
3
2
Sample Output 0
5
1
6
CODE
if __name__ == '__main__':
a = int(input())
b = int(input())
print(a + b)
print(a - b)
print(a * b)
4. Loops
The provided code stub reads and integer, n, from STDIN. For all non-negative
integers i<n, print i^2.
Input Format
The first and only line contains the integer, .
Output Format
Print n lines, one corresponding to each .
Sample Input 0
5
Sample Output 0
0
1
4
9
16
CODE
if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i*i)
5.List Comprehensions
Let’s learn about list comprehensions! You are given three integers X, Y and Z representing the
dimensions of a cuboid along with an integer . You have to print a list of all possible coordinates
given by (i, j, k) on a 3D grid where the sum of i+j+k is not equal to N . Here, 0<=i<=X; 0<=j<=Y;
0<=k<=Z.
Input Format
Four integers X,Y,Z and N each on four separate lines, respectively.
Constraints
Print the list in lexicographic increasing order.
Sample Input
1
1
1
2
Sample Output
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1].
CODE
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
6.Nested Lists
Given the names and grades for each student in a class of N students, store them
in a nested list and print the name(s) of any student(s) having the second lowest
grade.
Note: If there are multiple students with the second lowest grade, order their
names alphabetically and print each name on a new line.
Input Format
The first line contains an integer,N , the number of students.
The 2N subsequent lines describe each student over 2 lines.
- The first line contains a student's name.
- The second line contains their grade.
Constraints
● 2<=N<=5
● There will always be one or more students having the second lowest grade.
Output Format
Print the name(s) of any student(s) having the second lowest grade in. If there are
multiple students, order their names alphabetically and print each one on a new line.
Sample Input 0
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
Sample Output 0
Berry
Harry
CODE
marksheet=[]
scorelist=[]
if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input())
marksheet+=[[name,score]]
scorelist+=[score]
b=sorted(list(set(scorelist)))[1]
7.Tuples
Given an integer,n , and n space-separated integers as input, create a tuple, , of
those integers. Then compute and print the result of hash(t).
Note: hash() is one of the functions in the __builtins__ module, so it need not be
imported.
Input Format
The first line contains an integer,n , denoting the number of elements in the tuple.
The second line contains n space-separated integers describing the elements in tuple .
Output Format
Print the result of hash(t).
Sample Input 0
2
12
Sample Output 0
3713081631934410656
CODE
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
t = tuple(integer_list)
print(hash(t));
Sample Output 0
56.00
Explanation 0
CODE
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
print("{0:.2f}".format(round(sum(student_marks[query_name]) /
len(student_marks[query_name]), 2)))
9.Python: Division
The provided code stub reads two integers,a and b, from STDIN.
Add logic to print two lines. The first line should contain the result of integer division, a//b.
The second line should contain the result of float division,a / b.
No rounding or formatting is necessary.
Input Format
The first line contains the first integer,a.
The second line contains the second integer,b.
Output Format
Print the two lines as described above.
Sample Input 0
4
3
Sample Output 0
1
1.33333333333
CODE
if __name__ == '__main__':
a = int(input())
b = int(input())
print(a//b)
print(a/b)
10.Write a function
An extra day is added to the calendar almost every four years as February 29, and the
day is called a leap day. It corrects the calendar for the fact that our planet takes
approximately 365.25 days to orbit the sun. A leap year contains a leap day.
In the Gregorian calendar, three conditions are used to identify leap years:
● The year can be evenly divided by 4, is a leap year, unless:
● The year can be evenly divided by 100, it is NOT a leap year, unless:
● The year is also evenly divisible by 400. Then it is a leap year.
This means that in the Gregorian calendar, the years 2000 and 2400 are leap years,
while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. Source
Task
Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean
True, otherwise return False.
Note that the code stub provided reads from STDIN and passes arguments to the
is_leap function. It is only necessary to complete the is_leap function.
Input Format
Read year, the year to test.
Output Format
The function must return a Boolean value (True/False). Output is handled by the
provided code stub.
Sample Input 0
1990
Sample Output 0
False
Explanation 0
1990 is not a multiple of 4 hence it's not a leap year.
CODE
def is_leap(year):
leap = False
PAGE 2
1.Print Function
The included code stub will read an integer,n, from STDIN. Without using any string methods,
try to print the following: 123….n
Note that "..." represents the consecutive values in between.
Example
n=5
Print the string 12345
Input Format
The first line contains an integer .
Constraints
1 ≤ n ≤ 150
Output Format
Print the list of integers from 1 through as a string, without spaces.
Sample Input 0
3
Sample Output 0
123
CODE
if __name__ == '__main__':
n = int(input())
for i in range(1,n+1):
print(i,end=(""))
2.Lists
Consider a list (list = []). You can perform the following commands:
1. insert i e: Insert integer at position .
2. print: Print the list.
3. remove e: Delete the first occurrence of integer .
4. append e: Insert integer at the end of the list.
5. sort: Sort the list.
6. pop: Pop the last element from the list.
7. reverse: Reverse the list.
Initialize your list and read in the value of followed by lines of commands where each
command will be of the types listed above. Iterate through each command in order and perform
the corresponding operation on your list.
Input Format
The first line contains an integer, , denoting the number of commands.
Each line of the subsequent lines contains one of the commands described above.
Constraints
● The elements added to the list must be integers.
Output Format
For each command of type print, print the list on a new line.
Sample Input 0
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
CODE
if __name__ == '__main__':
N = int(input())
list=[]
while N!=0:
q=input().split()
if q[0].startswith("i"):
list.insert(int(q[1]),int(q[2]))
elif q[0].startswith("rem"):
list.remove(int(q[1]))
elif q[0].startswith("a"):
list.append(int(q[1]))
elif q[0].startswith("s"):
list.sort()
elif q[0].startswith("po"):
list.pop()
elif q[0].startswith("rev"):
list.reverse()
else:
print(list)
N=N-1
3.String Formatting
Given an integer, n, print the following values for each integer i from 1 to n:
Decimal Octal Hexadecimal (capitalized) Binary The four values must be printed on a
single line in the order specified above for each from 1 to 2. Each value should be
space-padded to match the width of the binary value of n.
Input Format
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.
Sample Input 0
17
Sample Output 0
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
CODE
def print_formatted(number):
# your code goes here
width = len("{0:b}".format(number))
4.Capitalize!
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.
Input Format
A single line of input containing the full name,S.
Constraints
●
● The string consists of alphanumeric characters and spaces.
Note: in a word only the first character is capitalized. Example 12abc when capitalized
remains 12abc.
Output Format
Print the capitalized string,S .
Sample Input
chris alan
Sample Output
Chris Alan
CODE
def solve(s):
for i in s.split():
s = s.replace(i,i.capitalize())
return s
5.sWAP cASE
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.
For Example:
Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2
Input Format
A single line containing a string S.
Constraints
0< len(S) ≤ 1000
Output Format
Print the modified string S.
Sample Input 0
HackerRank.com presents "Pythonist 2".
Sample Output 0
hACKERrANK.COM PRESENTS "pYTHONIST 2".
CODE
def swap_case(s):
s=s.swapcase()
return s
Task
You are given a string. Split the string on a " " (space) delimiter and join using a -
hyphen.
Input Format
The first line contains a string consisting of space separated words.
Output Format
Print the formatted string as explained above.
Sample Input
this is a string
Sample Output
this-is-a-string
CODE
def split_and_join(line):
a = line.split(" ")
a = "-".join(a)
return(a)
7.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.
Output Format
Output the integer number indicating the total number of occurrences of the substring in
the original string.
Sample Input
ABCDCDC
CDC
Sample Output
2
Concept
Some string processing examples, such as these, might be useful.
There are a couple of new concepts:
In Python, the length of a string is found by the function len(s), where is the string.
To traverse through the length of a string, use a for loop:
for i in range(0, len(s)):
print (s[i])
CODE
def count_substring(string, sub_string):
count = 0
for i in range(len(string)-len(sub_string)+1):
if (string[i:i+len(sub_string)] == sub_string):
count += 1
return count
CODE
import math
n,m,a=list(map(int,input().split()))
row,col=n/a,m/a
print(math.ceil(row)*math.ceil(col))
Sample Output 0
yes
Sample Input 1
0011
2130
Sample Output 1
no
CODE
Xa,Ya,Xb,Yb=list(map(int,(input().split())))
Xp,Yp,Xq,Yq=list(map(int,(input().split())))
if Xb-Xa==0 or Xq-Xp==0:
print("no")
else:
slope1=float(Yb-Ya)//float(Xb-Xa)
slope2=float(Yq-Yp)//float(Xq-Xp)
if slope1 == slope2:
print("yes")
else:
print("no")
PAGE 3
Q1. Number pattern
CODE
n = int(input())
for i in range(1,n+1):
for j in range(1,i+1):
print(j, end=(""))
print()
Q2 Number pattern
CODE
n = int(input())
for i in range(1,n+1):
for j in range(1,i+1):
print((i+j+1)%2,end="")
print()
Q3 number pattern
Sample input -- 5
Sample output
1
12
123
1234
12345
CODE
n = int(input())
for i in range(1,n+1):
print(" "*(n-i)+"".join(map(str,range(1,i+1))))
Q4 number pattern
Sample input --- 5
Output --
1 5
24
3
CODE
n=int(input())
for i in range(1, n//2 + 2):
for j in range(1, n + 1):
if j==i or j==n - i + 1:
print(j, end="")
else:
print(" ",end="")
print()
Q5 number pattern
Input -- 5
Output
1
2
3
4
5
CODE
n=int(input())
for i in range(1, n + 1):
for j in range(1, n + 1):
if j==i:
print(j, end="")
else:
print(" ",end="")
print()
Q6 area
Write a C program to calculate the area of the square where side of the square is given
as input.
Input -- 3
Output -- 9
CODE
n=int(input())
print(n*n)
Q7 hypotenuse
Write a program to calculate the hypotenuse of the right angled triangle where the two
sides of a triangle S1, S2 are given as input.Print the output to the stdout in floating
point format with exactly 2 decimal precession other the floating point number,no other
extra information should be printed.
Input --
Output --
5.00
CODE
import sys
import math
if __name__ == "__main__":
side1 = int(input().strip())
side2 = int(input().strip())
hypo2=side1*side1 + side2*side2
hypo = math.sqrt(hypo2)
print(f'{hypo:.2f}')
Q8 area of circle
Given the radius, find and print the area of the circle upto 6 decimal places.
Input -- 5
Output -- 78.539816
CODE
import math
radius=float(input())
area= math.pi*radius*radius
print(f'{area:.6f}')
Q9 reincarnation or power
In the world of numbers every number dies at some point and reincarnates. The newer
generation will always surpass the previous generation and hence every number X
upon incarnation will be promoted with a power Y i.e. X will now become X raised to the
power Y. The god of the world of numbers needs a small break and hence has given
you the task of reincarnating the incoming numbers after raising them to the power Y.
Input --- 2 4
output --- 16
CODE
x,y= map(int,input().split())
print(x**y)
CODE
n=int(input())
if n>1:
for i in range(2, n):
if(n%i==0):
print("no")
break
else:
print("yes")
else:
print("no")
PAGE 4
Q1 prime testing 2
You are given Q different queries. Each query consists of one number each i.e. N. You are to
write a program that, for each query tests whether the number is prime or not. You must output
Q different lines to stdout, ith line being "yes" if the N for ith query is a prime number and "no"
otherwise.
Input Format
First line contains one integer, the number of queries Q.
Next Q lines contain one integer each, the N for the queries.
Constraints
1 <= Q <= 10^5
1 <= N <= 10^5
Output Format
Output Q lines, on each line you must print "yes" or "no" depending on the primality of N in the
query.
Input
5
1
2
3
4
5
Output
no
yes
yes
No
yes
CODE
import math
m=int(input())
for i in range(m):
n = int(input())
if n == 1:
print('no')
elif n == 2:
print('yes')
else:
for j in range(2,math.floor(math.sqrt(n)) + 1):
if n % j==0:
print("no")
break
else:
print("yes")
Q2 domino piles
You are given a rectangular board of M × N squares. Also you are given an unlimited number of
standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked
to place as many dominoes as possible on the board so as to meet the following conditions:
1.Each domino completely covers two squares.
2.No two dominoes overlap.
3.Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
Input ---
24
Output ---
4
CODE
m,n= map(int,input().split())
a= m*n//2
print(f'{a:.0f}')
3. Modified array
You are given an array A of N elements : a0, a1, a2... an-1
Do the following for every element ai :
if i is even : ai = ai * 2
if i is odd : ai = ai / 2
Print the final array
Input Format
First line contains number N, the size of array A. Second line contains N integers, the elements
of array A.
Constraints
1 <= N <= 15
1 <= A <= 50
Output Format
Output N numbers, the final array.
Input
5
2 4 6 8 10
Output
4 2 12 4 20
CODE
N=int(input())
values=[int(i) for i in input().split()]
for i in range(N):
if i%2==0:
print(values[i]*2,end=" ")
else:
print(values[i]//2,end=" ")
Q4 Array as a hill
Array of integers is a hill, if:
it is strictly increasing in the beginning;
after that it is constant;
after that it is strictly decreasing.
The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both
of this blocks are absent.
For example, the following three arrays are a hill: [5, 7, 11, 11, 2, 1], [4, 4, 2], [7],
but the following three are not unimodal: [5, 5, 6, 6, 1], [1, 2, 1, 2], [4, 5, 5, 6].
Write a program that checks if an array is a hill.
Input Format
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the elements of the array.
Output Format
Print "yes" if the given array is a hill. Otherwise, print "no".
Q5 residue arithmetic
For operators with large integers, residue arithmetic is used. A residue of a number n modulo a
prime p is defined as the remainder obtained when we divide a by p. FOr example, if residue of
100 modulo 3 is 1. Two large primes are chosen and all numbers are expressed as modulo
those primes.
For example, if 7 and 3 were chosen as the primes, 25 would be represented as 4,1 in this
representation, 3 would be represented as 3,3 and 30 would be represented as 2,0.
Now if we do 25 * 3 - 30 in this model, we do the operation and compute the residue of the
result with each of the primes in turn. SO with respect to the prime 7, the result is 4 * 3 - 2 or 10
which has a residue of 3 modulo 7. With respect to 13, the operation is 12 * 3 - 4 = 32 whose
residue is 6 modulo 13. Hence the result is 3,6 in the residue notation. There is only one
number less than 91 which has this representation, and that is 45, which is what we expect.
In this problem we will be given 3 numbers a,b and c in residue notation for two primes p and q,
and we need to find the value of 2a + b - c in normal notation. It may be assumed that the result
is less than p * q and is non-negative. (c <= 2a + b)
Input
First line consists of two primes
Next 3 lines contains the three input numbers modulo those primes
Output
Print the value of 2a + b - c in normal notation
Sample Input 0
23 29
71
2 25
4 21
Sample Output 0
35
Q6 Negative marking
Raju is giving his JEE Main exam. The exam has Q questions and Raju needs S marks to pass.
Giving the correct answer to a question awards the student with 4 marks whereas giving the
incorrect answer to a question awards the student with negative 3 (-3) marks. If a student
chooses to not answer a question at all, he is awarded 0 marks.
Write a program to calculate the minimum accuracy that Raju will need in order to pass the
exam.
Input
Input consists of multiple test cases.
Each test case consists of two integers Q and S
Output
Print the minimum accuracy upto 2 decimal places
Print -1 if it is impossible to pass the exam
Sample Input 0
2
10 40
10 33
Sample Output 0
100.00
90.00
Q7 Reincarnation
In the world of numbers every number dies at some point and reincarnates. The newer
generation will always surpass the previous generation and hence every number X
upon incarnation will be promoted with a power Y i.e. X will now become X raised to the
power Y. The god of the world of numbers needs a small break and hence has given
you the task of reincarnating the incoming numbers after raising them to the power Y.
Input Format
Two numbers, X and Y.
Constraints
1 <= X <= 10
0 <= Y <= 10
Output Format
One number, X raised to the power Y.
Sample Input 0
24
Sample Output 0
16
Explanation 0
2 raised to the power 4 = 2 * 2 * 2 * 2 = 16
CODE
x,y=map(int,input().split())
print(x**y)
Q8 Domino Piles
You are given a rectangular board of M × N squares. Also you are given an unlimited
number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the
pieces. You are asked to place as many dominoes as possible on the board so as to
meet the following conditions:
1.Each domino completely covers two squares.
2.No two dominoes overlap.
3.Each domino lies entirely inside the board. It is allowed to touch the edges of the
board.
Find the maximum number of dominoes, which can be placed under these restrictions.
Input Format
In a single line you are given two integers M and N — board sizes in squares
Constraints
1 ≤ M ≤ N ≤ 16
Output Format
Output one number — the maximal number of dominoes, which can be placed.
Sample Input 0
24
Sample Output 0
4
CODE
r,y=map(int,input().split())
z=((r*y)//2)
print(z)
Sample Output 0
Weird
CODE
n=int(input())
if n % 2 == 1:
print("Weird")
elif n % 2 == 0 and 2 <= n <= 5:
print("Not Weird")
elif n % 2 == 0 and 6 <= n <= 20:
print("Weird")
else:
print("Not Weird")
Input--- 5 4
Output --- 9
CODE
a,b=list(map(float, input().split()))
if(a+b) - int(a+b)==0:
print(int(a+b))
else:
print(a+b)
PAGE 5
Q1 Alice and boar trips
Alice owns a company that transports tour groups between two islands. She has n trips booked,
and each trip has pi passengers. Alice has m boats for transporting people, and each boat's
maximum capacity is c passengers.
Given the number of passengers going on each trip, determine whether or not Alice can perform
all n trips using no more than m boats per individual trip. If this is possible, print Yes; otherwise,
print No.
Input Format
The first line contains three space-separated integers describing the respective values of n
(number of trips), c (boat capacity), and m (total number of boats). The second line contains n
space-separated integers describing the values of p0, p1, p2... pn-1
Constraints
1 <= n,c,m <= 100 1 <= pi <= 100
Output Format
Print Yes if Alice can perform all n booked trips using no more than m boats per trip; otherwise,
print No.
Sample Input 0
522
12143
Sample Output 0
Yes
CODE
n,c,m=list(map(int,input().split()))
pi =[int(i)for i in input().split()]
if m*c>=max(pi):
print("Yes")
else:
print("No")
Q2 Barua skywatcher
Barua is standing at x = 0 facing the positive x-axis. He loves watching stars but is too lazy to
move or even turn around at that matter. For the same reason he can see the stars located in
the first quadrant but cannot see the ones located in the second quadrant (because he doesn't
have eyes on his back). You are given the co-ordinates of N stars and you need to tell him the
fraction of the total stars that he will be able to observe.
Input Format: First line contains the integer N.
Next N lines contain two integers each, the x and the y co-ordinate of the ith star.
NOTE :
Barua can observe every star that is in front of him i.e in the first quadrant, the only ones he
cannot observe are the ones behind him i.e. lying in the second quadrant. He cannot observe
the stars that are vertically above him.
The third and the fourth quadrants are obviously the ground that Barua stands on.
Output Format:
Output one decimal number denoting the percentage of the total stars that Barua can observe.
NOTE : Print the answer upto 6 decimal places.
Input Constraints:
● 1 <= N <= 10^5
● 1 <= y[i] <= 1000
● -1000 <= x[i] <= 1000
Sample Input 0
6
22
56
-4 5
-1 1
73
-4 2
Sample Output 0
0.500000
CODE
n=int(input())
c=0
for i in range(n):
a,b=map(int,input().split())
if(a>0 and b>0):
c+=1
print("{:.6f}".format(c/n))
Sample Output 0
10
Q4 Exclusive OR
Find the XOR of two numbers and print it. Hint : Input the numbers as strings.
Input Format
First line contains first number X and second line contains second number Y. The numbers will
be given to you in binary form.
Constraints - 0 <= X <= 2^1000, 0 <= Y <= 2^1000
Output Format
Output one number in binary format, the XOR of two numbers.
Sample Input 0
11011
10101
Sample Output 0
01110