Hacker Rank Problems and Solutions https://www.hackerrank.com/jmeuser All problem statements are from www.hackerrank.com. All Domains Java Strings Java Regex Problem Statement Write a class called myRegex which will contain a string pattern. You need to write a regular expression and assign it to the pattern such that it can be used to validate an IP address. Use the following definition of an IP address: IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3. Some valid IP address: 000.12.12.034 121.234.12.12 23.45.12.56 Some invalid IP address: 000.12.234.23.23 666.666.23.23 .213.123.23.32 23.45.22.32. I.Am.not.an.ip In this problem you will be provided strings containing any combination of ASCII characters. You have to write a regular expression to find the valid IPs. Just write the myRegex class, and we will append your code after the following piece of code automatically before running it: import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Scanner; class Solution{ public static void main(String []args) { Scanner in = new Scanner(System.in); while(in.hasNext()) { String IP = in.next(); System.out.println(IP.matches(new myRegex().pattern)); } } } (The class written by you MUST NOT be public) Solution (Java, 25m) Pesky Parenthesis (I wrote class myRegex{ public String pattern = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]? [0-9])$"; } All Domains Java Strings Pattern Syntax Checker Problem Statement Using Regex, we can easily match or search for patterns in a text. Before searching for a pattern, we have to specify one using some well-defined syntax. In this problem, you are given a pattern. You have to check whether the syntax of the given pattern is valid. Note: In this problem, a regex is only valid if you can compile it using the Pattern.compile method. Input Format The first line of input contains an integer N, denoting the number of testcases. The next N lines contain a string of any printable characters representing the pattern of a regex. Output Format For each testcase, print "Valid" if the syntax of the given pattern is correct. Otherwise, print "Invalid". Do not print the quotes. Solution (Java, 10m) import java.util.Scanner; import java.util.regex.*; public class Solution { public static void main(String[] args){ Scanner in = new Scanner(System.in); int testCases = Integer.parseInt(in.nextLine()); // begin my code for(;0 < testCases; testCases--){ String pattern = in.nextLine(); try{ Pattern p = Pattern.compile(pattern); System.out.println("Valid"); } catch (PatternSyntaxException e){ System.out.println("Invalid"); } // end my code } } } All Domains Java Strings Java Anagrams Problem Statement Two strings A and B are called anagrams if they consist same characters, but may be in different orders. So the list of anagrams of CAT are "CAT", "ACT" , "TAC", "TCA" ,"ATC" and "CTA. Given two strings, print "Anagrams" if they are anagrams, print "Not Anagrams" if they are not. The strings may consist at most 50 english characters, the comparision should NOT be case sensitive. This exercise will verify that you are able to sort the characters of a string, or compare frequencies of characters. Solution (Java, 15m) Not the best solution, but a working one is better than nothing. I'm trying to solve problems and just move on rather than get caught up on any specific one. import java.util.Scanner; public class Solution { static boolean isAnagram(String A, String B) { // start my code int[] f = new int[26]; if(A.length()!=B.length()) return false; for(char c : A.toLowerCase().toCharArray()) f[c-'a']++; for(char c : B.toLowerCase().toCharArray()) if((f[c-'a']--)<0) return false; for(int n:f) if(0<n) return false; return true; // end my code } public static void main(String[] args) { Scanner sc=new Scanner(System.in); String A=sc.next(); String B=sc.next(); boolean ret=isAnagram(A,B); if(ret)System.out.println("Anagrams"); else System.out.println("Not Anagrams"); } } All Domains Java Strings Java String Reverse Problem Statement Given a string A, print "Yes" if it is a palindrome, print "No" otherwise. The strings will consist lower case english letters only. The strings will have at most 50 characters. Solution (Java, 20m with live music at Starbucks) import java.util.Scanner; public class Solution { private static boolean P(String x){ return 0==x.compareTo(new StringBuilder(x).reverse().toString()); } public static void main(String[] args) { Scanner sc=new Scanner(System.in); String A= sc.next(); System.out.println(P(A)?"Yes":"No"); } } All Domains Java Strings Java String Compare Problem Statement Given a string, find out the lexicographically smallest and largest substring of length k. [Note: Lexicographic order is also known as alphabetic order dictionary order. So "ball" is smaller than "cat", "dog" is smaller than "dorm". Capital letter always comes before smaller letter, so "Happy" is smaller than "happy" and "Zoo" is smaller than "ball".] Input Format First line will consist a string containing english alphabets which has at most 1000 characters. 2nd line will consist an integer k. Output Format In the first line print the lexicographically minimum substring. In the second line print the lexicographically maximum substring. Solution (Java, 15m) import java.util.Scanner; public class Solution{ private static String maxString(String A, String B){ return 0<A.compareTo(B)?A:B; } private static String minString(String A, String B){ return 0<A.compareTo(B)?B:A; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); String s = sc.next(); int k = sc.nextInt(); String m,M; m = M = s.substring(0,k); for(int i=1;i<s.length()-k+1;++i){ m = minString(m,s.substring(i,i+k)); M = maxString(M,s.substring(i,i+k)); } System.out.println(m); System.out.println(M); } } All Domains Java Strings Java Strings Introduction Problem Statement A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. (Wikipedia) In this problem we will test your knowledge of Java Strings. A string can be declared in following way: String my_string="Hello World!" Each elements of a string is called a character. Number of characters in a string is called string length. In this problem you wil be given two strings A and B as input. They will contain only lower case english letters. You have to answer the following questions: What is the total length of string A and B? Is string A lexicographically larger than than B? print "Yes" or "No". Make first letter of both the strings uppercase and print them in a single line seperated by a space. [Note: Lexicographic order is also known as alphabetic order dictionary order. So "ball" is smaller than "cat", "dog" is smaller than "dorm" and "dogg". ] Sample Input hello java Sample Output 9 No Hello Java Solution (Java, 15m) import java.util.Scanner; public class Solution { private static String firstToUpperCase(String x){ return x.substring(0,1).toUpperCase()+x.substring(1); } public static void main(String[] args) { Scanner sc=new Scanner(System.in); String A=sc.next(); String B=sc.next(); System.out.println(A.length()+B.length()); System.out.println(0<A.compareTo(B)?"Yes":"No"); System.out.println(firstToUpperCase(A)+" "+firstToUpperCase(B)); } } All Domains Java Introduction Java Static Initializer Block Problem Statement Static initialization blocks are executed when the class is loaded, and you can initialize static variables in those blocks. It's time to test your knowledge of Static initialization blocks. You can read about it here. You are given a class Solution with a main method. Complete the given code so that it outputs the area of a parallelogram with breadth B and height H. You should read the variables from the standard input. If B<=0 or H <=0, the output should be "java.lang.Exception: Breadth and height must be positive" without quotes. Input Format There are two lines of input. The first line contains B: the breadth of the parallelogram. The next line contains H: the height of the parallelogram. Constraints −100<=B<=100 −100<=H<=100 Output Format If both values are greater than zero, then the main method must output the area of the parallelogram. Otherwise, print "java.lang.Exception: Breadth and height must be positive" without quotes. Solution (Java, 15m) import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { //begin my code private static Scanner sc = new Scanner(System.in); private static boolean flag = false; public static int B,H; static{ B = sc.nextInt(); H = sc.nextInt(); if(0<B && 0<H) flag = true; else System.out.println("java.lang.Exception: Breadth and height must be positive"); } //end my code public static void main(String[] args){ if(flag){ int area=B*H; System.out.print(area); } }//end of main }//end of class All Domains Java Introduction Java End-of-file Problem Statement In computing, End Of File (commonly abbreviated EOF) is a condition in a computer operating system where no more data can be read from a data source. (Wikipedia) Sometimes you don't know how many lines are there in a file and you need to read the file until EOF or End-of-file. In this problem you need to read a file until EOF and print the contents of the file. You must take input from stdin(System.in). Hints: One way to do this is to use hasNext() function in java scanner class. Input Format Each line will contain a non-empty string. Read until EOF. Output Format For each line, print the line number followed by a single space and the line content. Sample Input Hello world I am a file Read me until end-of-file. Sample Output 1 Hello world 2 I am a file 3 Read me until end-of-file. Solution (Java, 10m) import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n=1; // assumes there are less than 9223372036854775806 lines to be enumerated while(sc.hasNext()){ System.out.println(n+" "+sc.nextLine()); n++; } } } All Domains Java Introduction Java Datatypes Problem Statement Java has 8 Primitive Data Types; they are char, boolean, byte, short, int, long, float, and double. In this problem we are only concerned about integer datatypes used to hold integer values (byte, short, int, long). Let's take a closer look at them: byte data type is an 8-bit signed integer. short data type is an 16-bit signed integer. int data type is an 32-bit signed integer. long data type is an 64-bit signed integer. (Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) Given an integer number, you have to determine which of these datatypes you can use to store that number. If there are multiple suitable datatypes, list them all in the order above. To make the problem easier, some part of the code is already provided in the editor. Input Format The first line will contain an integer T, which denotes the number of inputs that will follow. Each of the next T lines will contain an integer n. The number can be arbitrarily large or small! Output Format For each n, list all the datatypes it can be fitted into ordered by the size of the datatype. If it can't be fitted into any of these datatypes, print "n can't be fitted anywhere." See the sample output for the exact formatting. Sample Input 5 -150 150000 1500000000 213333333333333333333333333333333333 -100000000000000 Sample Output -150 can be fitted in: * short * int * long 150000 can be fitted in: * int * long 1500000000 can be fitted in: * int * long 213333333333333333333333333333333333 can't be fitted anywhere. -100000000000000 can be fitted in: * long Solution (Java, 15m) (I forgot to indicate a long literal in my first attempt, this is my second) (An alternate solution would parse in a BigInteger so that no error would occur and one would simply use the BigInteger's information to decide what primitive type could hold its numeric value) import java.util.Scanner; class Solution{ public static void main(String []argh){ Scanner sc = new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++) { try{ long x=sc.nextLong(); System.out.println(x+" can be fitted in:"); if(-128<=x && x<=127)System.out.println("* byte"); if(-32768<=x && x<=32767)System.out.println("* short"); if(-2147483648<=x && x<=2147483647)System.out.println("* int"); if(-9223372036854775808L<=x && x<=9223372036854775807L)System.out.println("* long"); } catch(Exception e){ System.out.println(sc.next()+" can't be fitted anywhere."); } } } } All Domains Java Introduction Java Loops Problem Statement In this problem you will test your knowledge of Java loops. Given three integers a, b, and n, output the following series: a+2^0 *b,a+2^0*b+2^1*b,......,a+2^0b+2^1b+...+2^n−1b Input Format The first line will contain the number of testcases t. Each of the next t lines will have three integers, a, b, and n. Constraints: 0<=a,b<=50 1<=n<=15 Output Format Print the answer to each test case in separate lines. Solution (Java, 10m) import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); int a,b,n; // b,n < a < 50 + 15 * 2^14 * 50 = 12 288 050 < 2 147 483 647 for(int i=0;i<t;i++){ a = sc.nextInt(); b = sc.nextInt(); n = sc.nextInt(); for(int j=0; j<n; j++){ a += b * Math.pow(2,j); System.out.print(a+" "); } System.out.println(); } } } All Domains Java Introduction Java Output Formatting Problem Statement Java System.out.printf function allowes you to print formatted output. This problem will test your knowledge on this topic. Take exactly 3 lines of input. Each line consists of a string and an integer. Suppose this is the sample input: java 100 cpp 65 python 50 The strings will have at most 10 alphabetic characters and the integers will range between 0 to 999. In each line of output there should be two columns. The string should be in the first column and the integer in the second column. This is the output for the input above: ================================ java 100 cpp 065 python 050 ================================ The first column should be left justified using exactly 15 characters. The integer of the second column should have exactly 3 digits. If the original input has less than 3 digits, you should pad with zeros to the left. To make the problem easier, some part of the solution is already given in the editor, just complete the remaining parts. Solution (Java, 5m) import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("================================"); String s1; int x; for(int i=0;i<3;i++) { s1=sc.next(); x=sc.nextInt(); System.out.printf("%-15s%03d%n",s1,x); } System.out.println("================================"); } } All Domains Java Introduction Java Stdin and Stdout 2 Problem Statement In most of the problems in Hackerrank, you need to read input from stdin or standard input and write your output in stdout or standard output. One way to take input from stdin is to use Scanner class and reading from System.in. Alternatively, you can use BufferedReader class. You can write your output to stdout simply using System.out.printf function. In this problem you just need to read the inputs from stdin and print them in stdout. Input Format: There will be three lines of input. The first line will have an integer. The second line will have a double number. The last line will consist of a string. Output Format: Print the string in the first line, the double in the second line and the integer in the third line. See the sample output for exact formatting. To make the problem easier, some part of the code is already provided in the editor. Note that Scanner's nextInt() method doesn't read the last newline character of the input, you need to keep this in mind if you use nextLine() after using nextInt(). Solution (Java, 10m) import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int x=sc.nextInt(); double y =sc.nextDouble(); sc.nextLine(); // throw away rest of line after y String s = sc.nextLine(); System.out.println("String: "+s); System.out.println("Double: "+y); System.out.println("Int: "+x); } } All Domains Java Introduction Java If-Else Problem Statement Given an integer N as input, check the following: If N is odd, print "Weird". If N is even and, in between the range of 2 and 5(inclusive), print "Not Weird". If N is even and, in between the range of 6 and 20(inclusive), print "Weird". If N is even and N>20, print "Not Weird". We given you partially completed code in the editor, complete it to solve the problem. Input Format There is a single line of input: integer N. Constraints 1<=N<=100 Output Format Print "Weird" if the number is weird. Otherwise, print "Not Weird". Do not print the quotation marks. Solution (Java, 2m) import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); String ans=""; if(n%2==1) ans = "Weird"; else { if(2<=n && n<=5) ans = "Not Weird"; if(6<=n && n<=20) ans = "Weird"; if(20<n) ans = "Not Weird"; } System.out.println(ans); } } All Domains Java Introduction Java Stdin and Stdout 1 Problem Statement In most of the Hackerrank challenges, you need to read input from stdin (standard input) and write your output in stdout (standard output). One way to take input from stdin is to use Scanner class and reading from System.in. You can write your output to stdout simply using System.out.printf function. In this problem you need to read 3 integers from stdin and print them in stdout. Solution (Java, 1m) import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int a=sc.nextInt(); int b=sc.nextInt(); int c=sc.nextInt(); System.out.println(a); System.out.println(b); System.out.println(c); } } All Domains Java Introduction Welcome to Java! Problem Statement Welcome to the world of Java! Just print "Hello World." and "Hello Java." in two separate lines to complete this challenge. The code stub in the editor already creates the main function and solution class. All you have to do is copy and paste the following lines inside the main function. System.out.println("Hello World."); System.out.println("Hello Java."); Sample Output Hello World. Hello Java. Solution (Java, 1m) public class Solution { public static void main(String []argv) { System.out.println("Hello World.\nHello Java."); } } For Loop Input Format You will be given two positive integers, a and b (a<=b), separated by a newline. Output Format For each integer n in [a,b] (so all numbers in that range): If 1<=n<=9, then print the English representation of it. That is "one" for 1, "two" for 2, and so on. Else if n>9 and it is even, then print "even". Else if n>9 and it is odd, then print "odd". Solution (C++, 15m) #include<cstdio> #define R return #define IN(e...) scanf(e) #define OUT(e...) printf(e) #define C(c,t...) if(c){t;}else typedef int I; typedef void V; #define F(e...) for(e) #define I(n,e...) {I i=0,_i=(n);F(;i<_i;++i){e;}} inline V f(I n){ C(n==1,OUT("one")) C(n==2,OUT("two")) C(n==3,OUT("three")) C(n==4,OUT("four")) C(n==5,OUT("five")) C(n==6,OUT("six")) C(n==7,OUT("seven")) C(n==8,OUT("eight")) C(n==9,OUT("nine")) C(n%2==0,OUT("even")) OUT("odd"); OUT("\n"); } I main(){ I m,n;IN("%i\n%i",&m,&n); I(1+n-m,f(m+i)); R 0; } Conditional Statements You are given a positive integer, n,: If 1<=n<=9, then print the English representation of it. That is "one" for 1, "two" for 2, and so on. Otherwise print "Greater than 9" (without quotes). Input Format Input will contain only one integer, n. Output Format Print the output as described above. Solution (C++, 10m) #include<cstdio> #define IN(e...) scanf(e) #define OUT(e...) printf(e) #define R return #define C(c,t...) if(c){t;}else typedef int I; I main(){ I n; IN("%i",&n); C(n==1,OUT("one")) C(n==2,OUT("two")) C(n==3,OUT("three")) C(n==4,OUT("four")) C(n==5,OUT("five")) C(n==6,OUT("six")) C(n==7,OUT("seven")) C(n==8,OUT("eight")) C(n==9,OUT("nine")) OUT("Greater than 9"); R 0; } Basic Data Types Input Format Input will consists of an int, long, long long, char, float and double, each separated by a space. Output Format Print the elements in the same order, but each in a new line. Solution (C++, 10m) #include<cstdio> #define IN(e...) scanf(e) #define OUT(e...) printf(e) #define R return typedef int I; typedef long L; typedef long long LL; typedef char C; typedef float F; typedef double D; I main() { I i;L li;LL lli;C c;F f;D lf; IN("%i %li %lli %c %f %lf",&i,&li,&lli,&c,&f,&lf); OUT("%i\n%li\n%lli\n%c\n%f\n%lf",i,li,lli,c,f,lf); R 0; } 2D Array - DS Problem Statement You are given a 6*6 2D array. An hourglass in an array is a portion shaped like this: a b c d e f g For example, if we create an hourglass using the number 1 within an array full of zeros, it may look like this: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Actually there are many hourglasses in the array above. The three leftmost hourglasses are the following: 1 1 1 1 1 0 1 0 0 1 0 0 1 1 1 1 1 0 1 0 0 The sum of an hourglass is the sum of all the numbers within it. The sum for the hourglasses above are 7, 4, and 2, respectively. In this problem you have to print the largest sum among all the hourglasses in the array. Input Format There will be exactly 6 lines, each containing 6 integers seperated by spaces. Each integer will be between -9 and 9 inclusive. Output Format Print the answer to this problem on a single line. Solution (15m) #include <stdio.h> #define IN(e...) scanf(e) #define OUT(e...) printf(e) #define MAX(m,n) ((m)>(n)?(m):(n)) #define R return #define F(e...) for(e) typedef int I; #define I(m,e...) {I i=0,_i=(m);F(;i<_i;++i){e;}} #define J(n,e...) {I j=0,_j=(n);F(;j<_j;++j){e;}} #define K(n,e...) {I k=0,_k=(n);F(;k<_k;++k){e;}} I main() { I s,a[6][6],M=-63; I(6,J(6,IN("%i ",&a[i][j]))); I(4,J(4, s=0; K(3,s+=a[i][j+k]); s+=a[i+1][j+1]; K(3,s+=a[i+2][j+k]); M=MAX(M,s);)); OUT("%i\n",M); R 0; } Arrays - DS Problem Statement An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. You'll be an given array of N integers and you have to print the integers in the reverse order. Input Format The first line of the input contains N,where N is the number of integers.The next line contains N integers separated by a space. Constraints 1<=N<=1000 1<=Ai<=10000, where Ai is the ith integer in the array. Output Format Print the N integers of the array in the reverse order in a single line separated by a space. Solution 1 (5m) #include<stdio.h> typedef int I; #define R return #define F(e...) for(e) #define J(n,e...) {I j=0, Mj=(n); F(; j<Mj; ++j){e;}} #define I(e...) scanf(e) #define O(e...) printf(e) int main() { I n; I("%i", &n); I a[1000]; J(n, I("%i ", &a[j])); J(n, O("%i ", a[n-j-1])) R 0; } Solution 2 (15m using a function) #include <stdio.h> typedef int I; typedef void V; #define R return #define F(e...) for(e) #define J(n,e...) {I j=0, Mj=(n);F(;j<Mj;++j){e;}} #define I(e...) scanf(e) #define O(e...) printf(e) V reverse(I*,I); V reverse(I *a, I n){I t; J(n/2, t=a[j]; a[j]=a[n-j-1]; a[n-j-1]=t;)} I main() { I a[1000], n; I("%i",&n); J(n,I("%i ",&a[j])); reverse(a,n); J(n, O("%i ",a[j])) R 0; } XML2 - Find the maximum depth Problem Statement You are given a valid XML document and you have to print the maximum level of nesting in it. The first line of input is the number of XML lines followed by the XML lines. Take the depth of root as 0. Input Format The first line shows the number of lines in XML document followed by the XML document. Output Format An integer value Solution (20m) import xml.etree.ElementTree I = ''.join([input() for _ in range(int(input()))]) root = xml.etree.ElementTree.fromstring(I) def m(r): d = [m(c) for c in r] return 0 if []==d else 1 + max(d) print(m(root)) XML 1 - Find the Score Problem Statement You are given a valid XML document and you have to print its score. The first line of input is the number of XML lines followed by the XML lines. Score is given by the sum of score of each element. For any element, score is equal to the number of attributes it has. Input Format The first line shows the number of lines in XML document followed by the XML document. Output Format An integer score Solution (1hr I started to try and understand XML in general, but just finished the problem instead) import xml.etree.ElementTree I = ''.join([input() for _ in range(int(input()))]) root = xml.etree.ElementTree.fromstring(I) def score(root): return len(root.attrib) + sum([score(child) for child in root]) print(score(root)) Detect HTML tags, attributes and attribute values Problem Statement You are given an HTML code snippet of N lines. Your task is to detect and print all HTML tags, attributes and attribute values. Print the detected items in the following format: Tag1 Tag2 -> Attribute2[0] > Attribute_value2[0] -> Attribute2[1] > Attribute_value2[1] -> Attribute2[2] > Attribute_value2[2] Tag3 -> Attribute3[0] > Attribute_value3[0] -> symbol indicates that tag contains an attribute. It is immediately followed by the name of attribute and attribute value. > symbol acts as a separator of attribute and attribute value. If an HTML tag has no attribute then simply print the name of the tag. Note: Do not detect any HTML tag, attribute and attribute value, inside the HTML comment tags (<!-- Comments -->).Comments can be multiline also. All attributes have an attribute value. Input Format First line contains, integer N, number of lines in HTML code snippet. Next N lines contain, HTML code. Constraints 0<N<100 Output Format Print the HTML tags, attributes and attribute values in order of their occurence from top to bottom in the snippet. Ensure proper formatting, as explained in the problem statement. Solution (1m, it was almost exactly the same as HTMLParser - Part 1) from html.parser import HTMLParser class h(HTMLParser): def handle_starttag(self, t, a): print(t) for x,y in a: print('->',x,'>',y) def handle_startendtag(self, t, a): print(t) for x,y in a: print('->',x,'>',y) p = h() I = [input() for _ in range(int(input()))] for x in I: p.feed(x) HTMLParser - Part 2 Task You are given an HTML code snippet of N lines. Your task is to print single−line comments, multi−line comments and data. Format for printing the result is: >>> Single-line Comment Comment >>> Data My Data >>> Multi-line Comment Comment_multiline[0] Comment_multiline[1] >>> Data My Data >>> Single-line Comment: Note : Do not print data if data == '\n'. Input Format First line contains, integer N, number of lines in HTML code snippet. Next N lines contain, HTML code. Constraints 0<N<100 Output Format Print the single−line comments, multi−line comments and data in order of their occurence from top to bottom in the snippet. Ensure proper formatting, as explained in the problem statement. Solution (20m) from html.parser import HTMLParser class hp(HTMLParser): def handle_data(self, x): if x!='\r': print('>>> Data') print(x) def handle_comment(self, x): y = x.split('\r') if 1==len(y): print('>>> Single-line Comment') print(*y) else: print('>>> Multi-line Comment') for z in y: print(z) N = int(input()) I = ''.join([input() for _ in range(N)]) p = hp() p.feed(I) HTML Parser - Part 1 Task You are given an HTML code snippet of N lines. Your task is to print start tags, end tags and empty tags separately. Format for printing the result is: Start : Tag1 End : Tag1 Start : Tag2 -> Attribute2[0] > Attribute_value2[0] -> Attribute2[1] > Attribute_value2[1] -> Attribute2[2] > Attribute_value2[2] Start : Tag3 -> Attribute3[0] > None Empty : Tag4 -> Attribute4[0] > Attribute_value4[0] End : Tag3 End : Tag2 -> symbol indicates that tag contains an attribute. It is immediately followed by the name of attribute and attribute value. > symbol acts as a separator of attribute and attribute value. If an HTML tag has no attribute then simply print the name of the tag. If an attribute has no attribute value then simply print the name of attribute value as None. Note: Do not detect any HTML tag, attribute and attribute value, inside the HTML comment tags (<!-- Comments -->).Comments can be multiline also. Input Format First line contains, integer N, number of lines in HTML code snippet. Next N lines contain, HTML code. Constraints 0<N<100 Output Format Print the HTML tags, attributes and attribute values in order of their occurence from top to bottom in the snippet. Ensure proper formatting, as explained in the problem statement. Solution (1hr wasted finding that HTMLParser module from py2.x is now html.parser from py3.x) from html.parser import HTMLParser class h(HTMLParser): def handle_starttag(self, t, a): print('Start :',t) for x,y in a: print('->',x,'>',y) def handle_endtag(self, t): print('End :',t) def handle_startendtag(self, t, a): print('Empty :',t) for x,y in a: print('->',x,'>',y) p = h() I = [input() for _ in range(int(input()))] for x in I: p.feed(x) Hex Color Code Problem Statement CSS colors are defined using a hexadecimal (HEX) notation for the combination of Red, Green, and Blue color values (RGB). Specifications of HEX Color Code It must start with a '#' symbol. It can have 3 or 6 digits. Each digit is in the range of 0 to F. (i.e. 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, A, B, C, D, E and F). A-F letters can be in lower case too. (i.e. a, b, c, d, e and f are also valid digits). CSS Code Pattern Selector { Property: Value; } Input Format First line contains, integer N. Next N lines contain, CSS Code. Constraints 0<N<50 Output Format Output color codes with '#' in separate lines. Solution (20m) from re import findall re=r'[^\A](#[A-Fa-f0-9]{6}|#[A-Fa-f0-9]{3})' I=[input() for _ in range(int(input()))] O=[x for y in I for x in findall(re,y)] for x in O: print(x) Validating Roman Numerals Problem Statement You are given a string and you have to validate whether it's a valid Roman numeral. If it is valid, print True, otherwise print False. Try to create a regular expression for a valid Roman numeral. Input Format A string containing Roman Characters Output Format A one line string containing True or False Constraints The number will be between 1 and 3999 (both included) Solution (20min) from re import match re='^(M{0,3})(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$' print('True' if match(re,input()) else 'False') Validating Phone Numbers Problem Statement Let's dive into the interesting topic of regular expressions! You are given some inputs and you are required to check whether they are valid mobile numbers. A valid mobile number is a ten digit number starting with 7, 8 or 9. Input Format The first line contains an integer N followed by N lines, each containing some string. Output Format For every string listed, print YES if it is a valid mobile number and NO if it isn’t. Constraints 1 <= N <= 10 Mobile Number contains valid alpha-numeric characters 2 <= len(Number) <= 15 Solution (10m) from re import match I=[input() for _ in range(int(input()))] O=['YES' if match('^[789][0-9]{9}$',x) else 'NO' for x in I] for x in O: print(x) Regex Substitution Task You are given a text of N lines. The text contains && and || symbols. Your task is to modify : && to and || to or Both && and || should have space " " on both sides. Input Format First line contains integer, N. Next N lines contains the text. Constraints 0<N<100 Neither && nor || occur in start or end of each line. Output Format Output the modified text. Solution (20m had some trouble understanding the form of the desired result from the given specifications) from re import sub I=[input() for _ in range(int(input()))] A=I B=[] while A!=B: B=A A=[sub(' && ',' and ',x) for x in A] A=[sub(' \|\| ',' or ',x) for x in A] for x in A: print(x) Validating Email Address with Filter Problem Statement You are given an integer N followed by N email addresses. Your task is to print a list containing valid email addresses, in lexicographic order. A valid email address is of the format username@websitename.extension Username can only contain letters, digits, dash and underscore. Website name can have letters and digits. Maximum length of the extension is 3. Input Format An integer N followed by N lines, each containing a string. Constraints Each line is a nonempty string. Output Format A list containing valid email addresses in lexicographic order. If the list is empty, just output an empty list, []. Solution (30m, I was going to do it with filters, but that was taking WAY too long so re) from re import match I=[input() for _ in range(int(input()))] re='^[a-zA-Z][a-zA-Z0-9-_]*@[a-zA-Z0-9]+\.[a-zA-Z]{1,3}$' O=sorted([x for x in I if match(re,x)]) print(O) Map and Lambda Functions Problem Statement Let's learn some new python concepts! 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 An integer N Output Format A list containing cubes of first N fibonacci numbers. Constraints 0<=N<=15 Solution (10m) def fib(n): return fib(n-1)+fib(n-2) if n>1 else 1 if n==1 else 0 print(list(map(lambda x:x**3,[fib(n) for n in range(int(input()))]))) Class 2 - Find the torsional angle Problem Statement You are given four points A, B, C and D in the 3-dimensional cartesian coordinate system. You are required to print the angle between the plane made by points A, B, C and B, C, D in degrees(NOT RADIAN). Let the angle be PHI. Cos(PHI) = (X . Y)/|X||Y| where X = AB x BC and Y = BC x CD. Here X.Y mean dot product between X and Y. AB x BC mean cross product between line segment AB and BC. AB = B - A. Input Format X, Y and Z coordinates of a point in one line separated by space, where they are floating numbers. Output Format Angle with precision of two digits after decimal. Solution (50m I wish I could work these problems in N) import math def minus(x,y): return [u-v for u,v in zip(x,y)] def dot(x,y): return sum([u*v for u,v in zip(x,y)]) def norm(x): return math.sqrt(dot(x,x)) def det(x,y): return x[0]*y[1]-x[1]*y[0] def cross(x,y): return [det(x[1:],y[1:]), det(x[::2],y[::2]), det(x[:-1],y[:-1])] def abd(x,y): return math.degrees(math.acos(dot(u,v)/(norm(u)*norm(v)))) a,b,c,d=[[float(x) for x in input().split()] for _ in range(4)] u=cross(minus(b,a), minus(c,b)) v=cross(minus(c,b), minus(d,c)) print('{:0.2f}'.format(abd(u,v))) Classes: Dealing with Complex Numbers Problem Statement 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. The precision of both the real and imaginary part should be two digits after decimal. Input Format Real and imaginary part of a number separated by space. Output Format For two complex numbers C and D, the output should be in the following sequence C + D C - D C * D C / D mod(C) mod(D) For complex numbers with non-zero real(A) and complex part(B), the output should be in the following format: A + Bi Replace the plus symbol (+) with a minus symbol (-) when B < 0 For complex numbers with a zero complex part i.e. real numbers, the output should just be the real number. For complex numbers where the real part is zero and the complex part(B) is non-zero, the output should be: Bi Solution (30m formatting output to a poorly given specification takes a long time) u=complex(*[float(x) for x in input().split()]) v=complex(*[float(x) for x in input().split()]) I=[[x.real,x.imag] for x in [u+v, u-v, u*v, u/v, abs(u), abs(v)]] for x,y in I: if y==0: print('{:0.2f}'.format(x)) elif x==0: print('{:0.2f}i'.format(y)) elif y<0: print('{:0.2f} - {:0.2f}i'.format(x,-y)) else: print('{:0.2f} + {:0.2f}i'.format(x,y)) Sort Data Task You are given two values a and b. Your task is to do integer division and print a/b. Input Format First line contains, number of test cases T. Next T line contains, space separated values of a and b. Constraints 0<T<10 Output Format Print value of a//b. In case of ZeroDivisionError or ValueError, print the error code. Solution (10m) I=[input().split() for _ in range(int(input()))] for x in I: try: print(int(x[0])//int(x[1])) except (ZeroDivisionError, ValueError) as e: print('Error Code:',e) Problem Statement You are given data in a tabular format i.e. the data contains N rows and each row contains M space-separated elements. You can imagine the M items to be different attributes (like height, weight, energy, etc) and each of the N rows as an instance or a sample. Your task is to sort the table on the Kth attribute and print the final resulting table. [If two attributes are the same for different rows, print the row that appeared first in the input] Input Format First line contains N and M separated by a space. Next N lines contain M elements each. The last line contains K. Constraints 1<|=N,M<|=1000 0<|=K<M each element <|=1000 Output Format Print the N lines of the sorted table, each line has space-separated elements. Check the sample below for clarity. Solution (10m) I=[[int(x) for x in input().split()] for _ in range(int(input().split()[0]))] k=int(input()) O=sorted(I,key=lambda x: x[k]) for x in O: print(*x) Zipped! Task The National University, conducts an examination of N students in X subjects. Your task is to compute average scores of each student. Average score=Sum of scores obtained in all subjects by a studentTotal number of subjects The format for general mark sheet is : Student ID ___1_____2_____3_____4_____5__ Subject 1 | 89 90 78 93 80 Subject 2 | 90 91 85 88 86 Subject 3 | 91 92 83 89 90.5 |______________________________ Average 90 91 82 90 85.5 Input Format First line contains, space separated values of N and X. Next X lines contains, space separated marks obtained by students in a particular subject. Constraints 0<N<|=100 0<X<|=100 Output Format Print averages of all students in separate lines. Averages must be correct upto 1 decimal place. Solution (15m) n=int(input().split()[1]) I=[[float(x) for x in input().split()] for _ in range(n)] O=[sum(x)/n for x in zip(*I)] for x in O: print(x) Time Delta Problem Statement Timestamps are given in the format: Day dd Mon yyyy hh:mm:ss +xxxx Here +xxxx represents the timezone. See sample below for details. Task Given 2 timestamps, print the absolute difference (in seconds) between them. Input Format First line contains T representing T testcases. Each testcase contains 2 lines, representing time t1 and time t2. Output Format Print the absolute difference (t1−t2) in seconds. Constraints It is guaranteed that input contains only valid timestamps and the year can reach up to 3000. Solution (2 days) This is the first real problem requiring an understanding of how to go through documentation to find a solution that is "good enough". I learned that, in general, computers and time are difficult to combine. Also, the real problem was that I wrote "import datetime" in my original code. It should have been "from datetime import datetime", similar but two days difference in solving the problem. from datetime import datetime I=[[datetime.strptime(input(),'%a %d %b %Y %H:%M:%S %z') for x in range(2)] for _ in range(int(input()))] O=[abs(x[0]-x[1]).total_seconds() for x in I] for x in O: print(int(x)) Calendar Module Task You are given the date of the day. Your task is to find what day it is on that date. Input Format Single line containing space separated month, day and year in MM DD YYYY format. Constraints 2000<year<3000 Output Format Output the correct day. Solution (15m) import calendar I=[int(x) for x in input().split()] print(calendar.day_name[calendar.weekday(I[2],I[0],I[1])].upper()) Most Commons Problem Statement You are given a string S. The string consists of lowercase alphabets. Your task is to find top three most common characters in the string S. Input Format Single line containing string S. Constraints 3<len(S)<104 Output Format Print the most common characters along with their count of occurrences in three lines. Output must sorted in descending order of count of occurrences. If count of occurrences is same then sort in ascending order of characters. Solution (30m, took a while to figure out how to sort things correctly, there is a better way to do this all from a different perspective) from collections import Counter for x in sorted(Counter(input()).items(),key=lambda x:(-x[1],x[0]))[:3]: print(*x) collections.Counter() Task Raghu is a shoe shop owner. His shop has X number of shoes. He has a list containing 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. Input Format First line contains, X number of shoes. Second line contains, space separated size of the shoes. Third line contains, N number of customers. Next N line contain, space separated values of shoe size and xi price of shoe. Constraints 0<X<103 0<N<103 20<xi<100 2<shoe size<20 Output Format Print the amount of money earned by Raghu Sample Input 10 2 3 4 5 6 8 7 6 5 18 6 6 55 6 45 6 55 4 40 18 60 10 50 Sample Output 200 Explanation Customer 1 : Purchased shoe of size 6 for $ 55. Customer 2 : Purchased shoe of size 6 for $ 45. Customer 3 : Size 6 not available, so no purchase. Customer 4 : Purchased shoe of size 4 for $ 40. Customer 5 : Purchased shoe of size 18 for $ 60. Customer 6 : Size 10 not available, so no purchase. Total money earned = 55 + 45 + 40 + 60 = $ 200 Solution (10m) from collections import Counter input() C=Counter(input().split()) I=[input().split() for _ in range(int(input()))] s=0 for x in I: if C[x[0]]>0: C[x[0]]-=1 s+=int(x[1]) print(s) Maximize It! Problem Statement You are given a function f(X)=X*^2. You are also given K lists. The ith list consists of Ni elements. You have to pick exactly one element from each list such that S=(f(X1)+f(X2)+...+f(Xk))%M is maximized. Xi denotes the element picked from the ith list . Find the maximized value Smax thus obtained. % denotes the modulo operator. Input Format First line contains 2 space separated integers K and M. Then follow K lines. The (i+1)th line contains an integer Ni followed by Ni space separated integers denoting the elements in the list. Output Format A single integer denoting the value Smax. Constraints 1<|=K<|=7 1<|=M<|=1000 1<|=Ni<|=7 1<|=Magnitudeofelementsinlist<|=109 Solution (15m) from itertools import product I=[int(x) for x in input().split()] N=[[int(x)**2 for x in input().split()[1:]] for _ in range(I[0])] print(max([sum(x)%I[1] for x in product(*N)])) itertools.combinations_with_replacement() Task You are given a string S. Your task is to print all possible combinations with replacement of size k, of the string in lexicographic sorted order. Input Format Single line containing space separated , string S and value k. Constraints 0<N<10 0<k<|=len(S) String contains only UPPERCASE characters. Output Format Print combinations with replacement of string S in separate lines. Solution (5m) from itertools import combinations_with_replacement I=input().split() c=combinations_with_replacement(sorted(I[0]),int(I[1])) O=[''.join(x) for x in c] print('\n'.join(O)) itertools.combinations() Task You are given a string S. Your task is to print all possible combinations up to size k, of the string in lexicographic sorted order. Input Format Single line containing space separated, string S and value k. Constraints 0<N<10 0<k<|=len(S) String contains only UPPERCASE characters. Output Format Print combinations of string S in separate lines. Solution (15m) from itertools import combinations I=input().split() s=sorted(I[0]) c=[x for i in range(1,1+int(I[1])) for x in combinations(s,i)] O=[''.join(x) for x in c] print('\n'.join(O)) itertools.permutations() Task You are given a string S. Your task is to print all possible permutations of size k of the string in lexicographic sorted order. Input Format Single line containing space separated , string S and value k. Constraints 0<N<10 0<k<|=len(S) String contains only UPPERCASE characters. Output Format Print permutations of string S in separate lines. Solution (15m) from itertools import permutations I=input().split() p=permutations(sorted(I[0]),int(I[1])) O=[''.join(x) for x in p] print('\n'.join(O)) itertools.product() Task Your are given a two lists A and B. Your task is to compute Cartesian Product AXB. Note : A and B are sorted lists and the cartesian product's tuples should be emitted in sorted order. Input Format First line contains, space separated elements of list A. Second line contains, space separated elements of list B. Both lists have no duplicate integer elements. Constraints 0<A<30 0<B<30 Output Format Output space separated tuples of Cartesian Product. Solution (10m) from itertools import product A=[int(x) for x in input().split()] B=[int(x) for x in input().split()] print(*product(A,B)) Find Angle MBC ABC is a right angle triangle, right angled at B. Therefore, angle ABC=90°. Point M is the mid-point of hypotenuse AC. You are given the lengths AB and BC. Your task is to find angle MBC ( angle theta°, as shown in figure ) in degrees. Input Format First line contains, length of side AB. Second line contains, length of side BC. Constraints 0<AB<100 0<BC<100 Lengths AB and BC are natural numbers. Output Format Output angle MBC in degrees. Note: Round-off the angle to nearest integer. Examples: If angle is 56.5000001°, then output 57°. If angle is 56.5000000°, then output 57°. If angle is 56.4999999°, then output 56°. 0°<theta°<90° Solution (10m had to be written in Python 2.x per questions limits) import math d=math.degrees(math.atan2(int(input()),int(input()))) O=str(int(round(d)))+'°' print(O) Polar Coordinates Task You are given a complex z. Your task is to convert it to polar coordinate. Input Format Single line containing complex number z. Output Format Two lines: First line contains, value of r. Second line contains, value of phi. Solution (10m) import cmath for x in cmath.polar(complex(input())): print(x) Check Strict Superset Problem Statement You are given a set A and N numbers of other sets. Your job is to find whether set A is a strict superset of all the N sets. Print True, if it is a strict superset of all N sets otherwise print False. A strict superset has atleast one element which not in its subset. Input Format First line contains, space separated elements of set A. Second line contains, integer N. Next N lines contain, space separated elements of other sets. Constraints 0<len(set(A))<501 0<N<21 0<len(otherSets)<101 Output Format Print True if set A is strict superset of all N the sets otherwise print False. Solution (15m again... X-Files slows things down and makes them a bit messier) A=set(input().split()) I=[set(input().split()) for _ in range(int(input()))] q=[(x<=A)&(x!=A) for x in I] print(all(q)) The Captains Room Problem Statement Mr. Anant Asankhya is the manager at INFINITE hotel. The hotel has an infinite amount of rooms. One fine day, a finite number of tourists came to stay at the hotel. Tourists consisted of : a Captain. Equal sized group of families (size K each and K ≠ 1). The Captain was given a separate room and rest were given one room per group. Mr. Anant has an unordered list of randomly arranged room entries. The list consists of room numbers of all the tourists. The room numbers will appear K times per group except for the Captain's room. Mr. Anant needs help from you to find the Captain's room number. Total number of Tourists or total group of families is not known to you. You only have the value of K and room number list. Input Format First line consists of K (The size of each group). Second line consists of room number list. Constraints 1<K<1000 Output Format Output the Captain's room number. Solution (10m, messy and slow solution) import collections C=collections.Counter() input() for x in input().split(): C[x]+=1 for x in C.items(): if x[1]==1: print(x[0]) break Set Mutations TASK You are given a set A and N numbers of other sets. These N sets have to perform some specific mutation operations to set A. Your task is to execute those operations and print the sum of elements of set A. Input Format First line contains, number of elements in set A. Second line contains, space separated list of elements of set A. Third line contains, N, number of other sets. Next 2*N lines are divided into N parts of two lines each. First line of each part contains, space separated entries of operation name and length of other set. Second line of each part contains, space separated list of elements of other set. 0 < len(set(A)) < 1000 0 < len(otherSets) < 100 0 < N < 100 Output Format Output the sum of elements of set A. Solution (10m) input() s=set(input().split()) I=[[input().split()[0], set(input().split())] for _ in range(int(input()))] for x in I: y=x[1] eval('s.'+x[0]+'(y)') print(sum({int(x) for x in s})) Set .union() Operation Task Students of District College have subscription of English and French newspapers. Some students have subscribed to only English, some have subscribed to only French and some have subscribed to both newspapers. You are given two sets of roll numbers of students, who have subscribed to English and French newspapers. Your task is to find total number of students who have subscribed to at least one newspaper. Input Format First line contains, number of students who have subscribed to English newspaper. Second line contains, space separated list of roll numbers of students, who have subscribed to English newspaper. Third line contains, number of students who have subscribed to French newspaper. Fourth line contains, space separated list of roll numbers of students, who have subscribed to French newspaper. Constraints 0<Total number of students in college<1000 Output Format Output total number of students who have at least one subscription. Solution (8m) input() s=set(input().split()) input() print(len(s.union(set(input().split())))) Set .discard(), .remove() & .pop() Task You have a non-empty set s and you have to execute N commands given in N lines. Commands will be pop, remove and discard. Input Format First line contains integer n, number of elements in set. Second line contains space separated elements of set s. All elements are non-negative integers, less than or equal to 9. Third line contains integer N, number of commands. Next N lines contains pop, remove and discard commands. Constraints 0<n<20 0<N<20 Output Format Print sum of elements of set 's' in output. Solution (8m) input() s={int(x) for x in input().split()} I=[input().split() for x in range(int(input()))] for x in I: eval('s.'+x[0]+'('+','.join(x[1:])+')') print(sum(s)) set.add() Task Apply your knowledge of .add() operation, to help your friend 'Hari'. Hari has a huge collection of country stamps. He decided to count total number of distinct country stamps he has collected. He asked you to help him. You pick stamps one by one from a stack of 'N' country stamps. Your task is to find the total number of distinct country stamps. Input Format First line contains N, total number of country stamps. Next N lines contains, names of the country stamp. Constraints 0<N<1000 Output Format Output the total number of distinct country stamps. Solution (1m, I did not use the method suggested) print(len({input() for _ in range(int(input()))})) Introduction to Sets Task Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student 'Mickey' to compute an average of all the plants with distinct heights in her greenhouse. Input Format First line contains, total number of plants in greenhouse. Second line contains, space separated height of plants in the greenhouse. Total number of plants is upto 100 plants. Output Format Output the average value of height. Solution (5m) input() H={int(x) for x in input().split()} print(sum(H)/len(H)) Piling Up! Problem Statement There is a horizontal row of n cubes. Side length of each cube from left to right is given. You need to create a new vertical pile of cubes. The new pile should be such that if cubei is on cubej then sideLengthj≥sideLengthi. But at a time, you can only pick either the leftmost or the rightmost cube only. Print "Yes" if its possible, "No" otherwise. Input Format First line contains a single integer T, denoting the number of test cases. For each testcase, there are 2 lines. First line of each test case contains n. Second line of each test case contains n space separated integers, the sideLengths of the cubes in that order. Constraints 1<|=T<|=5 1<|=n<|=105 1<|=sideLength<231 Output Format For each testcase, output a single line containing a single word, either a "Yes" or a "No". Solution (50m) I made a dirty recursive solution first, but it took too long to run on the larger lists, so I turned it into a loopy solution (which is ugly). Recursive solution (ugly to some people) def q(x): return 'Yes' if len(x)<=2 else q(x[1:-1]) if min(x[1],x[-2])<=max(x[0],x[-1]) else 'No' I=[[int(x) for x in input().split()] for _ in range(2*int(input()))] for x in I[1::2]: print(q(x)) Loopy solution (ugly to some people, though clearly faster because people don't like to optimize recursion since it's hard) for _ in range(int(input())): l,r=0,int(input())-1 L=[int(x) for x in input().split()] q='Yes' while(l<r): if min(L[l+1],L[r-1])>max(L[l],L[r]): q='No' break l+=1 r-=1 print(q) Word Order Problem Statement You are given n words. Some words may repeat. For each word, you have to output its number of occurences. But the output order should correspond with the order of the first appearance of the word. See the sample input/output for clarification. Note that each line in the input ends with a "\n" character. Constraints: 1<:n<:105 Sum of lengths of all the words do not exceed 106 All words are composed of lowercase-latin alphabets only. Input Format First line contains n. n lines follow, ith one contains the ith word. Output Format Output 2 lines. On the first line, output the number of distinct words in the input. In the second line, for each distinct word, output its number of occurences in the order specified in the problem statement. Solution (10m) import collections C=collections.Counter() I=[input() for x in range(int(input()))] L=[] for x in I: if C[x]==0: L.append(x) C[x]+=1 O=[C[x] for x in L] print(len(L)) print(*O) No Idea! Problem Statement There is an array of n integers, and 2 disjoint sets of m integers each A and B. You like all integers in A and dislike all integers in B. Your initial happiness is 0 and for each integer in the array, i, if i∈A, you add 1 to your happiness, if i∈B, you add −1 to your happiness, else your happiness does not change. Output your final happiness at the end. Note that since A and B are sets, they have no repeated elements. But, the array might contain duplicate elements. Constraints 1<|=n<|=105 1<|=m<|=105 1<|=Any integer in the input<|=109 Input Format First line contains n and m. Second line contains n integers, the array. Third and fourth lines contain m integers, A and B respectively. Output Format Output a single integer, the answer. Solution (30m took time to find collections.Counter() ) import collections C=collections.Counter() input() I=input().split() A=input().split() B=input().split() for x in I: C[x] += 1 O=sum([C[x] for x in A])-sum([C[x] for x in B]) print(O) DefaultDict Tutorial Problem Statement DefaultDict is a container in the collections class of Python. It is almost the same as the usual dictionary (dict) container but with one difference. The value fields' data-type is specified upon initialization. A basic snippet showing the usage follows: from collections import defaultdict d = defaultdict(list) d['python'].append("awesome") d['something-else'].append("not relevant") d['python'].append("language") for i in d.items(): print i This prints: ('python', ['awesome', 'language']) ('something-else', ['not relevant']) In this challenge, you will be given 2 integers (n and m) and n words which might repeat, say they belong to a word group A. Then you'll be given m other words belonging to word group B. For each of these m words, you have to check whether the word has appeared in A or not. If it has then you have to print indices of all of its occurrences. If it has not then just print −1. Constraints 1<:n<:10000 1<:m<:100 1<:length of each word in the input<:100 Input Format The first line contains n and m. The next n lines contain the words belonging to A. The next m lines contain the words belonging to B. Output Format Output m lines. The ith line should contain the 1 indexed positions of occurrences of the ith word, separated by spaces, of the last m lines of the input. Solution (5m) (I did not solve it as they asked, I did it "the right way" :) (Also, vector/tree extensions of basic arithmetic operations are desperately needed) import itertools def where(x): return itertools.chain.from_iterable([[i]*j for i,j in enumerate(x)]) I=[int(x) for x in input().split()] A=[input() for x in range(I[0])] B=[input() for x in range(I[1])] W=[list(where([x==y for x in A])) for y in B] O=[[1+x for x in y] for y in W] for x in O: if x==[]: print(-1) else: print(*x) The Minion Game Problem Statement Kevin and Stuart, wants to play 'The Minion Game'. Bob is the match referee. Bob's task is to declare the winner and ensure that no rules are broken. Stuart is Player 1 and Kevin is Player 2. About Game Rules The game is a two player game. Players are given a string S. Both the players have to make words using the letters of string S. Player 1 has to make words starting with consonants. Player 2 has to make words starting with vowels. Game ends when both players have made all possible substrings. Scoring Player get +1 Point for each occurrence of the word in the string S. Example: If string S = BANANA Word made by Player 2 = ANA 'ANA' is occuring twice in 'BANANA'. Hence, Player 2 will get 2 Points. Input Format Single line containing string S. Note: String S contains only capital alphabets [A-Z]. Constraints 0<len(S)<=106 Output Format Print the name of the winner along with the total score. If the game is draw, print Draw. Solution (40m took time to find a "good" definition for where) import itertools def where(x): return itertools.chain.from_iterable([[i]*j for i,j in enumerate(x)]) s=input() L=len(s) K=sum([L-x for x in where([y in 'AEIOU' for y in s])]) S=(L*(L+1)//2)-K if K==S: print('Draw') elif K>S: print('Kevin',K) else: print('Stuart',S) Designer Door Mat Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat. Design specifications are as follows: 1. Size of mat must be NXM. (N is an odd natural number and M is 3 times N.) 2. Design should have 'WELCOME' written in the center. 3. Design pattern should only use '|', '.' and '-' characters. Sample Designs Size: 7 x 21 ---------.|.--------- ------.|..|..|.------ ---.|..|..|..|..|.--- -------WELCOME------- ---.|..|..|..|..|.--- ------.|..|..|.------ ---------.|.--------- Size: 11 x 33 ---------------.|.--------------- ------------.|..|..|.------------ ---------.|..|..|..|..|.--------- ------.|..|..|..|..|..|..|.------ ---.|..|..|..|..|..|..|..|..|.--- -------------WELCOME------------- ---.|..|..|..|..|..|..|..|..|.--- ------.|..|..|..|..|..|..|.------ ---------.|..|..|..|..|.--------- ------------.|..|..|.------------ ---------------.|.--------------- Input Format Single line containing space separated values of N and M. Constraints 5<N<101 15<M<303 Output Format Output the design pattern. Solution (20m) N, M = map(int,input().split()) # More than 6 lines of code will result in 0 score. Blank lines are not counted. T=[(k*'.|.').center(M,'-') for k in range(1,N, 2)] print('\n'.join(T)) print('WELCOME'.center(M,'-')) print('\n'.join(T[::-1])) Text Wrap Task You are given string S and width w. Your task is to wrap the string into a paragraph of width w. Input Format First line contains, string S. Second line contains, width w. Constraints 0<len(S)<1000 0<w<len(S) Output Format Print the text wrapped paragraph. Solution (15m) import textwrap s=input() print(textwrap.fill(s,int(input()))) Text Alignment Make this using the code below: H HHH HHHHH HHHHHHH HHHHHHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHHHHHHHHHHHHHHHHHHHHHH HHHHHHHHHHHHHHHHHHHHHHHHH HHHHHHHHHHHHHHHHHHHHHHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHH HHHHHHHHH HHHHHHH HHHHH HHH H Solution (20m of testing and retesting and just... ya) #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(thicknes s)).rjust(thickness*6)) String Validators Task You are given a string S. Your task is to find if string S contains, alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters. Input Format Single line containing, string S. Constraints 0<len(S)<1000 Output Format In First line, print True if S has alphanumeric character otherwise print False. In Second line, print True if S has alphabetical character otherwise print False. In Third line, print True if S has digits otherwise print False. In Fourth line, print True if S has lowercase character otherwise print False. In Fifth line, print True if S has uppercase character otherwise print False. Solution (10m) A nasty solution to something that could be done in less space and with less time. s=input() print(any([x.isalnum() for x in s])) print(any([x.isalpha() for x in s])) print(any([x.isdigit() for x in s])) print(any([x.islower() for x in s])) print(any([x.isupper() for x in s])) Find a String Problem Statement In this challenge, the user enters a string and a substring and you have to print the number of times that substring occurs in that string. String traversal will take place from left to right, not from right to left. NOTE : Letters of string are case-sensitive. Input Format Two strings each in a new line. Constraints 1 <= len(string) <= 200 each character in the string is an ascii character. Output Format An integer number indicating the total number of occurrences of that string. Solution (10m) s=list(input()) ss=input() print([''.join(s[x:x+len(ss)]) for x in range(len(s)-len(ss)+1)].count(ss)) Mutations Task You have to read a string, change the character at a given index and print the string. Input Format First line contains a string, S. Next line contains an integer i and a character c. Output Format Using any of the method explained above. Replace the character at index i with c. Solution (3m) s=input() I=input().split() i=int(I[0]) c=I[1] print(s[:i]+c+s[1+i:]) String Split and Join Task You are given a string. Split the string on " " (space) delimiter and join using a - hyphen. Input Format The first line contains a string consisting of words separated by space. Output Format Print the formatted string as explained above. Solution (1m) print('-'.join(input().split())) sWAP cASE Problem Statement You are given a string S. Your task is to swap case, i.e., convert all lower case letters to upper case and vice versa. Solution (10m) print(''.join([x.upper() if x.islower() else x.lower() for x in input()])) Nested list Problem Statement Now we will see how to implement a nested list. There is a classroom of 'n' students and you are given their names and marks in physics. Store them in a nested list and print the name of each student who got the second lowest marks in physics. NOTE: If there are more than one student getting same marks, make sure you print the names of all students in alphabetical order, in different lines. Input Format Integer N followed by alternating sequence of N strings and N numbers. Output Format Name of student. Constraints 1<|=N<|=5 Solution (15m, a horribly slow solution though) I=[list((input(),float(input()))) for x in range(int(input()))] I.sort() L=list(set([x[1] for x in I])) L.sort() L= (L[1] if len(L)>1 else L[0]) for x in I: if x[1]==L: print(x[0]) Find second largest number in a list Solution (20m, finding good initial values for M took a while float("-inf")) input() I=[int(x) for x in input().split()] M=[float("-inf"),float("-inf")] for x in I: if x>M[0]: M[1]=M[0] M[0]=x elif M[0]>x and x>M[1]: M[1]=x print(M[1]) List Comprehensions Lets learn about list comprehensions! You are given three integers X, Y and Z denoting the dimensions of a Cuboid. You have to print a list of all possible coordinates on the three dimensional grid, such that at any point the sum Xi + Yi + Zi is not equal to N. If X = 2, then possible values of Xi can be 0, 1 and 2. The same applies to Y and Z. Input Format Four integers X, Y, Z and N in four different lines. Output Format You have to print the list, in increasing order. Solution (20m) There is a better way to do this, but this works for now. Also, python should have primitive support for multidimensional comprehension. M=[1+int(input()) for x in range(3)] N=int(input()) T=[[x,y,z] for x in range(M[0]) for y in range(M[1]) for z in range(M[2])] L=[] for x in T: if N!=sum(x): L.append(x) print(L) Sets-Symmetric Difference Problem Statement Lets learn about a new datatype 'sets'! You are given two set of integers M and N and you have to print their symmetric difference in ascending order. The first line of input contains value of M followed by M integers, then value of N followed by N integers. Symmetric difference between M and N mean those values which either exist in M or in N but not in both. Input Format Value of M followed by M integers, then value of N followed by N integers. Output Format Integers in ascending order, one per line. Solution (30m) Took a long while to figure out how to sort correctly. I've included a report on my error in understanding the sort() method at jmeuser.github.io/html/error.html input() x=set(map(int,input().split())) input() y=set(map(int,input().split())) z=list((x.union(y)).difference(x.intersection(y))) z.sort() for u in z: print(u) Tuples Task You are given an integer N in one line. The next line contains N space-separated integers. Create a tuple of those N integers. Lets call it T. Compute hash(T) and print it. Note hash() is one of the function in __builtins__ module. Input Format The first line contains N. The next line contains N space-separated integer values. Output Format Print the computed value. Solution (4m) input() print(hash(tuple([int(x) for x in input().split()]))) Lists Task You have to initialize your list L = [] and follow the N commands given in N lines. x.append(y) # add y to the end of the list x (k: x,y) x.extend(y) # join the list y to the end of the list x (k: x,y) x.insert(y,z) # insert z at index z in x x.remove(y) # remove first occurrence of y in x x.pop() # give last item of x and remove last item of x from x x.pop(y) # give x[y] and remove x[y] from x x.index(y) # give index of first occurrence of y in x (error otherwise) x.count(y) # give count of occurrences of y in x x.sort() # sort x in increasing x.reverse() # reverse the order of items of x Commands will be 1 of the 8 commands as given above, other than extend, and each command will have its value separated by space. Solution (20m Took time to find x.join(y) method for a string x) L=[] I=[input().split() for x in range(int(input()))] # input C=[x[0]+'('+','.join(x[1:])+')' for x in I] # command list for x in C: if x=='print()': print(L) else: eval('L.'+x) Finding the percentage Problem Statement There is a record of 'n' students, each record having name of student, percent marks obtained in Maths, Physics and Chemistry. Marks can be floating values. The user enters an integer 'n' followed by names and marks for the 'n' students. You are required to save the record in a dictionary data type. The user then enters name of a student and you are required to print the average percentage marks obtained by that student, correct to two decimal places. Input Format Integer N followed by name and marks for N students, followed by the name of the particular student. Output Format Average percentage of marks obtained Constraints 2 <= N <= 10 0 <= Marks <= 100 Solution (30min, I didn't know string.split() tokenized as I wanted) I=[input().split() for x in range(int(input()))] #input d={x[0]: [float(y) for y in x[1:]] for x in I} #dictionary a=d[input()] #entry print("{0:.2f}".format(sum(a)/len(a))) #output Interchange Two Numbers This is a poorly written question, it even tries to force you to use tuples. Here is a solution that uses tuples in the way that I can best think it wants: a=int(input()) b=int(input()) a,b=b,a print(a) print(b) or perhaps a,b=int(input()),int(input()) a,b=b,a print(a,b) Print triangle like: 1 22 333 4444 etc.. for i in range(1,input()): print(i*(10**i-1)/9) Read an integer n and print a list of the squares of each integer from 0 to n-1 n=int(raw_input()); for i in range(0,n): print(i**2) Input and Output Problem Statement For any program that we write the basic things that we need to do is take the input and print the expected output. In C++ you can take the input using cin and print the output using cout.Unlike C where you need the format specifier in printf and scanf, here you can use cin and cout. Taking Input: If you want to input a number: cin>>n , where n is the number. If you want to input a number and a string: cin>>n>>s, where s is the string. Printing output: If you want to output a single number: cout<<n If you want to output a number and a string separated by a new line: cout<<n<<endl<<s (where endl moves the pinter to the new line and then string gets printed.) Take three numbers as inputs and print the sum of the three numbers. Input Format The first line of the input contains three integers A,B and C. (1<|= & <|=1000) 2\ A,B,C Output Format In a single line print the sum of the three numbers. Solution #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int a,b,c; cin>>a; cin>>b; cin>>c; cout<<a+b+c; return 0; } Hello, World ! Problem Statement Let's start with the mandatory ritual. Print the string "Hello, World!". You can either use printf (preferred for this tutorial) or cout. Solution #include <iostream> #include <cstdio> using namespace std; int main() { printf("Hello, World!"); return 0; } Library Fine Problem Statement The Head Librarian at a library wants you to make a program that calculates the fine for returning the book after the return date. You are given the actual and the expected return dates. Calculate the fine as follows: If the book is returned on or before the expected return date, no fine will be charged, in other words fine is 0. If the book is returned in the same month as the expected return date, Fine = 15 Hackos * Number of late days If the book is not returned in the same month but in the same year as the expected return date, Fine = 500 Hackos * Number of late months If the book is not returned in the same year, the fine is fixed at 10000 Hackos. Input Format You are given the actual and the expected return dates in D M Y format respectively. There are two lines of input. The first line contains the D M Y values for the actual return date. The next line contains the D M Y values for the expected return date. Constraints 1<:D<:31 1<:M<:12 1<:Y<:3000 Output Format Output a single value equal to the fine. Solution (29m, I've gotta stop watching X-Files) typedef int I; #define C(c,t...) if(c){t;}else #include<stdio.h> #define I(e...) scanf(e) #define O(e...) printf(e) main(){I x,ad,am,ay,ed,em,ey;I("%i %i %i\n%i %i %i",&ad,&am,&ay,&ed,&em,&ey);C(ey<ay,x=10000)C(ay< ey,x=0)C(em<am,x=500*(am-em))C(am<em,x=0)C(ed<ad,x=15*(ad-ed))x=0;O("%i ",x);} Time Conversion Problem Statement You are given time in AM/PM format. Convert this into a 24 hour format. Note 12:00:00AM is 00:00:00 12:00:00PM is 12:00:00 Input Format AM/PM format i.e. hh:mm:ssAM or hh:mm:ssPM with 01<:hh<:12 00<:mm<:59 00<:ss<:59 Output Format 24h format i.e. hh:mm:ss with 00<:hh<:23 00<:mm<:59 00<:ss<:59 Solution (31m, took me a while to find %02i for 00 output format) typedef int I;typedef char C; #include<stdio.h> #define I(e...) scanf(e) #define O(e...) printf(e) main(){I h,m,s;C x;I("%i:%i:%i%cM",&h,&m,&s,&x);O("%02i:%02i:%02i",h+12*((x=='P') -(h==12)),m,s);} Staircase Problem Statement Your teacher has given you the task to draw the structure of a staircase. Being an expert programmer, you decided to make a program for the same. You are given the height of the staircase. You need to print a staircase as shown in the example. Input Format You are given an integer N depicting the height of the staircase. Constraints 1<:N<:100 Output Format Draw a staircase of height N like: # ## ### #### ##### ###### Solution (1h, with X-Files :) ) I looked for an equivalent to a[3]={0} but with '#' for 0. a[100]={'#'} only makes a[1]=='#' so I use J(n,a[j]='#') typedef int I;typedef char C; #define J(n,e...) {I j=0,Mj=(n);for(;j<Mj;++j){e;}} #include<stdio.h> #define I(e...) scanf(e) #define O(e...) printf(e) main(){I n;C a[100];I("%i",&n);J(n,a[j]='#');J(n,O("%*.*s",n,1+j,a))} Plus Minus Problem Statement You're given an array containing integer values. You need to print the fraction of count of positive numbers, negative numbers and zeroes to the total numbers. Print the value of the fractions correct to 3 decimal places. Input Format First line contains N, which is the size of the array. Next line contains N integers A1,A2,A3,...,AN, separated by space. Constraints 1<:N<:100 −100<:A[i]<:100 Output Format Output three values on different lines equal to the fraction of count of positive numbers, negative numbers and zeroes to the total numbers respectively correct to 3 decimal places. Solution (1h, with dinner ;) ) typedef int I; #define J(n,e...) {I j=0,Mj=(n);for(;j<Mj;++j){e;}} #include<stdio.h> #define I(e...) scanf(e) #define O(e...) printf(e) main(){I n,x,a[3]={0};I("%i",&n);J(n,I("%i",&x),++a[(x<=0)+(x==0)];);J(3,O("%. 3f\n",1.0*a[j]/n));} Diagonal Difference Problem Statement You are given a n by n square matrix. Calculate the absolute difference of the sums across the two main diagonals. Input Format The first line contains a single integer N. The next N lines contain N integers (each) describing the matrix. Constraints 1<:N<:100 −100<:A[i]<:100 Output Format Output a single integer equal to the absolute difference in the sums across the diagonals. Solution (29m) typedef int I; #define ABS(a) ({0<(a)?(a):-(a);}) #define J(n,e...) {I j=0,Mj=(n);for(;j<Mj;++j){e;}} #define K(n,e...) {I k=0,Mk=(n);for(;k<Mk;++k){e;}} #include<stdio.h> #define I(e...) scanf(e) #define O(e...) printf(e) main(){I n,x=0;I("%i",&n);I a[n];J(n,K(n,I("%i",&a[k]));x+=a[j]-a[n-j-1]);O("%i",ABS(x));} Find Point Problem Statement Given two points P and Q, output the symmetric point of point P about Q. Input format The first line contains an integer T representing the number of test cases (T <: 15) Each test case contains Px Py Qx Qy representing the (x,y) coordinates of P and Q, all of them being integers. Constraints 1 <: T <: 15 -100 <: x, y <: 100 Output format For each test case output x and y coordinates of the symmetric point (each point in a new line). Solution typedef int I; #define K(n,e...) {I k=0,Mk=(n);for(;k<Mk;++k){e;}} #include<stdio.h> #define I(e...) scanf(e) #define O(e...) printf(e) main(){I n,u,v,x,y;I("%i",&n);K(n,I("%i %i %i %i",&u,&v,&x,&y),O("%i %i\n",2*x-u,2*y-v))} A Very Big Sum Problem Statement You are given an array of integers of size N. You need to print the sum of the elements of the array. Note: The range of the 32-bit integer is (−2)^31 to (2^31)−1 or [−2147483648,2147483647]. When we add several integer values, the resulting sum might exceed this range. You might need to use long long int in C/C++ or long data type in Java to store such sums. Input Format The first line of the input consists of an integer N. The next line contains N space-separated integers describing the array. Constraints 1<:N<:10 0<:A[i]<:10^10 Output Format Output a single value equal to the sum of the elements of the array. Solution typedef int I; typedef long long LL; #define K(n,e...) {I k=0,Mk=(n);for(;k<Mk;++k){e;}} #include<stdio.h> #define I(e...) scanf(e) #define O(e...) printf(e) main(){I n;I("%i",&n);LL x,y=0;K(n,I("%lli ",&x),y+=x);O("%lli",y);} Simple Array Sum Problem Statement You are given an array of integers of size N. You need to print the sum of the elements of the array. Input Format The first line of the input consists of an integer N. The next line contains N space-separated integers describing the array. Constraints 1<:N<:1000 0<:A[i]<:1000 Output Format Output a single value equal to the sum of the elements of the array. Solution typedef int I; #define K(n,e...) {I k=0,Mk=(n);for(;k<Mk;++k){e;}} #include<stdio.h> #define I(e...) scanf(e) #define O(e...) printf(e) main(){I n,x,y=0;I("%d",&n);K(n,I("%d ",&x),y+=x);O("%d",y);} Solve me Second Problem Statement Scan two numbers from STDIN, and print the sum A+B on STDOUT. Input Format The first line contains T (number of test cases) followed by T lines. Each line contains A and B, separated by a space. Output Format An integer that denotes Sum (A+B) printed on new line for every test case. Constraints 1<:T,A,B<:1000 Solution typedef int I; #define K(n,e...) {I k=0,Mk=(n);for(;k<Mk;++k){e;}} #include<stdio.h> #define I(e...) scanf(e) #define O(e...) printf(e) main(){I n,x,y;I("%i",&n);K(n,I("%i %i",&x,&y),O("%i\n",x+y))}