├── sample.py ├── README.md ├── staircase.py ├── print_post_from_in_pre.cpp ├── cavity_map.py ├── jack_and_jill_actual_soln.py ├── popular_characters.py ├── roys_lucky_number.py ├── pangrams.py ├── finddigits.py ├── funny_strings.py ├── chocolate_feast.py ├── sherlock_and_anagrams.py ├── nonoverlapping_palidromic_subsequences.py ├── sherlock_and_beast.py ├── jack_and_jill.py ├── two_strings.py ├── letter_islands.py ├── cut_the_sticks.py ├── love_letter_mystery.py └── cipher.py /sample.py: -------------------------------------------------------------------------------- 1 | a = "123" 2 | if "5" in a: 3 | print "hi" 4 | else: 5 | print "hello" 6 | 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Solutions to Hackerank problems in Python. 2 | 3 | Problem statements are available in corresponding python file 4 | -------------------------------------------------------------------------------- /staircase.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement 3 | 4 | Your teacher has given you the task of drawing a staircase structure. Being an expert programmer, you decided to make a program to draw it for you instead. Given the required height, can you print a staircase as shown in the example? 5 | 6 | Input 7 | You are given an integer N depicting the height of the staircase. 8 | 9 | Output 10 | Print a staircase of height N that consists of # symbols and spaces. For example for N=6, here's a staircase of that height: 11 | 12 | # 13 | ## 14 | ### 15 | #### 16 | ##### 17 | ###### 18 | Note: The last line has 0 spaces before it. 19 | """ 20 | # Complete the function below. 21 | 22 | 23 | def StairCase(n): 24 | for i in range(1,n+1): 25 | stair_array = [] 26 | j = 1 27 | while(j <= n): 28 | if(j <= i): 29 | stair_array.append('#') 30 | else: 31 | stair_array.append(' ') 32 | j = j + 1 33 | 34 | reversed_array = list(reversed(stair_array)) 35 | for element in reversed_array: 36 | print(element), 37 | print 38 | _n = int(raw_input().strip("\n")) 39 | StairCase(_n) 40 | -------------------------------------------------------------------------------- /print_post_from_in_pre.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A utility function to search x in arr[] of size n 5 | int search(int arr[], int x, int n) 6 | { 7 | for (int i = 0; i < n; i++) 8 | if (arr[i] == x) 9 | return i; 10 | return -1; 11 | } 12 | 13 | // Prints postorder traversal from given inorder and preorder traversals 14 | void printPostOrder(int in[], int pre[], int n) 15 | { 16 | // The first element in pre[] is always root, search it 17 | // in in[] to find left and right subtrees 18 | int root = search(in, pre[0], n); 19 | 20 | // If left subtree is not empty, print left subtree 21 | if (root != 0) 22 | printPostOrder(in, pre+1, root); 23 | 24 | // If right subtree is not empty, print right subtree 25 | if (root != n-1) 26 | printPostOrder(in+root+1, pre+root+1, n-root-1); 27 | 28 | // Print root 29 | cout << pre[0] << " "; 30 | } 31 | 32 | // Driver program to test above functions 33 | int main() 34 | { 35 | int in[] = {4, 2, 5, 1, 3, 6}; 36 | int pre[] = {1, 2, 4, 5, 3, 6}; 37 | int n = sizeof(in)/sizeof(in[0]); 38 | cout << "Postorder traversal " << endl; 39 | printPostOrder(in, pre, n); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /cavity_map.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement 3 | 4 | You are given a square map of size n×n. Each cell of the map has a value denoting its depth. We will call a cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent to it has strictly smaller depth. Two cells are adjacent if they have a common side (edge). 5 | 6 | You need to find all the cavities on the map and depict them with the uppercase character X. 7 | 8 | Input Format 9 | 10 | The first line contains an integer, n, denoting the size of the map. Each of the following n lines contains n positive digits without spaces. Each digit (1-9) denotes the depth of the appropriate area. 11 | 12 | Constraints 13 | 1≤n≤100 14 | Output Format 15 | 16 | Output n lines, denoting the resulting map. Each cavity should be replaced with character X. 17 | 18 | Sample Input 19 | 20 | 4 21 | 1112 22 | 1912 23 | 1892 24 | 1234 25 | Sample Output 26 | 27 | 1112 28 | 1X12 29 | 18X2 30 | 1234 31 | Explanation 32 | 33 | The two cells with the depth of 9 fulfill all the conditions of the Cavity definition and have been replaced by X. 34 | 35 | """ 36 | 37 | n = int(raw_input().strip()) 38 | grid = [] 39 | grid_i = 0 40 | for grid_i in xrange(n): 41 | grid_t = str(raw_input().strip()) 42 | grid.append(grid_t) 43 | print grid[3][2] 44 | -------------------------------------------------------------------------------- /jack_and_jill_actual_soln.py: -------------------------------------------------------------------------------- 1 | """ 2 | Jack and Jill are two friends. They both are hungry but they have only a few cakes with them. So they started playing a game to grab those cakes. Initially they have N number of cakes with them. Jack starts the game by making the first move. The game is such that in each turn one has to choose a move from a set of moves which consists of all the possible moves for removing p cakes from the table, where p is any prime and k is any non­negative integer. The winner is the one who takes the last cake. Identify who will win the game, assuming both the players follow a perfect strategy? If Jack wins, what will be the smallest possible number that he can remove in his first move? 3 | Input 4 | An integer T, denoting the number of test cases. 5 | Each test case contains one integer N, the number of chips on the table. 6 | Output 7 | Print "Jack" if Jack wins or "Jill" if Jill wins. Print the output for each test case on a 8 | new line (without quotes). 9 | Constraints 10 | 1 <= T <= 100000 11 | 1 <= N <= 100000 12 | Sample Input : 13 | 3 14 | 1 15 | 5 16 | 6 17 | Sample Output: 18 | Jack 1 19 | Jack 5 20 | Jill 21 | """ 22 | 23 | n = input() 24 | for test in xrange(0,n): 25 | num_cakes = input() 26 | rem = num_cakes % 6 27 | if rem == 0: 28 | print("Jill") 29 | else: 30 | print("Jack "+str(rem)) 31 | -------------------------------------------------------------------------------- /popular_characters.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pǿpųłǻř Čħǻřǻčțěřș (Čǿđıňģ) 3 | Ỳǿų ħǻvě ǻ łıșț ǿf șțřıňģș, ěǻčħ ǿf ẅħıčħ ıș čǿmpǿșěđ ǿf łǿẅěřčǻșě łěțțěřș 4 | fřǿm 'ǻ' țǿ 'ž'. Ǻ "pǿpųłǻř" čħǻřǻčțěř ıș đěfıňěđ țǿ bě ǿňě ẅħıčħ ǻppěǻřș ıň 5 | ǻłł țħě șțřıňģș. 6 | Ģıvěň ǻ łıșț ǿf șțřıňģș, čǿųňț țħě ňųmběř ǿf pǿpųłǻř čħǻřǻčțěřș. 7 | İňpųț Fǿřmǻț 8 | Țħě fıřșț łıňě čǿňșıșțș ǿf Ň, țħě ňųmběř ǿf șțřıňģș. 9 | Țħě ňěxț Ň łıňěș ǻřě țħě Ň șțřıňģș (čǿmpǿșěđ ǿf łǿẅěřčǻșě łěțțěřș fřǿm 'ǻ' 10 | țǿ 'ž'). 11 | Ǿųțpųț Fǿřmǻț 12 | Přıňț țħě ňųmběř ǿf pǿpųłǻř čħǻřǻčțěřș ıň țħě șțřıňģș. İf țħěřě ǻřě ňǿňě, 13 | přıňț 0. 14 | Čǿňșțřǻıňțș 15 | 1 ≤ Ň ≤ 100 16 | Ěǻčħ șțřıňģ čǿňșıșțș ǿf ǿňłỳ șmǻłł łǻțıň łěțțěřș ('ǻ'-'ž'). 17 | 1 ≤ Łěňģțħ ǿf ěǻčħ șțřıňģ ≤ 100 18 | Șǻmpłě İňpųț 19 | 3 20 | abcdde 21 | baccd 22 | eeabg 23 | Șǻmpłě Ǿųțpųț 24 | 2 25 | Ěxpłǻňǻțıǿň 26 | Țħě ǿňłỳ pǿpųłǻř čħǻřǻčțěřș ǻřě 'ǻ' ǻňđ 'b', șıňčě țħěșě ǻřě țħě ǿňłỳ 27 | čħǻřǻčțěřș țħǻț ǻppěǻř ıň ěvěřỳ șțřıňģ. 28 | """ 29 | main_dict = {} 30 | count = 0 31 | if __name__ == '__main__': 32 | n = input() 33 | for i in range(n): 34 | input_string = raw_input() 35 | str_array = set(input_string) 36 | for char in str_array: 37 | if char in main_dict: 38 | main_dict[char] = main_dict[char] + 1 39 | else: 40 | main_dict[char] = 1 41 | for element in main_dict: 42 | if main_dict[element] == int(n): 43 | count = count + 1 44 | if count == 0: 45 | print "No Common characters in the string" 46 | else: 47 | print count 48 | 49 | 50 | -------------------------------------------------------------------------------- /roys_lucky_number.py: -------------------------------------------------------------------------------- 1 | """ 2 | Roy loves to play with numbers and digits. His lucky numbers are 3 and 5 for that 3 | he believes that the numbers containing 3 and 5 are also lucky numbers for him. 4 | For example 335, 355, 533 are lucky but 435, 137 etc. aren’t lucky. Now Roy is 5 | interested in some extra­lucky numbers. 6 | Extra lucky numbers are those which contains 3 and 5 and removing some but not 7 | all digits you can covert that into a lucky number. Like 37455 is extra lucky as you 8 | can convert that to a lucky number by removing 7 and 4. 9 | Now Roy wants to develop an algorithm which will help him to calculate the 10 | number of positive dividers of a given number (n) which are extra lucky. Help him 11 | to develop that algorithm. 12 | Input 13 | Output 14 | Constraints 15 | 1 ≤ T ≤ 10 16 | 1 ≤ n ≤ 10^9 17 | Time Limit : 1 second. 18 | Sample Input : 19 | 10 20 | 1 21 | 2 22 | 3 23 | 4 24 | 5 25 | 6 26 | 7 27 | 8 28 | 9 29 | 10 30 | Sample Output : 31 | 0 32 | 0 33 | 1 34 | 0 35 | 1 36 | 1 37 | 0 38 | 0 39 | 2 40 | 1 41 | """ 42 | def prime_factors(n): 43 | i = 2 44 | factors = [] 45 | while i * i <= n: 46 | if n % i: 47 | i += 1 48 | else: 49 | n //= i 50 | factors.append(i) 51 | if n > 1: 52 | factors.append(n) 53 | return factors 54 | 55 | output_array = [] 56 | test_case = input() 57 | for i in xrange(0,test_case): 58 | n = input() 59 | factors_n = prime_factors(n) 60 | count = 0 61 | for factor in factors_n: 62 | if factor == 3 or factor == 5: 63 | count += 1 64 | output_array.append(count) 65 | for element in output_array: 66 | print element 67 | -------------------------------------------------------------------------------- /pangrams.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement 3 | Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.) 4 | After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams. 5 | Given a sentence s, tell Roy if it is a pangram or not. 6 | Input Format 7 | Input consists of a string s. 8 | Constraints 9 | Length of s can be at most 103 (1≤|s|≤103) and it may contain spaces, lower case and upper case letters. Lower-case and upper-case instances of a letter are considered the same. 10 | Output Format 11 | Output a line containing pangram if s is a pangram, otherwise output not pangram. 12 | Sample Input 13 | Input #1 14 | We promptly judged antique ivory buckles for the next prize 15 | Input #2 16 | We promptly judged antique ivory buckles for the prize 17 | Sample Output 18 | Output #1 19 | pangram 20 | Output #2 21 | not pangram 22 | Explanation 23 | In the first test case, the answer is pangram because the sentence contains all the letters of the English alphabet. 24 | """ 25 | ascii_array = [] 26 | def pangram(string): 27 | lower_string = string.lower() 28 | for i in range(len(lower_string)): 29 | ascii_array.append(ord(lower_string[i])) 30 | for i in range(97, 123): 31 | if i not in ascii_array: 32 | return 'Not Pangram' 33 | return 'Pangram' 34 | 35 | if __name__ == '__main__': 36 | input_string = raw_input() 37 | print pangram(input_string) 38 | 39 | -------------------------------------------------------------------------------- /finddigits.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement 3 | 4 | Given an integer, N, traverse its digits (d1,d2,...,dn) and determine how many digits evenly divide N (i.e.: count the number of times N divided by each digit di has a remainder of 0). Print the number of evenly divisible digits. 5 | 6 | Note: Each digit is considered to be unique, so each occurrence of the same evenly divisible digit should be counted (i.e.: for N=111, the answer is 3). 7 | 8 | Input Format 9 | 10 | The first line is an integer, T, indicating the number of test cases. 11 | The T subsequent lines each contain an integer, N. 12 | 13 | Constraints 14 | 1≤T≤15 15 | 0= m): 52 | new_choc = int(choc/m) 53 | total_choc = total_choc + new_choc 54 | choc = choc - (new_choc)*m + new_choc 55 | result.append(total_choc) 56 | for output in result: 57 | print(int(output)) 58 | 59 | -------------------------------------------------------------------------------- /sherlock_and_anagrams.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement 3 | Given a string S, find the number of "unordered anagrammatic pairs" of substrings. 4 | Input Format 5 | First line contains T, the number of testcases. Each testcase consists of string S in one line. 6 | Constraints 7 | 1≤T≤10 8 | 2≤length(S)≤100 9 | String S contains only the lowercase letters of the English alphabet. 10 | Output Format 11 | For each testcase, print the required answer in one line. 12 | Sample Input 13 | 2 14 | abba 15 | abcd 16 | Sample Output 17 | 4 18 | 0 19 | Explanation 20 | Let's say S[i,j] denotes the substring Si,Si+1,⋯,Sj. 21 | testcase 1: 22 | For S=abba, anagrammatic pairs are: {S[1,1],S[4,4]}, {S[1,2],S[3,4]}, {S[2,2],S[3,3]} and {S[1,3],S[2,4]}. 23 | testcase 2: 24 | No anagrammatic pairs. 25 | """ 26 | def find_sub_string(string): 27 | temp_array = [] 28 | for i in range(0, len(string)): 29 | for j in range(i, len(string)): 30 | temp_array.append(string[i:j+1]) 31 | return temp_array 32 | 33 | def check_for_anagrams(string): 34 | count = 0 35 | substring_array = find_sub_string(string) 36 | sorted_str_array = [] 37 | for substring in substring_array: 38 | sorted_str_array.append(''.join(sorted(substring))) 39 | # sorted_str_array.append(sorted(substring)) 40 | final_sorted = sorted(sorted_str_array) 41 | seen = set() 42 | for i in range(len(final_sorted)): 43 | for j in range(i+1, len(final_sorted)): 44 | if final_sorted[i] == final_sorted[j]: 45 | count = count + 1 46 | 47 | 48 | """ 49 | for n in sorted_str_array: 50 | if n in seen: 51 | print n 52 | count = count + 1 53 | else: 54 | seen.add(n) 55 | print seen 56 | """ 57 | return count 58 | 59 | if __name__ == '__main__': 60 | n = input() 61 | n = int(n) 62 | string_array = [] 63 | for i in range(n): 64 | input_string = raw_input() 65 | string_array.append(input_string) 66 | for i in range(n): 67 | val = check_for_anagrams(string_array[i]) 68 | print val 69 | -------------------------------------------------------------------------------- /nonoverlapping_palidromic_subsequences.py: -------------------------------------------------------------------------------- 1 | """ 2 | A palindrome is a word, phrase, number, or other sequence of characters which 3 | reads the same forward and backwards . For example :"madam" "dad" are 4 | palindromes but "sir", "sad" are not. 5 | You are given a string s. You have to select exactly two non- 6 | overlapping palindromic subsequences A and B from the string to maximize the 7 | fun score. 8 | The fun score, for selecting two subsequences, is the product of their 9 | respective lengths. There can be many ways to choose A and B, but your goal is 10 | to maximize the score. 11 | There can't be any overlap or crossover between the subsequences. 12 | Constraints: 13 | 1 < |s| <= 3000 14 | Only lower­case English characters. 15 | Input Format: 16 | You need to complete a function called funPal which takes a single string s as a 17 | parameter. 18 | Output Format: 19 | Return a single integer denoting the maximum score you can get from s. 20 | Sample Input #00: 21 | acdapmpomp 22 | Sample Output #00: 23 | 15 24 | Explanation #00: 25 | You can select A="aca" and B="pmpmp". The product is 3*5=15. 26 | Sample Input #01: 27 | axbawbaseksqke 28 | Sample Output #01: 29 | 25 30 | Explanation #01: 31 | You can select A="ababa" and B="ekske". The product is 5*5=25. Another 32 | possible solution is A="ababa" and B="ekqke" which also gives 25. 33 | """ 34 | from itertools import combinations 35 | def get_combination(string): 36 | string_array = [] 37 | for y in range(len(string)-1,1,-1): 38 | for x in combinations(string,y): 39 | if ''.join(x)==''.join(x)[::-1]: 40 | string_array.append(''.join(x)) 41 | break 42 | return string_array 43 | def funPal(string): 44 | palindrome_len = [] 45 | for i in range(0, len(string)): 46 | str1_array = [] 47 | str2_array = [] 48 | string1 = string[:i] 49 | string2 = string[i:] 50 | str1_array = get_combination(string1) 51 | str2_array = get_combination(string2) 52 | if str1_array and str2_array: 53 | print str1_array[0], "\t", str2_array[0] 54 | palindrome_len.append(len(str1_array[0]) * len(str2_array[0])) 55 | return max(palindrome_len) 56 | 57 | _s = raw_input() 58 | res = funPal(_s); 59 | print res 60 | 61 | -------------------------------------------------------------------------------- /sherlock_and_beast.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement 3 | Sherlock Holmes suspects his archenemy, Professor Moriarty, is once again plotting something diabolical. Sherlock's companion, Dr. Watson, suggests Moriarty may be responsible for MI6's recent issues with their supercomputer, The Beast. 4 | Shortly after resolving to investigate, Sherlock receives a note from Moriarty boasting about infecting The Beast with a virus; however, he also gives him a clue—a number, N. Sherlock determines the key to removing the virus is to find the largest Decent Number having N digits. 5 | A Decent Number has the following properties: 6 | Its digits can only be 3's and/or 5's. 7 | The number of 3's it contains is divisible by 5. 8 | The number of 5's it contains is divisible by 3. 9 | Moriarty's virus shows a clock counting down to The Beast's destruction, and time is running out fast. Your task is to help Sherlock find the key before The Beast is destroyed! 10 | Constraints 11 | 1≤T≤20 12 | 1≤N≤100000 13 | Input Format 14 | The first line is an integer, T, denoting the number of test cases. 15 | The T subsequent lines each contain an integer, N, detailing the number of digits in the number. 16 | Output Format 17 | Print the largest Decent Number having N digits; if no such number exists, tell Sherlock by printing -1. 18 | Sample Input 19 | 4 20 | 1 21 | 3 22 | 5 23 | 11 24 | Sample Output 25 | -1 26 | 555 27 | 33333 28 | 55555533333 29 | Explanation 30 | 31 | For N=1, there is no such number. 32 | For N=3, 555 is the only possible number. 33 | For N=5, 33333 is the only possible number. 34 | For N=11, 55555533333 and all permutations of these digits are valid numbers; among them, the given number is the largest one. 35 | """ 36 | T = int(input()) 37 | for i in range(T): 38 | k = int(input()) 39 | n5 = k 40 | n3 = 0 41 | done = False 42 | while n5 >= 0: 43 | if n5%3 == 0 and n3%5 == 0: 44 | for j in range(n5): 45 | print('5',end='') 46 | for j in range(n3): 47 | print('3',end='') 48 | print() 49 | done = True 50 | break 51 | n5 -= 1 52 | n3 += 1 53 | if not done: 54 | print(-1) 55 | -------------------------------------------------------------------------------- /jack_and_jill.py: -------------------------------------------------------------------------------- 1 | """ 2 | Jack and Jill are two friends. They both are hungry but they have only a few cakes with them. So they started playing a game to grab those cakes. Initially they have N number of cakes with them. Jack starts the game by making the first move. The game is such that in each turn one has to choose a move from a set of moves which consists of all the possible moves for removing p cakes from the table, where p is any prime and k is any non­negative integer. The winner is the one who takes the last cake. Identify who will win the game, assuming both the players follow a perfect strategy? If Jack wins, what will be the smallest possible number that he can remove in his first move? 3 | Input 4 | An integer T, denoting the number of test cases. 5 | Each test case contains one integer N, the number of chips on the table. 6 | Output 7 | Print "Jack" if Jack wins or "Jill" if Jill wins. Print the output for each test case on a 8 | new line (without quotes). 9 | Constraints 10 | 1 <= T <= 100000 11 | 1 <= N <= 100000 12 | Sample Input : 13 | 3 14 | 1 15 | 5 16 | 6 17 | Sample Output: 18 | Jack 1 19 | Jack 5 20 | Jill 21 | """ 22 | def get_prime(n): 23 | prime_nos = [] 24 | for x in range(2,n+1): 25 | prime = True 26 | for i in range(2,x): 27 | if (x%i==0): 28 | prime = False 29 | if prime == True: 30 | prime_nos.append(x) 31 | return get_moves(prime_nos, n) 32 | 33 | def get_moves(prime_nos, n): 34 | moves_array = [] 35 | for no in prime_nos: 36 | i = 0 37 | while True: 38 | if (no ** i <= n): 39 | moves_array.append(no ** i) 40 | i = i+1 41 | else: 42 | break 43 | return list(set(moves_array)) 44 | 45 | def get_small_move(moves, n): 46 | print moves 47 | if n == 0: 48 | return 0 49 | for move in moves: 50 | if (n-move) not in moves: 51 | small_move = move 52 | return small_move 53 | else: 54 | get_small_move(moves, n-move) 55 | return 0 56 | 57 | 58 | 59 | 60 | if __name__ == '__main__': 61 | n = raw_input() 62 | n = int(n) 63 | moves = [] 64 | moves = get_prime(n) 65 | if n == 1: 66 | small_move = 1 67 | else: 68 | small_move = 0 69 | small_move = get_small_move(moves, n) 70 | if small_move == 0 and n != 1: 71 | print "Jill" 72 | else: 73 | print "Jack ", small_move 74 | 75 | -------------------------------------------------------------------------------- /two_strings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement 3 | You are given two strings, A and B. Find if there is a substring that appears in both A and B. 4 | Input Format 5 | Several test cases will be given to you in a single file. The first line of the input will contain a single integer T, the number of test cases 6 | Then there will be T descriptions of the test cases. Each description contains two lines. The first line contains the string A and the second line contains the string B. 7 | Output Format 8 | For each test case, display YES (in a newline), if there is a common substring. Otherwise, display NO. 9 | Constraints 10 | All the strings contain only lowercase Latin letters. 11 | 1<=T<=10 12 | 1<=|A|,|B|<=105 13 | Sample Input 14 | 2 15 | hello 16 | world 17 | hi 18 | world 19 | Sample Output 20 | YES 21 | NO 22 | Explanation 23 | For the 1st test case, the letter o is common between both strings, hence the answer YES. (Furthermore, the letter l is also common, but you only need to find one common substring.) 24 | For the 2nd test case, hi and world do not have a common substring, hence the answer NO. 25 | """ 26 | def common_start(sa, sb): 27 | """ returns the longest common substring from the beginning of sa and sb """ 28 | def _iter(): 29 | for a, b in zip(sa, sb): 30 | if a == b: 31 | yield a 32 | else: 33 | return 34 | 35 | return ''.join(_iter()) 36 | 37 | 38 | def find_sub_string(string): 39 | temp_array = [] 40 | for i in range(0, len(string)): 41 | for j in range(i, len(string)): 42 | temp_array.append(string[i:j+1]) 43 | return set(temp_array) 44 | 45 | def check_for_substrings(string1, string2): 46 | for character in string1: 47 | if character in string2: 48 | return True 49 | return False 50 | 51 | if __name__ == '__main__': 52 | n = input() 53 | n = int(n)*2 54 | string_array = [] 55 | for i in range(n): 56 | input_string = input() 57 | string_array.append(input_string) 58 | for i in range(0, n, 2): 59 | val = check_for_substrings(string_array[i], string_array[i+1]) 60 | if val == True: 61 | print "YES" 62 | else: 63 | print "NO" 64 | 65 | 66 | """ 67 | t = input() 68 | assert t<=10 and t>=1 69 | for _ in range(t): 70 | s = list(raw_input()) 71 | assert len(s) >=1 and len(s)<= 10000 72 | su = 0 73 | for i in range(0,len(s)/2): 74 | su+= abs(ord(s[i]) - ord(s[-1-i])) 75 | print su 76 | 77 | 78 | 79 | """ 80 | -------------------------------------------------------------------------------- /letter_islands.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given string s and number k. 3 | Consider a substring p of string s. For each position of string s mark it if there is an occurence of the substring that covers the position. More formally, position i will be marked if there exists such index j that: j≤i≤j+|p|−1 and sjsj+1…sj+|p|−1=p. We will tell p produce x islands if all the marked positions form x groups of contiguous positions. 4 | For example, if we have a string ababaewabaq the substring aba marks the positions 1, 2, 3, 4, 5, 8, 9, 10; that is XXXXXewXXXq (X denotes marked position). We can see 2 groups of contiguous positions, that is 2 islands. Finally, substring aba produces 2 islands in the string ababaewabaq. 5 | Your task is to calculate the number of different substrings of string s, that produces exactly k islands in it. 6 | Input Format 7 | The first line contains string s (1≤|s|≤105). The string consists of lowercase letters only. The second line contains an integer k (1≤k≤|s|). 8 | Output Format 9 | Output a single integer − the answer to the problem. 10 | Sample Input 11 | abaab 12 | 2 13 | Sample Output 14 | 3 15 | Explanation 16 | All the suitable substrings are: a, ab, b. 17 | """ 18 | def find_sub_string(string): 19 | temp_array = [] 20 | for i in range(0, len(string)): 21 | for j in range(i, len(string)): 22 | temp_array.append(string[i:j+1]) 23 | return set(temp_array) 24 | 25 | 26 | def find_island(string, substring, k): 27 | island_dict = {} 28 | island_count = 0 29 | for element in substring: 30 | mystring = string 31 | mystring = mystring.replace(element, "x") 32 | island_dict[element] = find_contiguous_position(mystring) 33 | print element, "\t", mystring, "\t", find_contiguous_position(mystring) 34 | for key in island_dict: 35 | if island_dict[key] == k: 36 | island_count = island_count + 1 37 | print island_count 38 | 39 | def find_contiguous_position(string): 40 | count = 0 41 | for i in range(0, len(string)): 42 | if (string[i] == 'x' and (i == len(string)-1 or string[i+1] != 'x')): 43 | count = count + 1 44 | return count 45 | 46 | if __name__ == '__main__': 47 | substring = [] 48 | input_string = input() 49 | k = input() 50 | substring = find_sub_string(input_string) 51 | find_island(input_string, substring, k) 52 | 53 | -------------------------------------------------------------------------------- /cut_the_sticks.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement 3 | 4 | You are given N sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick. 5 | 6 | Suppose we have six sticks of the following lengths: 7 | 5 4 4 2 2 8 8 | 9 | Then, in one cut operation we make a cut of length 2 from each of the six sticks. For the next cut operation four sticks are left (of non-zero length), whose lengths are the following: 10 | 3 2 2 6 11 | 12 | The above step is repeated until no sticks are left. 13 | 14 | Given the length of N sticks, print the number of sticks that are left before each subsequent cut operations. 15 | 16 | Note: For each cut operation, you have to recalcuate the length of smallest sticks (excluding zero-length sticks). 17 | 18 | Input Format 19 | The first line contains a single integer N. 20 | The next line contains N integers: a0, a1,...aN-1 separated by space, where ai represents the length of ith stick. 21 | 22 | Output Format 23 | For each operation, print the number of sticks that are cut, on separate lines. 24 | 25 | Constraints 26 | 1 ≤ N ≤ 1000 27 | 1 ≤ ai ≤ 1000 28 | 29 | Sample Input #00 30 | 31 | 6 32 | 5 4 4 2 2 8 33 | Sample Output #00 34 | 35 | 6 36 | 4 37 | 2 38 | 1 39 | Sample Input #01 40 | 41 | 8 42 | 1 2 3 4 3 3 2 1 43 | Sample Output #01 44 | 45 | 8 46 | 6 47 | 4 48 | 1 49 | Explanation 50 | 51 | Sample Case #00 : 52 | 53 | sticks-length length-of-cut sticks-cut 54 | 5 4 4 2 2 8 2 6 55 | 3 2 2 _ _ 6 2 4 56 | 1 _ _ _ _ 4 1 2 57 | _ _ _ _ _ 3 3 1 58 | _ _ _ _ _ _ DONE DONE 59 | Sample Case #01 60 | 61 | sticks-length length-of-cut sticks-cut 62 | 1 2 3 4 3 3 2 1 1 8 63 | _ 1 2 3 2 2 1 _ 1 6 64 | _ _ 1 2 1 1 _ _ 1 4 65 | _ _ _ 1 _ _ _ _ 1 1 66 | _ _ _ _ _ _ _ _ DONE DONE 67 | """ 68 | def cut_sticks(sticks): 69 | count = 0 70 | if sticks: 71 | small_stick = min(sticks) 72 | else: 73 | return 74 | new_sticks = [] 75 | for element in sticks: 76 | count = count + 1 77 | new_element = element - small_stick 78 | if new_element != 0: 79 | new_sticks.append(new_element) 80 | print count 81 | cut_sticks(new_sticks) 82 | 83 | if __name__ == '__main__': 84 | n = int(input()) 85 | string = raw_input() 86 | str_array = string.split(' ') 87 | sticks = map(lambda x: int(x), str_array) 88 | cut_sticks(sticks) 89 | -------------------------------------------------------------------------------- /love_letter_mystery.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement 3 | James found a love letter his friend Harry has written for his girlfriend. James is a prankster, so he decides to meddle with the letter. He changes all the words in the letter into palindromes. 4 | To do this, he follows two rules: 5 | He can reduce the value of a letter, e.g. he can change d to c, but he cannot change c to d. 6 | In order to form a palindrome, if he has to repeatedly reduce the value of a letter, he can do it until the letter becomes a. Once a letter has been changed to a, it can no longer be changed. 7 | Each reduction in the value of any letter is counted as a single operation. Find the minimum number of operations required to convert a given string into a palindrome. 8 | Input Format 9 | The first line contains an integer T, i.e., the number of test cases. 10 | The next T lines will contain a string each. The strings do not contain any spaces. 11 | Constraints 12 | 1≤T≤10 13 | 1≤ length of string ≤104 14 | All characters are lower case English letters. 15 | Output Format 16 | A single line containing the number of minimum operations corresponding to each test case. 17 | Sample Input 18 | 4 19 | abc 20 | abcba 21 | abcd 22 | cba 23 | Sample Output 24 | 2 25 | 0 26 | 4 27 | 2 28 | Explanation 29 | For the first test case, abc -> abb -> aba. 30 | For the second test case, abcba is already a palindromic string. 31 | For the third test case, abcd -> abcc -> abcb -> abca = abca -> abba. 32 | For the fourth test case, cba -> bba -> aba 33 | """ 34 | count = 0 35 | def checkpalindrome(string, index, ascii_char): 36 | #abcd 37 | print "index: ", index, " asciichar: ", chr(ascii_char) 38 | global count 39 | original_string = string 40 | reversed_string = string[::-1] 41 | if reversed_string == string: 42 | return 43 | else: 44 | if(original_string[index] == chr(ascii_char) and index > len(original_string)/2): 45 | checkpalindrome(original_string, index-1, ascii_char+1) 46 | else: 47 | print "else part" 48 | original_string[index] = chr(ord(original_string[index]) - 1) 49 | print original_string[index] 50 | count = count + 1 51 | checkpalindrome(original_string, index, ascii_char) 52 | 53 | 54 | 55 | if __name__ == '__main__': 56 | n = input() 57 | string_array = [] 58 | for i in range(n): 59 | input_string = raw_input() 60 | string_array.append(input_string) 61 | for string in string_array: 62 | print string 63 | checkpalindrome(list(string), len(string)-1, 97) 64 | print count 65 | count = 0 66 | -------------------------------------------------------------------------------- /cipher.py: -------------------------------------------------------------------------------- 1 | """ 2 | Alice has taken up cryptography course. She recently learnt the interesting topic 3 | 4 | of transposition ciphers. In transposition ciphers, the cipher is keyed by a word or 5 | 6 | phrase not containing any repeated letters. The purpose of the key is to order the 7 | 8 | columns, with column 1 being under the lexicographically smallest key letter and 9 | 10 | so on. The plaintext is written horizontally, in rows, padded to fill the matrix if need 11 | 12 | be(with abcdef....). The ciphertext* is read out by columns, starting with the 13 | 14 | column whose key letter is the lowest. Help her convert 15 | 16 | Note: Lexicographical ordering is same as the roman alphabetical ordering i.e. A 17 | 18 | is smallest and B is greater than A and Z is the greatest. 19 | 20 | Input format: 21 | 22 | First line contains the key, a single word with all uppercase alphabets without any 23 | 24 | white spaces in between. 25 | 26 | Second line contains an integer N 27 | 28 | N lines follow, each containing a single plaintext, a word with all uppercase 29 | 30 | alphabets without any white spaces in between. 31 | 32 | Output format: 33 | 34 | Output is N lines each containing the ciphertext for the corresponding plaintext, 35 | 36 | with all uppercase roman alphabets. 37 | 38 | Constraints: 39 | 40 | 1<=N<=1000 41 | 42 | 1<=Key length<=10 43 | 44 | 1<=Plaintext length<=1000 45 | 46 | Sample Input 47 | 48 | DELHI 49 | 50 | 1 51 | 52 | thankyouforyourcooperation 53 | 54 | https://www.hackerrank.com/tests/eoihki03k1o/questions/fn23ecjcs87 1/3 55 | 56 | 1/3/2016 VISA Coding Challenge 2015-2016 :: powered by HackerRank 57 | 58 | Sample Output 59 | 60 | TYRCRNHOYOAANFUPICKOREODAUOOTB 61 | 62 | Explanation 63 | 64 | key: DELHI 65 | 66 | Plaintext: thankyouforyourcooperation 67 | 68 | 1 2 5 3 4 69 | 70 | t h a n k 71 | 72 | y o u f o 73 | 74 | r y o u r 75 | 76 | c o o p e 77 | 78 | r a t i o 79 | 80 | n a b c d ­> last row is having only 1 character, so we pad it with abcd. 81 | 82 | As you read the columns vertically, based on the key, you will arrive at the 83 | 84 | ciphertext: TYRCRNHOYOAANFUPICKOREOD 85 | 86 | """ 87 | 88 | 89 | def encode(txt,key): 90 | sz = len(key) # how big are the columns 91 | cols = list(map("".join,zip(*zip(*[iter(txt)]*sz)))) # list partitioned into columns 92 | return "".join([cols[key.index(str(c))] for c in range(1,sz+1)]) 93 | 94 | 95 | if __name__ == '__main__': 96 | key = raw_input() 97 | n = raw_input() 98 | output_array = [] 99 | sorted_key = sorted(key) 100 | final_key = [] 101 | for char in key: 102 | final_key.append(str(sorted_key.index(char) + 1)) 103 | key_string = ''.join(final_key) 104 | padding_text = "abcdefghijklmnopqrstuvwxyz" 105 | for i in range(int(n)): 106 | plain_text = raw_input() 107 | pad_no = len(plain_text)%len(key_string) 108 | if pad_no != 0: 109 | pad_length = len(key_string) - pad_no 110 | plain_text = plain_text + padding_text[:pad_length] 111 | encoded = encode(plain_text,key_string) 112 | output_array.append(encoded) 113 | for output in output_array: 114 | print output.upper() 115 | --------------------------------------------------------------------------------