ajaykhatri.in
Competitive Programming
Ajay Khatri
ajaykhatri.in
What is Competitive Programming?
Competitive programming is a mind sport usually held over the Internet or a
local network, involving participants trying to program according to provided
specifications.
Take any sport, let’s consider cricket for that matter, you walk in to bat for the
first time. Swing and a miss, do it couple of times and you’ll eventually hit one
over the ropes.
Now, consider a programming contest as a game of cricket, metaphorically.
Compile a code and submit, you may get a WA (Wrong Answer). Make changes
to code and eventually you will get your first AC (Accepted/Correct Answer).
ajaykhatri.in
What do these contests test?
● Algorithmic Skills
● Basic math skills
● Programming skills
● Speed (good typing speed helps)
● Creativity
● Debugging skills
ajaykhatri.in
How to get started?
● Understand Concept of Complexity (Time and Space both )in programs.
● Choose a programming language which you are more comfortable with.
● Learn about Data Structure , this is key , a lot of problems cannot be
solved Without knowing Data Structure (It's not just about algorithms and
Arrays).
● Learn Different Programming paradigms , recursion, dynamic
programming etc.
● Brush your basics Number theory, Modular arithmetic, Logarithmic
Exponentiation etc.
ajaykhatri.in
Problem Properties
● The correctness of an answer to the problem is absolute: it will be
checked by computers, not humans. No subjectiveness is present.
● The description contains a background story to hide the actual problem
and to make it interesting.Note that however, some problems have
straight forward statement as well.
● Some examples of input/output will be given. This is so that we won't
misunderstand the input/output format and even the problem
description itself.
● Ultimately, the problem is related to computer science, math, or logic.
Hence, the solution can be expressed algorithmically in a computer
program.
ajaykhatri.in
Example 1
If the input format states something like:
"The first line of input gives the no. of test cases with each test case having 2
numbers n and m.”
then it would look something like this:
3
2 5
6 8
3 9
ajaykhatri.in
Example 1 : Cont..
C code would be like:
int a, b, c;
scanf(“%d”,&a);
while(a>0){
a--;
scanf(“%d %d”,&b,&c);
}
ajaykhatri.in
Example 1 : Cont..
Say you want to write a function to calculate x^4.
We can simply solve this with:
z=x*x*x*x;
return z; //required 3 multiplication instructions.
But a better solution will be:
z=x*x;
z=z*z;
return z; //required 2 multiplication instructions.
ajaykhatri.in
Where to practice?
● TopCoder
● Hackerrank
● CodeChef
● Coderbyte
● Codewars
● Codeforce
● Hackerearth
● Hashcode
And many more...
ajaykhatri.in
Some Tips to CP
Learning to code is all about practicing. Participate regularly in the
programming contests. Solve the ones that you cannot solve in the contest,
after the contest.
Read the codes of highly rated programmers. Compare your solution with
them. You can see that it is simple and shorter than your solution. Analyze
how they have approached and improve your implementation skills.
ajaykhatri.in
Some Tips to CP : Cont..
Read the editorials after the contest. You can learn how to solve the problems
that you were not able to solve in the contest and learn alternative ways to solve the
problems which you could solve.
Do not spend too much time if you are not getting the solution or are stuck
somewhere.
After you feel that you have spent enough time, look at the editorials. Understand
the algorithm and code it. Do not look at the real solution before you have
attempted to write the code on your own.
ajaykhatri.in
Some Tips to CP : Cont..
Programming is a very practical and hands-on skill. You have to continuously do
it to be good at it.
It's not enough to solve the problem theoretically. You have to code it and get the
solution accepted. Knowing which algorithm/logic to use and implementing it are
two different things. It takes both to be good at programming
ajaykhatri.in
Why should you do it?
Everyday skills. Problem solving, focus, time management, stress management,
mental stamina, etc.
Specialized knowledge. Algorithms, AI, machine learning, computer vision, low-
level optimization and bunch of others.
You are spending time on coding / debugging, of course these skills get better.
It enables you to think more clearly and properly
Most importantly - Might help you in getting into Google, Facebook
ajaykhatri.in
Some Drawbacks
● Back Pain
● Back Pain
● Insomnia (sometimes when you're too serious!!)
● & Back Pain
ajaykhatri.in
Some Prestigious Contests:
● ACM – ICPC
● Google Code Jam
● Topcoder Open
● Facebook Hacker Cup
● IndiaHacks Programming Contest
ajaykhatri.in
Some Regular Contests:
● Week Of Code - HackerRank
● Monthly Easy - HackerEarth
● Monthly Circuit - HackerEarth
● 101 Hack - HackerRank
● ProjectEuler+ - HackerRank (Indefinitely Open)
● CodeArena - HackerEarth (Head to Head and Indefinitely Open)
ajaykhatri.in
LET'S START CODING!!!
ajaykhatri.in
File Handling in Python
Read File
f = open("abc.txt", "r")
for x in f:
print(x)
Remove File
import os
os.remove("abc.txt")
Write File
f = open("abc.txt", "w")
#append a
f.write("First linen")
f.write("Another Line")
f.close()
ajaykhatri.in
String split() Method in Python
#separator and maxsplit are optional
string.split(separator, maxsplit)
txt = "hello, my name is Ajay."
x = txt.split(" ")
print(x) #['hello,', 'my', 'name', 'is', 'Ajay.']
#txt = "ajay khatri" # ['ajay', '', '', 'khatri']
ajaykhatri.in
map() function in Python
map() function returns a map object(which is an iterator) of
the results after applying the given function to each item of
a given iterable (list, tuple etc.)
Syntax :
map(fun, iter)
NOTE : The returned value from map() (map object) then can be passed to
functions like list() (to create a list), set() (to create a set) .
ajaykhatri.in
map() function in Python : Cont
Example 1
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
#output : [2, 4, 6, 8]
Example 2 : take input from user
and sum all numbers separated by
space
i = input()
input =list(map(int,i.split()))
print(sum(input))
ajaykhatri.in
Calculate Time taken by a Program to Execute in Python
import time
start = time.time()
for i in range(100):
print(i)
end = time.time()
print(f"Runtime of the program is {end - start}")
ajaykhatri.in
Problem 1 : ATM
ajaykhatri.in
Problem 1 : ATM
Ajay would like to withdraw X Rs from an ATM. The cash machine
will only accept the transaction if X is a multiple of 5, and Ajay’s
account balance has enough cash to perform the withdrawal
transaction (including bank charges). For each successful
withdrawal the bank charges 0.50 Rs . Calculate Ajay’s account
balance after an attempted transaction.
ajaykhatri.in
Problem 1 : ATM
Input
Positive integer 0 < X <= 2000 - the amount of cash which Ajay wishes to
withdraw.
Nonnegative number 0<= Y <= 2000 with two digits of precision - Ajay’s initial
account balance.
Output
Output the account balance after the attempted transaction, given as a
number with two digits of precision. If there is not enough money in the
account to complete the transaction, output the current bank balance.
ajaykhatri.in
Problem 1 : ATM
Example - Successful Transaction
Input: 30 120.00
Output: 89.50
Example - Incorrect Withdrawal Amount (not multiple of 5)
Input: 42 120.00
Output: 120.00
Example - Insufficient Funds
Input: 300 120.00
Output: 120.00
ajaykhatri.in
Problem 1 : Practice
Time : 15 minute
ajaykhatri.in
Problem 2 : Angry Professor
ajaykhatri.in
Problem 2 : Angry Professor
A Computer Network professor has a class of students. Frustrated
with their lack of discipline, the professor decides to cancel class if
fewer than some number of students are present when class
starts. Arrival times go from on time () to arrived late ().
Given the arrival time of each student and a threshold number of
attendees, determine if the class is cancelled.
ajaykhatri.in
Problem 2 : Angry Professor
Function Description
Write a angryProfessor function. It must return YES if class is cancelled, or NO
otherwise.
parameter:
int k: the threshold number of students
int a[n]: the arrival times of the n students
Returns
string: either YES or NO
ajaykhatri.in
Problem 2 : Angry Professor
ajaykhatri.in
Problem 2 : Angry Professor
ajaykhatri.in
Problem 2 : Angry Professor
ajaykhatri.in
Problem 2 : Practice
Time : 15 minute
ajaykhatri.in
Problem 3 : Sherlock and Squares
ajaykhatri.in
Problem 3 : Sherlock and Squares
ajaykhatri.in
Problem 3 : Sherlock and Squares
ajaykhatri.in
Problem 3 : Sherlock and Squares
ajaykhatri.in
Problem 3 : Sherlock and Squares
ajaykhatri.in
Problem 3 : Practice
Time : 30 minute
ajaykhatri.in
Problem 4 : Ajay and Ringroad
ajaykhatri.in
Problem 4 : Ajay and Ringroad
Ajay lives in a city that has n houses built along the main ringroad. The
ringroad houses are numbered 1 through n in the clockwise order. The
ringroad traffic is one way and also is clockwise.
Ajay has recently moved into the ringroad house number 1. As a result, he's
got m things to do. In order to complete the i-th task, he needs to be in the
house number ai and complete all tasks with numbers less than i. Initially, Ajay
is in the house number 1, find the minimum time he needs to complete all her
tasks if moving from a house to a neighboring one along the ringroad takes
one unit of time.
ajaykhatri.in
Problem 4 : Ajay and Ringroad
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The
second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Ajay can
have multiple consecutive tasks in one house.
Output
Print a single integer — the time Ajay needs to complete all tasks.
ajaykhatri.in
Problem 4 : Ajay and Ringroad
Sample Input 1
input
4 3
3 2 3
output
6
Note : 1 → 2 → 3 → 4 → 1 → 2 → 3
Sample Input 1
input
4 3
2 3 3
output
2
Note : 1 → 2 → 3
ajaykhatri.in
Problem 4 : Practice
Time : 30 minute
ajaykhatri.in
Problem 5 : Lapindrome
ajaykhatri.in
Problem 5 : Lapindrome
Lapindrome is defined as a string which when split in the middle, gives two
halves having the same characters and same frequency of each character. If
there are odd number of characters in the string, we ignore the middle
character and check for lapindrome. For example gaga is a lapindrome, since
the two halves ga and ga have the same characters with same frequency. Also,
abccab, rotor and xyzxy are a few examples of lapindromes. Note that abbaab
is NOT a lapindrome. The two halves contain the same characters but their
frequencies do not match.
Your task is simple. Given a string, you need to tell if it is a lapindrome.
ajaykhatri.in
Problem 5 : Lapindrome
Input:
First line of input contains a single integer T, the number of test cases.
Each test is a single line containing a string S composed of only lowercase
English alphabet.
Output:
For each test case, output on a separate line: "YES" if the string is a
lapindrome and "NO" if it is not.
ajaykhatri.in
Problem 5 : Lapindrome
Input:
First line of input contains a single integer T, the number of test cases.
Each test is a single line containing a string S composed of only lowercase English alphabet.
Output:
For each test case, output on a separate line: "YES" if the string is a lapindrome and "NO" if it
is not.
Constraints:
1 ≤ T ≤ 100
2 ≤ |S| ≤ 1000, where |S| denotes the length of S
ajaykhatri.in
Problem 5 : Lapindrome
Input:
6
gaga
abcde
rotor
xyzxy
abbaab
ababc
Output:
YES
NO
YES
YES
NO
NO
ajaykhatri.in
Problem 5 : Practice
Time : 30 minute
ajaykhatri.in
References
● https://www.codechef.com/
● https://www.hackerrank.com/
● https://codeforces.com/
● https://www.hackerearth.com/
ajaykhatri.in
Thank You
www.ajaykhatri.in

Competitive Programming Guide

  • 1.
  • 2.
    ajaykhatri.in What is CompetitiveProgramming? Competitive programming is a mind sport usually held over the Internet or a local network, involving participants trying to program according to provided specifications. Take any sport, let’s consider cricket for that matter, you walk in to bat for the first time. Swing and a miss, do it couple of times and you’ll eventually hit one over the ropes. Now, consider a programming contest as a game of cricket, metaphorically. Compile a code and submit, you may get a WA (Wrong Answer). Make changes to code and eventually you will get your first AC (Accepted/Correct Answer).
  • 3.
    ajaykhatri.in What do thesecontests test? ● Algorithmic Skills ● Basic math skills ● Programming skills ● Speed (good typing speed helps) ● Creativity ● Debugging skills
  • 4.
    ajaykhatri.in How to getstarted? ● Understand Concept of Complexity (Time and Space both )in programs. ● Choose a programming language which you are more comfortable with. ● Learn about Data Structure , this is key , a lot of problems cannot be solved Without knowing Data Structure (It's not just about algorithms and Arrays). ● Learn Different Programming paradigms , recursion, dynamic programming etc. ● Brush your basics Number theory, Modular arithmetic, Logarithmic Exponentiation etc.
  • 5.
    ajaykhatri.in Problem Properties ● Thecorrectness of an answer to the problem is absolute: it will be checked by computers, not humans. No subjectiveness is present. ● The description contains a background story to hide the actual problem and to make it interesting.Note that however, some problems have straight forward statement as well. ● Some examples of input/output will be given. This is so that we won't misunderstand the input/output format and even the problem description itself. ● Ultimately, the problem is related to computer science, math, or logic. Hence, the solution can be expressed algorithmically in a computer program.
  • 6.
    ajaykhatri.in Example 1 If theinput format states something like: "The first line of input gives the no. of test cases with each test case having 2 numbers n and m.” then it would look something like this: 3 2 5 6 8 3 9
  • 7.
    ajaykhatri.in Example 1 :Cont.. C code would be like: int a, b, c; scanf(“%d”,&a); while(a>0){ a--; scanf(“%d %d”,&b,&c); }
  • 8.
    ajaykhatri.in Example 1 :Cont.. Say you want to write a function to calculate x^4. We can simply solve this with: z=x*x*x*x; return z; //required 3 multiplication instructions. But a better solution will be: z=x*x; z=z*z; return z; //required 2 multiplication instructions.
  • 9.
    ajaykhatri.in Where to practice? ●TopCoder ● Hackerrank ● CodeChef ● Coderbyte ● Codewars ● Codeforce ● Hackerearth ● Hashcode And many more...
  • 10.
    ajaykhatri.in Some Tips toCP Learning to code is all about practicing. Participate regularly in the programming contests. Solve the ones that you cannot solve in the contest, after the contest. Read the codes of highly rated programmers. Compare your solution with them. You can see that it is simple and shorter than your solution. Analyze how they have approached and improve your implementation skills.
  • 11.
    ajaykhatri.in Some Tips toCP : Cont.. Read the editorials after the contest. You can learn how to solve the problems that you were not able to solve in the contest and learn alternative ways to solve the problems which you could solve. Do not spend too much time if you are not getting the solution or are stuck somewhere. After you feel that you have spent enough time, look at the editorials. Understand the algorithm and code it. Do not look at the real solution before you have attempted to write the code on your own.
  • 12.
    ajaykhatri.in Some Tips toCP : Cont.. Programming is a very practical and hands-on skill. You have to continuously do it to be good at it. It's not enough to solve the problem theoretically. You have to code it and get the solution accepted. Knowing which algorithm/logic to use and implementing it are two different things. It takes both to be good at programming
  • 13.
    ajaykhatri.in Why should youdo it? Everyday skills. Problem solving, focus, time management, stress management, mental stamina, etc. Specialized knowledge. Algorithms, AI, machine learning, computer vision, low- level optimization and bunch of others. You are spending time on coding / debugging, of course these skills get better. It enables you to think more clearly and properly Most importantly - Might help you in getting into Google, Facebook
  • 14.
    ajaykhatri.in Some Drawbacks ● BackPain ● Back Pain ● Insomnia (sometimes when you're too serious!!) ● & Back Pain
  • 15.
    ajaykhatri.in Some Prestigious Contests: ●ACM – ICPC ● Google Code Jam ● Topcoder Open ● Facebook Hacker Cup ● IndiaHacks Programming Contest
  • 16.
    ajaykhatri.in Some Regular Contests: ●Week Of Code - HackerRank ● Monthly Easy - HackerEarth ● Monthly Circuit - HackerEarth ● 101 Hack - HackerRank ● ProjectEuler+ - HackerRank (Indefinitely Open) ● CodeArena - HackerEarth (Head to Head and Indefinitely Open)
  • 17.
  • 18.
    ajaykhatri.in File Handling inPython Read File f = open("abc.txt", "r") for x in f: print(x) Remove File import os os.remove("abc.txt") Write File f = open("abc.txt", "w") #append a f.write("First linen") f.write("Another Line") f.close()
  • 19.
    ajaykhatri.in String split() Methodin Python #separator and maxsplit are optional string.split(separator, maxsplit) txt = "hello, my name is Ajay." x = txt.split(" ") print(x) #['hello,', 'my', 'name', 'is', 'Ajay.'] #txt = "ajay khatri" # ['ajay', '', '', 'khatri']
  • 20.
    ajaykhatri.in map() function inPython map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Syntax : map(fun, iter) NOTE : The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) .
  • 21.
    ajaykhatri.in map() function inPython : Cont Example 1 # Return double of n def addition(n): return n + n # We double all numbers using map() numbers = (1, 2, 3, 4) result = map(addition, numbers) print(list(result)) #output : [2, 4, 6, 8] Example 2 : take input from user and sum all numbers separated by space i = input() input =list(map(int,i.split())) print(sum(input))
  • 22.
    ajaykhatri.in Calculate Time takenby a Program to Execute in Python import time start = time.time() for i in range(100): print(i) end = time.time() print(f"Runtime of the program is {end - start}")
  • 23.
  • 24.
    ajaykhatri.in Problem 1 :ATM Ajay would like to withdraw X Rs from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Ajay’s account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal the bank charges 0.50 Rs . Calculate Ajay’s account balance after an attempted transaction.
  • 25.
    ajaykhatri.in Problem 1 :ATM Input Positive integer 0 < X <= 2000 - the amount of cash which Ajay wishes to withdraw. Nonnegative number 0<= Y <= 2000 with two digits of precision - Ajay’s initial account balance. Output Output the account balance after the attempted transaction, given as a number with two digits of precision. If there is not enough money in the account to complete the transaction, output the current bank balance.
  • 26.
    ajaykhatri.in Problem 1 :ATM Example - Successful Transaction Input: 30 120.00 Output: 89.50 Example - Incorrect Withdrawal Amount (not multiple of 5) Input: 42 120.00 Output: 120.00 Example - Insufficient Funds Input: 300 120.00 Output: 120.00
  • 27.
    ajaykhatri.in Problem 1 :Practice Time : 15 minute
  • 28.
  • 29.
    ajaykhatri.in Problem 2 :Angry Professor A Computer Network professor has a class of students. Frustrated with their lack of discipline, the professor decides to cancel class if fewer than some number of students are present when class starts. Arrival times go from on time () to arrived late (). Given the arrival time of each student and a threshold number of attendees, determine if the class is cancelled.
  • 30.
    ajaykhatri.in Problem 2 :Angry Professor Function Description Write a angryProfessor function. It must return YES if class is cancelled, or NO otherwise. parameter: int k: the threshold number of students int a[n]: the arrival times of the n students Returns string: either YES or NO
  • 31.
  • 32.
  • 33.
  • 34.
    ajaykhatri.in Problem 2 :Practice Time : 15 minute
  • 35.
    ajaykhatri.in Problem 3 :Sherlock and Squares
  • 36.
    ajaykhatri.in Problem 3 :Sherlock and Squares
  • 37.
    ajaykhatri.in Problem 3 :Sherlock and Squares
  • 38.
    ajaykhatri.in Problem 3 :Sherlock and Squares
  • 39.
    ajaykhatri.in Problem 3 :Sherlock and Squares
  • 40.
    ajaykhatri.in Problem 3 :Practice Time : 30 minute
  • 41.
    ajaykhatri.in Problem 4 :Ajay and Ringroad
  • 42.
    ajaykhatri.in Problem 4 :Ajay and Ringroad Ajay lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Ajay has recently moved into the ringroad house number 1. As a result, he's got m things to do. In order to complete the i-th task, he needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Ajay is in the house number 1, find the minimum time he needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.
  • 43.
    ajaykhatri.in Problem 4 :Ajay and Ringroad Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Ajay can have multiple consecutive tasks in one house. Output Print a single integer — the time Ajay needs to complete all tasks.
  • 44.
    ajaykhatri.in Problem 4 :Ajay and Ringroad Sample Input 1 input 4 3 3 2 3 output 6 Note : 1 → 2 → 3 → 4 → 1 → 2 → 3 Sample Input 1 input 4 3 2 3 3 output 2 Note : 1 → 2 → 3
  • 45.
    ajaykhatri.in Problem 4 :Practice Time : 30 minute
  • 46.
  • 47.
    ajaykhatri.in Problem 5 :Lapindrome Lapindrome is defined as a string which when split in the middle, gives two halves having the same characters and same frequency of each character. If there are odd number of characters in the string, we ignore the middle character and check for lapindrome. For example gaga is a lapindrome, since the two halves ga and ga have the same characters with same frequency. Also, abccab, rotor and xyzxy are a few examples of lapindromes. Note that abbaab is NOT a lapindrome. The two halves contain the same characters but their frequencies do not match. Your task is simple. Given a string, you need to tell if it is a lapindrome.
  • 48.
    ajaykhatri.in Problem 5 :Lapindrome Input: First line of input contains a single integer T, the number of test cases. Each test is a single line containing a string S composed of only lowercase English alphabet. Output: For each test case, output on a separate line: "YES" if the string is a lapindrome and "NO" if it is not.
  • 49.
    ajaykhatri.in Problem 5 :Lapindrome Input: First line of input contains a single integer T, the number of test cases. Each test is a single line containing a string S composed of only lowercase English alphabet. Output: For each test case, output on a separate line: "YES" if the string is a lapindrome and "NO" if it is not. Constraints: 1 ≤ T ≤ 100 2 ≤ |S| ≤ 1000, where |S| denotes the length of S
  • 50.
    ajaykhatri.in Problem 5 :Lapindrome Input: 6 gaga abcde rotor xyzxy abbaab ababc Output: YES NO YES YES NO NO
  • 51.
    ajaykhatri.in Problem 5 :Practice Time : 30 minute
  • 52.
  • 53.

Editor's Notes

  • #19 "r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append - Opens a file for appending, creates the file if it does not exist "w" - Write - Opens a file for writing, creates the file if it does not exist "x" - Create - Creates the specified file, returns an error if the file exists "t" - Text - Default value. Text mode "b" - Binary - Binary mode (e.g. images)
  • #20 "r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append - Opens a file for appending, creates the file if it does not exist "w" - Write - Opens a file for writing, creates the file if it does not exist "x" - Create - Creates the specified file, returns an error if the file exists "t" - Text - Default value. Text mode "b" - Binary - Binary mode (e.g. images)
  • #23 Python f-string is the newest Python syntax to do string formatting. It is available since Python 3.6. Python f-strings provide a faster, more readable, more concise, and less error prone way of formatting strings in Python.
  • #28 #https://www.codechef.com/problems/HS08TEST inputs = input().split() cash_withdraw =float(inputs[0]) cash =float(inputs[1]) #cash_withdraw,cash=map(float, input().split()) if(cash<cash_withdraw+0.5): print(cash) elif(cash_withdraw%5!=0): print(cash) else: print(cash-(cash_withdraw+0.5))
  • #35 #https://www.hackerrank.com/challenges/angry-professor/problem #!/bin/python3 import math import os import random import re import sys # # Complete the 'angryProfessor' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. INTEGER k # 2. INTEGER_ARRAY a # def angryProfessor(k, a): # Write your code here ontime=0 for i in a: if i <=0: ontime = ontime+1 if ontime >=k : return "NO" else: return "YES" if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input().strip()) for t_itr in range(t): first_multiple_input = input().rstrip().split() n = int(first_multiple_input[0]) k = int(first_multiple_input[1]) a = list(map(int, input().rstrip().split())) result = angryProfessor(k, a) fptr.write(result + '\n') fptr.close()
  • #41 #https://www.hackerrank.com/challenges/sherlock-and-squares/problem #!/bin/python3 import math import os import random import re import sys # # Complete the 'squares' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER a # 2. INTEGER b # def squares(a, b): # Write your code here s=0 for i in range(a,b+1): if (i**0.5) %1==0: s=s+1 return s if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') q = int(input().strip()) for q_itr in range(q): first_multiple_input = input().rstrip().split() a = int(first_multiple_input[0]) b = int(first_multiple_input[1]) result = squares(a, b) fptr.write(str(result) + '\n') fptr.close()
  • #45 NoteIn the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units.
  • #46 #https://codeforces.com/contest/339/problem/B n,m = map(int,input().strip().split()) #print(n,m) task = map(int,input().strip().split()) currentLoc = 1 result = 0 for t in task: if(t >= currentLoc): result = result + t- currentLoc else: result = result + n - currentLoc + t #print(result) currentLoc = t print(result)
  • #52 #https://www.codechef.com/problems/LAPIN for _ in range(int(input())): s = input() k = len(s)//2 if len(s)%2 == 0: x,y = s[:k] , s[k:] else: x,y = s[:k] , s[1+k:] if sorted(x) == sorted(y): print('YES') else: print("NO")
  • #54 #https://www.codechef.com/problems/LAPIN for _ in range(int(input())): s = input() k = len(s)//2 if len(s)%2 == 0: x,y = s[:k] , s[k:] else: x,y = s[:k] , s[1+k:] if sorted(x) == sorted(y): print('YES') else: print("NO")