├── README.md └── solutions ├── 001_Say_Hello_World_With_Python.md ├── 002_Python_If_Else.md ├── 003_Arithmetic_Operators.md ├── 004_Division.md ├── 005_Loops.md ├── 006_Write_a_function.md ├── 007_Print_Function.md ├── 008_List_Comprehensions.md ├── 009_Find_the_Runner_Up_Score.md ├── 010_Nested_Lists.md ├── 011_Finding_The_Percentage.md ├── 012_Lists.md ├── 013_Tuples.md ├── 014_sWAP_cASE.md ├── 015_String_Split_and_Join.md ├── 016_What_s_Your_Name.md ├── 017_Mutations.md ├── 018_Find_a_string.md ├── 019_String_Validators.md ├── 020_Text_Alignment.md ├── 021_Text_Wrap.md ├── 022_Designer_Door_Mat.md ├── 022_String_Formatting.md ├── 023_Alphabet_Rangoli.md ├── 024_Capitalize.md ├── 025_The_Minion_Game.md ├── 027_Merge_the_Tools.md ├── 030_collections_Counter.md ├── 031_itertools_permutations.md ├── 034_DefaultDict_Tutorial.md ├── 037_Collections_namedtuple.md ├── 041_Collections_OrderedDict.md ├── 047_Word_Order.md ├── 049_Collections_deque.md ├── 051_Company_Logo.md ├── 1_1_Sock_Merchant.md ├── 1_2_Counting_Valleys.md ├── 1_3_Jumping_on_the_Clouds.md ├── 1_4_Repeated_String.md ├── 1_appsmart_Python_Dictionary.md ├── 2_1_2D_Array_DS.md ├── 2_2_Arrays_Left_Rotation.md ├── 2_3_New_Year_Chaos.md ├── 2_4_Minimum_Swaps_2.md ├── 2_Pycode2015_Dictionary_Assignment.md ├── 3_1_Hash_Tables_Ransom_Note.md ├── 3_2_Two_Strings.md ├── 3_3_Sherlock_and_Anagrams.md ├── 3_4_Count_Triplets.md ├── 3_5_Frequency_Queries.md ├── Day_0-Hello_World.md ├── Day_10_Binary_Numbers.md ├── Day_11_2D_Arrays.md ├── Day_12_Inheritance.md ├── Day_13_Abstract_Classes.md ├── Day_14-Scope.md ├── Day_15_Linked_List.md ├── Day_16_Exceptions_String_to_Integer.md ├── Day_17_More_Exceptions.md ├── Day_18_Queues_and_Stacks.md ├── Day_19_Interfaces.md ├── Day_1_Data_Types.md ├── Day_20_Sorting.md ├── Day_22_Binary_Search_Trees.md ├── Day_23_BST_Level_Order_Traversal.md ├── Day_24_More_Linked_Lists.md ├── Day_25_Running_Time_and_Complexity.md ├── Day_26_Nested_Logic.md ├── Day_27_Testing.md ├── Day_28_RegEx_Patterns_and_Intro_to_Databases.md ├── Day_29_Bitwise_AND.md ├── Day_2_Operators.md ├── Day_3_Intro_to_Conditional_Statements.md ├── Day_4_Class_vs_Instance.md ├── Day_5_Loops.md ├── Day_6_Lets_Review.md ├── Day_7_Arrays.md ├── Day_8_Dictionaries_and_Maps.md ├── Day_9_Recursion_3.md └── badges.png /solutions/001_Say_Hello_World_With_Python.md: -------------------------------------------------------------------------------- 1 | # 001 - Say "Hello, World!" With Python 2 | ## Problem 3 | 4 | Here is a sample line of code that can be executed in Python: 5 | 6 | ```python 7 | print("Hello, World!") 8 | ``` 9 | 10 | You can just as easily store a string as a variable and then print it to stdout: 11 | 12 | ```python 13 | my_string = "Hello, World!" 14 | print(my_string) 15 | ``` 16 | 17 | The above code will print `Hello, World!` on your screen. 18 | 19 | ***Input Format*** 20 | 21 | You do not need to read any input in this challenge. 22 | 23 | ***Output Format*** 24 | 25 | Print `Hello, World!` to stdout. 26 | 27 | ***Sample Output 0*** 28 | 29 | ``` 30 | Hello, World! 31 | ``` 32 | 33 | --- 34 | 35 | ## Solution 36 | ```python 37 | print("Hello, World!") 38 | ``` 39 | -------------------------------------------------------------------------------- /solutions/002_Python_If_Else.md: -------------------------------------------------------------------------------- 1 | # 002 - Python If-Else 2 | ## Problem 3 | 4 | Given an integer, `n`, perform the following conditional actions: 5 | 6 | - If `n` is odd, print `Weird` 7 | - If `n` is even and in the inclusive range of 2 to 5, print `Not Weird` 8 | - If `n` is even and in the inclusive range of 6 to 20, print `Weird` 9 | - If `n` is even and greater than 20, print `Not Weird` 10 | 11 | #### Input Format 12 | A single line containing a positive integer, `n`. 13 | 14 | #### Constraints 15 | 1 <= n <= 100 16 | 17 | #### Output Format 18 | Print `Weird` if the number is weird; otherwise, print `Not Weird`. 19 | 20 | ``` 21 | Sample Inputs 22 | 3 23 | 24 24 | ``` 25 | 26 | ``` 27 | Sample Output 28 | Weird 29 | Not Weird 30 | ``` 31 | 32 | #### Given Code 33 | 34 | ```python 35 | if __name__ == '__main__': 36 | n = int(input().strip()) 37 | ``` 38 | 39 | ## Solution 1 40 | 41 | ```python 42 | def weirdo(num): 43 | if num % 2 != 0: 44 | return "Weird" 45 | else: 46 | if 2 <= num <= 5: 47 | return "Not Weird" 48 | elif 6 <= num <= 20: 49 | return "Weird" 50 | elif num > 20: 51 | return "Not Weird" 52 | 53 | 54 | if __name__ == '__main__': 55 | n = int(input().strip()) 56 | ``` 57 | 58 | 59 | 60 | ## Solution 2 61 | 62 | ```python 63 | def odd(num): 64 | if num % 2 != 0: 65 | return "Weird" 66 | else: 67 | return even(num) 68 | 69 | def even(num): 70 | if 2 <= num <= 5: 71 | return "Not Weird" 72 | elif 6 <= num <= 20: 73 | return "Weird" 74 | elif num > 20: 75 | return "Not Weird" 76 | 77 | N = int(input()) 78 | print(odd(N)) 79 | ``` 80 | -------------------------------------------------------------------------------- /solutions/003_Arithmetic_Operators.md: -------------------------------------------------------------------------------- 1 | # 003 - Arithmetic Operators 2 | ## Task 3 | 4 | Read two integers from STDIN and print three lines where: 5 | 6 | 1. The first line contains the sum of the two numbers. 7 | 2. The second line contains the difference of the two numbers (first - second). 8 | 3. The third line contains the product of the two numbers. 9 | 10 | #### Input Format 11 | The first line contains the first integer, `a` . The second line contains the second integer,`b` . 12 | 13 | #### Constraints 14 | * 1 <= a <= 1010 15 | 16 | * 1 <= b <= 1010 17 | 18 | #### Output Format 19 | Print the three lines as explained above. 20 | 21 | ``` 22 | Sample Inputs 23 | 3 24 | 2 25 | ``` 26 | 27 | ``` 28 | Sample Output 29 | 5 30 | 1 31 | 6 32 | ``` 33 | 34 | #### Explanation 35 | 36 | 3 + 2 => 5 37 | 3 - 2 => 1 38 | 3 * 2 => 6 39 | 40 | 41 | #### Given Code 42 | 43 | ```python 44 | if __name__ == '__main__': 45 | a = int(input()) 46 | b = int(input()) 47 | ``` 48 | 49 | ## Solution 1 50 | 51 | ```python 52 | if __name__ == '__main__': 53 | a = int(input()) 54 | b = int(input()) 55 | 56 | print(a + b) 57 | print(a - b) 58 | print(a * b) 59 | ``` 60 | 61 | ## Solution 2 62 | 63 | ```python 64 | if __name__ == '__main__': 65 | a = int(input()) 66 | b = int(input()) 67 | 68 | def add_two(x,y): 69 | return x + y 70 | 71 | def ext_two(x,y): 72 | return x - y 73 | 74 | def mul_two(x,y): 75 | return x * y 76 | 77 | print(add_two(a,b)) 78 | print(ext_two(a,b)) 79 | print(mul_two(a,b)) 80 | ``` 81 | -------------------------------------------------------------------------------- /solutions/004_Division.md: -------------------------------------------------------------------------------- 1 | # 004 - Division 2 | ## Task 3 | Read two integers and print two lines. The first line should contain integer division, `a` // `b` . The second line should contain float division, `a`/`b` . 4 | 5 | You don't need to perform any rounding or formatting operations. 6 | 7 | #### Input Format 8 | 9 | The first line contains the first integer, `a`. The second line contains the second integer, `b`. 10 | 11 | 12 | #### Output Format 13 | 14 | Print the two lines as described above. 15 | 16 | ``` 17 | Sample Input : 18 | 4 19 | 3 20 | ``` 21 | 22 | ``` 23 | Sample Output : 24 | 1 25 | 1.33333333333 26 | ``` 27 | 28 | #### Given Code 29 | 30 | ```python 31 | if __name__ == '__main__': 32 | a = int(input()) 33 | b = int(input()) 34 | ``` 35 | 36 | ## Solution 1 37 | 38 | ```python 39 | if __name__ == '__main__': 40 | a = int(input()) 41 | b = int(input()) 42 | 43 | print(int(a / b)) 44 | print(float(a / b)) 45 | ``` 46 | 47 | ## Solution 2 48 | 49 | ```python 50 | if __name__ == '__main__': 51 | a = int(input()) 52 | b = int(input()) 53 | 54 | def division_int(x,y): 55 | return x // y 56 | 57 | def division_flt(x,y): 58 | return x / y 59 | 60 | print(division_int(a,b)) 61 | print(division_flt(a,b)) 62 | ``` 63 | -------------------------------------------------------------------------------- /solutions/005_Loops.md: -------------------------------------------------------------------------------- 1 | # 005 - Loops 2 | ## Task 3 | Read an integer `N`. For all non-negative integers `i < N`, print **i2**. See the sample for details. 4 | 5 | #### Input Format 6 | 7 | The first and only line contains the integer, `N`. 8 | 9 | #### Constraints 10 | 1 <= N <= 20 11 | 12 | #### Output Format 13 | 14 | Print `N` lines, one corresponding to each `i`. 15 | 16 | ``` 17 | Sample Input : 18 | 5 19 | ``` 20 | 21 | ``` 22 | Sample Output : 23 | 0 24 | 1 25 | 4 26 | 9 27 | 16 28 | ``` 29 | 30 | #### Given Code 31 | 32 | ```python 33 | if __name__ == '__main__': 34 | n = int(input()) 35 | ``` 36 | 37 | 38 | ## Solution 1 39 | 40 | ```python 41 | if __name__ == '__main__': 42 | n = int(input()) 43 | 44 | for i in range(n): 45 | print(i**2) 46 | ``` 47 | 48 | 49 | ## Solution 2 50 | 51 | ```python 52 | if __name__ == '__main__': 53 | n = int(input()) 54 | i = 0 55 | while i < n: 56 | r = i * i 57 | i = i + 1 58 | print(r) 59 | ``` 60 | -------------------------------------------------------------------------------- /solutions/006_Write_a_function.md: -------------------------------------------------------------------------------- 1 | # 006 - Write a function 2 | ## Task 3 | We add a Leap Day on February 29, almost every four years. The leap day is an extra, or intercalary day and we add it to the shortest month of the year, February. 4 | 5 | In the Gregorian calendar three criteria must be taken into account to identify leap years: 6 | * The year can be evenly divided by 4, is a leap year, unless: 7 | * The year can be evenly divided by 100, it is NOT a leap year, unless: 8 | * The year is also evenly divisible by 400. Then it is a leap year. 9 | 10 | This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. 11 | 12 | You are given the year, and you have to write a function to check if the year is leap or not. 13 | 14 | Note that you have to complete the function and remaining code is given as template. 15 | 16 | #### Input Format 17 | 18 | Read y, the year that needs to be checked. 19 | 20 | #### Constraints 21 | 1900 <= y <= 105 22 | 23 | #### Output Format 24 | 25 | Output is taken care of by the template. Your function must return a boolean value (True/False) 26 | 27 | ``` 28 | Sample Input : 29 | 1990 30 | ``` 31 | 32 | ``` 33 | Sample Output : 34 | False 35 | ``` 36 | 37 | #### Explanation 38 | 1990 is not a multiple of 4 hence it's not a leap year. 39 | 40 | #### Given Code 41 | 42 | ```python 43 | def is_leap(year): 44 | leap = False 45 | 46 | # Write your logic here 47 | 48 | return leap 49 | 50 | year = int(input()) 51 | print(is_leap(year)) 52 | ``` 53 | 54 | ## Solution 1 55 | 56 | ```python 57 | def is_leap(year): 58 | return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) 59 | 60 | year = int(input()) 61 | print(is_leap(year)) 62 | ``` 63 | 64 | ## Solution 2 65 | 66 | ```python 67 | def is_leap(year): 68 | leap = False 69 | 70 | # Write your logic here 71 | if year % 4 == 0: 72 | if year % 100 == 0 : 73 | if year % 400 == 0: 74 | leap = True 75 | else: 76 | leap = False 77 | else: 78 | leap = True 79 | else : 80 | leap = False 81 | return leap 82 | 83 | year = int(input()) 84 | print(is_leap(year)) 85 | ``` 86 | -------------------------------------------------------------------------------- /solutions/007_Print_Function.md: -------------------------------------------------------------------------------- 1 | # 007 - Print Function 2 | ## Task 3 | Read an integer `N` . 4 | 5 | Without using any string methods, try to print the following: 6 | `123...N` 7 | 8 | Note that "..." represents the values in between. 9 | 10 | #### Input Format 11 | 12 | The first line contains an integer `N`. 13 | 14 | 15 | #### Output Format 16 | 17 | Output the answer as explained in the task. 18 | 19 | ``` 20 | Sample Input : 21 | 3 22 | ``` 23 | 24 | ``` 25 | Sample Output : 26 | 123 27 | ``` 28 | 29 | 30 | #### Given Code 31 | 32 | ```python 33 | if __name__ == '__main__': 34 | n = int(input()) 35 | ``` 36 | 37 | ---- 38 | 39 | ## Solution 1 40 | 41 | ```python 42 | if __name__ == '__main__': 43 | n = int(input()) 44 | print(*range(1, n + 1), sep="") 45 | ``` 46 | 47 | 48 | ## Solution 2 49 | 50 | ```python 51 | if __name__ == '__main__': 52 | n = int(input()) 53 | print("".join([str(x) for x in range(1,n+1)])) 54 | ``` 55 | 56 | 57 | ## Solution 3 58 | 59 | ```python 60 | if __name__ == '__main__': 61 | n = int(input()) 62 | lst = [x for x in range(1,n+1)] 63 | print(*lst, sep="") 64 | ``` 65 | 66 | 67 | ## Solution 4 68 | 69 | ```python 70 | if __name__ == '__main__': 71 | n = int(input()) 72 | lst = "" 73 | for num in range(1, n+1): 74 | lst += str(num) 75 | print(lst) 76 | ``` 77 | 78 | ## Solution 5 79 | 80 | ```python 81 | if __name__ == '__main__': 82 | n = int(input()) 83 | lst = [] 84 | for num in range(1, n+1): 85 | lst.append(str(num)) 86 | print("".join(lst)) 87 | ``` 88 | -------------------------------------------------------------------------------- /solutions/008_List_Comprehensions.md: -------------------------------------------------------------------------------- 1 | # 008 - List Comprehensions 2 | ## Problem 3 | You are given three integers `X`, `Y` and `Z` representing the dimensions of a cuboid along with an integer `N`. You have to print a list of all possible coordinates given by `(i,j,k)` on a 3D grid where the sum of `i + j + k` is not equal to `N`. Here, `0 <= i <= X; 0 <= j <= Y; 0 <= k <= Z` 4 | 5 | 6 | #### Input Format 7 | 8 | Four integers `X`, `Y`, `X` and `Y` each on four separate lines, respectively. 9 | 10 | 11 | #### Constraints 12 | Print the list in lexicographic increasing order. 13 | 14 | #### Output Format 15 | 16 | Output the answer as explained in the task. 17 | 18 | ``` 19 | Sample Input : 20 | 1 21 | 1 22 | 1 23 | 2 24 | ``` 25 | 26 | ``` 27 | Sample Output : 28 | [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]] 29 | ``` 30 | 31 | #### Explanation 32 | ***Concept*** : You have already used lists in previous hacks. List comprehensions are an elegant way to build a list without having to use different for loops to append values one by one. This example might help. 33 | 34 | ***Example*** : You are given two integers x and y . You need to find out the ordered pairs ( i , j ) , such that ( i + j ) is not equal to n and print them in lexicographic order.( 0 <= i <= x ) and ( 0 <= j <= y) This is the code if we dont use list comprehensions in Python. 35 | 36 | ```python 37 | x = int ( raw_input()) 38 | y = int ( raw_input()) 39 | n = int ( raw_input()) 40 | ar = [] 41 | p = 0 42 | 43 | for i in range ( x + 1 ) : 44 | for j in range( y + 1): 45 | if i+j != n: 46 | ar.append([]) 47 | ar[p] = [ i , j ] 48 | p+=1 49 | print(ar) 50 | ``` 51 | 52 | Other smaller codes may also exist, but using list comprehensions is always a good option. Code using list comprehensions: 53 | 54 | ```python 55 | x = int ( raw_input()) 56 | y = int ( raw_input()) 57 | n = int ( raw_input()) 58 | print [ [ i, j] for i in range( x + 1) for j in range( y + 1) if ( ( i + j ) != n )] 59 | ``` 60 | 61 | ``` 62 | Sample Input : 63 | 2 64 | 2 65 | 2 66 | 2 67 | ``` 68 | 69 | ``` 70 | Sample Output : 71 | [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 2], [0, 2, 1], [0, 2, 2], [1, 0, 0], [1, 0, 2], [1, 1, 1], [1, 1, 2], [1, 2, 0], [1, 2, 1], [1, 2, 2], [2, 0, 1], [2, 0, 2], [2, 1, 0], [2, 1, 1], [2, 1, 2], [2, 2, 0], [2, 2, 1], [2, 2, 2]] 72 | ``` 73 | 74 | 75 | #### Given Code 76 | 77 | ```python 78 | if __name__ == '__main__': 79 | x = int(input()) 80 | y = int(input()) 81 | z = int(input()) 82 | n = int(input()) 83 | ``` 84 | 85 | ## Solution 1 86 | 87 | ```python 88 | if __name__ == '__main__': 89 | x = int(input()) 90 | y = int(input()) 91 | z = int(input()) 92 | n = int(input()) 93 | 94 | nums = [[i, j, k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if (i+j+k) != n] 95 | print(nums) 96 | ``` 97 | 98 | 99 | ## Solution 2 100 | 101 | ```python 102 | if __name__ == '__main__': 103 | x = int(input()) 104 | y = int(input()) 105 | z = int(input()) 106 | n = int(input()) 107 | 108 | ar = [] 109 | p = 0 110 | 111 | for i in range ( x + 1 ) : 112 | for j in range( y + 1): 113 | for k in range( z + 1): 114 | if i+j+k != n: 115 | ar.append([]) 116 | ar[p] = [ i , j, k ] 117 | p+=1 118 | print(ar) 119 | ``` 120 | -------------------------------------------------------------------------------- /solutions/009_Find_the_Runner_Up_Score.md: -------------------------------------------------------------------------------- 1 | # 009 - Find the Runner-Up Score 2 | ## Problem 3 | 4 | Given the participants' score sheet for your University Sports Day, you are required to find the runner-up `n` score. You are given scores. Store them in a list and find the score of the runner-up. 5 | 6 | 7 | #### Input Format 8 | 9 | The first line contains `n`. The second line contains an array `A[]` of `n` integers each separated by a space. 10 | 11 | 12 | #### Constraints 13 | 2 <= n <= 10 14 | -100 <= A[i] <= 100 15 | 16 | #### Output Format 17 | 18 | Print the runner-up score. 19 | 20 | ``` 21 | Sample Input : 22 | 5 23 | 2 3 6 6 5 24 | ``` 25 | 26 | ``` 27 | Sample Output : 28 | 5 29 | ``` 30 | 31 | #### Explanation 32 | Given list is `[2,3,6,6,5]`. The maximum score is 6, second maximum is 5. Hence, we print 5 as the runner-up score. 33 | 34 | 35 | #### Given Code 36 | 37 | ```python 38 | if __name__ == '__main__': 39 | n = int(input()) 40 | arr = map(int, input().split()) 41 | ``` 42 | 43 | 44 | ## Solution 1 45 | 46 | ```python 47 | if __name__ == '__main__': 48 | n = int(input()) 49 | arr = map(int, input().split()) 50 | 51 | print(sorted(set(arr), reverse=True)[1]) 52 | ``` 53 | 54 | 55 | ## Solution 2 56 | 57 | ```python 58 | if __name__ == '__main__': 59 | n = int(input()) 60 | arr = list(map(int, input().split())) 61 | mx = max(arr) 62 | sc = None 63 | 64 | for num in arr: 65 | if num == mx: 66 | pass 67 | elif sc == None: 68 | sc = num 69 | elif num > sc: 70 | sc = num 71 | 72 | print(sc) 73 | ``` 74 | 75 | 76 | 77 | ## Solution 3 78 | 79 | ```python 80 | if __name__ == '__main__': 81 | n = int(input()) 82 | arr = map(int, input().split()) 83 | 84 | lst = list(arr) 85 | scores = list() 86 | 87 | for score in lst: 88 | if score not in scores: 89 | scores.append(score) 90 | else : 91 | continue 92 | ordr = sorted(scores, reverse=True) 93 | print(ordr[1]) 94 | ``` 95 | 96 | 97 | 98 | ## Solution 4 99 | 100 | ``` 101 | def remove_n(list, n): 102 | new_arr = [num for num in list if num != n] 103 | return new_arr 104 | 105 | arr = list(arr) 106 | new_arr = remove_n(arr, max(arr)) 107 | print(max(new_arr)) 108 | ``` 109 | -------------------------------------------------------------------------------- /solutions/010_Nested_Lists.md: -------------------------------------------------------------------------------- 1 | # 010 - Nested Lists 2 | ## Problem 3 | Given the names and grades for each student in a Physics class of `N` students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. 4 | 5 | **Note**: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. 6 | 7 | #### Input Format 8 | 9 | The first line contains an integer, `N`, the number of students. 10 | 11 | The `2N` subsequent lines describe each student over `N` lines; the first line contains a student's name, and the second line contains their grade. 12 | 13 | 14 | #### Constraints 15 | 2 <= N <= 5 16 | 17 | There will always be one or more students having the second lowest grade. 18 | 19 | #### Output Format 20 | 21 | Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line. 22 | 23 | ``` 24 | Sample Input : 25 | 5 26 | Harry 27 | 37.21 28 | Berry 29 | 37.21 30 | Tina 31 | 37.2 32 | Akriti 33 | 41 34 | Harsh 35 | 39 36 | ``` 37 | 38 | ``` 39 | Sample Output : 40 | Berry 41 | Harry 42 | ``` 43 | 44 | #### Explanation 45 | There are 5 students in this class whose names and grades are assembled to build the following list: 46 | 47 | `python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]` 48 | 49 | The lowest grade of 37.2 belongs to Tina. The second lowest grade of 37.21 belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line. 50 | 51 | 52 | #### Given Code 53 | 54 | ```python 55 | if __name__ == '__main__': 56 | for _ in range(int(input())): 57 | name = input() 58 | score = float(input()) 59 | ``` 60 | 61 | 62 | ## Solution 63 | 64 | ```python 65 | if __name__ == '__main__': 66 | students = [] 67 | for _ in range(int(input())): 68 | name = input() 69 | score = float(input()) 70 | students.append([name, score]) 71 | mn = min(students, key=lambda x: x[1]) 72 | nonlowest = sorted([student for student in students if student[1] > mn[1]], key= lambda x: x[1]) 73 | seconds = sorted([student[0] for student in nonlowest if student[1] == nonlowest[0][1]]) 74 | for student in seconds: 75 | print(student) 76 | ``` 77 | -------------------------------------------------------------------------------- /solutions/011_Finding_The_Percentage.md: -------------------------------------------------------------------------------- 1 | # 011 - Finding The Percentage 2 | ## Problem 3 | 4 | You have a record of `N` students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry. The marks can be floating values. The user enters some integer `N` followed by the names and marks for `N` students. You are required to save the record in a dictionary data type. The user then enters a student's name. Output the average percentage marks obtained by that student, correct to two decimal places. 5 | 6 | #### Input Format 7 | 8 | The first line contains the integer `N`, the number of students. The next `N` lines contains the name and marks obtained by that student separated by a space. The final line contains the name of a particular student previously listed. 9 | 10 | 11 | 12 | #### Constraints 13 | 14 | 2 <= `N` <= 10 15 | 0 <= `Marks` <= 100 16 | 17 | 18 | 19 | #### Output Format 20 | 21 | Print one line : The average of the marks obtained by the particular student correct to 2 decimal places. 22 | 23 | **Sample Input 0** 24 | 25 | ``` 26 | 3 27 | Krishna 67 68 69 28 | Arjun 70 98 63 29 | Malika 52 56 60 30 | Malika 31 | ``` 32 | 33 | **Sample Output 0** 34 | 35 | ``` 36 | 56.00 37 | ``` 38 | 39 | **Explanation 0** 40 | 41 | Marks for Malika are `{52,56,60}` whose average is (52+56+60)/3 = 56 42 | 43 |
44 | 45 | 46 | **Sample Input 1** 47 | 48 | ``` 49 | 2 50 | Harsh 25 26.5 28 51 | Anurag 26 28 30 52 | Harsh 53 | ``` 54 | 55 | **Sample Output 1** 56 | 57 | ``` 58 | 26.50 59 | ``` 60 | 61 |
62 | 63 | 64 | #### Given Code 65 | 66 | ```python 67 | if __name__ == '__main__': 68 | n = int(input()) 69 | student_marks = {} 70 | for _ in range(n): 71 | name, *line = input().split() 72 | scores = list(map(float, line)) 73 | student_marks[name] = scores 74 | query_name = input() 75 | ``` 76 | 77 | ## Solution 1 78 | 79 | ```python 80 | if __name__ == '__main__': 81 | n = int(input()) 82 | student_marks = {} 83 | for _ in range(n): 84 | name, *line = input().split() 85 | scores = list(map(float, line)) 86 | student_marks[name] = scores 87 | query_name = input() 88 | 89 | def find_percentage(name): 90 | return f"{sum(student_marks[name]) / len(student_marks[name]):.2f}" 91 | 92 | print(find_percentage(query_name)) 93 | ``` 94 | 95 | ## Solution 2 96 | 97 | ```python 98 | from functools import reduce 99 | 100 | if __name__ == '__main__': 101 | n = int(input()) 102 | student_marks = {} 103 | for _ in range(n): 104 | name, *line = input().split() 105 | scores = list(map(float, line)) 106 | student_marks[name] = scores 107 | query_name = input() 108 | 109 | marks = student_marks[query_name] 110 | sum_marks = reduce(lambda x, y: x + y, marks, 0) 111 | avg_marks = sum_marks/len(marks) 112 | print("{:.2f}".format(avg_marks)) 113 | ``` 114 | -------------------------------------------------------------------------------- /solutions/012_Lists.md: -------------------------------------------------------------------------------- 1 | # 012 - Lists 2 | ## Problem 3 | 4 | Consider a list (`list = []`). You can perform the following commands: 5 | 6 | 1. `insert i e` : Insert integer `e` at position `i` 7 | 2. `print` : Print the list 8 | 3. `remove e` : Delete the first occurrence of integer `e` 9 | 4. `append e` : Insert integer `e` at the end of the list 10 | 5. `sort` : Sort the list 11 | 6. `pop` : Pop the last element from the list 12 | 7. `reverse` : Reverse the list 13 | 14 | Initialize your list and read in the value of `n` followed by `n` lines of commands where each command will be of the `7` types listed above. Iterate through each command in order and perform the corresponding operation on your list. 15 | 16 | 17 | #### Input Format 18 | 19 | The first line contains an integer, `n`, denoting the number of commands. 20 | 21 | Each line `i` of the `n` subsequent lines contains one of the commands described above. 22 | 23 | 24 | #### Constraints 25 | 26 | The elements added to the list must be integers 27 | 28 | 29 | #### Output Format 30 | 31 | For each command of type `print`, print the list on a new line. 32 | 33 | 34 | **Sample Input 0** 35 | 36 | ``` 37 | 12 38 | insert 0 5 39 | insert 1 10 40 | insert 0 6 41 | print 42 | remove 6 43 | append 9 44 | append 1 45 | sort 46 | print 47 | pop 48 | reverse 49 | print 50 | ``` 51 | 52 | **Sample Output 0** 53 | 54 | ``` 55 | [6, 5, 10] 56 | [1, 5, 9, 10] 57 | [9, 5, 1] 58 | ``` 59 | 60 | 61 |
62 | 63 | 64 | #### Given Code 65 | 66 | ```python 67 | if __name__ == '__main__': 68 | N = int(input()) 69 | ``` 70 | 71 | ## Solution 72 | 73 | ```python 74 | if __name__ == '__main__': 75 | N = int(input()) 76 | the_list = list() 77 | 78 | for _ in range(N): 79 | query = input().split() 80 | if query[0] == "print": 81 | print(the_list) 82 | elif query[0] == "insert": 83 | the_list.insert(int(query[1]), int(query[2])) 84 | elif query[0] == "remove": 85 | the_list.remove(int(query[1])) 86 | elif query[0] == "append": 87 | the_list.append(int(query[1])) 88 | elif query[0] == "sort": 89 | the_list = sorted(the_list) 90 | elif query[0] == "pop": 91 | the_list.pop() 92 | elif query[0] == "reverse": 93 | the_list.reverse() 94 | ``` 95 | -------------------------------------------------------------------------------- /solutions/013_Tuples.md: -------------------------------------------------------------------------------- 1 | # 013 - Tuples 2 | ## Problem 3 | 4 | ### Task 5 | 6 | Given an integer, `n`, and `n` space-separated integers as input, create a tuple, `t`, of those `n` integers. Then compute and print the result of `hash(t)`. 7 | 8 | **Note**: `hash()` is one of the functions in the `__builtins__` module, so it need not be imported. 9 | 10 | 11 | ### Input Format 12 | 13 | The first line contains as integer, `n`, denoting the number of elements in the tuple. 14 | 15 | The second line contains `n` space-separated integers describing the elements in tuple `t`. 16 | 17 | 18 | ### Output Format 19 | 20 | Print the result of `hash(t)`. 21 | 22 | 23 | **Sample Input 0** 24 | 25 | ``` 26 | 2 27 | 1 2 28 | ``` 29 | 30 | **Sample Output 0** 31 | 32 | ``` 33 | 3713081631934410656 34 | ``` 35 | 36 | 37 |
38 | 39 | 40 | ### Given Code 41 | 42 | ```python 43 | if __name__ == '__main__': 44 | n = int(input()) 45 | integer_list = map(int, input().split()) 46 | ``` 47 | 48 | ## Solution 49 | 50 | ```python 51 | if __name__ == '__main__': 52 | n = int(input()) 53 | integer_list = map(int, input().split()) 54 | print(hash(tuple(integer_list))) 55 | ``` 56 | -------------------------------------------------------------------------------- /solutions/014_sWAP_cASE.md: -------------------------------------------------------------------------------- 1 | # 014 - sWAP cASE 2 | ## Problem 3 | 4 | You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. 5 | 6 | **For Example** 7 | 8 | ``` 9 | Www.HackerRank.com → wWW.hACKERrANK.COM 10 | Pythonist 2 → pYTHONIST 2 11 | ``` 12 | 13 | 14 | ### Input Format 15 | 16 | A single line containing a string `S`. 17 | 18 | 19 | ### Constraints 20 | 21 | 0 < `len(S)` <= 1000 22 | 23 | 24 | ### Output Format 25 | 26 | Print the modified string `S`. 27 | 28 | 29 | **Sample Input 0** 30 | 31 | ``` 32 | HackerRank.com presents "Pythonist 2". 33 | ``` 34 | 35 | **Sample Output 0** 36 | 37 | ``` 38 | hACKERrANK.COM PRESENTS "pYTHONIST 2". 39 | ``` 40 | 41 | 42 |
43 | 44 | 45 | ### Given Code 46 | 47 | ```python 48 | def swap_case(s): 49 | return 50 | 51 | if __name__ == '__main__': 52 | s = input() 53 | result = swap_case(s) 54 | print(result) 55 | ``` 56 | 57 | 58 | ## Solution 1 59 | 60 | ```python 61 | def swap_case(s): 62 | return s.swapcase() 63 | 64 | if __name__ == '__main__': 65 | s = input() 66 | result = swap_case(s) 67 | print(result) 68 | ``` 69 | 70 | 71 | ## Solution 2 72 | 73 | ```python 74 | def swap_case(s): 75 | swapped = "" 76 | 77 | for c in s: 78 | if c.islower(): 79 | swapped = swapped + c.upper() 80 | elif c.isupper(): 81 | swapped = swapped + c.lower() 82 | else: 83 | swapped = swapped + c 84 | 85 | return swapped 86 | 87 | if __name__ == '__main__': 88 | s = input() 89 | result = swap_case(s) 90 | print(result) 91 | ``` 92 | -------------------------------------------------------------------------------- /solutions/015_String_Split_and_Join.md: -------------------------------------------------------------------------------- 1 | # 015 - String Split and Join 2 | ## Problem 3 | 4 | In Python, a string can be split on a delimiter. 5 | 6 | **Example** 7 | 8 | ```python 9 | >>> a = "this is a string" 10 | >>> a = a.split(" ") # a is converted to a list of strings. 11 | >>> print a 12 | ['this', 'is', 'a', 'string'] 13 | ``` 14 | 15 | Joining a string is simple : 16 | 17 | ```python 18 | >>> a = "-".join(a) 19 | >>> print a 20 | this-is-a-string 21 | ``` 22 | 23 | 24 | ### Task 25 | 26 | You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen. 27 | 28 | ### Input Format 29 | 30 | The first line contains a string consisting of space separated words. 31 | 32 | ### Output Format 33 | 34 | Print the formatted string as explained above. 35 | 36 | 37 | **Sample Input** 38 | 39 | ``` 40 | this is a string 41 | ``` 42 | 43 | **Sample Output** 44 | 45 | ``` 46 | this-is-a-string 47 | ``` 48 | 49 | 50 |
51 | 52 | 53 | ### Given Code 54 | 55 | ```python 56 | def split_and_join(line): 57 | # write your code here 58 | 59 | if __name__ == '__main__': 60 | line = input() 61 | result = split_and_join(line) 62 | print(result) 63 | ``` 64 | 65 | 66 | ## Solution 67 | 68 | ```python 69 | def split_and_join(line): 70 | return "-".join(line.split()) 71 | 72 | if __name__ == '__main__': 73 | line = input() 74 | result = split_and_join(line) 75 | print(result) 76 | ``` 77 | -------------------------------------------------------------------------------- /solutions/016_What_s_Your_Name.md: -------------------------------------------------------------------------------- 1 | # 016 - What's Your Name? 2 | ## Problem 3 | 4 | 5 | You are given the firstname and lastname of a person on two different lines. Your task is to read them and print the following: 6 | 7 | 8 | ```python 9 | Hello firstname lastname! You just delved into python. 10 | ``` 11 | 12 | ### Input Format 13 | 14 | The first line contains the first name, and the second line contains the last name. 15 | 16 | 17 | ### Constraints 18 | 19 | The length of the first and last name <= 10. 20 | 21 | 22 | ### Output Format 23 | 24 | Print the output as mentioned above. 25 | 26 |
27 | 28 | **Sample Input** 29 | 30 | ``` 31 | Ross 32 | Taylor 33 | ``` 34 | 35 |
36 | 37 | **Sample Output** 38 | 39 | ``` 40 | Hello Ross Taylor! You just delved into python. 41 | ``` 42 | 43 |
44 | 45 | **Explanation** 46 | 47 | The input read by the program is stored as a string data type. A string is a collection of characters. 48 | 49 | 50 |
51 | 52 | 53 | ### Given Code 54 | 55 | ```python 56 | def print_full_name(a, b): 57 | print("") 58 | 59 | if __name__ == '__main__': 60 | first_name = input() 61 | last_name = input() 62 | print_full_name(first_name, last_name) 63 | ``` 64 | 65 | 66 | ## Solution 67 | 68 | ```python 69 | def print_full_name(a, b): 70 | print(f"Hello {a} {b}! You just delved into python.") 71 | 72 | if __name__ == '__main__': 73 | first_name = input() 74 | last_name = input() 75 | print_full_name(first_name, last_name) 76 | ``` 77 | -------------------------------------------------------------------------------- /solutions/017_Mutations.md: -------------------------------------------------------------------------------- 1 | # 017 - Mutations 2 | ## Problem 3 | 4 | We have seen that lists are mutable (they can be changed), and tuples are immutable (they cannot be changed). 5 | 6 | Let's try to understand this with an example. 7 | 8 | You are given an immutable string, and you want to make changes to it. 9 | 10 | **Example** 11 | 12 | ``` 13 | >>> string = "abracadabra" 14 | ``` 15 | 16 | You can access an index by: 17 | 18 | ``` 19 | >>> print(string[5]) 20 | a 21 | ``` 22 | 23 | What if you would like to assign a value? 24 | 25 | ``` 26 | >>> string[5] = 'k' 27 | Traceback (most recent call last): 28 | File "", line 1, in 29 | TypeError: 'str' object does not support item assignment 30 | ``` 31 | 32 | How would you approach this? 33 | 34 | * One solution is to convert the string to a list and then change the value. 35 | 36 | **Example** 37 | 38 | ``` 39 | >>> string = "abracadabra" 40 | >>> l = list(string) 41 | >>> l[5] = 'k' 42 | >>> string = ''.join(l) 43 | >>> print string 44 | abrackdabra 45 | ``` 46 | 47 | * Another approach is to slice the string and join it back. 48 | 49 | 50 | **Example** 51 | 52 | ``` 53 | >>> string = string[:5] + "k" + string[6:] 54 | >>> print string 55 | abrackdabra 56 | ``` 57 | 58 | 59 | ### Task 60 | 61 | Read a given string, change the character at a given index and then print the modified string. 62 | 63 | 64 | ### Input Format 65 | 66 | The first line contains a string, `S`. 67 | 68 | The next line contains an integer `i`, denoting the index location and a character `c` separated by a space. 69 | 70 | 71 | ### Output Format 72 | 73 | Using any of the methods explained above, replace the character at index `i` with character `c`. 74 | 75 |
76 | 77 | **Sample Input** 78 | 79 | ``` 80 | abracadabra 81 | 5 k 82 | ``` 83 | 84 |
85 | 86 | **Sample Output** 87 | 88 | ``` 89 | abrackdabra 90 | ``` 91 | 92 |
93 | 94 | 95 | ### Given Code 96 | 97 | ```python 98 | def mutate_string(string, position, character): 99 | return 100 | 101 | if __name__ == '__main__': 102 | s = input() 103 | i, c = input().split() 104 | s_new = mutate_string(s, int(i), c) 105 | print(s_new) 106 | ``` 107 | 108 | 109 | ## Solution 110 | 111 | ```python 112 | def mutate_string(string, position, character): 113 | return "".join([character if e == position else c for e,c in enumerate(string)]) 114 | 115 | if __name__ == '__main__': 116 | s = input() 117 | i, c = input().split() 118 | s_new = mutate_string(s, int(i), c) 119 | print(s_new) 120 | ``` 121 | -------------------------------------------------------------------------------- /solutions/018_Find_a_string.md: -------------------------------------------------------------------------------- 1 | # 018 - Find a string 2 | 3 | ## Problem 4 | 5 | In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left. 6 | 7 | **NOTE**: String letters are case-sensitive. 8 | 9 | 10 | ### Input Format 11 | 12 | The first line of input contains the original string. The next line contains the substring. 13 | 14 | ### Constraints 15 | 16 | 1 <= `len(string)` <= 200 17 | 18 | Each character in the string is an ascii character. 19 | 20 | 21 | ### Output Format 22 | 23 | Output the integer number indicating the total number of occurrences of the substring in the original string. 24 | 25 |
26 | 27 | **Sample Input** 28 | 29 | ``` 30 | ABCDCDC 31 | CDC 32 | ``` 33 | 34 |
35 | 36 | **Sample Output** 37 | 38 | ``` 39 | 2 40 | ``` 41 | 42 | 43 | 44 | ### Concept 45 | 46 | Some string processing examples, [such as these](http://www.thelearningpoint.net/computer-science/learning-python-programming-and-data-structures/learning-python-programming-and-data-structures--tutorial-12--string-manipulation), might be useful. 47 | 48 | There are a couple of new concepts: 49 | 50 | In Python, the length of a string is found by the function `len(s)`, where `s` is the string. 51 | 52 | To traverse through the length of a string, use a for loop: 53 | 54 | ```python 55 | for i in range(0, len(s)): 56 | print (s[i]) 57 | ``` 58 | 59 | A range function is used to loop over some length: 60 | 61 | ```python 62 | range (0, 5) 63 | ``` 64 | 65 | Here, the range loops over `0` to `4`. `5` is excluded. 66 | 67 | 68 |
69 | 70 | 71 | ### Given Code 72 | 73 | ```python 74 | def count_substring(string, sub_string): 75 | return 76 | 77 | if __name__ == '__main__': 78 | string = input().strip() 79 | sub_string = input().strip() 80 | 81 | count = count_substring(string, sub_string) 82 | print(count) 83 | ``` 84 | 85 | 86 | ## Solution 87 | 88 | ```python 89 | def count_substring(string, sub_string): 90 | counter = 0 91 | for i,c in enumerate(string): 92 | if i + len(sub_string) > len(string): 93 | break 94 | if string[i:i+len(sub_string)] == sub_string: 95 | counter += 1 96 | return counter 97 | 98 | 99 | if __name__ == '__main__': 100 | string = input().strip() 101 | sub_string = input().strip() 102 | 103 | count = count_substring(string, sub_string) 104 | print(count) 105 | ``` 106 | -------------------------------------------------------------------------------- /solutions/019_String_Validators.md: -------------------------------------------------------------------------------- 1 | # 019 - String Validators 2 | 3 | ## Problem 4 | 5 | Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc. 6 | 7 |
8 | 9 | `str.isalnum()` 10 | 11 | This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9). 12 | 13 | ``` 14 | >>> print 'ab123'.isalnum() 15 | True 16 | >>> print 'ab123#'.isalnum() 17 | False 18 | ``` 19 | 20 | 21 |
22 | 23 | `str.isalpha()` 24 | 25 | This method checks if all the characters of a string are alphabetical (a-z and A-Z). 26 | 27 | 28 | ``` 29 | >>> print 'abcD'.isalpha() 30 | True 31 | >>> print 'abcd1'.isalpha() 32 | False 33 | ``` 34 | 35 | 36 |
37 | 38 | `str.isdigit()` 39 | 40 | This method checks if all the characters of a string are digits (0-9). 41 | 42 | 43 | ``` 44 | >>> print '1234'.isdigit() 45 | True 46 | >>> print '123edsd'.isdigit() 47 | False 48 | ``` 49 | 50 | 51 |
52 | 53 | `str.islower()` 54 | 55 | This method checks if all the characters of a string are lowercase characters (a-z). 56 | 57 | ``` 58 | >>> print 'abcd123#'.islower() 59 | True 60 | >>> print 'Abcd123#'.islower() 61 | False 62 | ``` 63 | 64 | 65 |
66 | 67 | `str.isupper()` 68 | 69 | This method checks if all the characters of a string are uppercase characters (A-Z). 70 | 71 | ``` 72 | >>> print 'ABCD123#'.isupper() 73 | True 74 | >>> print 'Abcd123#'.isupper() 75 | False 76 | ``` 77 | 78 |
79 | 80 | ### Task 81 | 82 | You are given a string `S`. 83 | 84 | Your task is to find out if the string `S` contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters. 85 | 86 | 87 | ### Input Format 88 | 89 | A single line containing a string `S`. 90 | 91 | 92 | ### Constraints 93 | 94 | 0 < `len(S)` < 1000 95 | 96 | 97 | 98 | ### Output Format 99 | 100 | In the first line, print `True` if `S` has any alphanumeric characters. Otherwise, print `False`. 101 | In the second line, print `True` if `S` has any alphabetical characters. Otherwise, print `False`. 102 | In the third line, print `True` if `S` has any digits. Otherwise, print `False`. 103 | In the fourth line, print `True` if `S` has any lowercase characters. Otherwise, print `False`. 104 | In the fifth line, print `True` if `S` has any uppercase characters. Otherwise, print `False`. 105 | 106 |
107 | 108 | **Sample Input** 109 | 110 | ``` 111 | qA2 112 | ``` 113 | 114 |
115 | 116 | **Sample Output** 117 | 118 | ``` 119 | True 120 | True 121 | True 122 | True 123 | True 124 | ``` 125 | 126 | 127 | 128 |
129 | 130 | 131 | ### Given Code 132 | 133 | ```python 134 | if __name__ == '__main__': 135 | s = input() 136 | ``` 137 | 138 | 139 | ## Solution 140 | 141 | ```python 142 | if __name__ == '__main__': 143 | def validator(s): 144 | alnum, alpha, digits, lower, upper = False, False, False, False, False 145 | 146 | for c in s: 147 | if c.isalnum(): 148 | alnum = True 149 | if c.isalpha(): 150 | alpha = True 151 | if c.isdigit(): 152 | digits = True 153 | if c.islower(): 154 | lower = True 155 | if c.isupper(): 156 | upper = True 157 | 158 | print(alnum) 159 | print(alpha) 160 | print(digits) 161 | print(lower) 162 | print(upper) 163 | 164 | 165 | s = input() 166 | validator(s) 167 | ``` 168 | -------------------------------------------------------------------------------- /solutions/020_Text_Alignment.md: -------------------------------------------------------------------------------- 1 | # 020 - Text Alignment 2 | 3 | ## Problem 4 | 5 | In Python, a string of text can be aligned left, right and center. 6 | 7 |
8 | 9 | `.ljust(width)` 10 | 11 | This method returns a left aligned string of length width. 12 | 13 | ``` 14 | >>> width = 20 15 | >>> print 'HackerRank'.ljust(width,'-') 16 | HackerRank---------- 17 | ``` 18 | 19 | 20 |
21 | 22 | `.center(width)` 23 | 24 | This method returns a centered string of length width. 25 | 26 | 27 | ``` 28 | >>> width = 20 29 | >>> print 'HackerRank'.center(width,'-') 30 | -----HackerRank----- 31 | ``` 32 | 33 | 34 |
35 | 36 | `.rjust(width)` 37 | 38 | This method checks if all the characters of a string are digits (0-9). 39 | 40 | 41 | ``` 42 | >>> width = 20 43 | >>> print 'HackerRank'.rjust(width,'-') 44 | ----------HackerRank 45 | ``` 46 | 47 | 48 |
49 | 50 | ### Task 51 | 52 | You are given a partial code that is used for generating the HackerRank Logo of variable thickness. 53 | 54 | Your task is to replace the blank (`______`) with `rjust`, `ljust` or `center`. 55 | 56 | 57 | ### Input Format 58 | 59 | A single line containing the thickness value for the logo. 60 | 61 | 62 | ### Constraints 63 | 64 | The thickness must be an odd number. 65 | 66 | 0 < `thickness` < 50 67 | 68 | 69 | 70 | ### Output Format 71 | 72 | Output the desired logo. 73 | 74 |
75 | 76 | **Sample Input** 77 | 78 | ``` 79 | 5 80 | ``` 81 | 82 |
83 | 84 | **Sample Output** 85 | 86 | ``` 87 | H 88 | HHH 89 | HHHHH 90 | HHHHHHH 91 | HHHHHHHHH 92 | HHHHH HHHHH 93 | HHHHH HHHHH 94 | HHHHH HHHHH 95 | HHHHH HHHHH 96 | HHHHH HHHHH 97 | HHHHH HHHHH 98 | HHHHHHHHHHHHHHHHHHHHHHHHH 99 | HHHHHHHHHHHHHHHHHHHHHHHHH 100 | HHHHHHHHHHHHHHHHHHHHHHHHH 101 | HHHHH HHHHH 102 | HHHHH HHHHH 103 | HHHHH HHHHH 104 | HHHHH HHHHH 105 | HHHHH HHHHH 106 | HHHHH HHHHH 107 | HHHHHHHHH 108 | HHHHHHH 109 | HHHHH 110 | HHH 111 | H 112 | ``` 113 | 114 | 115 | 116 |
117 | 118 | 119 | ### Given Code 120 | 121 | ```python 122 | #Replace all ______ with rjust, ljust or center. 123 | 124 | thickness = int(input()) #This must be an odd number 125 | c = 'H' 126 | 127 | #Top Cone 128 | for i in range(thickness): 129 | print((c*i).______(thickness-1)+c+(c*i).______(thickness-1)) 130 | 131 | #Top Pillars 132 | for i in range(thickness+1): 133 | print((c*thickness).______(thickness*2)+(c*thickness).______(thickness*6)) 134 | 135 | #Middle Belt 136 | for i in range((thickness+1)//2): 137 | print((c*thickness*5).______(thickness*6)) 138 | 139 | #Bottom Pillars 140 | for i in range(thickness+1): 141 | print((c*thickness).______(thickness*2)+(c*thickness).______(thickness*6)) 142 | 143 | #Bottom Cone 144 | for i in range(thickness): 145 | print(((c*(thickness-i-1)).______(thickness)+c+(c*(thickness-i-1)).______(thickness)).______(thickness*6)) 146 | ``` 147 | 148 | 149 | ## Solution 150 | 151 | ```python 152 | #Replace all ______ with rjust, ljust or center. 153 | 154 | thickness = int(input()) #This must be an odd number 155 | c = 'H' 156 | 157 | # Top Cone 158 | for i in range(thickness): 159 | print((c * i).rjust(thickness - 1) + c + (c * i).ljust(thickness - 1)) 160 | 161 | # Top Pillars 162 | for i in range(thickness + 1): 163 | print((c * thickness).center(thickness * 2) + (c * thickness).center(thickness * 6)) 164 | 165 | # Middle Belt 166 | for i in range((thickness + 1) // 2): 167 | print((c * thickness * 5).center(thickness * 6)) 168 | 169 | # Bottom Pillars 170 | for i in range(thickness + 1): 171 | print((c * thickness).center(thickness * 2) + (c * thickness).center(thickness * 6)) 172 | 173 | # Bottom Cone 174 | for i in range(thickness): 175 | print(((c * (thickness - i - 1)).rjust(thickness) + c + (c * (thickness - i - 1)).ljust(thickness)).rjust(thickness * 6)) 176 | ``` 177 | -------------------------------------------------------------------------------- /solutions/021_Text_Wrap.md: -------------------------------------------------------------------------------- 1 | # 021 - Text Wrap 2 | 3 | ## Task 4 | 5 | You are given a string `S` and width `w`. 6 | 7 | Your task is to wrap the string into a paragraph of width `w`. 8 | 9 |
10 | 11 | ### Input Format 12 | 13 | The first line contains a string, `S`. 14 | 15 | The second line contains the width, `w`. 16 | 17 | 18 | ### Constraints 19 | 20 | 21 | 0 < `len(S)` < 1000
22 | 0 < `w` < `len(S)` 23 | 24 | 25 | 26 | ### Output Format 27 | 28 | Print the text wrapped paragraph. 29 | 30 |
31 | 32 | **Sample Input** 33 | 34 | ``` 35 | ABCDEFGHIJKLIMNOQRSTUVWXYZ 36 | 4 37 | ``` 38 | 39 |
40 | 41 | **Sample Output** 42 | 43 | ``` 44 | ABCD 45 | EFGH 46 | IJKL 47 | IMNO 48 | QRST 49 | UVWX 50 | YZ 51 | ``` 52 | 53 | 54 | 55 |
56 | 57 | 58 | ### Given Code 59 | 60 | ```python 61 | import textwrap 62 | 63 | def wrap(string, max_width): 64 | return 65 | 66 | if __name__ == '__main__': 67 | string, max_width = input(), int(input()) 68 | result = wrap(string, max_width) 69 | print(result) 70 | ``` 71 | 72 | 73 | ## Solution 74 | 75 | ```python 76 | import textwrap 77 | 78 | def wrap(string, max_width): 79 | return "\n".join([string[i:i+max_width] for i in range(0, len(string), max_width)]) 80 | 81 | if __name__ == '__main__': 82 | string, max_width = input(), int(input()) 83 | result = wrap(string, max_width) 84 | print(result) 85 | ``` 86 | -------------------------------------------------------------------------------- /solutions/022_Designer_Door_Mat.md: -------------------------------------------------------------------------------- 1 | # 022 - Designer Door Mat 2 | 3 | ## Problem 4 | 5 | Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications. 6 | 7 | * Mat size must be `N` x `M`. (`N` is an odd natural number, and `M` is times `N`.) 8 | * The design should have "WELCOME" written in the center. 9 | * The design pattern should only use `|,.` and `-` characters. 10 | 11 | 12 |
13 | 14 | ### Sample Design 15 | 16 | ``` 17 | Size: 7 x 21 18 | ---------.|.--------- 19 | ------.|..|..|.------ 20 | ---.|..|..|..|..|.--- 21 | -------WELCOME------- 22 | ---.|..|..|..|..|.--- 23 | ------.|..|..|.------ 24 | ---------.|.--------- 25 | 26 | Size: 11 x 33 27 | ---------------.|.--------------- 28 | ------------.|..|..|.------------ 29 | ---------.|..|..|..|..|.--------- 30 | ------.|..|..|..|..|..|..|.------ 31 | ---.|..|..|..|..|..|..|..|..|.--- 32 | -------------WELCOME------------- 33 | ---.|..|..|..|..|..|..|..|..|.--- 34 | ------.|..|..|..|..|..|..|.------ 35 | ---------.|..|..|..|..|.--------- 36 | ------------.|..|..|.------------ 37 | ---------------.|.--------------- 38 | ``` 39 | 40 |
41 | 42 | ### Input Format 43 | 44 | A single line containing the space separated values of `N` and `M`. 45 | 46 |
47 | 48 | 49 | ### Constraints 50 | 51 | 52 | 5 < `N` < 101
53 | 15 < `M` < 303 54 | 55 | 56 |
57 | 58 | ### Output Format 59 | 60 | Output the design pattern. 61 | 62 |
63 | 64 | **Sample Input** 65 | 66 | ``` 67 | 9 27 68 | ``` 69 | 70 |
71 | 72 | **Sample Output** 73 | 74 | ``` 75 | ------------.|.------------ 76 | ---------.|..|..|.--------- 77 | ------.|..|..|..|..|.------ 78 | ---.|..|..|..|..|..|..|.--- 79 | ----------WELCOME---------- 80 | ---.|..|..|..|..|..|..|.--- 81 | ------.|..|..|..|..|.------ 82 | ---------.|..|..|.--------- 83 | ------------.|.------------ 84 | ``` 85 | 86 | 87 | 88 |
89 | 90 | 91 | ### Given Code 92 | 93 | ```python 94 | # Enter your code here. Read input from STDIN. Print output to STDOUT 95 | ``` 96 | 97 | 98 | ## Solution 99 | 100 | ```python 101 | user_input = input().split() 102 | 103 | n,m = int(user_input[0]), int(user_input[1]) 104 | 105 | s = 1 106 | 107 | for line in range(n+1): 108 | if line < int(n/2): 109 | print((".|."*s).center(m, "-")) 110 | s += 2 111 | elif line == round(n/2): 112 | print("WELCOME".center(m, "-")) 113 | elif line > int(n/2) and s > 1: 114 | s -= 2 115 | print((".|."*s).center(m, "-")) 116 | ``` 117 | -------------------------------------------------------------------------------- /solutions/022_String_Formatting.md: -------------------------------------------------------------------------------- 1 | # 022 - String Formatting 2 | 3 | ## Problem 4 | 5 | Given an integer, `n`, print the following values for each integer `i` from 1 to `n`: 6 | 7 | 1. Decimal 8 | 2. Octal 9 | 3. Hexadecimal (capitalized) 10 | 4. Binary 11 | 12 | The four values must be printed on a single line in the order specified above for each `i` from `1` to `n`. Each value should be space-padded to match the width of the binary value of `n`. 13 | 14 |
15 | 16 | ### Input Format 17 | 18 | A single integer denoting `n`. 19 | 20 | 21 | ### Constraints 22 | 23 | 24 | 1 < `n` < 99 25 | 26 | 27 | 28 | ### Output Format 29 | 30 | Print `n` lines where each line `i` (in the range `1 <= i <= n`) contains the respective decimal, octal, capitalized hexadecimal, and binary values of `i`. Each printed value must be formatted to the width of the binary value of `n`. 31 | 32 |
33 | 34 | **Sample Input** 35 | 36 | ``` 37 | 17 38 | ``` 39 | 40 |
41 | 42 | **Sample Output** 43 | 44 | ``` 45 | 1 1 1 1 46 | 2 2 2 10 47 | 3 3 3 11 48 | 4 4 4 100 49 | 5 5 5 101 50 | 6 6 6 110 51 | 7 7 7 111 52 | 8 10 8 1000 53 | 9 11 9 1001 54 | 10 12 A 1010 55 | 11 13 B 1011 56 | 12 14 C 1100 57 | 13 15 D 1101 58 | 14 16 E 1110 59 | 15 17 F 1111 60 | 16 20 10 10000 61 | 17 21 11 10001 62 | ``` 63 | 64 | 65 | 66 |
67 | 68 | 69 | ### Given Code 70 | 71 | ```python 72 | def print_formatted(number): 73 | # your code goes here 74 | 75 | if __name__ == '__main__': 76 | n = int(input()) 77 | print_formatted(n) 78 | ``` 79 | 80 | 81 | ## Solution 1 82 | 83 | ```python 84 | w = len(str(bin(number)).replace('0b','')) 85 | print("\n".join([f"{str(i).rjust(w,' ')} {oct(i)[2:].rjust(w,' ')} {hex(i)[2:].upper().rjust(w,' ')} {bin(i)[2:].rjust(w,' ')}" for i in range(1,number+1)])) 86 | ``` 87 | 88 | 89 | ## Solution 2 90 | 91 | ```python 92 | def print_formatted(number): 93 | w = len(str(bin(number)).replace('0b','')) 94 | 95 | for i in range(1, number+1): 96 | print(f"{str(i).rjust(w,' ')} {oct(i)[2:].rjust(w,' ')} {hex(i)[2:].upper().rjust(w,' ')} {bin(i)[2:].rjust(w,' ')}") 97 | 98 | 99 | if __name__ == '__main__': 100 | n = int(input()) 101 | print_formatted(n) 102 | ``` 103 | -------------------------------------------------------------------------------- /solutions/023_Alphabet_Rangoli.md: -------------------------------------------------------------------------------- 1 | # 023 - Alphabet Rangoli 2 | 3 | ## Problem 4 | 5 | You are given an integer, `N`, Your task is to print an alphabet rangoli of size `N`. (Rangoli is a form of Indian folk art based on creation of patterns.) 6 | 7 | Different sizes of alphabet rangoli are shown below: 8 | 9 | ``` 10 | #size 3 11 | 12 | ----c---- 13 | --c-b-c-- 14 | c-b-a-b-c 15 | --c-b-c-- 16 | ----c---- 17 | 18 | #size 5 19 | 20 | --------e-------- 21 | ------e-d-e------ 22 | ----e-d-c-d-e---- 23 | --e-d-c-b-c-d-e-- 24 | e-d-c-b-a-b-c-d-e 25 | --e-d-c-b-c-d-e-- 26 | ----e-d-c-d-e---- 27 | ------e-d-e------ 28 | --------e-------- 29 | 30 | #size 10 31 | 32 | ------------------j------------------ 33 | ----------------j-i-j---------------- 34 | --------------j-i-h-i-j-------------- 35 | ------------j-i-h-g-h-i-j------------ 36 | ----------j-i-h-g-f-g-h-i-j---------- 37 | --------j-i-h-g-f-e-f-g-h-i-j-------- 38 | ------j-i-h-g-f-e-d-e-f-g-h-i-j------ 39 | ----j-i-h-g-f-e-d-c-d-e-f-g-h-i-j---- 40 | --j-i-h-g-f-e-d-c-b-c-d-e-f-g-h-i-j-- 41 | j-i-h-g-f-e-d-c-b-a-b-c-d-e-f-g-h-i-j 42 | --j-i-h-g-f-e-d-c-b-c-d-e-f-g-h-i-j-- 43 | ----j-i-h-g-f-e-d-c-d-e-f-g-h-i-j---- 44 | ------j-i-h-g-f-e-d-e-f-g-h-i-j------ 45 | --------j-i-h-g-f-e-f-g-h-i-j-------- 46 | ----------j-i-h-g-f-g-h-i-j---------- 47 | ------------j-i-h-g-h-i-j------------ 48 | --------------j-i-h-i-j-------------- 49 | ----------------j-i-j---------------- 50 | ------------------j------------------ 51 | ``` 52 | 53 | 54 | The center of the rangoli has the first alphabet letter `a`, and the boundary has the Nth alphabet letter (in alphabetical order). 55 | 56 |
57 | 58 | ### Input Format 59 | 60 | Only one line of input containing `N`, the size of the rangoli. 61 | 62 | 63 | ### Constraints 64 | 65 | 66 | 0 < `N` < 27 67 | 68 | 69 | 70 | ### Output Format 71 | 72 | Print the alphabet rangoli in the format explained above. 73 | 74 |
75 | 76 | **Sample Input** 77 | 78 | ``` 79 | 5 80 | ``` 81 | 82 |
83 | 84 | **Sample Output** 85 | 86 | ``` 87 | --------e-------- 88 | ------e-d-e------ 89 | ----e-d-c-d-e---- 90 | --e-d-c-b-c-d-e-- 91 | e-d-c-b-a-b-c-d-e 92 | --e-d-c-b-c-d-e-- 93 | ----e-d-c-d-e---- 94 | ------e-d-e------ 95 | --------e-------- 96 | ``` 97 | 98 | 99 | 100 |
101 | 102 | 103 | ### Given Code 104 | 105 | ```python 106 | def print_rangoli(size): 107 | # your code goes here 108 | 109 | if __name__ == '__main__': 110 | n = int(input()) 111 | print_rangoli(n) 112 | ``` 113 | 114 | 115 | ## Solution 116 | 117 | ```python 118 | def print_rangoli(size): 119 | alphabet = "abcdefghijklmnopqrstuvwxyz"[:size] 120 | center = "-".join([c for c in alphabet[::-1]] + [c for c in alphabet[1:]]) 121 | design = [] 122 | for i in range(1, size+1): 123 | letters = [c for c in alphabet[-i:]] 124 | if len(letters) == 1: 125 | design.append("-".join(letters).center(len(center), "-")) 126 | else: 127 | design.append("-".join(letters[::-1] + letters[1:]).center(len(center), "-")) 128 | 129 | print("\n".join(design + design[::-1][1:])) 130 | 131 | if __name__ == '__main__': 132 | n = int(input()) 133 | print_rangoli(n) 134 | ``` 135 | -------------------------------------------------------------------------------- /solutions/024_Capitalize.md: -------------------------------------------------------------------------------- 1 | # 024 - Capitalize 2 | 3 | ## Problem 4 | 5 | You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, `alison heck` should be capitalized correctly as `Alison Heck`. 6 | 7 | Given a full name, your task is to capitalize the name appropriately. 8 | 9 | 10 |
11 | 12 | ### Input Format 13 | 14 | A single line of input containing the full name, `S`. 15 | 16 | 17 | ### Constraints 18 | 19 | 20 | * 0 < `len(S)` < 1000 21 | * The string consists of alphanumeric characters and spaces. 22 | 23 | Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc. 24 | 25 | 26 | 27 | ### Output Format 28 | 29 | Print the capitalized string, `S`. 30 | 31 |
32 | 33 | **Sample Input** 34 | 35 | ``` 36 | chris alan 37 | ``` 38 | 39 |
40 | 41 | **Sample Output** 42 | 43 | ``` 44 | Chris Alan 45 | ``` 46 | 47 | 48 | 49 |
50 | 51 | 52 | ### Given Code 53 | 54 | ```python 55 | # Complete the solve function below. 56 | def solve(s): 57 | 58 | if __name__ == '__main__': 59 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 60 | 61 | s = input() 62 | 63 | result = solve(s) 64 | 65 | fptr.write(result + '\n') 66 | 67 | fptr.close() 68 | ``` 69 | 70 | 71 | ## Solution 72 | 73 | ```python 74 | # Complete the solve function below. 75 | def solve(s): 76 | return ' '.join((word.capitalize() for word in s.split(' '))) 77 | 78 | 79 | if __name__ == '__main__': 80 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 81 | 82 | s = input() 83 | 84 | result = solve(s) 85 | 86 | fptr.write(result + '\n') 87 | 88 | fptr.close() 89 | ``` 90 | -------------------------------------------------------------------------------- /solutions/025_The_Minion_Game.md: -------------------------------------------------------------------------------- 1 | # 025 - The Minion Game 2 | 3 | ## Problem 4 | 5 | Kevin and Stuart want to play the **The Minion Game**. 6 | 7 | **Game Rules** 8 | 9 | Both players are given the same string `S`.
10 | Both players have to make substrings using the letters of the string `S`.
11 | Stuart has to make words starting with consonants.
12 | Kevin has to make words starting with wovels.
13 | The game ends when both players have made all possible substrings. 14 | 15 |
16 | 17 | **Scoring** 18 | 19 | A player gets +1 point for each occurrence of the substring in the string `S`. 20 | 21 |
22 | 23 | **For Example** 24 | 25 | String `S = BANANA`
26 | Kevin's wovel beginning word = `ANA`
27 | Here, `ANA` occurs twice in `BANANA`. Hence, Kevin will get 2 points. 28 | 29 | 30 |
31 | 32 | For better understanding, see the image below : 33 | 34 | ![](https://s3.amazonaws.com/hr-challenge-images/9693/1450330231-04db904008-banana.png) 35 | 36 | 37 |
38 | 39 | ### Input Format 40 | 41 | A single line of input containing the full name, `S`.
42 | 43 | **Note** : The string `S` will contain only uppercase letters: `[A - Z]`. 44 | 45 | 46 |
47 | 48 | ### Constraints 49 | 50 | 51 | 0 < `len(S)` < 106 52 | 53 | 54 |
55 | 56 | ### Output Format 57 | 58 | Print one line : the name of the winner and their score separated by a space. 59 | 60 | If the game is a draw, print `Draw` 61 | 62 |
63 | 64 | **Sample Input** 65 | 66 | ``` 67 | BANANA 68 | ``` 69 | 70 |
71 | 72 | **Sample Output** 73 | 74 | ``` 75 | Stuart 12 76 | ``` 77 | 78 | 79 | 80 |
81 | 82 | 83 | **Note**: Vowels are only defined as `AEIOU`. In this problem, `Y` is not considered a vowel. 84 | 85 |
86 | 87 | 88 | ### Given Code 89 | 90 | ```python 91 | def minion_game(string): 92 | # your code goes here 93 | 94 | if __name__ == '__main__': 95 | s = input() 96 | minion_game(s) 97 | ``` 98 | 99 | 100 | ## Solution 101 | 102 | ```python 103 | def minion_game(string): 104 | wovels = "AEIOU" 105 | 106 | kev = 0 107 | stu = 0 108 | 109 | for i in range(len(string)): 110 | if s[i] in wovels: 111 | kev += len(string)-i 112 | else: 113 | stu += len(string)-i 114 | 115 | if kev > stu: 116 | print("Kevin", kev) 117 | elif kev < stu: 118 | print("Stuart", stu) 119 | else: 120 | print("Draw") 121 | ``` 122 | -------------------------------------------------------------------------------- /solutions/027_Merge_the_Tools.md: -------------------------------------------------------------------------------- 1 | # 027 - Merge the Tools! 2 | 3 | 4 | ## Problem 5 | 6 | Consider the following: 7 | * A string, `s`, of length `n` where *s = c0c1...cn-1* 8 | * An integer, `k`, where `k` is a factor of `n` 9 | 10 | We can split `s` into `n/k` subsegments where each subsegment, *ti*, consists of a contiguous block of `k` characters in `s`. Then, use each *ti* to create string *ui* such that: 11 | * The characters in *ui* are a subsequence of the characters in *ti* 12 | * Any repeat occurrence of a character is removed from the string such that each character in *ui* occurs exactly once. In other words, if the character at some index `j` in *ti* occurs at a previous index < `j` in *ti*, then do not include the character in string *ui* 13 | 14 | Given `s` and `k`, print `n/k` lines where each line `i` denotes string *ui* 15 | 16 |
17 | 18 | 19 | ### Input Format 20 | 21 | The first line contains a single string denoting `s`. 22 | 23 | The second line contains an integer, `k`, denoting the length of each subsegment. 24 | 25 |
26 | 27 | ### Constraints 28 | 29 | 30 | * 1 <= `n` <= 104, where `n` is the length of `s` 31 | * 1 <= `k` <= `n` 32 | * It is guaranteed that `n` is a multiple of `k` 33 | 34 | 35 | 36 |
37 | 38 | 39 | 40 | ### Output Format 41 | 42 | Print `n/k` lines where each line `i` contains string *ui* 43 | 44 |
45 | 46 | 47 | 48 | **Sample Input** 49 | 50 | 51 | 52 | ``` 53 | AABCAAADA 54 | 3 55 | ``` 56 | 57 |
58 | 59 | 60 | **Sample Output** 61 | 62 | 63 | ``` 64 | AB 65 | CA 66 | AD 67 | ``` 68 | 69 | 70 |
71 | 72 | 73 | **Explanation** 74 | 75 | String `s` is split into `n/k = 9/3 = 3` equal parts of length `k = 3`. We convert each *ti* to *ui* by removing any subsequent occurrences non-distinct characters in *ti*: 76 | 77 | 1. *t0* = `AAB` -> *u0* -> `AB` 78 | 2. *t1* = `CAA` -> *u1* -> `CA` 79 | 3. *t2* = `ADA` -> *u2* -> `AD` 80 | 81 | We then print each *ui* on a new line. 82 | 83 |
84 | 85 | 86 | ### Given Code 87 | 88 | ```python 89 | def merge_the_tools(string, k): 90 | # your code goes here 91 | 92 | if __name__ == '__main__': 93 | string, k = raw_input(), int(raw_input()) 94 | merge_the_tools(string, k) 95 | ``` 96 | 97 | 98 |
99 | 100 | 101 | ## Solution 1 102 | 103 | ```python 104 | def merge_the_tools(string, k): 105 | subs = [string[i:i+k] if i+k <= len(string) else string[i:] for i in range(0, len(string), k)] 106 | uniques = [] 107 | for sub in subs: 108 | u = "" 109 | for char in sub: 110 | if char not in u: 111 | u = u + char 112 | uniques.append(u) 113 | print("\n".join(uniques)) 114 | 115 | 116 | if __name__ == '__main__': 117 | string, k = input(), int(input()) 118 | merge_the_tools(string, k) 119 | ``` 120 | 121 | 122 |
123 | 124 | 125 | ## Solution 2 126 | 127 | ```python 128 | def merge_the_tools(string, k): 129 | uniques = [] 130 | for i in range(0, len(string), k): 131 | u = "" 132 | for ch in string[i:i+k]: 133 | if ch not in u: 134 | u = u + ch 135 | uniques.append(u) 136 | print("\n".join(uniques)) 137 | 138 | 139 | if __name__ == '__main__': 140 | string, k = input(), int(input()) 141 | merge_the_tools(string, k) 142 | ``` 143 | -------------------------------------------------------------------------------- /solutions/030_collections_Counter.md: -------------------------------------------------------------------------------- 1 | # 030 - collections.Counter() 2 | 3 | ## Problem 4 | 5 | [collections.Counter()](https://docs.python.org/2/library/collections.html#collections.Counter) 6 | 7 | A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values. 8 | 9 | 10 | **Sample Code** 11 | 12 | ```python 13 | from collections import Counter 14 | 15 | myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3] 16 | 17 | print(Counter(myList)) 18 | print(Counter(myList).items()) 19 | print(Counter(myList).keys()) 20 | print(Counter(myList).values()) 21 | ``` 22 | 23 | ``` 24 | Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1}) 25 | dict_items([(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]) 26 | dict_keys([1, 2, 3, 4, 5]) 27 | dict_values([3, 4, 4, 2, 1]) 28 | ``` 29 | 30 |
31 | 32 | ### Task 33 | 34 | 35 | `Raghu` is a shoe shop owner. His shop has `X` number of shoes. 36 | 37 | He has a list containing the size of each shoe he has in his shop. 38 | 39 | 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. 40 | 41 | Your task is to compute how much money `Raghu` earned. 42 | 43 |
44 | 45 | ### Input Format 46 | 47 | The first line contains `X`, the number of shoes. 48 | 49 | The second line contains the space separated list of all the shoe sizes in the shop. 50 | 51 | The third line contains `N`, the number of customers. 52 | 53 | The next `N` lines contain the space separated values of the `shoe size` desired by the customer and **xi**, the price of the shoe. 54 | 55 | 56 |
57 | 58 | ### Constraints 59 | 60 | 61 | * 0 < `X` < 103 62 | * 0 < `N` < 103 63 | * 20 < **xi** < 100 64 | * 2 < `shoe size` < 20 65 | 66 | 67 |
68 | 69 | ### Output Format 70 | 71 | Print the amount of money earned by `Raghu`. 72 | 73 |
74 | 75 | **Sample Input** 76 | 77 | ``` 78 | 10 79 | 2 3 4 5 6 8 7 6 5 18 80 | 6 81 | 6 55 82 | 6 45 83 | 6 55 84 | 4 40 85 | 18 60 86 | 10 50 87 | ``` 88 | 89 |
90 | 91 | **Sample Output** 92 | 93 | ``` 94 | 200 95 | ``` 96 | 97 | 98 |
99 | 100 | **Explanation** 101 | 102 | Customer 1 : Purchased size 6 shoe for $55
103 | Customer 2 : Purchased size 6 shoe for $45
104 | Customer 3 : Size 6 no longer available, so no purchase
105 | Customer 4 : Purchased size 4 shoes for $40
106 | Customer 5 : Purchased size 18 show for $60
107 | Customer 6 : Size 10 not available, so no purchase
108 | 109 | Total money earned = 55 + 45 + 40 + 60 = $200 110 | 111 |
112 | 113 | 114 | ## Solution 115 | 116 | ```python 117 | from collections import Counter 118 | 119 | 120 | def earned(sales, stock): 121 | earned = 0 122 | 123 | for i in range(sales): 124 | sale = input().split(" ") 125 | shoe, price = sale[0], int(sale[1]) 126 | 127 | if shoe in stock and stock[shoe] >= 1: 128 | earned += price 129 | stock[shoe] -= 1 130 | else: 131 | continue 132 | 133 | return earned 134 | 135 | 136 | stock_len = int(input()) 137 | stock = dict(Counter([i for i in input().split(" ")])) 138 | sales = int(input()) 139 | 140 | 141 | 142 | print(earned(sales, stock)) 143 | ``` 144 | -------------------------------------------------------------------------------- /solutions/031_itertools_permutations.md: -------------------------------------------------------------------------------- 1 | # 031 - itertools.permutations() 2 | 3 | ## Problem 4 | 5 | [itertools.permutations()](https://docs.python.org/2/library/itertools.html#itertools.permutations) 6 | 7 | This tool returns successive `r` length permutations of elements in an iterable. 8 | 9 | If `r` is not specified or is `None`, then `r` defaults to the length of the iterable, and all possible full length permutatons are generated. 10 | 11 | Permutations are printed in a lexicographic sorted order. So, if the input iterable is sorted, the permutation tuples will be produced in a sorted order. 12 | 13 | **Sample Code** 14 | 15 | ```python 16 | from itertools import permutations 17 | 18 | print(permutations(["1", "2", "3"])) 19 | print(list(permutations(["1", "2", "3"]))) 20 | print(list(permutations(["1", "2", "3"], 2))) 21 | print(list(permutations("abc", 3))) 22 | ``` 23 | 24 | ``` 25 | 26 | [('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')] 27 | [('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')] 28 | [('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')] 29 | ``` 30 | 31 |
32 | 33 | ### Task 34 | 35 | 36 | You are given a string `S`. 37 | 38 | Your task is to print all possible permutations of size `k` of the string in lexicographic sorted order. 39 | 40 |
41 | 42 | ### Input Format 43 | 44 | A single line containing the space separated string `S` and the integer value `k`. 45 | 46 | 47 |
48 | 49 | ### Constraints 50 | 51 | 52 | 0 < `k` < `len(S)` 53 | 54 | The string contains only UPPERCASE characters. 55 | 56 | 57 |
58 | 59 | ### Output Format 60 | 61 | Print the permutations of the string `S` on separate lines. 62 | 63 |
64 | 65 | **Sample Input** 66 | 67 | ``` 68 | HACK 2 69 | ``` 70 | 71 |
72 | 73 | **Sample Output** 74 | 75 | ``` 76 | AC 77 | AH 78 | AK 79 | CA 80 | CH 81 | CK 82 | HA 83 | HC 84 | HK 85 | KA 86 | KC 87 | KH 88 | ``` 89 | 90 | 91 |
92 | 93 | **Explanation** 94 | 95 | All possible size `2` permutations of the string `"HACK"` are printed in lexicographic sorted order. 96 | 97 |
98 | 99 | 100 | ## Solution 101 | 102 | ```python 103 | from itertools import permutations 104 | 105 | def per(s, size): 106 | return "\n".join(sorted(["".join(i) for i in permutations(s,size)])) 107 | 108 | 109 | user = input().split(" ") 110 | 111 | s, size = user[0], int(user[1]) 112 | 113 | print(per(s,size)) 114 | ``` 115 | -------------------------------------------------------------------------------- /solutions/034_DefaultDict_Tutorial.md: -------------------------------------------------------------------------------- 1 | # 034 - DefaultDict Tutorial 2 | 3 | ## Problem 4 | 5 | The `defaultdict` tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but the only difference is that a `defaultdict` will have a default value if that key has not been set yet. If you didn't use a `defaultdict` you'd have to check to see if that key exists, and if it doesn't, set it to what you want. 6 | 7 | **For example** 8 | 9 | ```python 10 | from collections import defaultdict 11 | 12 | d = defaultdict(list) 13 | d["python"].append("awesome") 14 | d["something-else"].append("not relevant") 15 | d["python"].append("language") 16 | 17 | for i in d.items(): 18 | print(i) 19 | ``` 20 | 21 | This prints : 22 | 23 | ``` 24 | ('python', ['awesome', 'language']) 25 | ('something-else', ['not relevant']) 26 | ``` 27 | 28 | 29 | In this challenge, you will be given `2` integers, `n` and `m`. There are `n` words, which might repeat, in word group `A`. There are `m` words belonging to word group `B`. For each `m` words, check whether the word has appeared in group `A` or not. Print the indices of each occurrence of `m` in group `A`. If it does not appear, print `-1`. 30 | 31 |
32 | 33 | 34 | 35 | ### Constraints 36 | 37 | 38 | * 1 <= `n` <= 10000 39 | * 1 <= `m` <= 100 40 | * 1 <= `length of each word in the input` <= 100 41 | 42 | 43 | 44 |
45 | 46 | ### Input Format 47 | 48 | The first line contains integers, `n` and `m` separated by a space. 49 | 50 | The next `n` lines contains the words belonging to group `A`. 51 | 52 | The next `m` lines contains the words belonging to group `B`. 53 | 54 | 55 | 56 |
57 | 58 | ### Output Format 59 | 60 | Output `m` lines. 61 | 62 | The **ith** line should contain the `1`-indexed positions of the occurrences of the **ith** word separated by spaces. 63 | 64 |
65 | 66 | **Sample Input** 67 | 68 | ``` 69 | 5 2 70 | a 71 | a 72 | b 73 | a 74 | b 75 | a 76 | b 77 | ``` 78 | 79 |
80 | 81 | **Sample Output** 82 | 83 | ``` 84 | 1 2 4 85 | 3 5 86 | ``` 87 | 88 | 89 |
90 | 91 | **Explanation** 92 | 93 | `a` appeared `3` times in positions `1`, `2` and `4`.
94 | `b` appeared `2` times in positions `3` and `5`.
95 | 96 | In the sample problem, if `c` also appeared in word group `B`, you would print `-1`. 97 | 98 |
99 | 100 | 101 | ## Solution 102 | 103 | ```python 104 | from collections import defaultdict 105 | 106 | n, m = list(map(int, input().split())) 107 | 108 | thedict = defaultdict(list) 109 | 110 | for i in range(n): 111 | thedict[input()].append(i+1) 112 | 113 | for i in range(m): 114 | print(" ".join(map(str, thedict[input()])) or -1) 115 | ``` 116 | -------------------------------------------------------------------------------- /solutions/037_Collections_namedtuple.md: -------------------------------------------------------------------------------- 1 | # 037 - Collections.namedtuple() 2 | 3 | 4 | ## Problem 5 | 6 | [collections.namedtuple()](https://docs.python.org/2/library/collections.html#collections.namedtuple) 7 | 8 | 9 | Basically, namedtuples are easy to create, lightweight object types. 10 | 11 | They turn tuples into convenient containers for simple tasks. 12 | 13 | With namedtuples, you don't have to use integer indices for accessing members of a tuple. 14 | 15 | 16 | 17 | **Example** 18 | 19 | *Code 01* 20 | 21 | ```python 22 | from collections import namedtuple 23 | 24 | Point = namedtuple("Point", "x,y") 25 | pt1 = Point(1,2) 26 | pt2 = Point(3,4) 27 | dot_product = (pt1.x * pt2.x) + (pt1.y * pt2.y) 28 | print(pt1) 29 | print(pt2) 30 | print(dot_product) 31 | ``` 32 | 33 | 34 | ``` 35 | Point(x=1, y=2) 36 | Point(x=3, y=4) 37 | 11 38 | ``` 39 | 40 | 41 |
42 | 43 | *Code 02* 44 | 45 | ```python 46 | from collections import namedtuple 47 | 48 | Car = namedtuple("Car", "Price Mileage Colour Class") 49 | xyz = Car(Price = 100000, Mileage = 30, Colour = "Cyan", Class = "Y") 50 | print(xyz) 51 | print(xyz.Price) 52 | print(xyz.Class) 53 | ``` 54 | 55 | 56 | ``` 57 | Car(Price=100000, Mileage=30, Colour='Cyan', Class='Y') 58 | 100000 59 | Y 60 | ``` 61 | 62 | 63 | 64 |
65 | 66 | 67 | ### Task 68 | 69 | 70 | Dr. John Wesley has a spreadsheet containing a list of student's IDs, marks, class and name. 71 | 72 | Your task is to help Dr. Wesley calculate the average marks of the students. 73 | 74 | 75 | ``` 76 | Average = Sum of all marks / Total Students 77 | ``` 78 | 79 | 80 | Note :
81 | 1. Columns can be in any order. IDs, marks, class and name can be written in any order in the spreadsheet.
82 | 2. Column names are `ID`, `MARKS`, `CLASS` and `NAME`. (The spelling and case type of these names won't change.) 83 | 84 |
85 | 86 | ### Input Format 87 | 88 | The first line contains an integer `N`, the total number of students. 89 | 90 | The second line contains the names of the columns in any order. 91 | 92 | The next `N` lines contains the `marks`, `IDs`, `name` and `class`, under their respective column names. 93 | 94 | 95 |
96 | 97 | ### Constraints 98 | 99 | 100 | 1 <= `N` <= 100 101 | 102 | 103 | 104 |
105 | 106 | 107 | 108 | ### Output Format 109 | 110 | Print the average marks of the list corrected to 2 decimal places. 111 | 112 |
113 | 114 | 115 | 116 | **Sample Input** 117 | 118 | *Testcase 01* 119 | 120 | ``` 121 | 5 122 | ID MARKS NAME CLASS 123 | 1 97 Raymond 7 124 | 2 50 Steven 4 125 | 3 91 Adrian 9 126 | 4 72 Stewart 5 127 | 5 80 Peter 6 128 | ``` 129 | 130 |
131 | 132 | *Testcase 01* 133 | 134 | ``` 135 | 5 136 | MARKS CLASS NAME ID 137 | 92 2 Calum 1 138 | 82 5 Scott 2 139 | 94 2 Jason 3 140 | 55 8 Glenn 4 141 | 82 2 Fergus 5 142 | ``` 143 | 144 |
145 | 146 | **Sample Output** 147 | 148 | 149 | *Testcase 01* 150 | 151 | ``` 152 | 78.00 153 | ``` 154 | 155 | 156 |
157 | 158 | *Testcase 02* 159 | 160 | ``` 161 | 81.00 162 | ``` 163 | 164 | 165 |
166 | 167 | **Explanation** 168 | 169 | *Testcase 01* 170 | 171 | Average = (97 + 50 + 91 + 72 + 80) / 5 172 | 173 | Can you solve this challenge in 4 lines of code or less? 174 | 175 | NOTE : There is no penalty for solutions that are correct but have more than 4 lines. 176 | 177 | 178 |
179 | 180 | 181 | ## Solution 182 | 183 | ```python 184 | from collections import namedtuple 185 | 186 | N = int(input().strip()) 187 | Student = namedtuple("Student", ",".join(input().strip().split())) 188 | 189 | print(format(sum([int(i.MARKS) for i in [Student(*input().strip().split()) for _ in range(N)]]) / N, '.2f')) 190 | ``` 191 | -------------------------------------------------------------------------------- /solutions/041_Collections_OrderedDict.md: -------------------------------------------------------------------------------- 1 | # 041 - Collections.OrderedDict() 2 | 3 | 4 | ## Problem 5 | 6 | [collections.OrderedDict()](https://docs.python.org/2/library/collections.html#ordereddict-objects) 7 | 8 | 9 | An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged. 10 | 11 | 12 | **Example** 13 | 14 | *Code* 15 | 16 | ```python 17 | from collections import OrderedDict 18 | 19 | ordinary_dictionary = {} 20 | ordinary_dictionary["a"] = 1 21 | ordinary_dictionary["b"] = 2 22 | ordinary_dictionary["c"] = 3 23 | ordinary_dictionary["d"] = 4 24 | ordinary_dictionary["e"] = 5 25 | print(ordinary_dictionary) 26 | 27 | ordered_dictionary = OrderedDict() 28 | ordered_dictionary["a"] = 1 29 | ordered_dictionary["b"] = 2 30 | ordered_dictionary["c"] = 3 31 | ordered_dictionary["d"] = 4 32 | ordered_dictionary["e"] = 5 33 | print(ordered_dictionary) 34 | ``` 35 | 36 | 37 | ``` 38 | {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} 39 | OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) 40 | ``` 41 | 42 | 43 | 44 |
45 | 46 | 47 | ### Task 48 | 49 | 50 | You are the manager of a supermarket. 51 | 52 | You have a list of `N` items together with their prices that consumers bought on a particular day. 53 | 54 | Your task is to print each `item_name` and `net_price` in order of its first occurrence. 55 | 56 | 57 |
58 | 59 | `item_name` : Name of the item.
60 | `net_price` : Quantity of the item sold multiplied by the price of each item. 61 | 62 | 63 |
64 | 65 | ### Input Format 66 | 67 | The first line contains the number of items, `N`. 68 | 69 | The next `N` lines contains the item's name and price, separated by a space. 70 | 71 | 72 |
73 | 74 | ### Constraints 75 | 76 | 77 | 0 < `N` <= 100 78 | 79 | 80 | 81 |
82 | 83 | 84 | 85 | ### Output Format 86 | 87 | Print the `item_name` and `net_price` in order of its first occurrence. 88 | 89 |
90 | 91 | 92 | 93 | **Sample Input** 94 | 95 | 96 | 97 | ``` 98 | 9 99 | BANANA FRIES 12 100 | POTATO CHIPS 30 101 | APPLE JUICE 10 102 | CANDY 5 103 | APPLE JUICE 10 104 | CANDY 5 105 | CANDY 5 106 | CANDY 5 107 | POTATO CHIPS 30 108 | ``` 109 | 110 |
111 | 112 | 113 | **Sample Output** 114 | 115 | 116 | 117 | ``` 118 | BANANA FRIES 12 119 | POTATO CHIPS 60 120 | APPLE JUICE 20 121 | CANDY 20 122 | ``` 123 | 124 | 125 | 126 |
127 | 128 | **Explanation** 129 | 130 | 131 | BANANA FRIES : Quantity bought : 1, Price 12
132 | Net Price : 12
133 | POTATO CHIPS : Quantity bought : 2, Price 30
134 | Net Price : 60
135 | APPLE JUICE : Quantity bought : 2, Price 10
136 | Net Price : 20
137 | CANDY : Quantity bought : 4, Price : 5
138 | Net Price : 20 139 | 140 |
141 | 142 | 143 | ## Solution 144 | 145 | ```python 146 | from collections import OrderedDict 147 | 148 | 149 | sales = OrderedDict() 150 | 151 | for i in range(int(input())): 152 | sale = input().split() 153 | item_name, price = " ".join(sale[:-1]), int(sale[-1]) 154 | 155 | if item_name in sales: 156 | sales[item_name] += price 157 | else: 158 | sales[item_name] = price 159 | 160 | 161 | print("\n".join([f"{k} {v}" for k,v in sales.items()])) 162 | ``` 163 | -------------------------------------------------------------------------------- /solutions/047_Word_Order.md: -------------------------------------------------------------------------------- 1 | # 047 - Word Order 2 | 3 | 4 | ## Problem 5 | 6 | 7 | You are given `n` words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification. 8 | 9 | **Note**: Each input line ends with a `"\n"` character. 10 | 11 | 12 |
13 | 14 | 15 | ### Constraints 16 | 17 | 18 | 1 <= `n` <= 106 19 | 20 | The sum of the lengths of all words do not exceed 106. 21 | 22 | All the words are composed of lowercase English letters only. 23 | 24 | 25 | 26 |
27 | 28 | ### Input Format 29 | 30 | The first line contains the integer, `n`. 31 | 32 | The next `n` lines each contain a word. 33 | 34 | 35 | 36 |
37 | 38 | 39 | 40 | ### Output Format 41 | 42 | Output 2 lines. 43 | 44 | On the first line, output the number of distinct words from the input. 45 | 46 | On the second line, output the number of occurrences for each distinct word according to their appearance in the input. 47 | 48 |
49 | 50 | 51 | 52 | **Sample Input** 53 | 54 | 55 | 56 | ``` 57 | 4 58 | bcdef 59 | abcdefg 60 | bcde 61 | bcdef 62 | ``` 63 | 64 |
65 | 66 | 67 | **Sample Output** 68 | 69 | 70 | 71 | ``` 72 | 3 73 | 2 1 1 74 | ``` 75 | 76 | 77 | 78 |
79 | 80 | **Explanation** 81 | 82 | There are 3 distinct words. Here, `bcdef` appears twice in the input at the first and last positions. The other words appear once each. The order of the first appearances are `bcdef`, `abcdefg` and `bcde` which corresponds to the output. 83 | 84 | 85 |
86 | 87 | 88 | ## Solution 1 89 | 90 | ```python 91 | words = {} 92 | 93 | for i in range(int(input())): 94 | word = input() 95 | if word in words: 96 | words[word] += 1 97 | else: 98 | words[word] = 1 99 | 100 | print(len(words)) 101 | print(*[v for k,v in words.items()]) 102 | ``` 103 | 104 | 105 |
106 | 107 | 108 | ## Solution 2 109 | 110 | ```python 111 | from collections import OrderedDict 112 | 113 | words = OrderedDict() 114 | 115 | for i in range(int(input())): 116 | word = input() 117 | if word in words: 118 | words[word] += 1 119 | else: 120 | words[word] = 1 121 | 122 | print(len(words)) 123 | print(*[v for k,v in words.items()]) 124 | ``` 125 | -------------------------------------------------------------------------------- /solutions/049_Collections_deque.md: -------------------------------------------------------------------------------- 1 | # 049 - Collections.deque() 2 | 3 | 4 | ## Problem 5 | 6 | [Collections.deque()](https://docs.python.org/2/library/collections.html#collections.deque) 7 | 8 | 9 | A deque is a double-ended queue. It can be used to add or remove elements from both ends. 10 | 11 | Deques support thread safe, memory efficient appends and pops from either side of the deque with approximately the same `O(1)` performance in either direction. 12 | 13 | Click on the link to learn more about **deque() methods**. 14 | 15 | Click on the link to learn more about various approaches to working with deques : **Deque Recipes**. 16 | 17 | 18 |
19 | 20 | **Example** 21 | 22 | ```python 23 | from collections import deque 24 | 25 | d = deque() 26 | d.append(1) 27 | print(d) 28 | 29 | d.appendleft(2) 30 | print(d) 31 | 32 | d.clear() 33 | print(d) 34 | 35 | d.extend("1") 36 | print(d) 37 | 38 | d.extendleft("234") 39 | print(d) 40 | 41 | print(d.count("1")) 42 | 43 | print(d.pop()) 44 | 45 | print(d) 46 | 47 | print(d.popleft()) 48 | 49 | print(d) 50 | 51 | d.extend("7896") 52 | print(d) 53 | 54 | d.remove("2") 55 | print(d) 56 | 57 | d.reverse() 58 | print(d) 59 | 60 | d.rotate(3) 61 | print(d) 62 | ``` 63 | 64 |
65 | 66 | ### Constraints 67 | 68 | 69 | Perform `append`, `pop`, `popleft` and `appendleft` methods on an empty degue `d` 70 | 71 |
72 | 73 | 74 | ### Input Format 75 | 76 | The first line contains an integer `N`, the number of operations. 77 | 78 | The next `N` lines contains the space separated names of methods an their values. 79 | 80 |
81 | 82 | ### Constraints 83 | 84 | 85 | 1 < `N` <= 100 86 | 87 | 88 | 89 |
90 | 91 | 92 | 93 | ### Output Format 94 | 95 | Print the space separated elements of deque `d`. 96 | 97 |
98 | 99 | 100 | 101 | **Sample Input** 102 | 103 | 104 | 105 | ``` 106 | 6 107 | append 1 108 | append 2 109 | append 3 110 | appendleft 4 111 | pop 112 | popleft 113 | ``` 114 | 115 |
116 | 117 | 118 | **Sample Output** 119 | 120 | 121 | ``` 122 | 1 2 123 | ``` 124 | 125 | 126 |
127 | 128 | 129 | ## Solution 130 | 131 | ```python 132 | from collections import deque 133 | 134 | def eval_d(N): 135 | d = deque() 136 | 137 | for i in range(N): 138 | user = input().split() 139 | if len(user) > 1: 140 | m, e = user[0], user[1] 141 | else: 142 | m = user[0] 143 | 144 | if m == "append": 145 | d.append(e) 146 | elif m == "appendleft": 147 | d.appendleft(e) 148 | elif m == "pop": 149 | d.pop() 150 | elif m == "popleft": 151 | d.popleft() 152 | 153 | return " ".join([i for i in d]) 154 | 155 | print(eval_d(int(input()))) 156 | ``` 157 | -------------------------------------------------------------------------------- /solutions/051_Company_Logo.md: -------------------------------------------------------------------------------- 1 | # 051 - Company Logo 2 | 3 | 4 | ## Problem 5 | 6 | A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name. They are now trying out various combinations of company names and logos based on this condition. Given a string `s`, which is the company name in lowercase letters, your task is to find the top three most common characters in the string. 7 | 8 | * Print the three most common characters along with their occurrence count. 9 | * Sort in descending order of occurrence count. 10 | * If the occurrence count is the same, sort the characters in alphabetical order. 11 | 12 | For example, according to the conditions described alone, 13 | 14 | GOOGLE would have it's logo with the letters G, O, E. 15 | 16 | 17 |
18 | 19 | 20 | ### Input Format 21 | 22 | A single line of input containing the string `S`. 23 | 24 |
25 | 26 | ### Constraints 27 | 28 | 29 | 3 < `len(S)` <= 104 30 | 31 | 32 | 33 |
34 | 35 | 36 | 37 | ### Output Format 38 | 39 | Print the three most common characters along with their occurrence count each on a separate line. 40 | 41 | Sort output in descending order of occurrence count. 42 | 43 | If the occurrence count is the same, sort the characters in alphabetical order. 44 | 45 |
46 | 47 | 48 | 49 | **Sample Input** 50 | 51 | 52 | 53 | ``` 54 | aabbbccde 55 | ``` 56 | 57 |
58 | 59 | 60 | **Sample Output** 61 | 62 | 63 | ``` 64 | b 3 65 | a 2 66 | c 2 67 | ``` 68 | 69 | 70 |
71 | 72 | 73 | **Explanation** 74 | 75 | `aabbbccde` 76 | 77 | Here, b occurs 3 times. It is printed first. 78 | 79 | Both a and c occur 2 times. So, a is printed in the second line and c in the third line because a comes before c in the alphabet. 80 | 81 | Note: The string `S` has at least 3 distinct characters. 82 | 83 |
84 | 85 | 86 | ### Given Code 87 | 88 | ```python 89 | import math 90 | import os 91 | import random 92 | import re 93 | import sys 94 | 95 | 96 | 97 | if __name__ == '__main__': 98 | s = input() 99 | ``` 100 | 101 | 102 |
103 | 104 | 105 | ## Solution 106 | 107 | ```python 108 | import math 109 | import os 110 | import random 111 | import re 112 | import sys 113 | 114 | 115 | 116 | if __name__ == '__main__': 117 | s = input() 118 | 119 | letters = {l:s.count(l) for l in s} 120 | print("\n".join([f"{l} {letters[l]}" for l in sorted(sorted(letters), key=lambda x: letters[x], reverse=True)[:3]])) 121 | ``` 122 | -------------------------------------------------------------------------------- /solutions/1_1_Sock_Merchant.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Interview Preparation Kit 2 | ## 1. Warm-up Challenges 3 | 4 | ### 1.1. Sock Merchant 5 | 6 | #### Problem 7 | John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. 8 | 9 | For example, there are `n=7` socks with colors `ar=[1,2,1,2,1,3,2]`. There is one pair of color `1` and one of color `2`. There are three odd socks left, one of each color. The number of pairs is `2`. 10 | 11 | 12 |
13 | 14 | **Function Description** 15 | 16 | Complete the `sockMerchant` function in the editor below. It must return an integer representing the number of matching pairs of socks that are available. 17 | 18 | `sockMerchant` has the following parameter(s): 19 | * `n`: the number of socks in the pile 20 | * `ar`: the colors of each sock 21 | 22 | 23 |
24 | 25 | #### Input Format 26 | 27 | The first line contains an integer `n`, the number of socks represented in `ar`. 28 | 29 | The second line contains `n` space-separated integers describing the colors `ar[i]` of the socks in the pile. 30 | 31 |
32 | 33 | #### Constraints 34 | 35 | 36 | * 1 <= `n` <= 100 37 | * 1 <= `ar[i]` <= 100 where 0 <= `i` <= `n` 38 | 39 |
40 | 41 | #### Output Format 42 | 43 | Return the total number of matching pairs of socks that John can sell. 44 | 45 |
46 | 47 | **Sample Input** 48 | 49 | ``` 50 | 9 51 | 10 20 20 10 10 30 50 10 20 52 | ``` 53 | 54 |
55 | 56 | **Sample Output** 57 | 58 | ``` 59 | 3 60 | ``` 61 | 62 | 63 | **Explanation** 64 | 65 | ![](https://s3.amazonaws.com/hr-challenge-images/25168/1474122392-c7b9097430-sock.png) 66 | 67 |
68 | 69 | 70 | ### Given Code 71 | 72 | ```python 73 | import math 74 | import os 75 | import random 76 | import re 77 | import sys 78 | 79 | # Complete the sockMerchant function below. 80 | def sockMerchant(n, ar): 81 | 82 | if __name__ == '__main__': 83 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 84 | 85 | n = int(input()) 86 | 87 | ar = list(map(int, input().rstrip().split())) 88 | 89 | result = sockMerchant(n, ar) 90 | 91 | fptr.write(str(result) + '\n') 92 | 93 | fptr.close() 94 | 95 | ``` 96 | 97 | 98 | ## Solution 1 99 | 100 | ```python 101 | #!/bin/python3 102 | 103 | import math 104 | import os 105 | import random 106 | import re 107 | import sys 108 | 109 | # Complete the sockMerchant function below. 110 | def sockMerchant(n, ar): 111 | return sum([v//2 for k,v in {i:ar.count(i) for i in ar}.items()]) 112 | 113 | if __name__ == '__main__': 114 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 115 | 116 | n = int(input()) 117 | 118 | ar = list(map(int, input().rstrip().split())) 119 | 120 | result = sockMerchant(n, ar) 121 | 122 | fptr.write(str(result) + '\n') 123 | 124 | fptr.close() 125 | ``` 126 | 127 | 128 | 129 | ## Solution 2 130 | 131 | ```python 132 | #!/bin/python3 133 | 134 | import math 135 | import os 136 | import random 137 | import re 138 | import sys 139 | 140 | # Complete the sockMerchant function below. 141 | def sockMerchant(n, ar): 142 | colors = {c:ar.count(c) for c in ar} 143 | pairs = sum([colors[c] // 2 for c in colors]) 144 | return pairs 145 | 146 | if __name__ == '__main__': 147 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 148 | 149 | n = int(input()) 150 | 151 | ar = list(map(int, input().rstrip().split())) 152 | 153 | result = sockMerchant(n, ar) 154 | 155 | fptr.write(str(result) + '\n') 156 | 157 | fptr.close() 158 | ``` 159 | 160 | 161 | 162 | ## Solution 3 163 | 164 | ```python 165 | #!/bin/python3 166 | 167 | import math 168 | import os 169 | import random 170 | import re 171 | import sys 172 | 173 | # Complete the sockMerchant function below. 174 | def sockMerchant(n, ar): 175 | colors = {} 176 | for color in ar: 177 | if color in colors: 178 | colors[color] += 1 179 | else: 180 | colors[color] = 1 181 | 182 | pairs = 0 183 | 184 | for color in colors: 185 | pairs += colors[color] // 2 186 | 187 | return pairs 188 | 189 | if __name__ == '__main__': 190 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 191 | 192 | n = int(input()) 193 | 194 | ar = list(map(int, input().rstrip().split())) 195 | 196 | result = sockMerchant(n, ar) 197 | 198 | fptr.write(str(result) + '\n') 199 | 200 | fptr.close() 201 | ``` 202 | -------------------------------------------------------------------------------- /solutions/1_2_Counting_Valleys.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Interview Preparation Kit 2 | ## 1. Warm-up Challenges 3 | 4 | ### 1.2. Counting Valleys 5 | 6 | #### Problem 7 | 8 | Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly `n` steps. For every step he took, he noted if it was an uphill, `U`, or a downhill, `D` step. Gary's hikes start and end at sea level and each step up or down represents a `1` unit change in altitude. We define following terms : 9 | 10 | * A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level. 11 | * A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level. 12 | 13 | Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through. 14 | 15 | For example, if Gary's path is `s = [DDUUUUDD]`, he first enters a valley `2` units deep. Then he climbs out an up onto a mountain `2` units high. Finally, he returns to sea level and ends his hike. 16 | 17 |
18 | 19 | **Function Description** 20 | 21 | Complete the `countingValley` function in the editor below. It must return an integer that denotes of valleys Gary traversed. 22 | 23 | `countingValley` has the following parameter(s): 24 | * `n`: the number of steps Gary takes 25 | * `s`: a string describing his path 26 | 27 |
28 | 29 | #### Input Format 30 | 31 | The first line contains an integer `n`, the number of steps in Gary's hike. 32 | 33 | The second line contains a single string `s`, of `n` characters that describe his path. 34 | 35 |
36 | 37 | #### Constraints 38 | 39 | 40 | * 2 <= `n` <= 106 41 | * `s[i]` ∈ `{UD}` 42 | 43 |
44 | 45 | #### Output Format 46 | 47 | Print a single integer that denotes the number of valleys Gary walked through during his hike. 48 | 49 |
50 | 51 | **Sample Input** 52 | 53 | ``` 54 | 8 55 | UDDDUDUU 56 | ``` 57 | 58 |
59 | 60 | **Sample Output** 61 | 62 | ``` 63 | 1 64 | ``` 65 | 66 | 67 | **Explanation** 68 | 69 | If we represent `_` as sea level, a step up as `/`, and a step down as `\`, Gary's hike can be drawn as : 70 | 71 | ``` 72 | _/\ _ 73 | \ / 74 | \/\/ 75 | ``` 76 | 77 | 78 | He enters and leaves one valley. 79 | 80 | 81 |
82 | 83 | 84 | ### Given Code 85 | 86 | ```python 87 | 88 | import math 89 | import os 90 | import random 91 | import re 92 | import sys 93 | 94 | # Complete the countingValleys function below. 95 | def countingValleys(n, s): 96 | 97 | if __name__ == '__main__': 98 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 99 | 100 | n = int(input()) 101 | 102 | s = input() 103 | 104 | result = countingValleys(n, s) 105 | 106 | fptr.write(str(result) + '\n') 107 | 108 | fptr.close() 109 | 110 | ``` 111 | 112 | 113 | ## Solution 1 114 | 115 | ```python 116 | import math 117 | import os 118 | import random 119 | import re 120 | import sys 121 | 122 | def countingValleys(n, s): 123 | a = 0 124 | v = 0 125 | 126 | for i in s: 127 | if i == "U": 128 | a += 1 129 | if a == 0: 130 | v += 1 131 | else: 132 | a -= 1 133 | 134 | return v 135 | 136 | 137 | if __name__ == '__main__': 138 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 139 | 140 | n = int(input()) 141 | 142 | s = input() 143 | 144 | result = countingValleys(n, s) 145 | 146 | fptr.write(str(result) + '\n') 147 | 148 | fptr.close() 149 | ``` 150 | 151 |
152 | 153 | 154 | ## Solution 2 155 | 156 | ```python 157 | import math 158 | import os 159 | import random 160 | import re 161 | import sys 162 | 163 | def countingValleys(n, s): 164 | a = 0 165 | l = [0] 166 | v = 0 167 | 168 | for i in range(n): 169 | if s[i] == "U": 170 | a += 1 171 | else: 172 | a -= 1 173 | l.append(a) 174 | 175 | for i,s in enumerate(l): 176 | if l[i-1] < 0 and s == 0: 177 | v += 1 178 | return v 179 | 180 | 181 | if __name__ == '__main__': 182 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 183 | 184 | n = int(input()) 185 | 186 | s = input() 187 | 188 | result = countingValleys(n, s) 189 | 190 | fptr.write(str(result) + '\n') 191 | 192 | fptr.close() 193 | ``` 194 | -------------------------------------------------------------------------------- /solutions/1_3_Jumping_on_the_Clouds.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Interview Preparation Kit 2 | ## 1. Warm-up Challenges 3 | 4 | ### 1.3. Jumping on the Clouds 5 | 6 | #### Problem 7 | 8 | Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus `1` or `2`. She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting position to the last cloud. It is always possible to win the game. 9 | 10 | For each game, Emma will get an array of clouds numbered `0` if they are safe or `1` if they must be avoided. For example, `c = [0,1,0,0,0,1,0]` indexed from `0...6`. The number on each cloud is its index in the list so she must avoid the clouds at indexes `1` and `5`. She could follow the following two paths : 11 | 12 | - 0 -> 2 -> 4 -> 6 13 | - 0 -> 2 -> 3 -> 4 -> 6 14 | 15 | The first path takes `3` jumps while the second takes `4`. 16 | 17 |
18 | 19 | **Function Description** 20 | 21 | Complete the `jumpingOnClouds` function in the editor below. It should return the minimum number of jumps required, as an integer. 22 | 23 | `jumpingOnClouds` has the following parameter(s): 24 | * `c`: an array of binary integers 25 | 26 |
27 | 28 | #### Input Format 29 | 30 | The first line contains an integer `n`, the total number of clouds. The second line contains `n` space-separated binary integers describing clouds `c[i]` where `0 <= i < n`. 31 | 32 |
33 | 34 | #### Constraints 35 | 36 | * 2 <= `n` <= 100 37 | * `c[i]` ∈ `{0,1}` 38 | * `c[0]` = `c[n-1]` = 0 39 | 40 |
41 | 42 | #### Output Format 43 | 44 | Print the minimum number of jumps needed to win the game. 45 | 46 |
47 | 48 | **Sample Input 0** 49 | 50 | ``` 51 | 7 52 | 0 0 1 0 0 1 0 53 | ``` 54 | 55 |
56 | 57 | **Sample Output 0** 58 | 59 | ``` 60 | 4 61 | ``` 62 | 63 | 64 | **Explanation 0** 65 | 66 | Emma must avoid `c[2]` and `c[5]`. She can win the game with a minimum of `4` jumps. 67 | 68 | ![](https://s3.amazonaws.com/hr-challenge-images/20832/1461134731-c258160d15-jump2.png) 69 | 70 | 71 | 72 |
73 | 74 | **Sample Input 1** 75 | 76 | ``` 77 | 6 78 | 0 0 0 0 1 0 79 | ``` 80 | 81 |
82 | 83 | **Sample Output 1** 84 | 85 | ``` 86 | 3 87 | ``` 88 | 89 | 90 | **Explanation 1** 91 | 92 | The only thundercloud to avoid is `c[4]`. Emma can win the game in `3` jumps. 93 | 94 | ![](https://s3.amazonaws.com/hr-challenge-images/20832/1461136358-764298d363-jump5.png) 95 | 96 | 97 | 98 |
99 | 100 | 101 | ### Given Code 102 | 103 | ```python 104 | import math 105 | import os 106 | import random 107 | import re 108 | import sys 109 | 110 | # Complete the jumpingOnClouds function below. 111 | def jumpingOnClouds(c): 112 | 113 | if __name__ == '__main__': 114 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 115 | 116 | n = int(input()) 117 | 118 | c = list(map(int, input().rstrip().split())) 119 | 120 | result = jumpingOnClouds(c) 121 | 122 | fptr.write(str(result) + '\n') 123 | 124 | fptr.close() 125 | ``` 126 | 127 | 128 | ## Solution 129 | 130 | ```python 131 | import math 132 | import os 133 | import random 134 | import re 135 | import sys 136 | 137 | # Complete the jumpingOnClouds function below. 138 | def jumpingOnClouds(c): 139 | jumps = [] 140 | x = 0 141 | 142 | for i in range(len(c)): 143 | if c[x] == 0: 144 | if x + 2 <= len(c)-1 and c[x+2] == 0: 145 | jumps.append(i+2) 146 | x += 2 147 | elif x + 1 <= len(c)-1 and c[x+1] == 0: 148 | jumps.append(i+1) 149 | x += 1 150 | 151 | return len(jumps) 152 | 153 | if __name__ == '__main__': 154 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 155 | 156 | n = int(input()) 157 | 158 | c = list(map(int, input().rstrip().split())) 159 | 160 | result = jumpingOnClouds(c) 161 | 162 | fptr.write(str(result) + '\n') 163 | 164 | fptr.close() 165 | ``` 166 | -------------------------------------------------------------------------------- /solutions/1_4_Repeated_String.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Interview Preparation Kit 2 | ## 1. Warm-up Challenges 3 | 4 | ### 1.4. Repeated String 5 | 6 | #### Problem 7 | 8 | Lilah has a string, `s`, of lowercase English letters that she repeated infinitely many times. 9 | 10 | Given an integer, `n`, find and print the number of letter `a`'s in the first `n` letters of Lilah's infinite string. 11 | 12 | For example, if the string `s = "abcac"` and `n=10`, the substring we consider is `"abcacabcac"`, the first `10` characters of her indefinite string. There are `4` occurrences of `a` in the substring. 13 | 14 |
15 | 16 | **Function Description** 17 | 18 | Complete the `repeatedString` function in the editor below. It should return an integer representing the number of occurrences of `a` in the prefix of length `n` in the indefinitely repeating string. 19 | 20 | `repeatedString` has the following parameter(s): 21 | * `s`: a string to repeat 22 | * `n`: the number of characters to consider 23 | 24 |
25 | 26 | #### Input Format 27 | 28 | The first line contains a single string, `s`. 29 | 30 | The second line contains an integer, `n`. 31 | 32 |
33 | 34 | #### Constraints 35 | 36 | * 1 <= |`s`| <= 100 37 | * 1 <= `n` <= 106 38 | * For 25% of the test cases, `n` <= 106 39 | 40 | 41 |
42 | 43 | #### Output Format 44 | 45 | Print 46 | a single integer denoting the number of letter `a`'s in the first `n` letters of the infinite string created by repeating `s` infinitely many times. 47 | 48 |
49 | 50 | **Sample Input 0** 51 | 52 | ``` 53 | aba 54 | 10 55 | ``` 56 | 57 |
58 | 59 | **Sample Output 0** 60 | 61 | ``` 62 | 7 63 | ``` 64 | 65 | 66 | **Explanation 0** 67 | 68 | The first `n=10` letters of the infinite string are `abaabaabaa`. Because there are `7` `a`'s, we print `7` on a new line. 69 | 70 | 71 | 72 |
73 | 74 | **Sample Input 1** 75 | 76 | ``` 77 | a 78 | 1000000000000 79 | ``` 80 | 81 |
82 | 83 | **Sample Output 1** 84 | 85 | ``` 86 | 1000000000000 87 | ``` 88 | 89 | 90 | **Explanation 1** 91 | 92 | Because all of the first `n = 1000000000000` letters of the infinite string are `a`, we print `1000000000000` on a new line. 93 | 94 | 95 | 96 |
97 | 98 | 99 | ### Given Code 100 | 101 | ```python 102 | import math 103 | import os 104 | import random 105 | import re 106 | import sys 107 | 108 | # Complete the repeatedString function below. 109 | def repeatedString(s, n): 110 | 111 | if __name__ == '__main__': 112 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 113 | 114 | s = input() 115 | 116 | n = int(input()) 117 | 118 | result = repeatedString(s, n) 119 | 120 | fptr.write(str(result) + '\n') 121 | 122 | fptr.close() 123 | ``` 124 | 125 | 126 | ## Solution 127 | 128 | ```python 129 | import math 130 | import os 131 | import random 132 | import re 133 | import sys 134 | 135 | # Complete the repeatedString function below. 136 | def repeatedString(s, n): 137 | a_s = s.count("a") 138 | return (a_s * (n // len(s))) + s[:n%len(s)].count("a") if "a" in s else 0 139 | 140 | 141 | if __name__ == '__main__': 142 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 143 | 144 | s = input() 145 | 146 | n = int(input()) 147 | 148 | result = repeatedString(s, n) 149 | 150 | fptr.write(str(result) + '\n') 151 | 152 | fptr.close() 153 | ``` 154 | -------------------------------------------------------------------------------- /solutions/1_appsmart_Python_Dictionary.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Challenges 2 | ## appSMART : Python One 3 | 4 | ### 1. Python Dictionary 5 | 6 | #### Problem 7 | Welcome to last day of Python One Online A/L ICT Revision. We think now you all have a good knowledge in python. Now you are ready to get all marks for python questions in A/L ICT paper. Today we are going to use dictionaries. Today you have to help Sasindu to sort some image files. Think and code in python to help him. 8 | 9 | Sasindu need to sort a list of image names according to their image number. 10 | 11 | ![](https://2.bp.blogspot.com/-ARBdXF-chmc/V2GCQKAes3I/AAAAAAAAAyw/SbunWcXAEYIRhFpSyeauUwy1YptvA0nQgCLcB/s320/img%2Bnumber.png) 12 | 13 | 14 | All image names have the same format ('IMG' + image number + image format) such as IMG1.jpg, IMG2.jpg, IMG3.png, IMG6.bmp, etc. 15 | Help him to sort them in ascending order according. 16 | අද ඔබ සසිනිදුට පිංතූර කිහිපයක් අණුක්‍රමණයට උදව් වන්න. ඔබට ලැබෙන සියලු පිංතූර නාමයන් ('IMG' +පිංතූර අංකය + පිංතූර වර්ගය ) ලෙස වේ. උදහරණ IMG1.jpg, IMG2.jpg, IMG3.png, IMG6.bmp ආදී වශයෙනි්. සසිනිදු පිංතූර අංකය වැඩි වන ආකාරයට අනුක්‍රමණය කළ යුතුය. 17 | 18 | 19 | 20 |
21 | 22 | #### Input Format 23 | 24 | One line consists names of images separated by spaces. 25 | 26 |
27 | 28 | #### Constraints 29 | 30 | 31 | Image number > 0 32 | 33 |
34 | 35 | #### Output Format 36 | 37 | Print a list that contains all image names, sorted in ascending order using image number. 38 | 39 |
40 | 41 | **Sample Input** 42 | 43 | ``` 44 | IMG1.jpg IMG11.jpg IMG2.jpg IMG20.png IMG19.jpg 45 | ``` 46 | 47 |
48 | 49 | **Sample Output** 50 | 51 | ``` 52 | ['IMG1.jpg', 'IMG2.jpg', 'IMG11.jpg', 'IMG19.jpg', 'IMG20.png'] 53 | ``` 54 | 55 | 56 | **Explanation** 57 | 58 | Go to below link to learn more about python dictionaries http://shilpasayura.com/dev/python/ 59 | 60 |
61 | 62 | 63 | ### Given Code 64 | 65 | ```python 66 | 67 | ``` 68 | 69 | 70 | ## Solution 71 | 72 | ```python 73 | def slicer(string): 74 | s = string.find("IMG") 75 | f = string.find(".") 76 | return int(string[s+3:f]) 77 | 78 | user = input() 79 | user_list = user.split() 80 | 81 | user_list = sorted(user_list, key= lambda x: slicer(x)) 82 | print(user_list) 83 | ``` 84 | -------------------------------------------------------------------------------- /solutions/2_1_2D_Array_DS.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Interview Preparation Kit 2 | ## 2. Arrays 3 | 4 | ### 2.1. 2D Array - DS 5 | 6 | #### Problem 7 | 8 | Given a 6 x 6 2D Array, `arr`: 9 | 10 | ``` 11 | 1 1 1 0 0 0 12 | 0 1 0 0 0 0 13 | 1 1 1 0 0 0 14 | 0 0 0 0 0 0 15 | 0 0 0 0 0 0 16 | 0 0 0 0 0 0 17 | ``` 18 | 19 | We define an hourglass in `A` to be a subset of values with indices falling in this pattern in `arr`'s graphical representation: 20 | 21 | ``` 22 | a b c 23 | d 24 | e f g 25 | ``` 26 | 27 | 28 | There are 16 hourglasses in `arr`, and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in `arr`, then print the maximum hourglass sum. 29 | 30 | For example, given the 2D array: 31 | 32 | 33 | ``` 34 | -9 -9 -9 1 1 1 35 | 0 -9 0 4 3 2 36 | -9 -9 -9 1 2 3 37 | 0 0 8 6 6 0 38 | 0 0 0 -2 0 0 39 | 0 0 1 2 4 0 40 | ``` 41 | 42 | 43 | We calculate the following 16 hourglass values: 44 | 45 | ``` 46 | -63, -34, -9, 12, 47 | -10, 0, 28, 23, 48 | -27, -11, -2, 10, 49 | 9, 17, 25, 18 50 | ``` 51 | 52 | Our highest hourglass value is 28 from the hourglass: 53 | 54 | 55 | ``` 56 | 0 4 3 57 | 1 58 | 8 6 6 59 | ``` 60 | 61 | Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this challenge. 62 | 63 | 64 |
65 | 66 | **Function Description** 67 | 68 | Complete the function `hourglassSum` in the editor below. It should return an integer, the maximum hourglass sum in the array. 69 | 70 | `hourglassSum` has the following parameter(s): 71 | * `arr`: an array of integers 72 | 73 |
74 | 75 | #### Input Format 76 | 77 | Each of the 6 lines of inputs `arr[i]` contains 6 space-separated integers `arr[i][j]`. 78 | 79 |
80 | 81 | #### Constraints 82 | 83 | * -9 <= `arr[i][j]` <= 9 84 | * 0 <= `i,j` <= 5 85 | 86 | 87 | 88 |
89 | 90 | #### Output Format 91 | 92 | Print the largest (maximum) hourglass sum found in `arr`. 93 | 94 |
95 | 96 | **Sample Input 0** 97 | 98 | ``` 99 | 1 1 1 0 0 0 100 | 0 1 0 0 0 0 101 | 1 1 1 0 0 0 102 | 0 0 2 4 4 0 103 | 0 0 0 2 0 0 104 | 0 0 1 2 4 0 105 | ``` 106 | 107 |
108 | 109 | **Sample Output 0** 110 | 111 | ``` 112 | 19 113 | ``` 114 | 115 | 116 | **Explanation 0** 117 | 118 | `arr` contains the following hourglasses: 119 | 120 | ![](https://s3.amazonaws.com/hr-assets/0/1534256743-35b846ad4a-hourglasssum.png) 121 | 122 | 123 | The hourglass with the maximum sum(19) is: 124 | 125 | ``` 126 | 2 4 4 127 | 2 128 | 1 2 4 129 | ``` 130 | 131 |
132 | 133 |
134 | 135 | 136 | ### Given Code 137 | 138 | ```python 139 | #!/bin/python3 140 | 141 | import math 142 | import os 143 | import random 144 | import re 145 | import sys 146 | 147 | # Complete the hourglassSum function below. 148 | def hourglassSum(arr): 149 | 150 | 151 | if __name__ == '__main__': 152 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 153 | 154 | arr = [] 155 | 156 | for _ in range(6): 157 | arr.append(list(map(int, input().rstrip().split()))) 158 | 159 | result = hourglassSum(arr) 160 | 161 | fptr.write(str(result) + '\n') 162 | 163 | fptr.close() 164 | 165 | ``` 166 | 167 | 168 | ## Solution 169 | 170 | ```python 171 | #!/bin/python3 172 | 173 | import math 174 | import os 175 | import random 176 | import re 177 | import sys 178 | 179 | # Complete the hourglassSum function below. 180 | def hourglassSum(arr): 181 | sums = [] 182 | 183 | for c in range(4): 184 | for r in range(4): 185 | sums.append(sum(arr[c][r:r+3]) + arr[c+1][r+1] + sum(arr[c+2][r:r+3])) 186 | 187 | return max(sums) 188 | 189 | 190 | if __name__ == '__main__': 191 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 192 | 193 | arr = [] 194 | 195 | for _ in range(6): 196 | arr.append(list(map(int, input().rstrip().split()))) 197 | 198 | result = hourglassSum(arr) 199 | 200 | fptr.write(str(result) + '\n') 201 | 202 | fptr.close() 203 | 204 | ``` 205 | -------------------------------------------------------------------------------- /solutions/2_2_Arrays_Left_Rotation.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Interview Preparation Kit 2 | ## 2. Arrays 3 | 4 | ### 2.2. Arrays: Left Rotation 5 | 6 | #### Problem 7 | 8 | A left rotation operation on an array shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array `[1,2,3,4,5]`, then the array would become `[3,4,5,1,2]`. 9 | 10 | Given an array `a` of `n` integers and a number, `d` , perform `d` left rotations on the array. Return the updated array to be printed as a single line of space-separated integers. 11 | 12 |
13 | 14 | **Function Description** 15 | 16 | Complete the function `rotLeft` in the editor below. It should return the resulting array of integers. 17 | 18 | `rotLeft` has the following parameter(s): 19 | 20 | * An array of integers `a`. 21 | * An integer `d`, the number of rotations. 22 | 23 |
24 | 25 | #### Input Format 26 | 27 | The first line contains two space-separated integers `n` and `d`, the size of `a` and the number of left rotations you must perform. 28 | 29 | The second line contains `n` space-separated integers `a[i]`. 30 | 31 |
32 | 33 | #### Constraints 34 | 35 | * 1 <= `n` <= 105 36 | * 1 <= `d` <= `n` 37 | * 1 <= `a[i]` <= 106 38 | 39 | 40 | 41 |
42 | 43 | #### Output Format 44 | 45 | Print a single line of `n` space-separated integers denoting the final state of the array after performing `d` left rotations. 46 | 47 |
48 | 49 | **Sample Input 0** 50 | 51 | ``` 52 | 5 4 53 | 1 2 3 4 5 54 | ``` 55 | 56 |
57 | 58 | **Sample Output 0** 59 | 60 | ``` 61 | 5 1 2 3 4 62 | ``` 63 | 64 | 65 | **Explanation 0** 66 | 67 | When we perform `d = 4` left rotations, the array undergoes the following sequence of changes: 68 | 69 | ``` 70 | [1,2,3,4,5] -> [2,3,4,5,1] -> [3,4,5,1,2] -> [4,5,1,2,3] -> [5,1,2,3,4] 71 | ``` 72 | 73 |
74 | 75 | 76 | 77 | ### Given Code 78 | 79 | ```python 80 | import math 81 | import os 82 | import random 83 | import re 84 | import sys 85 | 86 | # Complete the rotLeft function below. 87 | def rotLeft(a, d): 88 | 89 | 90 | if __name__ == '__main__': 91 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 92 | 93 | nd = input().split() 94 | 95 | n = int(nd[0]) 96 | 97 | d = int(nd[1]) 98 | 99 | a = list(map(int, input().rstrip().split())) 100 | 101 | result = rotLeft(a, d) 102 | 103 | fptr.write(' '.join(map(str, result))) 104 | fptr.write('\n') 105 | 106 | fptr.close() 107 | ``` 108 | 109 | 110 | ## Solution 111 | 112 | ```python 113 | import math 114 | import os 115 | import random 116 | import re 117 | import sys 118 | 119 | # Complete the rotLeft function below. 120 | def rotLeft(a, d): 121 | return a[d:] + a[:d] 122 | 123 | if __name__ == '__main__': 124 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 125 | 126 | nd = input().split() 127 | 128 | n = int(nd[0]) 129 | 130 | d = int(nd[1]) 131 | 132 | a = list(map(int, input().rstrip().split())) 133 | 134 | result = rotLeft(a, d) 135 | 136 | fptr.write(' '.join(map(str, result))) 137 | fptr.write('\n') 138 | 139 | fptr.close() 140 | ``` 141 | -------------------------------------------------------------------------------- /solutions/2_3_New_Year_Chaos.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Interview Preparation Kit 2 | ## 2. Arrays 3 | 4 | ### 2.3. New Year Chaos 5 | 6 | #### Problem 7 | 8 | It's New Year's Day and everyone's in line for the Wonderland rollercoaster ride! There are a number of people queued up, and each person wears a sticker indicating their initial position in the queue. Initial positions increment by 1 from 1 at the front of the line to `n` at the back. 9 | 10 | Any person in the queue can bribe the person directly in front of them to swap positions. If two people swap positions, they still wear the same sticker denoting their original places in line. One person can bribe at most two others. For example, if `n = 8` and `Person 5` bribes `Person 4`, the queue will look like this: `1,2,3,5,4,6,7,8`. 11 | 12 | Fascinated by this chaotic queue, you decide you must know the minimum number of bribes that took place to get the queue into its current state! 13 | 14 |
15 | 16 | **Function Description** 17 | 18 | Complete the function `minimumBribes` in the editor below. It must print an integer representing the minimum number of bribes necessary, or `Too chaotic `if the line configuration is not possible. 19 | 20 | `minimumBribes` has the following parameter(s): 21 | 22 | * `q`: an array of integers 23 | 24 |
25 | 26 | #### Input Format 27 | 28 | The first line contains an integer `t`, the number of test cases. 29 | 30 | Each of the next `t` pairs of lines are as follows: 31 | - The first line contains an integer `t`, the number of people in the queue 32 | - The second line has `n` space-separated integers describing the final state of the queue. 33 | 34 |
35 | 36 | #### Constraints 37 | 38 | * 1 <= `t` <= 10 39 | * 1 <= `n` <= 105 40 | 41 | 42 |
43 | 44 | #### Subtasks 45 | 46 | For 60% score 1 <= `n` <= 102
47 | For 100% score 1 <= `n` <= 105 48 | 49 |
50 | 51 | #### Output Format 52 | 53 | Print an integer denoting the minimum number of bribes needed to get the queue into its final state. Print `Too chaotic` if the state is invalid, i.e. it requires a person to have bribed more than 2 people. 54 | 55 |
56 | 57 | **Sample Input** 58 | 59 | ``` 60 | 2 61 | 5 62 | 2 1 5 3 4 63 | 5 64 | 2 5 1 3 4 65 | ``` 66 | 67 |
68 | 69 | **Sample Output** 70 | 71 | ``` 72 | 3 73 | Too chaotic 74 | ``` 75 | 76 | 77 | **Explanation** 78 | 79 | *Test Case 1* 80 | 81 | The initial state: 82 | 83 | ![](https://s3.amazonaws.com/hr-challenge-images/494/1451665589-31d436ba19-pic11.png) 84 | 85 | 86 | After person 5 moves one position ahead by bribing person 4: 87 | 88 | ![](https://s3.amazonaws.com/hr-challenge-images/494/1451665679-6504422ed9-pic2.png) 89 | 90 | Now person 5 moves another position ahead by bribing person 3: 91 | 92 | ![](https://s3.amazonaws.com/hr-challenge-images/494/1451665818-27bd62bb0d-pic3.png) 93 | 94 | And person 2 moves one position ahead by bribing person 1: 95 | 96 | ![](https://s3.amazonaws.com/hr-challenge-images/494/1451666025-02a2395a00-pic5.png) 97 | 98 | 99 | So the final state is `2,1,5,3,4` after three bribing operations. 100 | 101 |
102 | 103 | *Test Case 2* 104 | 105 | No person can bribe more than two people, so its not possible to achieve the input state. 106 | 107 |
108 | 109 | 110 | 111 | ### Given Code 112 | 113 | ```python 114 | import math 115 | import os 116 | import random 117 | import re 118 | import sys 119 | 120 | # Complete the minimumBribes function below. 121 | def minimumBribes(q): 122 | 123 | 124 | 125 | if __name__ == '__main__': 126 | t = int(input()) 127 | 128 | for t_itr in range(t): 129 | n = int(input()) 130 | 131 | q = list(map(int, input().rstrip().split())) 132 | 133 | minimumBribes(q) 134 | ``` 135 | 136 | 137 | ## Solution 138 | 139 | ```python 140 | import math 141 | import os 142 | import random 143 | import re 144 | import sys 145 | 146 | # Complete the minimumBribes function below. 147 | def minimumBribes(q): 148 | moves = 0 149 | 150 | for i,n in enumerate(q): 151 | if n - i -1 > 2: 152 | print("Too chaotic") 153 | return 154 | 155 | for x in range(max(n-2,0),i): 156 | if q[x] > n: 157 | moves += 1 158 | 159 | print(moves) 160 | 161 | 162 | 163 | if __name__ == '__main__': 164 | t = int(input()) 165 | 166 | for t_itr in range(t): 167 | n = int(input()) 168 | 169 | q = list(map(int, input().rstrip().split())) 170 | 171 | minimumBribes(q) 172 | ``` 173 | -------------------------------------------------------------------------------- /solutions/2_4_Minimum_Swaps_2.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Interview Preparation Kit 2 | ## 2. Arrays 3 | 4 | ### 2.4. Minimum Swaps 2 5 | 6 | #### Problem 7 | 8 | You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order. 9 | 10 | For example, given the array `arr = [7,1,3,2,4,5,6]` we perform the following steps: 11 | 12 | ``` 13 | i arr swap (indices) 14 | 0 [7, 1, 3, 2, 4, 5, 6] swap (0,3) 15 | 1 [2, 1, 3, 7, 4, 5, 6] swap (0,1) 16 | 2 [1, 2, 3, 7, 4, 5, 6] swap (3,4) 17 | 3 [1, 2, 3, 4, 7, 5, 6] swap (4,5) 18 | 4 [1, 2, 3, 4, 5, 7, 6] swap (5,6) 19 | 5 [1, 2, 3, 4, 5, 6, 7] 20 | ``` 21 | 22 | It took 5 swaps to sort the array. 23 | 24 |
25 | 26 | **Function Description** 27 | 28 | Complete the function `minimumSwaps` in the editor below. It must return an integer representing the minimum number of swaps to sort the array. 29 | 30 | `minimumSwaps` has the following parameter(s): 31 | 32 | * `arr`: an unordered array of integers 33 | 34 |
35 | 36 | #### Input Format 37 | 38 | The first line contains an integer, `n` , the size of `arr`. 39 | The second line contains `n` space-separated integers `arr[i]`. 40 | 41 |
42 | 43 | #### Constraints 44 | 45 | * 1 ≤ `n` ≤ 105 46 | * 1 ≤ `arr[i]` ≤ `n` 47 | 48 | 49 |
50 | 51 | 52 | #### Output Format 53 | 54 | Return the minimum number of swaps to sort the given array. 55 | 56 |
57 | 58 | **Sample Input 0** 59 | 60 | ``` 61 | 4 62 | 4 3 1 2 63 | ``` 64 | 65 |
66 | 67 | **Sample Output 0** 68 | 69 | ``` 70 | 3 71 | ``` 72 | 73 | 74 | **Explanation 0** 75 | 76 | Given array `arr : [4,3,1,2]`
77 | After swapping `(0,2)` we get `arr : [1,3,4,2]`
78 | After swapping `(1,2)` we get `arr : [1,4,3,2]`
79 | After swapping `(1,3)` we get `arr : [1,2,3,4]`
80 | So, we need a minimum of 3 swaps to sort the array in ascending order. 81 | 82 |
83 | 84 | 85 | 86 | **Sample Input 1** 87 | 88 | ``` 89 | 5 90 | 2 3 4 1 5 91 | ``` 92 | 93 |
94 | 95 | **Sample Output 1** 96 | 97 | ``` 98 | 3 99 | ``` 100 | 101 | 102 | **Explanation 1** 103 | 104 | Given array `arr : [2,3,4,1,5]`
105 | After swapping `(2,3)` we get `arr : [2,3,1,4,5]`
106 | After swapping `(0,1)` we get `arr : [3,2,1,4,5]`
107 | After swapping `(0,2)` we get `arr : [1,2,3,4,5]`
108 | So, we need a minimum of 3 swaps to sort the array in ascending order. 109 | 110 |
111 | 112 | 113 | **Sample Input 2** 114 | 115 | ``` 116 | 7 117 | 1 3 5 2 4 6 7 118 | ``` 119 | 120 |
121 | 122 | **Sample Output 2** 123 | 124 | ``` 125 | 3 126 | ``` 127 | 128 | 129 | **Explanation 2** 130 | 131 | Given array `arr : [1,3,5,2,4,6,7`
132 | After swapping `(1,3)` we get `arr : [1,2,5,3,4,6,7]`
133 | After swapping `(2,3)` we get `arr : [1,2,3,5,4,6,7]`
134 | After swapping `(3,4)` we get `arr : [1,2,3,4,5,6,7]`
135 | So, we need a minimum of 3 swaps to sort the array in ascending order. 136 | 137 |
138 | 139 | 140 | 141 | ### Given Code 142 | 143 | ```python 144 | import math 145 | import os 146 | import random 147 | import re 148 | import sys 149 | 150 | # Complete the minimumSwaps function below. 151 | def minimumSwaps(arr): 152 | 153 | 154 | 155 | if __name__ == '__main__': 156 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 157 | 158 | n = int(input()) 159 | 160 | arr = list(map(int, input().rstrip().split())) 161 | 162 | res = minimumSwaps(arr) 163 | 164 | fptr.write(str(res) + '\n') 165 | 166 | fptr.close() 167 | ``` 168 | 169 | 170 | ## Solution 171 | 172 | ```python 173 | import math 174 | import os 175 | import random 176 | import re 177 | import sys 178 | 179 | # Complete the minimumSwaps function below. 180 | def minimumSwaps(arr): 181 | swaps = 0 182 | 183 | for i in range(0, n - 1): 184 | while arr[i] != i + 1: 185 | temp = arr[arr[i] - 1] 186 | arr[arr[i] - 1] = arr[i] 187 | arr[i] = temp 188 | swaps += 1 189 | return swaps 190 | 191 | 192 | 193 | if __name__ == '__main__': 194 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 195 | 196 | n = int(input()) 197 | 198 | arr = list(map(int, input().rstrip().split())) 199 | 200 | res = minimumSwaps(arr) 201 | 202 | fptr.write(str(res) + '\n') 203 | 204 | fptr.close() 205 | ``` 206 | -------------------------------------------------------------------------------- /solutions/2_Pycode2015_Dictionary_Assignment.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Challenges 2 | ## Pycode2015 3 | 4 | ### Dictionary-Assignment 5 | 6 | #### Problem 7 | 8 | Write a function `histogram()` that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary and print the in sorted order on 'key'. 9 | 10 | 11 | 12 |
13 | 14 | #### Input Format 15 | 16 | For each `"T"` test cases, we have one line: 17 | 18 | First line contains a strings for which the frequecy of characters to be generated 19 | 20 | 1 <= `T` <= 500 21 | 22 | 1 <= `N` <= 100 23 | 24 |
25 | 26 | 27 | 28 | #### Output Format 29 | 30 | For each of the test cases, print a dictionary that maps from frequencies to letters. For Eg. 31 | 32 | `for string S="'brontosaurus'` 33 | 34 | the program should create a dictionary 35 | 36 | `hist={'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}` 37 | 38 | The dictionary `'hist'` indicates that the letters `’a’` and `'b'` appear once; `'o'` appears twice, and so on. 39 | 40 | sort a dict by keys and print 41 | 42 | 43 | ``` 44 | Letter a apperas 1 time/s 45 | Letter b appears 1 time/s 46 | Letter n appears 1 time/s 47 | Letter o apperas 2 time/s 48 | ........ 49 | Letter u appears 2 time/s 50 | ``` 51 | 52 |
53 | 54 | **Sample Input** 55 | 56 | ``` 57 | 2 58 | abracadabra 59 | msrit 60 | ``` 61 | 62 |
63 | 64 | **Sample Output** 65 | 66 | ``` 67 | Letter a appears 5 time/s 68 | Letter b appears 2 time/s 69 | Letter c appears 1 time/s 70 | Letter d appears 1 time/s 71 | Letter r appears 2 time/s 72 | 73 | Letter i appears 1 time/s 74 | Letter m appears 1 time/s 75 | Letter r appears 1 time/s 76 | Letter s appears 1 time/s 77 | Letter t appears 1 time/s 78 | ``` 79 | 80 | 81 | **Explanation** 82 | 83 | The function dict creates a new dictionary with no items. Because dict is the name of a built-in function, you should avoid using it as a variable name. 84 | 85 | ```python 86 | >>> eng2sp = dict() 87 | >>> print eng2sp 88 | {} 89 | ``` 90 | 91 | The squiggly-brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use square brackets: 92 | 93 | 94 | ```python 95 | >>> eng2sp['one'] = 'uno' 96 | ``` 97 | 98 | **Important Note:** 99 | 100 | If we want to order or sort the dictionary objects by their keys, the simplest way to do so is by Python's built-in "sorted" method, which will take any iterable and return a list of the values which has been sorted (in ascending order by default) 101 | 102 |
103 | 104 | 105 | 106 | ## Solution 1 107 | 108 | ```python 109 | def histogram(string): 110 | hist = {c:string.count(c) for c in string} 111 | return "\n".join(sorted([f"Letter {k} appears {v} time/s" for k,v in hist.items()])) 112 | 113 | word = input("") 114 | 115 | print(histogram(word)) 116 | ``` 117 | 118 |
119 | 120 | 121 | 122 | ## Solution 2 123 | 124 | ```python 125 | def histogram(string): 126 | hist = {} 127 | 128 | for c in string: 129 | if c in hist: 130 | hist[c] += 1 131 | else: 132 | hist[c] = 1 133 | 134 | for k,v in sorted(hist.items()): 135 | print(f"Letter {k} appears {v} time/s") 136 | 137 | 138 | histogram(input("")) 139 | ``` 140 | -------------------------------------------------------------------------------- /solutions/3_2_Two_Strings.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Interview Preparation Kit 2 | ## 3. Dictionaries and Hashmaps 3 | 4 | ### 3.2. Two Strings 5 | 6 | #### Problem 7 | 8 | Given two strings, determine if they share a common substring. A substring may be as small as one character. For example, the words "a", "and", "art" share the common substring `a`. The words "be" and "cat" do not share a substring. 9 | 10 |
11 | 12 | **Function Description** 13 | 14 | Complete the function `twoStrings` in the editor below. It should return a string, either `YES` or `NO` based on whether the strings share a common substring. 15 | 16 | `twoStrings` has the following parameter(s): 17 | * `s1`, `s2`: two strings to analyze. 18 | 19 |
20 | 21 | #### Input Format 22 | 23 | The first line contains a single integer `p`, the number of test cases. 24 | 25 | The following `p` pairs of lines are as follows: 26 | * The first line contains string `s1`. 27 | * The second line contains string `s2` 28 | 29 |
30 | 31 | #### Constraints 32 | 33 | * `s1` and `s2` consist of characters in the range ascii[a-z]. 34 | * 1 <= `p` <= 10 35 | * 1 <= `|s1|`, `|s2|` <= 105 36 | 37 | 38 |
39 | 40 | #### Output Format 41 | 42 | For each pair of strings, return `YES` or `NO`. 43 | 44 |
45 | 46 | **Sample Input** 47 | 48 | ``` 49 | 2 50 | hello 51 | world 52 | hi 53 | world 54 | ``` 55 | 56 |
57 | 58 | **Sample Output** 59 | 60 | ``` 61 | YES 62 | NO 63 | ``` 64 | 65 | 66 |
67 | 68 | **Explanation** 69 | 70 | 71 | We have `p = 2` pairs to check: 72 | 73 | 1. `s1 = "hello"`, `s2 = "world"`. The substrings `"o"` and `"l"` are common to both strings. 74 | 2. `a = "hi"`, `b = "world"`. `s1` and `s2` share no common substrings. 75 | 76 | 77 |
78 | 79 | 80 | 81 | 82 | 83 | ### Given Code 84 | 85 | ```python 86 | import math 87 | import os 88 | import random 89 | import re 90 | import sys 91 | 92 | # Complete the twoStrings function below. 93 | def twoStrings(s1, s2): 94 | 95 | if __name__ == '__main__': 96 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 97 | 98 | q = int(input()) 99 | 100 | for q_itr in range(q): 101 | s1 = input() 102 | 103 | s2 = input() 104 | 105 | result = twoStrings(s1, s2) 106 | 107 | fptr.write(result + '\n') 108 | 109 | fptr.close() 110 | ``` 111 | 112 | 113 | ## Solution 1 114 | 115 | ```python 116 | import math 117 | import os 118 | import random 119 | import re 120 | import sys 121 | 122 | 123 | def twoStrings(s1, s2): 124 | for w in s1: 125 | if w in s2: 126 | return "YES" 127 | else: 128 | return "NO" 129 | 130 | 131 | if __name__ == '__main__': 132 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 133 | 134 | q = int(input()) 135 | 136 | for q_itr in range(q): 137 | s1 = input() 138 | 139 | s2 = input() 140 | 141 | result = twoStrings(s1, s2) 142 | 143 | fptr.write(result + '\n') 144 | 145 | fptr.close() 146 | ``` 147 | 148 | 149 | 150 | ## Solution 2 151 | 152 | ```python 153 | import math 154 | import os 155 | import random 156 | import re 157 | import sys 158 | 159 | 160 | def twoStrings(s1, s2): 161 | if len(set(s1).intersection(set(s2))) >= 1: 162 | return "YES" 163 | else: 164 | return "NO" 165 | 166 | 167 | if __name__ == '__main__': 168 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 169 | 170 | q = int(input()) 171 | 172 | for q_itr in range(q): 173 | s1 = input() 174 | 175 | s2 = input() 176 | 177 | result = twoStrings(s1, s2) 178 | 179 | fptr.write(result + '\n') 180 | 181 | fptr.close() 182 | ``` 183 | -------------------------------------------------------------------------------- /solutions/3_3_Sherlock_and_Anagrams.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Interview Preparation Kit 2 | ## 3. Dictionaries and Hashmaps 3 | 4 | ### 3.3. Sherlock and Anagrams 5 | 6 | #### Problem 7 | 8 | Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other. 9 | 10 | For example `s = mom`, the list of all anagrammatic pairs is `[m,m], [mo,om]` at positions [[0], [2], [[0,1], [1,2]]] recpectively. 11 | 12 |
13 | 14 | **Function Description** 15 | 16 | Complete the function `sherlockAndAnagrams` in the editor below. It must return an integer that represents the number of anagrammatic pairs of substrings in `s`. 17 | 18 | `sherlockAndAnagrams` has the followint parameter(s): 19 | * `s` : a string 20 | 21 |
22 | 23 | #### Input Format 24 | 25 | The first line contains an integer `q`, the number of queries. 26 | 27 | Each of the next `q` lines contains a string `s` to analyze. 28 | 29 |
30 | 31 | #### Constraints 32 | 33 | * String `s` contains only lowercase letters € ascii[a-z]. 34 | * 1 <= `q` <= 10 35 | * 2 <= `|s|` <= 100 36 | 37 | 38 |
39 | 40 | #### Output Format 41 | 42 | For each query, return the number of unordered anagrammatic pairs. 43 | 44 |
45 | 46 | **Sample Input 0** 47 | 48 | ``` 49 | 2 50 | abba 51 | abcd 52 | ``` 53 | 54 |
55 | 56 | **Sample Output 0** 57 | 58 | ``` 59 | 4 60 | 0 61 | ``` 62 | 63 | 64 |
65 | 66 | **Explanation 0** 67 | 68 | 69 | The list of anagrammatic pairs is `[a,a]`,` [ab,ba]`, `[b,b]` and `[abb,bba]` at positions `[[0,3]]`, `[[0,1], [2,3]]`, `[[1], [2]]` and `[[0,1,2],[1,2,3]]` respectively. 70 | 71 | No anagrammatic pairs exist in the second query as no character repeats. 72 | 73 | 74 |
75 | 76 | 77 | **Sample Input 1** 78 | 79 | ``` 80 | 2 81 | ifailuhkqq 82 | kkkk 83 | ``` 84 | 85 |
86 | 87 | **Sample Output 1** 88 | 89 | ``` 90 | 3 91 | 10 92 | ``` 93 | 94 | 95 |
96 | 97 | **Explanation 1** 98 | 99 | 100 | For thw first query, we have anagram pairs `[i,i]`, `[q,q]` and `[ifa,fai]` at positions `[[0], [3]]`, `[[8],[9]]` and `[[0,1,2],[1,2,3]]` respectively. 101 | 102 | For the second query: 103 | 104 | There are 6 anagrams of the form `[k,k]` at positions `[[0],[1], [[0],[2]], [[0],[3]], [[1],[2]], [[1],[3]]]` and `[[2],[3]]` 105 | 106 | There are 3 anagrams of the form `[kk,kk]` at positions `[[0,1], [1,2]]`, `[[0,1],[2,3]]` and `[[1,2],[2,3]]` 107 | 108 | There is 1 anagram of the form `[kkk,kkk]` at positions `[[0,1,2],[1,2,3]]` 109 | 110 | 111 | 112 |
113 | 114 | 115 | **Sample Input 2** 116 | 117 | ``` 118 | 1 119 | cdcd 120 | ``` 121 | 122 |
123 | 124 | **Sample Output 2** 125 | 126 | ``` 127 | 5 128 | ``` 129 | 130 | 131 |
132 | 133 | **Explanation 2** 134 | 135 | 136 | There are two anagrammatic pairs of lenght `1` : `[c,c]` and `[d,d]` 137 | 138 | There are three anagrammatic pairs of lenght `2` : `[cd,dc]`, `[cd,cd]`, `[dc,cd]` at positions `[[0,1], [1,2]]`, `[[0,1], [2,3]]`, `[[1,2],[2,3]]` respectively. 139 | 140 | 141 | 142 |
143 | 144 | 145 | ### Given Code 146 | 147 | ```python 148 | import math 149 | import os 150 | import random 151 | import re 152 | import sys 153 | 154 | # Complete the sherlockAndAnagrams function below. 155 | def sherlockAndAnagrams(s): 156 | 157 | if __name__ == '__main__': 158 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 159 | 160 | q = int(input()) 161 | 162 | for q_itr in range(q): 163 | s = input() 164 | 165 | result = sherlockAndAnagrams(s) 166 | 167 | fptr.write(str(result) + '\n') 168 | 169 | fptr.close() 170 | ``` 171 | 172 | 173 | ## Solution 174 | 175 | ```python 176 | import math 177 | import os 178 | import random 179 | import re 180 | import sys 181 | 182 | # Complete the sherlockAndAnagrams function below. 183 | def sherlockAndAnagrams(s): 184 | n = len(s) 185 | r = 0 186 | 187 | for i in range(1,n): 188 | d = {} 189 | for j in range(n-i+1): 190 | subs = "".join(sorted(s[j:j+i])) 191 | if subs in d: 192 | d[subs] += 1 193 | else: 194 | d[subs] =1 195 | r += d[subs]-1 196 | 197 | return r 198 | 199 | 200 | if __name__ == '__main__': 201 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 202 | 203 | q = int(input()) 204 | 205 | for q_itr in range(q): 206 | s = input() 207 | 208 | result = sherlockAndAnagrams(s) 209 | 210 | fptr.write(str(result) + '\n') 211 | 212 | fptr.close() 213 | 214 | ``` 215 | -------------------------------------------------------------------------------- /solutions/3_4_Count_Triplets.md: -------------------------------------------------------------------------------- 1 | # The HackerRank Interview Preparation Kit 2 | ## 3. Dictionaries and Hashmaps 3 | 4 | ### 3.4. Count Triplets 5 | 6 | #### Problem 7 | 8 | You are given an array and you need to find number of triplets of indices `(i,j,k)` such that the elements at those indices are in [geometric progression](https://en.wikipedia.org/wiki/Geometric_progression) for a given common ratio `r` and `i < j < k`. 9 | 10 | For example, `arr = [1,4,16,64]`. If `r=4`, we have `[1,4,16]` at indices `(0,1,2)` and `(1,2,3)`. 11 | 12 |
13 | 14 | **Function Description** 15 | 16 | Complete the `countTriplets` function in the editor below. It should return the number of triplets forming a geometric progression for a given `r` as an integer. 17 | 18 | `countTriplets` has the following parameter(s): 19 | * `arr` : an array of integers 20 | * `r` : an array of integers 21 | 22 | 23 |
24 | 25 | #### Input Format 26 | 27 | The first line contains two space-separated integers `n` and `r`, the size of `arr` and the common ratio. 28 | 29 | The next line contains `n` space-seperated integers `arr[i]`. 30 | 31 | 32 |
33 | 34 | #### Constraints 35 | 36 | * 1 <= `n` <= 105 37 | * 1 <= `r` <= 109 38 | * 1 <= `arr[i]` <= 109 39 | 40 | 41 |
42 | 43 | #### Output Format 44 | 45 | Return the count of triplets that form a geometric progression. 46 | 47 |
48 | 49 | **Sample Input 0** 50 | 51 | ``` 52 | 4 2 53 | 1 2 2 4 54 | ``` 55 | 56 |
57 | 58 | **Sample Output 0** 59 | 60 | ``` 61 | 2 62 | ``` 63 | 64 | 65 |
66 | 67 | **Explanation 0** 68 | 69 | 70 | There are `2` triplets in satisfying our criteria, whose indices are `(0,1,3)` and `(0,2,3)` 71 | 72 |
73 | 74 | 75 | **Sample Input 1** 76 | 77 | ``` 78 | 6 3 79 | 1 3 9 9 27 81 80 | ``` 81 | 82 |
83 | 84 | **Sample Output 1** 85 | 86 | ``` 87 | 6 88 | ``` 89 | 90 | 91 |
92 | 93 | **Explanation 1** 94 | 95 | 96 | The triplets satisfying are index `(0,1,2)`, `(0,1,3)`, `(1,2,4)`, `(1,3,4)`, `(2,4,5)` and `(3,4,5)` 97 | 98 | 99 |
100 | 101 | 102 | **Sample Input 2** 103 | 104 | ``` 105 | 5 5 106 | 1 5 5 25 125 107 | ``` 108 | 109 |
110 | 111 | **Sample Output 2** 112 | 113 | ``` 114 | 4 115 | ``` 116 | 117 | 118 |
119 | 120 | **Explanation 2** 121 | 122 | The triplets satisfying are index `(0,1,3)`, `(0,2,3)`, `(1,3,4)`, `(2,3,4)` 123 | 124 | 125 | 126 |
127 | 128 | 129 | ### Given Code 130 | 131 | ```python 132 | import math 133 | import os 134 | import random 135 | import re 136 | import sys 137 | 138 | # Complete the countTriplets function below. 139 | def countTriplets(arr, r): 140 | 141 | if __name__ == '__main__': 142 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 143 | 144 | nr = input().rstrip().split() 145 | 146 | n = int(nr[0]) 147 | 148 | r = int(nr[1]) 149 | 150 | arr = list(map(int, input().rstrip().split())) 151 | 152 | ans = countTriplets(arr, r) 153 | 154 | fptr.write(str(ans) + '\n') 155 | 156 | fptr.close() 157 | ``` 158 | 159 | 160 | ## Solution 1 161 | 162 | ```python 163 | import math 164 | import os 165 | import random 166 | import re 167 | import sys 168 | from collections import defaultdict 169 | 170 | # Complete the countTriplets function below. 171 | def countTriplets(arr, r): 172 | d1 = defaultdict(int) 173 | d2 = defaultdict(int) 174 | c = 0 175 | 176 | for i in reversed(arr): 177 | if i*r in d2: 178 | c += d2[i*r] 179 | if i*r in d1: 180 | d2[i] += d1[i*r] 181 | d1[i]+=1 182 | 183 | return c 184 | 185 | if __name__ == '__main__': 186 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 187 | 188 | nr = input().rstrip().split() 189 | 190 | n = int(nr[0]) 191 | 192 | r = int(nr[1]) 193 | 194 | arr = list(map(int, input().rstrip().split())) 195 | 196 | ans = countTriplets(arr, r) 197 | 198 | fptr.write(str(ans) + '\n') 199 | 200 | fptr.close() 201 | ``` 202 | 203 | 204 | 205 | 206 | ## Solution 2 207 | 208 | ```python 209 | import math 210 | import os 211 | import random 212 | import re 213 | import sys 214 | from collections import defaultdict 215 | 216 | # Complete the countTriplets function below. 217 | def countTriplets(arr, r): 218 | c = 0 219 | i = 0 220 | 221 | while i < len(arr) - 2: 222 | j = i + 1 223 | k = i + 2 224 | 225 | while j < len(arr) - 1: 226 | if arr[i] * r == arr[j] and arr[j] * r == arr[k]: 227 | print(arr[i], arr[j], arr[k]) 228 | c += 1 229 | 230 | if k == len(arr) - 1: 231 | j += 1 232 | k = j + 1 233 | else: 234 | k += 1 235 | i += 1 236 | 237 | return c 238 | 239 | 240 | 241 | if __name__ == '__main__': 242 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 243 | 244 | nr = input().rstrip().split() 245 | 246 | n = int(nr[0]) 247 | 248 | r = int(nr[1]) 249 | 250 | arr = list(map(int, input().rstrip().split())) 251 | 252 | ans = countTriplets(arr, r) 253 | 254 | fptr.write(str(ans) + '\n') 255 | 256 | fptr.close() 257 | ``` 258 | -------------------------------------------------------------------------------- /solutions/Day_0-Hello_World.md: -------------------------------------------------------------------------------- 1 | # HackerRank - 30 Days of Python 2 | ## Day 0 : Hello, World 3 | ### Problem 4 | #### Objective 5 | In this challenge, we review some basic concepts that will get you started with this series. You will need to use the same (or similar) syntax to read input and write output in challenges throughout HackerRank. 6 | 7 | #### Task 8 | To complete this challenge, you must save a line of input from stdin to a variable, print Hello, World. on a single line, and finally print the value of your variable on a second line. 9 | 10 | 11 | #### Output Format 12 | Print `Hello, World.` on the first line, and the contents of `inputString` on the second line. 13 | 14 | 15 | #### Given Code 16 | 17 | ```python 18 | # Read a full line of input from stdin and save it to our dynamically typed variable, input_string. 19 | input_string = input() 20 | 21 | # Print a string literal saying "Hello, World." to stdout. 22 | print('Hello, World.') 23 | 24 | # TODO: Write a line of code here that prints the contents of input_string to stdout. 25 | ``` 26 | 27 | ## Solution 28 | Below you'll find two separate solutions, one with two small differences. Because [HackerRank](https://www.hackerrank.com/)'s `input` part on first line in given code does not run when running in your own text editor and terminal. When I rearranged the code in my local text editor and terminal, HackerRank gives an error. That's why you can find the code versions that work in both the HackerRank system and on the local below. 29 | 30 | ```python 31 | input_string = input() 32 | print('Hello, World.') 33 | print(input_string) 34 | ``` 35 | 36 | **Output** 37 | 38 | ``` 39 | Hello, World. 40 | Welcome to 30 Days of Code! 41 | ``` 42 | -------------------------------------------------------------------------------- /solutions/Day_10_Binary_Numbers.md: -------------------------------------------------------------------------------- 1 | # Day 10: Binary Numbers 2 | ## Problem 3 | #### Objective 4 | 5 | Today, we're working with binary numbers. 6 | 7 | #### Task 8 | Given a base-`10` integer,`n` , convert it to binary (base-`2`). Then find and print the base-`10` integer denoting the maximum number of consecutive `1`'s in `n`'s binary representation. 9 | 10 | #### Input Format 11 | A single integer, `n`. 12 | 13 | #### Constraints 14 | 1 <= N <= 106 15 | 16 | Your submission must contain a recursive function named factorial. 17 | 18 | #### Output Format 19 | Print a single base-`10` integer denoting the maximum number of consecutive `1`'s in the binary representation of `n`. 20 | 21 | 22 | #### Sample Input 1 23 | 24 | ``` 25 | 5 26 | ``` 27 | 28 | #### Sample Output 1 29 | 30 | ``` 31 | 1 32 | ``` 33 | 34 | #### Sample Input 2 35 | 36 | ``` 37 | 13 38 | ``` 39 | 40 | #### Sample Output 2 41 | 42 | ``` 43 | 2 44 | ``` 45 | 46 | #### Explanation 47 | Sample Case 1: 48 | The binary representation of `5` is `101`, so the maximum number of consecutive `1`'s is `1`. 49 | 50 | Sample Case 2: 51 | The binary representation of `13` is `1101`, so the maximum number of consecutive `1`'s is `2`. 52 | 53 | 54 | ## Given code 55 | 56 | ```python 57 | import math 58 | import os 59 | import random 60 | import re 61 | import sys 62 | 63 | 64 | 65 | if __name__ == '__main__': 66 | n = int(input()) 67 | ``` 68 | 69 | ## Solution 1 70 | 71 | ```python 72 | import math 73 | import os 74 | import random 75 | import re 76 | import sys 77 | 78 | 79 | if __name__ == '__main__': 80 | n = int(input()) 81 | 82 | def ones(n): 83 | bin_n = "" 84 | 85 | while n != 0: 86 | bin_n = str(n % 2) + bin_n 87 | n = n // 2 88 | 89 | mx = max([len(i) for i in bin_n.split("0")]) 90 | return mx 91 | 92 | print(ones(n)) 93 | ``` 94 | 95 | 96 | ## Solution 2 97 | 98 | ```python 99 | import math 100 | import os 101 | import random 102 | import re 103 | import sys 104 | 105 | 106 | if __name__ == '__main__': 107 | n = int(input()) 108 | bin_num = "" 109 | 110 | while n != 0: 111 | r = n // 2 112 | remainder = n - 2 * r 113 | bin_num = str(remainder) + bin_num 114 | n = r 115 | 116 | slice = bin_num.split("0") 117 | 118 | con = None 119 | for i in slice: 120 | if con == None: 121 | con = len(i) 122 | else: 123 | if len(i) > con : 124 | con = len(i) 125 | else : 126 | continue 127 | print(con) 128 | ``` 129 | 130 | 131 | ## Solution 3 132 | 133 | ```python 134 | import math 135 | import os 136 | import random 137 | import re 138 | import sys 139 | 140 | 141 | 142 | if __name__ == '__main__': 143 | n = int(input()) 144 | remainder = [] 145 | 146 | while n >= 1 : 147 | r = n % 2 148 | remainder.append(int(r)) 149 | n = n / 2 150 | 151 | rev = remainder[::-1] 152 | bin_num = "".join(str(x) for x in rev) 153 | 154 | slice = bin_num.split("0") 155 | 156 | con = None 157 | for i in slice: 158 | if con == None: 159 | con = len(i) 160 | else: 161 | if len(i) > con : 162 | con = len(i) 163 | else : 164 | continue 165 | print(con) 166 | ``` 167 | -------------------------------------------------------------------------------- /solutions/Day_11_2D_Arrays.md: -------------------------------------------------------------------------------- 1 | # Day 11: 2D Arrays 2 | ## Problem 3 | #### Objective 4 | 5 | Today, we're building on our knowledge of Arrays by adding another dimension. 6 | 7 | **Context** 8 | 9 | Given a 6 X 6 2D Array, `A`: 10 | 11 | ``` 12 | 1 1 1 0 0 0 13 | 0 1 0 0 0 0 14 | 1 1 1 0 0 0 15 | 0 0 0 0 0 0 16 | 0 0 0 0 0 0 17 | 0 0 0 0 0 0 18 | ``` 19 | 20 | We define an hourglass in `A`to be subset of values with indices falling in this pattern in `A`'s graphical representation : 21 | 22 | ``` 23 | a b c 24 | d 25 | e f g 26 | ``` 27 | 28 | There are 16 hourglasses in `A`, and a hourglass sum is the sum of an hourglass' values. 29 | 30 | #### Task 31 | Calculate the hourglass sum for every hourglass in `A`, then print the maximum hourglass sum. 32 | 33 | #### Input Format 34 | There are 6 lines of input, where each line contains 6 space-seperated integers describing 2D Array `A`; every value in `A` will be in the inclusive range of -9 to 9. 35 | 36 | #### Constraints 37 | 38 | * -9 <= `A[i][j]` <= 9 39 | * 0 <= `i, j` <= 5 40 | 41 | 42 | #### Output Format 43 | Print the largest (maximum) hourglass sum found in `A`. 44 | 45 | 46 | #### Sample Input 47 | 48 | ``` 49 | 1 1 1 0 0 0 50 | 0 1 0 0 0 0 51 | 1 1 1 0 0 0 52 | 0 0 2 4 4 0 53 | 0 0 0 2 0 0 54 | 0 0 1 2 4 0 55 | ``` 56 | 57 | #### Sample Output 58 | 59 | ``` 60 | 19 61 | ``` 62 | 63 | #### Explanation 64 | `A` contains the following hourglasses: 65 | 66 | ``` 67 | 1 1 1 1 1 0 1 0 0 0 0 0 68 | 1 0 0 0 69 | 1 1 1 1 1 0 1 0 0 0 0 0 70 | 71 | 0 1 0 1 0 0 0 0 0 0 0 0 72 | 1 1 0 0 73 | 0 0 2 0 2 4 2 4 4 4 4 0 74 | 75 | 1 1 1 1 1 0 1 0 0 0 0 0 76 | 0 2 4 4 77 | 0 0 0 0 0 2 0 2 0 2 0 0 78 | 79 | 0 0 2 0 2 4 2 4 4 4 4 0 80 | 0 0 2 0 81 | 0 0 1 0 1 2 1 2 4 2 4 0 82 | ``` 83 | 84 | The hourglass with the maximum sum (19) is : 85 | 86 | ``` 87 | 2 4 4 88 | 2 89 | 1 2 4 90 | ``` 91 | 92 | ## Given code 93 | 94 | ```python 95 | import math 96 | import os 97 | import random 98 | import re 99 | import sys 100 | 101 | 102 | 103 | if __name__ == '__main__': 104 | arr = [] 105 | 106 | for _ in range(6): 107 | arr.append(list(map(int, input().rstrip().split()))) 108 | ``` 109 | 110 | ## Solution 1 111 | 112 | ```python 113 | import math 114 | import os 115 | import random 116 | import re 117 | import sys 118 | 119 | 120 | 121 | if __name__ == '__main__': 122 | arr = [] 123 | 124 | for _ in range(6): 125 | arr.append(list(map(int, input().rstrip().split()))) 126 | 127 | def maxsumofhourglasses(thearray): 128 | sums = [] 129 | 130 | for x in range(len(thearray)-2): 131 | for y in range(len(thearray)-2): 132 | sums.append(sum([arr[x][y], 133 | arr[x][y+1], 134 | arr[x][y+2], 135 | arr[x+1][y+1], 136 | arr[x+2][y], 137 | arr[x+2][y+1], 138 | arr[x+2][y+2]])) 139 | 140 | return max(sums) 141 | 142 | 143 | print(maxsumofhourglasses(arr)) 144 | ``` 145 | 146 | ## Solution 2 147 | 148 | ```python 149 | import math 150 | import os 151 | import random 152 | import re 153 | import sys 154 | 155 | 156 | 157 | if __name__ == '__main__': 158 | arr = [] 159 | 160 | for _ in range(6): 161 | arr.append(list(map(int, input().rstrip().split()))) 162 | 163 | sums = [] 164 | 165 | for x in range(len(arr)-2): 166 | for y in range(len(arr)-2): 167 | sums.append(sum([arr[x][y], arr[x][y+1], arr[x][y+2], arr[x+1][y+1], arr[x+2][y], arr[x+2][y+1], arr[x+2][y+2]])) 168 | 169 | print(max(sums)) 170 | ``` 171 | 172 | 173 | 174 | ## Solution 3 175 | 176 | ```python 177 | import math 178 | import os 179 | import random 180 | import re 181 | import sys 182 | 183 | 184 | 185 | if __name__ == '__main__': 186 | arr = [] 187 | 188 | for _ in range(6): 189 | arr.append(list(map(int, input().rstrip().split()))) 190 | 191 | max_sum = None 192 | 193 | for i in range(len(arr)-2) : 194 | for n in range(len(arr)-2): 195 | lst = [arr[i][n], arr[i][n+1], arr[i][n+2], arr[i+1][n+1], arr[i+2][n], arr[i+2][n+1], arr[i+2][n+2]] 196 | if max_sum == None: 197 | max_sum = sum(lst) 198 | elif sum(lst) > max_sum: 199 | max_sum = sum(lst) 200 | else: 201 | continue 202 | 203 | print(max_sum) 204 | ``` 205 | -------------------------------------------------------------------------------- /solutions/Day_12_Inheritance.md: -------------------------------------------------------------------------------- 1 | # Day 12: Inheritance 2 | ## Problem 3 | #### Objective 4 | 5 | Today, we're delving into Inheritance. 6 | 7 | #### Task 8 | You are given two classes, `Person` and `Student`, where `Person` is the base class and `Student` is the derived class. Completed code for `Person` and a declaration for `Student` are provided for you in the editor. Observe that `Student` inherits all the properties of `Person`. 9 | 10 | Complete the `Student` class by writing the following: 11 | 12 | * A `Student` class constructor, which has 4 parameters: 13 | - A string, `firstName` 14 | - A string, `lastName` 15 | - An integer, `id` 16 | - An integer array (or vector) of test scores, `scores` 17 | * A char `calculate()` method that calculates a `Student` object's average and returns the grade character representative of their calculated average: 18 | 19 | ![](https://s3.amazonaws.com/hr-challenge-images/17165/1458142706-3073bc9143-Grading.png) 20 | 21 | 22 | #### Input Format 23 | The locked stub code in your editor calls your `Student` class constructor and passes it the necessary arguments. It also calls the calculate method (which takes no arguments). 24 | 25 | You are not responsible for reading the following inğut from stdin: 26 | 27 | The first line contains `firstName`, `lastName`, and `id`, respectively. The second line contains the number of test scores. The third line of space-separated integers describes `scores`. 28 | 29 | #### Constraints 30 | 31 | * 1 <= |`firstName`|, |`lastName`| <= 9 32 | * |`id`| ≡ 7 33 | * 0 <= `score`, `average` <= 100 34 | 35 | 36 | #### Output Format 37 | This is handled by the locked stub code in your editor. Your output will be correct if your `Student` class constructor and `calculate()` method are properly implemented. 38 | 39 | 40 | #### Sample Input 41 | 42 | ``` 43 | Heraldo Memelli 8135627 44 | 2 45 | 100 80 46 | ``` 47 | 48 | #### Sample Output 49 | 50 | ``` 51 | Name : Memelli, Heraldo 52 | ID: 8135627 53 | Grade: 0 54 | ``` 55 | 56 | #### Explanation 57 | This student had 2 scores to average : 100 and 80. The student's averagre grade is (100 + 80)/2 = 90. An average grade of 90 corresponds to the letter grade `O`, so our `calculate()` method should return the character `'O'` 58 | 59 | ## Given code 60 | 61 | ```python 62 | class Person: 63 | def __init__(self, firstName, lastName, idNumber): 64 | self.firstName = firstName 65 | self.lastName = lastName 66 | self.idNumber = idNumber 67 | def printPerson(self): 68 | print("Name:", self.lastName + ",", self.firstName) 69 | print("ID:", self.idNumber) 70 | 71 | class Student(Person): 72 | # Class Constructor 73 | # 74 | # Parameters: 75 | # firstName - A string denoting the Person's first name. 76 | # lastName - A string denoting the Person's last name. 77 | # id - An integer denoting the Person's ID number. 78 | # scores - An array of integers denoting the Person's test scores. 79 | # 80 | # Write your constructor here 81 | 82 | 83 | # Function Name: calculate 84 | # Return: A character denoting the grade. 85 | # 86 | # Write your function here 87 | 88 | line = input().split() 89 | firstName = line[0] 90 | lastName = line[1] 91 | idNum = line[2] 92 | numScores = int(input()) # not needed for Python 93 | scores = list( map(int, input().split()) ) 94 | s = Student(firstName, lastName, idNum, scores) 95 | s.printPerson() 96 | print("Grade:", s.calculate()) 97 | ``` 98 | 99 | ## Solution 100 | 101 | ```python 102 | class Person: 103 | def __init__(self, firstName, lastName, idNumber): 104 | self.firstName = firstName 105 | self.lastName = lastName 106 | self.idNumber = idNumber 107 | def printPerson(self): 108 | print("Name:", self.lastName + ",", self.firstName) 109 | print("ID:", self.idNumber) 110 | 111 | class Student(Person): 112 | 113 | def __init__(self, firstName, lastName, idNum, scores): 114 | Person.__init__(self, firstName, lastName, idNum) 115 | self.scores = scores 116 | 117 | def calculate(self): 118 | a = sum(scores) / len(scores) 119 | if 90 <= a <= 100: 120 | return "O" 121 | elif 80 <= a < 90: 122 | return "E" 123 | elif 70 <= a < 90: 124 | return "A" 125 | elif 55 <= a < 70: 126 | return "P" 127 | elif 40 <= a < 55: 128 | return "D" 129 | else: 130 | return "T" 131 | 132 | line = input().split() 133 | firstName = line[0] 134 | lastName = line[1] 135 | idNum = line[2] 136 | numScores = int(input()) # not needed for Python 137 | scores = list( map(int, input().split()) ) 138 | s = Student(firstName, lastName, idNum, scores) 139 | s.printPerson() 140 | print("Grade:", s.calculate()) 141 | 142 | ``` 143 | -------------------------------------------------------------------------------- /solutions/Day_13_Abstract_Classes.md: -------------------------------------------------------------------------------- 1 | # Day 13: Abstract Classes 2 | ## Problem 3 | #### Objective 4 | 5 | Today, we're taking what we learned yesterday about Inheritance and extending it to Abstract Classes. Because this is a very specific Object-Oriented concept, submissions are limited to the few languages that use this construct. 6 | 7 | #### Task 8 | Given a `Book` class and a `Solution` class, write a `MyBook` class that does the following: 9 | 10 | * Inherits from `Book` 11 | * Has a parameterized constructor taking these 3 parameters: 12 | - string `title` 13 | - string `author` 14 | - int `price` 15 | * Implements the `Book` class' abstract `display()` method so it prints these 3 lines : 16 | - "Title:", a space, and then the current instance's `title` 17 | - "Author:", a space, and then the current instance's `author` 18 | - "Price:", a space, and then the current instance's `price` 19 | 20 | **Note** : Because these classes are being written in the same file, you must not use an access modifier (e.g. "public") when declaring `MyBook` or your code will not execute. 21 | 22 | #### Input Format 23 | You are not responsible for reading any input from stdin. The `Solution` class creates a `Book` object and calls the `MyBook` class constructor (passing it the necessary arguments). It then calls the display method on the `Book` object. 24 | 25 | 26 | #### Output Format 27 | The `void display()` method should print and label the respective `title`, `author`, and `price` of the `MyBook` object's instance (with each value on its own line) like so: 28 | 29 | ``` 30 | Title: $title 31 | Author: $author 32 | Price: $price 33 | ``` 34 | 35 | **Note**: The $ is prepended to variable names to indicate they are placeholders for variables. 36 | 37 | #### Sample Input 38 | The following input from stdin is handled by the locked stub code in your editor: 39 | 40 | ``` 41 | The Alchemist 42 | Paulo Coelho 43 | 248 44 | ``` 45 | 46 | #### Sample Output 47 | 48 | The following output is printed by your `display()` method: 49 | 50 | ``` 51 | Title: The Alchemist 52 | Author: Paulo Coelho 53 | Price: 248 54 | ``` 55 | 56 | 57 | ## Given code 58 | 59 | ```python 60 | from abc import ABCMeta, abstractmethod 61 | class Book(object, metaclass=ABCMeta): 62 | def __init__(self,title,author): 63 | self.title=title 64 | self.author=author 65 | @abstractmethod 66 | def display(): pass 67 | 68 | #Write MyBook class 69 | 70 | title=input() 71 | author=input() 72 | price=int(input()) 73 | new_novel=MyBook(title,author,price) 74 | new_novel.display() 75 | ``` 76 | 77 | ## Solution 78 | 79 | ```python 80 | from abc import ABCMeta, abstractmethod 81 | 82 | class Book(object, metaclass=ABCMeta): 83 | def __init__(self,title,author): 84 | self.title=title 85 | self.author=author 86 | @abstractmethod 87 | def display(): pass 88 | 89 | #Write MyBook class 90 | class MyBook(Book): 91 | def __init__(self, title, author, price): 92 | Book.__init__(self, title, author) 93 | self.price = price 94 | 95 | def display(self): 96 | print("Title:", title) 97 | print("Author:", author) 98 | print("Price:", price) 99 | 100 | title=input() 101 | author=input() 102 | price=int(input()) 103 | new_novel=MyBook(title,author,price) 104 | new_novel.display() 105 | ``` 106 | -------------------------------------------------------------------------------- /solutions/Day_14-Scope.md: -------------------------------------------------------------------------------- 1 | # Day 14: Scope 2 | ## Problem 3 | #### Objective 4 | 5 | Today, we're discussing scope. 6 | 7 | The absolute difference between two integers, `a` and `b`, is written as `|a-b|`. The maximum absolute difference between two integers in a set of positive integers, `elements`, is the largest absolute difference between any two integers in `eşements`. 8 | 9 | #### Task 10 | Complete the `Difference` class by writing the following : 11 | 12 | - A class constructor that takes an array of integers as a parameter and saves it to the `elements` instance variable. 13 | - A `computeDifference` method that finds the maximum absolute difference between any 2 numbers in `N` and stores it in the `maximumDifference` instance variable. 14 | 15 | 16 | #### Input Format 17 | You are not responsible for reading any input from stdin. The locked `Solution` class in your ediyor reads in 2 lines of input; the first line contains `N`, and the secon line describes the `elements` array. 18 | 19 | 20 | #### Constraints 21 | 22 | * a <= `N` <= 10 23 | * a <= `elements[i]` <= 100, where 0 <= `i` <= `N`-1 24 | 25 | 26 | #### Output Format 27 | You are not responsible for printing any output; the `Solution` class will print the value of the `maximumDifference` instance variable. 28 | 29 | 30 | 31 | #### Sample Input 32 | 33 | 34 | ``` 35 | 3 36 | 1 2 5 37 | ``` 38 | 39 | #### Sample Output 40 | 41 | 42 | ``` 43 | 4 44 | ``` 45 | 46 | 47 | #### Explanation 48 | 49 | The scope of the `elements` array and `maximumDifference` integer is the entire class instance. The class constructor saves the argument passed to the constructor as the `elements` instance variable (where the `computeDifference` method can access it.) 50 | 51 | To find the maximu difference, `computeDifference` chechs each element in the array and finds the maximum difference between any 2 elements: 52 | 53 | |1-2| = 1
54 | |1-5| = 4
55 | |2-5| = 3
56 | 57 | The maximum of these differences is 4, so it saves the value `4` as the `maximumDifference` instance variable. The locked stub code in the editor then prints the value stored as `maximumDifference`, whics is 4. 58 | 59 | 60 | ## Given code 61 | 62 | ```python 63 | class Difference: 64 | def __init__(self, a): 65 | self.__elements = a 66 | 67 | # Add your code here 68 | 69 | # End of Difference class 70 | 71 | _ = input() 72 | a = [int(e) for e in input().split(' ')] 73 | 74 | d = Difference(a) 75 | d.computeDifference() 76 | 77 | print(d.maximumDifference) 78 | ``` 79 | 80 | ## Solution 81 | 82 | ```python 83 | class Difference: 84 | def __init__(self, a): 85 | self.__elements = a 86 | self.maximumDifference = None 87 | 88 | def computeDifference(self): 89 | a_len = len(a) 90 | for i in a: 91 | for n in range(a_len): 92 | num = abs(i - a[n]) 93 | if self.maximumDifference == None: 94 | self.maximumDifference = num 95 | elif num > self.maximumDifference: 96 | self.maximumDifference = num 97 | return self.maximumDifference 98 | 99 | _ = input() 100 | a = [int(e) for e in input().split(' ')] 101 | print(a) 102 | 103 | d = Difference(a) 104 | d.computeDifference() 105 | 106 | print(d.maximumDifference) 107 | ``` 108 | -------------------------------------------------------------------------------- /solutions/Day_15_Linked_List.md: -------------------------------------------------------------------------------- 1 | # Day 15: Linked List 2 | ## Problem 3 | #### Objective 4 | 5 | Today we're working with Linked Lists. 6 | 7 | A `Node` class is provided for you in the editor. A `Node` object has an integer data field, `data`, and a Node instance pointer, `next`, pointing to another node (i.e.: the next node in a list). 8 | 9 | A Node `insert` function is also declared in your editor. It has two parameters: a pointer, `head`, pointing to the first node of a linked list, and an integer `data` value that must be added to the end of the list as a new Node object. 10 | 11 | 12 | #### Task 13 | 14 | Complete the insert function in your editor so that it creates a new Node (pass `data` as the Node constructor argument) and inserts it at the tail of the linked list referenced by the `head` parameter. Once the new node is added, return the reference to the `head` node. 15 | 16 | Note: If the `head` argument passed to the insert function is null, then the initial list is empty. 17 | 18 | 19 | #### Input Format 20 | 21 | The insert function has 2 parameters: a pointer to a Node named `head`, and an integer value, `data`. 22 | The constructor for Node has 1 parameter: an integer value for the `data` field. 23 | 24 | You do not need to read anything from stdin. 25 | 26 | 27 | #### Output Format 28 | 29 | Your insert function should return a reference to the `head` node of the linked list. 30 | 31 | #### Sample Input 32 | 33 | The following input is handled for you by the locked code in the editor: 34 | The first line contains `T`, the number of test cases. 35 | The `T` subsequent lines of test cases each contain an integer to be inserted at the list's tail. 36 | 37 | 38 | ``` 39 | 4 40 | 2 41 | 3 42 | 4 43 | 1 44 | ``` 45 | 46 | #### Sample Output 47 | 48 | The locked code in your editor prints the ordered data values for each element in your list as a single line of space-separated integers: 49 | 50 | ``` 51 | 2 3 4 1 52 | ``` 53 | 54 | 55 | #### Explanation 56 | 57 | 58 | `T = 4`, so the locked code in the editor will be inserting `4` nodes. 59 | 60 | The list is initially empty, so `head` is null; accounting for this, our code returns a new node containing the data value `2` as the `head` of our list. We then create and insert nodes `3`, `4`, `1` and at the tail of our list. The resulting list returned by the last call to `insert` is `[2,3,4,1]`, so the printed output is `2 3 4 1`. 61 | 62 | 63 | ![](https://s3.amazonaws.com/hr-challenge-images/17168/1456961238-28488bfa0d-LinkedListExplanation.png) 64 | 65 | 66 | ## Given code 67 | 68 | ```python 69 | class Node: 70 | def __init__(self,data): 71 | self.data = data 72 | self.next = None 73 | class Solution: 74 | def display(self,head): 75 | current = head 76 | while current: 77 | print(current.data,end=' ') 78 | current = current.next 79 | 80 | def insert(self,head,data): 81 | #Complete this method 82 | 83 | mylist= Solution() 84 | T=int(input()) 85 | head=None 86 | for i in range(T): 87 | data=int(input()) 88 | head=mylist.insert(head,data) 89 | mylist.display(head); 90 | ``` 91 | 92 | 93 | 94 | ## Solution 95 | 96 | ```python 97 | class Node: 98 | def __init__(self,data): 99 | self.data = data 100 | self.next = None 101 | 102 | class Solution: 103 | def display(self,head): 104 | current = head 105 | while current: 106 | print(current.data,end=' ') 107 | current = current.next 108 | 109 | def insert(self,head,data): 110 | node = Node(data) 111 | if head == None: 112 | head = node 113 | else: 114 | current = head 115 | while(current.next is not None): 116 | current = current.next 117 | current.next = node 118 | return head 119 | 120 | 121 | 122 | mylist= Solution() 123 | T=int(input()) 124 | head=None 125 | for i in range(T): 126 | data=int(input()) 127 | head=mylist.insert(head,data) 128 | mylist.display(head); 129 | ``` 130 | -------------------------------------------------------------------------------- /solutions/Day_16_Exceptions_String_to_Integer.md: -------------------------------------------------------------------------------- 1 | # Day 16: Exceptions - String to Integer 2 | ## Problem 3 | #### Objective 4 | 5 | Today, we're getting started with Exceptions by learning how to parse an integer from a string and print a custom error message. 6 | 7 | 8 | #### Task 9 | 10 | Read a string, `S` , and print its integer value; if `S` cannot be converted to an integer, print `Bad String`. 11 | 12 | Note: You must use the String-to-Integer and exception handling constructs built into your submission language. If you attempt to use loops/conditional statements, you will get a `0` score. 13 | 14 | #### Input Format 15 | 16 | A single string, `S` . 17 | 18 | 19 | #### Constraints 20 | 21 | * 1 <= |S| <= 6 where |S| is the length of string `S` 22 | * `S` is composed of either lowercase letters `(a-z)` or decimal digits `(0-9)` 23 | 24 | #### Output Format 25 | 26 | Print the parsed integer value of `S`, or `Bad String` if `S` cannot be converted to an integer. 27 | 28 | #### Sample Input 0 29 | 30 | 31 | ``` 32 | 3 33 | ``` 34 | 35 | #### Sample Output 0 36 | 37 | 38 | ``` 39 | 2 40 | ``` 41 | 42 | #### Sample Input 1 43 | 44 | 45 | ``` 46 | za 47 | ``` 48 | 49 | #### Sample Output 1 50 | 51 | 52 | ``` 53 | Bad String 54 | ``` 55 | 56 | #### Explanation 57 | 58 | 59 | Sample Case `0` contains an integer, so it should not raise an exception when we attempt to convert it to an integer. Thus, we print the `3`. 60 | 61 | Sample Case `1` does not contain any integers, so an attempt to convert it to an integer will raise an exception. Thus, our exception handler prints `Bad String`. 62 | 63 | 64 | ## Given code 65 | 66 | ```python 67 | import sys 68 | 69 | S = input().strip() 70 | ``` 71 | 72 | 73 | 74 | ## Solution 75 | 76 | ```python 77 | import sys 78 | 79 | S = input().strip() 80 | 81 | try: 82 | print(int(S)) 83 | except ValueError: 84 | print("Bad String") 85 | ``` 86 | -------------------------------------------------------------------------------- /solutions/Day_17_More_Exceptions.md: -------------------------------------------------------------------------------- 1 | # Day 17 : More Exceptions 2 | ## Problem 3 | #### Objective 4 | 5 | Yesterday's challenge taught you to manage exceptional situations by using try and catch blocks. In today's challenge, you're going to practice throwing and propagating an exception. 6 | 7 | 8 | #### Task 9 | 10 | Write a `Calculator` class with a single method: `int power(int,int)`. The power method takes two integers `n` and `p`, as parameters and returns the integer result of ***np***. If either `n` or `p` is negative, then the method must throw an exception with the message : `n and p should be non-negative`. 11 | 12 | Note : Do not use an access modifier (e.g.: public) in the declaration for your `Calculator` class. 13 | 14 | #### Input Format 15 | 16 | Input from stdin is handled for you by the locked stub code in your code editor. The first line contains an integer, `T`, the number of test cases. Each of `T` subsequent lines describes a test case in 2 space-separated integers denoting `n` and `p`, respectively. 17 | 18 | 19 | #### Constraints 20 | 21 | No Test Case will result in overflow for correctly written code. 22 | 23 | 24 | #### Output Format 25 | 26 | Output to stdout is handled for you by the locked stub code in your editor. There are `T` lines of output, where each line contains the result of ***np*** as calculated by your `Calculator` class' power method. 27 | 28 | #### Sample Input 29 | 30 | 31 | ``` 32 | 4 33 | 3 5 34 | 2 4 35 | -1 -2 36 | -1 3 37 | ``` 38 | 39 | #### Sample Output 40 | 41 | 42 | ``` 43 | 243 44 | 16 45 | n and p should be non-negative 46 | n and p should be non-negative 47 | ``` 48 | 49 | 50 | #### Explanation 51 | 52 | `T = 4` 53 | 54 | ***T0*** : `3` and `5` are positive so power returns the result of ***33*** which is `243` 55 | 56 | ***T1*** : `2` and `4` are positive so power returns the result of ***24*** which is `16` 57 | 58 | ***T2*** : Both inputs, `-1` and `-2` are negative, so power throws an exception `n and p should be non-negative` is printed. 59 | 60 | ***T3*** : One of the inputs `-1` is negative, so power throws an exception `n and p should be non-negative` is printed. 61 | 62 | 63 | ## Given code 64 | 65 | ```python 66 | #Write your code here 67 | 68 | myCalculator=Calculator() 69 | T=int(input()) 70 | for i in range(T): 71 | n,p = map(int, input().split()) 72 | try: 73 | ans=myCalculator.power(n,p) 74 | print(ans) 75 | except Exception as e: 76 | print(e) 77 | ``` 78 | 79 | 80 | 81 | ## Solution 82 | 83 | 84 | ```python 85 | class Calculator: 86 | 87 | def power(self, n, p): 88 | if n < 0 or p < 0: 89 | raise Exception("n and p should be non-negative") 90 | else: 91 | return n**p 92 | 93 | myCalculator=Calculator() 94 | T=int(input()) 95 | for i in range(T): 96 | n,p = map(int, input().split()) 97 | try: 98 | ans=myCalculator.power(n,p) 99 | print(ans) 100 | except Exception as e: 101 | print(e) 102 | ``` 103 | -------------------------------------------------------------------------------- /solutions/Day_19_Interfaces.md: -------------------------------------------------------------------------------- 1 | # Day 19 : Interfaces 2 | ## Problem 3 | #### Objective 4 | 5 | Today, we're learning about Interfaces. 6 | 7 | #### Task 8 | 9 | The `AdvancedArithmetic` interface and the method declaration for the abstract `divisorSum(n)` method are provided for you in the editor below. 10 | 11 | Complete the implementation of `Calculator` class, which implements the `AdvancedArithmetic` interface. The implementation for the `divisorSum(n)` method must return the sum of all divisors of `n`. 12 | 13 | #### Input Format 14 | 15 | A single line containing an integer, `n`. 16 | 17 | 18 | #### Constraints 19 | 20 | 1 <= `n` <= 1000 21 | 22 | 23 | #### Output Format 24 | 25 | You are not responsible for printing anything to stdout. The locked template code in the editor below will call you code and print the necessary output. 26 | 27 | #### Sample Input 28 | 29 | 30 | ``` 31 | 6 32 | ``` 33 | 34 | #### Sample Output 35 | 36 | 37 | ``` 38 | I implemented: AdvancedArithmetic 39 | 12 40 | ``` 41 | 42 | 43 | #### Explanation 44 | 45 | The integer `6` is evenly divisible by `1`, `2`, `3` and `6`. Our `divisorSum` method should return the sum of these numbers, which is `1 + 2 + 3 + 6 = 12`. The `Solution` class then prints `I implemented: AdvancedArithmetic` on the first line, followed by the sum returned by `divisorSum` which is `12`, on the second line. 46 | 47 | 48 | ## Given code 49 | 50 | ```python 51 | class AdvancedArithmetic(object): 52 | def divisorSum(n): 53 | raise NotImplementedError 54 | 55 | class Calculator(AdvancedArithmetic): 56 | def divisorSum(self, n): 57 | pass 58 | 59 | 60 | n = int(input()) 61 | my_calculator = Calculator() 62 | s = my_calculator.divisorSum(n) 63 | print("I implemented: " + type(my_calculator).__bases__[0].__name__) 64 | print(s) 65 | ``` 66 | 67 | 68 | 69 | ## Solution 70 | 71 | 72 | ```python 73 | class AdvancedArithmetic(object): 74 | def divisorSum(n): 75 | raise NotImplementedError 76 | 77 | class Calculator(AdvancedArithmetic): 78 | def divisorSum(self, n): 79 | return sum([num for num in range(1, n+1) if n % num == 0]) 80 | 81 | 82 | n = int(input()) 83 | my_calculator = Calculator() 84 | s = my_calculator.divisorSum(n) 85 | print("I implemented: " + type(my_calculator).__bases__[0].__name__) 86 | print(s) 87 | ``` 88 | -------------------------------------------------------------------------------- /solutions/Day_1_Data_Types.md: -------------------------------------------------------------------------------- 1 | # Day 1 : Data Types 2 | ## Problem 3 | #### Objective 4 | Today, we're discussing data types. 5 | 6 | #### Task 7 | Complete the code in the editor below. The variables `i`,`d` , and `s` are already declared and initialized for you. You must: 8 | 9 | 1. Declare 3 variables: one of type `int`, one of type `double`, and one of type `String`. 10 | 11 | 2. Read 3 lines of input from stdin (according to the sequence given in the `Input Format` section below) and initialize your 3 variables. 12 | 13 | 3. Use the + operator to perform the following operations: 14 | * Print the sum of `i` plus your int variable on a new line. 15 | * Print the sum of `d` plus your double variable to a scale of one decimal place on a new line. 16 | * Concatenate `s` with the string you read as input and print the result on a new line. 17 | 18 | #### Input Format 19 | The first line contains an integer that you must sum with `i`. 20 | 21 | The second line contains a double that you must sum with `d`. 22 | 23 | The third line contains a string that you must concatenate with `s`. 24 | 25 | #### Output Format 26 | Print the sum of both integers on the first line, the sum of both doubles (scaled to 1 decimal place) on the second line, and then the two concatenated strings on the third line. 27 | 28 | ``` 29 | Sample Input 30 | 12 31 | 4.0 32 | is the best place to learn and practice coding! 33 | ``` 34 | 35 | ``` 36 | 16 37 | 8.0 38 | HackerRank is the best place to learn and practice coding! 39 | ``` 40 | 41 | #### Explanation 42 | When we sum the integers 4 and 12, we get the integer 16. 43 | 44 | When we sum the floating-point numbers 4.0 and 4.0, we get 8.0. 45 | 46 | When we concatenate `HackerRank` with `is the best place to learn and practice coding!`, we get `HackerRank is the best place to learn and practice coding!.` 47 | 48 |
49 | 50 | --- 51 | 52 |
53 | 54 | ## Given Code 55 | 56 | ```python 57 | i = 4 58 | d = 4.0 59 | s = 'HackerRank ' 60 | # Declare second integer, double, and String variables. 61 | 62 | # Read and save an integer, double, and String to your variables. 63 | 64 | # Print the sum of both integer variables on a new line. 65 | 66 | # Print the sum of the double variables on a new line. 67 | 68 | # Concatenate and print the String variables on a new line 69 | # The 's' variable above should be printed first. 70 | ``` 71 | 72 | ## Solution 73 | 74 | ```python 75 | i = 4 76 | d = 4.0 77 | s = 'HackerRank ' 78 | 79 | n = int(input()) 80 | f = float(input()) 81 | s = input() 82 | 83 | print(i + n) 84 | print(d + f) 85 | print(s + s) 86 | ``` 87 | 88 | 89 |
90 | 91 | --- 92 | 93 |
94 | 95 | 96 | ## Test Cases 97 | 98 | **Input 1** 99 | 100 | ``` 101 | 12 102 | 4.0 103 | is the best place to learn and practice coding! 104 | ``` 105 | 106 | **Output 1** 107 | 108 | ``` 109 | 16 110 | 8.0 111 | is the best place to learn and practice coding!is the best place to learn and practice coding! 112 | ``` 113 | 114 |

115 | 116 | **Input 2** 117 | 118 | ``` 119 | 3 120 | 2.8 121 | is my favorite platform! 122 | ``` 123 | 124 | **Output 2** 125 | 126 | ``` 127 | 7 128 | 6.8 129 | is my favorite platform!is my favorite platform! 130 | ``` 131 | -------------------------------------------------------------------------------- /solutions/Day_20_Sorting.md: -------------------------------------------------------------------------------- 1 | # Day 20: Sorting 2 | ## Problem 3 | #### Objective 4 | 5 | Today, we're discussing a simple sorting algorithm called Bubble Sort. 6 | 7 | Consider the following version of Bubble Sort: 8 | 9 | ```java 10 | for (int i = 0; i < n; i++) { 11 | // Track number of elements swapped during a single array traversal 12 | int numberOfSwaps = 0; 13 | 14 | for (int j = 0; j < n - 1; j++) { 15 | // Swap adjacent elements if they are in decreasing order 16 | if (a[j] > a[j + 1]) { 17 | swap(a[j], a[j + 1]); 18 | numberOfSwaps++; 19 | } 20 | } 21 | 22 | // If no elements were swapped during a traversal, array is sorted 23 | if (numberOfSwaps == 0) { 24 | break; 25 | } 26 | } 27 | ``` 28 | 29 | #### Task 30 | 31 | Given an array, `a`, of size `n` distinct elements, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following 3 lines : 32 | 33 | 1. `Array is sorted in numSwaps swaps.` where `numSwaps` is the number of swaps that took place 34 | 2. `First Element: firstElement` where `firstElement` is the first element in the sorted array 35 | 3. `Last Element: lastElement` where `lastElement` is the last element in the sorted array 36 | 37 | ***Hint***: To complete this challenge, you will need to add a variable that keeps a running tally of all swaps that occur during execution. 38 | 39 | 40 | #### Input Format 41 | 42 | The first line contains an integer, `n`, denoting the number of elements in array `a`. 43 | 44 | The second line contains `n` space-separated integers describing the respective values of *a0, a1, ..., an-1*. 45 | 46 | 47 | #### Constraints 48 | 49 | 2 <= `n` <= 600 50 | 51 | 1 <= `a`i <= 2 x 106 , where 0 <= `i` <= `n` 52 | 53 | 54 | #### Output Format 55 | 56 | Print the following three lines of output : 57 | 58 | 1. `Array is sorted in numSwaps swaps.` where `numSwaps` is the number of swaps that took place 59 | 2. `First Element: firstElement` where `firstElement` is the first element in the sorted array 60 | 3. `Last Element: lastElement` where `lastElement` is the last element in the sorted array 61 | 62 | #### Sample Input 0 63 | 64 | 65 | ``` 66 | 3 67 | 1 2 3 68 | ``` 69 | 70 | #### Sample Output 0 71 | 72 | 73 | ``` 74 | Array is sorted in 0 swaps. 75 | First Element: 1 76 | Last Element: 3 77 | ``` 78 | 79 | #### Explanation 80 | 81 | The array is already sorted, so `0` swaps take place and we print the necessary `3` lines of output shown above. 82 | 83 | 84 | #### Sample Input 1 85 | 86 | 87 | ``` 88 | 3 89 | 3 2 1 90 | ``` 91 | 92 | #### Sample Output 1 93 | 94 | 95 | ``` 96 | Array is sorted in 3 swaps. 97 | First Element: 1 98 | Last Element: 3 99 | ``` 100 | 101 | 102 | #### Explanation 1 103 | 104 | The array `a = |3,2,1|` is not sorted, so we perform the following 3 swaps 105 | 106 | 1. `|3,2,1|` -> `|2,3,1|` 107 | 2. `|2,3,1|` -> `|2,1,3|` 108 | 3. `|2,1,3|` -> `|1,2,3|` 109 | 110 | At this point the array is sorted and we print the necessary 3 lines of output shown above. 111 | 112 | 113 | ## Given code 114 | 115 | ```python 116 | import sys 117 | 118 | n = int(input().strip()) 119 | a = list(map(int, input().strip().split(' '))) 120 | # Write Your Code Here 121 | ``` 122 | 123 | 124 | 125 | ## Solution 126 | 127 | 128 | ```python 129 | import sys 130 | 131 | n = int(input().strip()) 132 | a = list(map(int, input().strip().split(' '))) 133 | 134 | numSwaps = 0 135 | 136 | for x in range(n): 137 | swaps = 0 138 | for y in range(n-1): 139 | if a[y] > a[y+1]: 140 | temp = a[y] 141 | a[y] = a[y+1] 142 | a[y+1] = temp 143 | swaps += 1 144 | numSwaps += swaps 145 | 146 | if swaps == 0: 147 | break 148 | 149 | 150 | firstElement = a[0] 151 | lastElement = a[n-1] 152 | 153 | print(f"Array is sorted in {numSwaps} swaps.") 154 | print(f"First Element: {firstElement}") 155 | print(f"Last Element: {lastElement}") 156 | ``` 157 | -------------------------------------------------------------------------------- /solutions/Day_22_Binary_Search_Trees.md: -------------------------------------------------------------------------------- 1 | # Day 22: Binary Search Trees 2 | ## Problem 3 | #### Objective 4 | 5 | Today, we're working with Binary Search Trees (BSTs). 6 | 7 |
8 | 9 | #### Task 10 | 11 | The height of a binary search tree is the number of edges between the tree's root and furthest leaf. You are given a pointer, `root`, pointing to the root of a binary search tree. Complete the `getHeight` function provided in your editor so that it returns the height of the binary search tree. 12 | 13 |
14 | 15 | #### Input Format 16 | 17 | The locked stub code in your editor reads the following inputs and assembles them into a binary search tree: 18 | 19 | - The first line contains an integer, `n`, denoting the number of nodes in the three. 20 | - Each of the `n` subsequent lines contains an integer, `data`, denoting the value of an element that must be added to the BST. 21 | 22 |
23 | 24 | #### Output Format 25 | 26 | The locked stub code in your editor will print the integer returned by your `getHeight` function denoting the height of the BST. 27 | 28 |
29 | 30 | #### Sample Input 31 | 32 | 33 | ``` 34 | 7 35 | 3 36 | 5 37 | 2 38 | 1 39 | 4 40 | 6 41 | 7 42 | ``` 43 | 44 |
45 | 46 | #### Sample Output 47 | 48 | 49 | ``` 50 | 3 51 | ``` 52 | 53 |
54 | 55 | #### Explanation 56 | 57 | 58 | The input forms the following BST: 59 | 60 | ![](https://s3.amazonaws.com/hr-challenge-images/17175/1459894869-6bb53ce6eb-BST.png) 61 | 62 | 63 | The longest root-to-leaf path is shown below: 64 | 65 | ![](https://s3.amazonaws.com/hr-challenge-images/17175/1459895368-4955f9ce74-LongestRTL.png) 66 | 67 | 68 | There are 4 nodes in this path that are connected by 3 edges, meaning our BST's `height = 3`. Thus, we print `3` as our answer. 69 | 70 |
71 | 72 | ## Given code 73 | 74 | ```python 75 | class Node: 76 | def __init__(self,data): 77 | self.right=self.left=None 78 | self.data = data 79 | class Solution: 80 | def insert(self,root,data): 81 | if root==None: 82 | return Node(data) 83 | else: 84 | if data<=root.data: 85 | cur=self.insert(root.left,data) 86 | root.left=cur 87 | else: 88 | cur=self.insert(root.right,data) 89 | root.right=cur 90 | return root 91 | 92 | def getHeight(self,root): 93 | #Write your code here 94 | 95 | T=int(input()) 96 | myTree=Solution() 97 | root=None 98 | for i in range(T): 99 | data=int(input()) 100 | root=myTree.insert(root,data) 101 | height=myTree.getHeight(root) 102 | print(height) 103 | ``` 104 | 105 | 106 |
107 | 108 | ## Solution 109 | 110 | 111 | ```python 112 | class Node: 113 | def __init__(self,data): 114 | self.right=self.left=None 115 | self.data = data 116 | class Solution: 117 | def insert(self,root,data): 118 | if root==None: 119 | return Node(data) 120 | else: 121 | if data<=root.data: 122 | cur=self.insert(root.left,data) 123 | root.left=cur 124 | else: 125 | cur=self.insert(root.right,data) 126 | root.right=cur 127 | return root 128 | 129 | def getHeight(self,root): 130 | if root is None: 131 | return -1 132 | left_height = self.getHeight(root.left) 133 | right_height = self.getHeight(root.right) 134 | 135 | return 1 + max(left_height, right_height) 136 | 137 | 138 | T=int(input()) 139 | myTree=Solution() 140 | root=None 141 | for i in range(T): 142 | data=int(input()) 143 | root=myTree.insert(root,data) 144 | height=myTree.getHeight(root) 145 | print(height) 146 | ``` 147 | -------------------------------------------------------------------------------- /solutions/Day_23_BST_Level_Order_Traversal.md: -------------------------------------------------------------------------------- 1 | # Day 23 : BST Level-Order Traversal 2 | ## Problem 3 | #### Objective 4 | 5 | Today, we're going to further with Binary Search Trees. 6 | 7 |
8 | 9 | #### Task 10 | 11 | A level-order traversal, also known as breadth-first search, visits each level of a tree's nodes from left to right, top to bottom. You are given a pointer, `root`, pointing to the root of a binary search tree. Complete the `levelOrder` function provided in your editor so that it prints the level-order traversal of the binary search tree. 12 | 13 | **Hint** You'll find a queue helpful in completing this challenge. 14 | 15 |
16 | 17 | #### Input Format 18 | 19 | The locked stub code in your editor reads the following inputs and assembles them into a BST: 20 | - The first line contains an integer, `T` (the number of test cases) 21 | - The `T` subsequent lines each contain an integer, `data`, denoting the value of an element that must be added to the BST. 22 | 23 |
24 | 25 | #### Output Format 26 | 27 | Print the `data` value of each node in the tree's level-order traversal as a single line of `N` space-separated integers. 28 | 29 |
30 | 31 | #### Sample Input 32 | 33 | 34 | ``` 35 | 6 36 | 3 37 | 5 38 | 4 39 | 7 40 | 2 41 | 1 42 | ``` 43 | 44 |
45 | 46 | #### Sample Output 47 | 48 | 49 | ``` 50 | 3 2 5 1 4 7 51 | ``` 52 | 53 |
54 | 55 | #### Explanation 56 | 57 | 58 | The input forms the following binary search tree: 59 | 60 | ![](https://s3.amazonaws.com/hr-challenge-images/17176/1461696188-8eddd12300-BST.png) 61 | 62 | We traverse each level of the tree from the root download, and we process the nodes at each level from left to right. The resulting level-order traversal is 3 -> 2 -> 5 -> 1 -> 4 -> 7, and we print these data values as a single line of space-separated integers. 63 | 64 | 65 |
66 | 67 | ## Given code 68 | 69 | ```python 70 | import sys 71 | 72 | class Node: 73 | def __init__(self,data): 74 | self.right=self.left=None 75 | self.data = data 76 | class Solution: 77 | def insert(self,root,data): 78 | if root==None: 79 | return Node(data) 80 | else: 81 | if data<=root.data: 82 | cur=self.insert(root.left,data) 83 | root.left=cur 84 | else: 85 | cur=self.insert(root.right,data) 86 | root.right=cur 87 | return root 88 | 89 | def levelOrder(self,root): 90 | # write your code here 91 | 92 | T=int(input()) 93 | myTree=Solution() 94 | root=None 95 | for i in range(T): 96 | data=int(input()) 97 | root=myTree.insert(root,data) 98 | myTree.levelOrder(root) 99 | ``` 100 | 101 | 102 |
103 | 104 | ## Solution 105 | 106 | 107 | ```python 108 | import sys 109 | 110 | class Node: 111 | def __init__(self,data): 112 | self.right=self.left=None 113 | self.data = data 114 | class Solution: 115 | def insert(self,root,data): 116 | if root==None: 117 | return Node(data) 118 | else: 119 | if data<=root.data: 120 | cur=self.insert(root.left,data) 121 | root.left=cur 122 | else: 123 | cur=self.insert(root.right,data) 124 | root.right=cur 125 | return root 126 | 127 | def levelOrder(self,root): 128 | tree = [] 129 | queue = [root] 130 | while queue: 131 | node = queue.pop() 132 | tree.append(node.data) 133 | if node.left: 134 | queue.insert(0, node.left) 135 | if node.right: 136 | queue.insert(0, node.right) 137 | print(" ".join([str(i) for i in tree])) 138 | 139 | T=int(input()) 140 | myTree=Solution() 141 | root=None 142 | for i in range(T): 143 | data=int(input()) 144 | root=myTree.insert(root,data) 145 | myTree.levelOrder(root) 146 | ``` 147 | -------------------------------------------------------------------------------- /solutions/Day_24_More_Linked_Lists.md: -------------------------------------------------------------------------------- 1 | # Day 24 : More Linked Lists 2 | ## Problem 3 | 4 | #### Task 5 | 6 | A Node class is provided for you in the editor. A Node object has an integer data field, `data`, and a `Node` instance pointer, `next`, pointing to another node (i.e.: the next node in a list). 7 | 8 | A `removeDuplicates` function is declared in your editor, which takes a pointer to the `head` node of a linked list as a parameter. 9 | 10 | Complete `removeDuplicates` so that it deletes any duplicate nodes from the list and returns the head of the updated list. 11 | 12 | **Note** : The `head` pointer may be `null`, indicating that the list is empty. Be sure to reset your `next` pointer when performing deletions to avoid breaking the list. 13 | 14 |
15 | 16 | #### Input Format 17 | 18 | You do not need to read any input from stdin. The following input is hadled by the locked stub code and passed to the `removeDuplicates` function : 19 | - The first line contains an integer, `N`, the number of nobes to be inserted. 20 | - The `N` subsequent lines each contains an integer describing the `data` value of a node being inserted at the list's tail. 21 | 22 | 23 |
24 | 25 | #### Constraints 26 | 27 | The data elements of the linked list argument will always be in non-decreasing order. 28 | 29 |
30 | 31 | #### Output Format 32 | 33 | Your `removeDuplicates` function should return the head of the updated linked list. The locked stub code in your editor will print the returned list to stdout. 34 | 35 |
36 | 37 | #### Sample Input 38 | 39 | 40 | ``` 41 | 6 42 | 1 43 | 2 44 | 2 45 | 3 46 | 3 47 | 4 48 | ``` 49 | 50 |
51 | 52 | #### Sample Output 53 | 54 | 55 | ``` 56 | 1 2 3 4 57 | ``` 58 | 59 |
60 | 61 | #### Explanation 62 | 63 | `N = 6`, and our non-decreasing list is `{1,2,2,3,3,4}`. The values `2` and `3` both occur twice in the list, so we remove the two duplicate nodes. We then return ur updated (ascending) list, which is `{1,2,3,4}`. 64 | 65 | 66 |
67 | 68 | ## Given code 69 | 70 | ```python 71 | class Node: 72 | def __init__(self,data): 73 | self.data = data 74 | self.next = None 75 | class Solution: 76 | def insert(self,head,data): 77 | p = Node(data) 78 | if head==None: 79 | head=p 80 | elif head.next==None: 81 | head.next=p 82 | else: 83 | start=head 84 | while(start.next!=None): 85 | start=start.next 86 | start.next=p 87 | return head 88 | def display(self,head): 89 | current = head 90 | while current: 91 | print(current.data,end=' ') 92 | current = current.next 93 | 94 | 95 | def removeDuplicates(self,head): 96 | # write your code here 97 | 98 | 99 | mylist= Solution() 100 | T=int(input()) 101 | head=None 102 | for i in range(T): 103 | data=int(input()) 104 | head=mylist.insert(head,data) 105 | head=mylist.removeDuplicates(head) 106 | mylist.display(head); 107 | ``` 108 | 109 | 110 |
111 | 112 | ## Solution 113 | 114 | 115 | ```python 116 | class Node: 117 | def __init__(self,data): 118 | self.data = data 119 | self.next = None 120 | class Solution: 121 | def insert(self,head,data): 122 | p = Node(data) 123 | if head==None: 124 | head=p 125 | elif head.next==None: 126 | head.next=p 127 | else: 128 | start=head 129 | while(start.next!=None): 130 | start=start.next 131 | start.next=p 132 | return head 133 | def display(self,head): 134 | current = head 135 | while current: 136 | print(current.data,end=' ') 137 | current = current.next 138 | 139 | 140 | def removeDuplicates(self,head): 141 | uniques = [] 142 | current = head 143 | while current: 144 | if current.data not in uniques: 145 | uniques.append(current.data) 146 | current = current.next 147 | print(*sorted(uniques)) 148 | 149 | 150 | mylist= Solution() 151 | T=int(input()) 152 | head=None 153 | for i in range(T): 154 | data=int(input()) 155 | head=mylist.insert(head,data) 156 | head=mylist.removeDuplicates(head) 157 | mylist.display(head); 158 | ``` 159 | -------------------------------------------------------------------------------- /solutions/Day_25_Running_Time_and_Complexity.md: -------------------------------------------------------------------------------- 1 | # Day 25 : Running Time and Complexity 2 | ## Problem 3 | #### Objective 4 | 5 | 6 | Today, we're learning about running time! 7 | 8 |
9 | 10 | #### Task 11 | 12 | A prime is a natural number greater than `1` that has no positive divisors other than `1` and itself. Given a number, `n`, determine and print whether it's `Prime` or `Not prime`. 13 | 14 | **Note** : If possible, try to come up with a `O(√n)` primality algorithm, or see what sort of optimizations you come up with for an `O(n)` algorithm. Be sure to check out the Editorial after submitting your code. 15 | 16 |
17 | 18 | #### Input Format 19 | 20 | The first line contains an integer, `T`, the number of test cases. 21 | 22 | Each of the `T` subsequent lines contains an integer, `n`, to be tested for primality. 23 | 24 |
25 | 26 | #### Constraints 27 | 28 | * 1 ≤ `T` ≤ 30 29 | * 1 ≤ `n` ≤ 2 x 109 30 | 31 |
32 | 33 | #### Output Format 34 | 35 | For each test case, print whether `n` is `Prime` or `Not prime` on a new line. 36 | 37 |
38 | 39 | #### Sample Input 40 | 41 | 42 | ``` 43 | 3 44 | 12 45 | 5 46 | 7 47 | ``` 48 | 49 |
50 | 51 | #### Sample Output 52 | 53 | 54 | ``` 55 | Not prime 56 | Prime 57 | Prime 58 | ``` 59 | 60 |
61 | 62 | #### Explanation 63 | 64 | Test Case 0 : `n = 12` 65 | 66 | `12` is divisible by numbers other than `1` and itself (i.e.: 2,3,6), so we print `Not prime` on a new line. 67 | 68 |
69 | 70 | Test Case 1 : `n = 5` 71 | 72 | `5` is only divisible `1` and itself, so we print `Prime` on a new line. 73 | 74 |
75 | 76 | Test Case 2 : `n = 7` 77 | 78 | `7` is only divisible `1` and itself, we print `Prime` on a new line. 79 | 80 |
81 | 82 | ## Given code 83 | 84 | ```python 85 | # Enter your code here. Read input from STDIN. Print output to STDOUT 86 | ``` 87 | 88 | 89 |
90 | 91 | ## Solution 92 | 93 | 94 | ```python 95 | def isprime(n): 96 | if n == 1: 97 | return "Not prime" 98 | else: 99 | square_root = int(n**0.5) 100 | for i in range(2, square_root + 1): 101 | if ((n % i) == 0) and (i != n): 102 | return "Not prime" 103 | return "Prime" 104 | 105 | for i in range(int(input(""))): 106 | print(isprime(int(input("")))) 107 | ``` 108 | -------------------------------------------------------------------------------- /solutions/Day_26_Nested_Logic.md: -------------------------------------------------------------------------------- 1 | # Day 26 : Nested Logic 2 | ## Problem 3 | #### Objective 4 | 5 | Today's challenge puts your understanding of nested conditional statements to the test. You already have the knowledge to cpmplete this challenge. 6 | 7 |
8 | 9 | #### Task 10 | 11 | Your local library needs your help! Given the expected and actual return dates for a library book, create a program that calculates the fine (if any). The fee structure is as follows: 12 | 13 | 1. If the book is returned on or before the expected return date, no fine will be charged (i.e.: `fine = 0`) 14 | 2. If the book is returned afted the expected return day but still within the same calendar month and year as the expected return date, `fine = 15 Hackos x (the number of days late)`. 15 | 3. If the book is returned after the expected return month but still within the same calendar year as the expected return date, the `fine = 500 Hackos x (the number of months late)`. 16 | 4. If the book is returned after the calendar year in which it was expected, there is a fixed fine of `10000 Hackos`. 17 | 18 |
19 | 20 | #### Input Format 21 | 22 | The first line contains `3` space-separated integers denoting the respective `day`, `month` and `year` on which the book was actually returned. 23 | 24 | The second line contains `3` space-separated integers denoting the respective `day`, `month` and `year` on which the book was expected to be returned (due date). 25 | 26 |
27 | 28 | #### Constraints 29 | 30 | * 1 ≤ `D` ≤ 31 31 | * 1 ≤ `M` ≤ 12 32 | * 1 ≤ `Y` ≤ 3000 33 | * It is guaranteed that the dates will be valid Gregorian calendar dates 34 | 35 |
36 | 37 | #### Output Format 38 | 39 | Print a single integer denoting the library fine for the book received as input. 40 | 41 |
42 | 43 | #### Sample Input 44 | 45 | 46 | ``` 47 | 9 6 2015 48 | 6 6 2015 49 | ``` 50 | 51 |
52 | 53 | #### Sample Output 54 | 55 | 56 | ``` 57 | 45 58 | ``` 59 | 60 |
61 | 62 | #### Explanation 63 | 64 | Given the following return dates : 65 | 66 | Actual : Da = 9, Ma = 6, Ya = 2015
67 | Expected : De = 6, Me = 6, Ye = 2015
68 | Because Ye ≡ Ya , we know it is less than a year late
69 | Because Me ≡ Ma , we know it's less than a month late
70 | Because De < Da , we know that it was returned late (but still within the same month and year)
71 | Per the library's fee structure, we know that our fine will be `15 Hackos x (# days late)`. We then print the result of 15 x (Da - De) = 15 x (9-6) = 45 as our output. 72 | 73 |
74 | 75 | ## Given code 76 | 77 | ```python 78 | # Enter your code here. Read input from STDIN. Print output to STDOUT 79 | ``` 80 | 81 | 82 |
83 | 84 | ## Solution 85 | 86 | 87 | ```python 88 | def fine(actual, expected): 89 | a_day, a_month, a_year = tuple(map(int, actual.split(" "))) 90 | e_day, e_month, e_year = tuple(map(int, expected.split(" "))) 91 | 92 | if a_year < e_year: 93 | return 0 94 | elif a_year > e_year: 95 | return 10000 96 | else: 97 | if a_month < e_month: 98 | return 0 99 | elif a_month > e_month: 100 | return 500 * abs(a_month - e_month) 101 | elif a_day < e_day: 102 | return 0 103 | elif a_day > e_day: 104 | return 15 * abs(a_day - e_day) 105 | else: 106 | return 0 107 | 108 | 109 | actual = input("") 110 | expected = input("") 111 | 112 | print(fine(actual, expected)) 113 | ``` 114 | -------------------------------------------------------------------------------- /solutions/Day_28_RegEx_Patterns_and_Intro_to_Databases.md: -------------------------------------------------------------------------------- 1 | # Day 28 : RegEx, Patterns, and Intro to Databases 2 | ## Problem 3 | #### Objective 4 | 5 | Today, we're working with regular expressions. 6 | 7 |
8 | 9 | #### Task 10 | 11 | Consider a database table, Emails, which has the attributes First Name and Email ID. Given `N` rows of data simulating the Emails table, print an alphabetically-ordered list of people whose email address ends in `@gmail.com`. 12 | 13 |
14 | 15 | #### Input Format 16 | 17 | The first line contains an integer, `N`, total number of rows in the table. 18 | 19 | Each of the `N` subsequent lines contains `2` space-separated strings denoting a person's first name and email ID, respectively. 20 | 21 |
22 | 23 | #### Constraints 24 | 25 | * 2 ≤ `N` ≤ 30 26 | * Each of the first names consists of lower case letters `[a - z]` only. 27 | * Each of the email IDs consists of lower case letters `[a - z]`, `@` and `.` only. 28 | * The lenght of the first name is no longer than 20. 29 | * The lenght of the email ID is no longer than 50. 30 | 31 | 32 |
33 | 34 | #### Output Format 35 | 36 | Print an alphabetically-ordered list of first names for every user with a gmail account. Each name must be printed on a new line. 37 | 38 |
39 | 40 | #### Sample Input 41 | 42 | 43 | ``` 44 | 6 45 | riya riya@gmail.com 46 | julia julia@julia.me 47 | julia sjulia@gmail.com 48 | julia julia@gmail.com 49 | samantha samantha@gmail.com 50 | tanya tanya@gmail.com 51 | ``` 52 | 53 |
54 | 55 | #### Sample Output 56 | 57 | 58 | ``` 59 | julia 60 | julia 61 | riya 62 | samantha 63 | tanya 64 | ``` 65 | 66 |
67 | 68 | 69 | 70 | ## Given code 71 | 72 | ```python 73 | #!/bin/python3 74 | 75 | import math 76 | import os 77 | import random 78 | import re 79 | import sys 80 | 81 | 82 | 83 | if __name__ == '__main__': 84 | N = int(input()) 85 | 86 | for N_itr in range(N): 87 | firstNameEmailID = input().split() 88 | 89 | firstName = firstNameEmailID[0] 90 | 91 | emailID = firstNameEmailID[1] 92 | ``` 93 | 94 | 95 |
96 | 97 | ## Solution 1 98 | 99 | 100 | ```python 101 | import math 102 | import os 103 | import random 104 | import re 105 | import sys 106 | 107 | 108 | 109 | if __name__ == '__main__': 110 | N = int(input()) 111 | table = [] 112 | 113 | for N_itr in range(N): 114 | firstNameEmailID = input().split() 115 | 116 | firstName = firstNameEmailID[0] 117 | 118 | emailID = firstNameEmailID[1] 119 | 120 | if firstName.isalpha() and "@gmail.com" in emailID: 121 | table.append(firstName) 122 | 123 | print("\n".join(sorted(table))) 124 | ``` 125 | 126 |
127 | 128 | ## Solution 2 129 | 130 | 131 | ```python 132 | import math 133 | import os 134 | import random 135 | import re 136 | import sys 137 | 138 | 139 | 140 | if __name__ == '__main__': 141 | N = int(input()) 142 | table = [] 143 | 144 | for N_itr in range(N): 145 | firstNameEmailID = input().split() 146 | 147 | firstName = firstNameEmailID[0] 148 | 149 | emailID = firstNameEmailID[1] 150 | 151 | if re.search(".+@gmail\.com$", emailID): 152 | table.append(firstName) 153 | 154 | table.sort() 155 | 156 | print(*table, sep="\n") 157 | ``` 158 | -------------------------------------------------------------------------------- /solutions/Day_29_Bitwise_AND.md: -------------------------------------------------------------------------------- 1 | # Day 29 : Bitwise AND 2 | ## Problem 3 | #### Objective 4 | 5 | Welcome to the last day! Today, we're discussing bitwise operations. 6 | 7 |
8 | 9 | #### Task 10 | 11 | Given set `S = {1,2,3,...,N}`. Find two integers, `A` and `B` (where `A < B`), from set `S` such that the value of `A & B` is the maximum possible and also less than a given integer, `K`. In this case, `&` represents the bitwise `AND` operator. 12 | 13 |
14 | 15 | #### Input Format 16 | 17 | The first line contains an integer, `T`, the number of test cases. 18 | 19 | Each of the `T` subsequent lines defines a test case as `2` space-separated integers, `N` and `K`, respectively. 20 | 21 |
22 | 23 | #### Constraints 24 | 25 | * 1 ≤ `T` ≤ 103 26 | * 2 ≤ `N` ≤ 103 27 | * 2 ≤ `K` ≤ `N` 28 | 29 |
30 | 31 | #### Output Format 32 | 33 | For each test case, print the maximum possible value of `A&B` on a new line. 34 | 35 |
36 | 37 | #### Sample Input 38 | 39 | 40 | ``` 41 | 3 42 | 5 2 43 | 8 5 44 | 2 2 45 | ``` 46 | 47 |
48 | 49 | #### Sample Output 50 | 51 | 52 | ``` 53 | 1 54 | 4 55 | 0 56 | ``` 57 | 58 |
59 | 60 | #### Explanation 61 | 62 | `N = 5`, `K = 2`, `S = {1,2,3,4,5}` 63 | 64 | All possible values of `A` and `B` are: 65 | 66 | 1. `A = 1`, `B = 2` ; `A & B = 0` 67 | 2. `A = 1`, `B = 3` ; `A & B = 1` 68 | 3. `A = 1`, `B = 4` ; `A & B = 0` 69 | 4. `A = 1`, `B = 5` ; `A & B = 1` 70 | 5. `A = 2`, `B = 3` ; `A & B = 2` 71 | 6. `A = 2`, `B = 4` ; `A & B = 0` 72 | 7. `A = 2`, `B = 5` ; `A & B = 0` 73 | 8. `A = 3`, `B = 4` ; `A & B = 0` 74 | 9. `A = 3`, `B = 5` ; `A & B = 1` 75 | 10. `A = 4`, `B = 5` ; `A & B = 4` 76 | 77 | 78 | The maximum possible value of `A & B` that is also `< (K = 2)` is `1`, so we print `1` on a new line. 79 | 80 |
81 | 82 | 83 | 84 | ## Given code 85 | 86 | ```python 87 | import math 88 | import os 89 | import random 90 | import re 91 | import sys 92 | 93 | 94 | 95 | if __name__ == '__main__': 96 | t = int(input()) 97 | 98 | for t_itr in range(t): 99 | nk = input().split() 100 | 101 | n = int(nk[0]) 102 | 103 | k = int(nk[1]) 104 | ``` 105 | 106 | 107 |
108 | 109 | ## Solution 110 | 111 | 112 | ```python 113 | import math 114 | import os 115 | import random 116 | import re 117 | import sys 118 | 119 | 120 | 121 | if __name__ == '__main__': 122 | t = int(input()) 123 | 124 | def find_max(n,k): 125 | mx_bit = 0 126 | for i in range(1, n+1): 127 | for j in range(1, i): 128 | bit = i & j 129 | if mx_bit < bit < k: 130 | mx_bit = bit 131 | if mx_bit == k - 1: 132 | return mx_bit 133 | return mx_bit 134 | 135 | for t_itr in range(t): 136 | nk = input().split() 137 | 138 | n = int(nk[0]) 139 | 140 | k = int(nk[1]) 141 | 142 | print(find_max(n,k)) 143 | ``` 144 | -------------------------------------------------------------------------------- /solutions/Day_2_Operators.md: -------------------------------------------------------------------------------- 1 | # Day 2 : Operators 2 | ## Problem 3 | #### Objective 4 | In this challenge, you'll work with arithmetic operators. 5 | 6 | #### Task 7 | Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal's total cost. 8 | 9 | ***Note:*** Be sure to use precise values for your calculations, or you may end up with an incorrectly rounded result! 10 | 11 | #### Input Format 12 | There are 3 lines of numeric input: 13 | The first line has a double, `mealCost` (the cost of the meal before tax and tip). 14 | The second line has an integer, `tipPercent` (the percentage of being added as tip). 15 | The third line has an integer, `taxPercent` (the percentage of being added as tax). 16 | 17 | #### Output Format 18 | Print the total meal cost, where `totalCost` is the rounded integer result of the entire bill ( `mealCost` with added tax and tip). 19 | 20 | ``` 21 | Sample Input 22 | 12.00 23 | 20 24 | 8 25 | ``` 26 | 27 | ``` 28 | Sample Output 29 | 15 30 | ``` 31 | 32 | #### Explanation 33 | **Given:** 34 | 35 | `mealCost` = 12 36 | 37 | `tipPercent` = 20 38 | 39 | `taxPercent` = 8 40 | 41 | **Calculations:** 42 | 43 | tip = 12 x 20 / 100 = 2.4 44 | tax = 12 x 8 / 100 = 0.96 45 | totalCost = mealCost + tip + tax = 12 + 2.4 + 0.96 = 15.36 46 | round(totalCost) = 15 47 | 48 | We round `totalCost` to the nearest dollar (integer) and then print our result, 15 . 49 | 50 | #### Given Code 51 | 52 | ```python 53 | import math 54 | import os 55 | import random 56 | import re 57 | import sys 58 | 59 | # Complete the solve function below. 60 | def solve(meal_cost, tip_percent, tax_percent): 61 | 62 | if __name__ == '__main__': 63 | meal_cost = float(input()) 64 | 65 | tip_percent = int(input()) 66 | 67 | tax_percent = int(input()) 68 | 69 | solve(meal_cost, tip_percent, tax_percent) 70 | ``` 71 | 72 | ## Solution 1 73 | 74 | ```python 75 | import math 76 | import os 77 | import random 78 | import re 79 | import sys 80 | 81 | # Complete the solve function below. 82 | def solve(meal_cost, tip_percent, tax_percent): 83 | tip = float(meal_cost * (tip_percent / 100)) 84 | tax = float(meal_cost * (tax_percent / 100)) 85 | totalCost = float(meal_cost) + tip + tax 86 | print(round(totalCost)) 87 | 88 | if __name__ == '__main__': 89 | meal_cost = float(input()) 90 | 91 | tip_percent = int(input()) 92 | 93 | tax_percent = int(input()) 94 | 95 | solve(meal_cost, tip_percent, tax_percent) 96 | ``` 97 | 98 | --- 99 | 100 | 101 | ## Solution 2 102 | 103 | ```python 104 | import math 105 | import os 106 | import random 107 | import re 108 | import sys 109 | 110 | # Complete the solve function below. 111 | def solve(meal_cost, tip_percent, tax_percent): 112 | tip = meal_cost * tip_percent / 100 113 | tax = meal_cost * tax_percent /100 114 | totalCost = meal_cost + tip + tax 115 | print(round(totalCost)) 116 | 117 | if __name__ == '__main__': 118 | meal_cost = float(input()) 119 | 120 | tip_percent = int(input()) 121 | 122 | tax_percent = int(input()) 123 | 124 | solve(meal_cost, tip_percent, tax_percent) 125 | ``` 126 | 127 | 128 | --- 129 | 130 | ## Solution 3 131 | 132 | ```python 133 | import math 134 | import os 135 | import random 136 | import re 137 | import sys 138 | 139 | # Complete the solve function below. 140 | def solve(meal_cost, tip_percent, tax_percent): 141 | totalCost = meal_cost + (meal_cost * tip_percent / 100) + (meal_cost * tax_percent / 100) 142 | print(round(totalCost)) 143 | 144 | if __name__ == '__main__': 145 | meal_cost = float(input()) 146 | 147 | tip_percent = int(input()) 148 | 149 | tax_percent = int(input()) 150 | 151 | solve(meal_cost, tip_percent, tax_percent) 152 | ``` 153 | 154 | 155 | --- 156 | 157 | ## Test Cases 158 | 159 | **Input 1** 160 | 161 | ``` 162 | 12 163 | 20 164 | 8 165 | ``` 166 | 167 | **Output 1** 168 | 169 | ``` 170 | 15 171 | ``` 172 | 173 |

174 | 175 | **Input 2** 176 | 177 | ``` 178 | 15.50 179 | 15 180 | 10 181 | ``` 182 | 183 | **Output 2** 184 | 185 | ``` 186 | 19 187 | ``` 188 | -------------------------------------------------------------------------------- /solutions/Day_3_Intro_to_Conditional_Statements.md: -------------------------------------------------------------------------------- 1 | # Day 3 : Intro to Conditional Statements 2 | ## Problem 3 | #### Objective 4 | In this challenge, we're getting started with conditional statements. 5 | 6 | #### Task 7 | Given an integer, `n`, perform the following conditional actions: 8 | 9 | If `n` is odd, print `Weird` 10 | 11 | If `n` is even and in the inclusive range of 2 to 5, print `Not Weird` 12 | 13 | If `n` is even and in the inclusive range of 6 to 20, print `Weird` 14 | 15 | If `n` is even and greater than 20, print `Not Weird` 16 | 17 | #### Input Format 18 | A single line containing a positive integer, `n`. 19 | 20 | #### Constraints 21 | 1 <= n <= 100 22 | 23 | #### Output Format 24 | Print `Weird` if the number is weird; otherwise, print `Not Weird`. 25 | 26 | ``` 27 | Sample Inputs 28 | 3 29 | 24 30 | ``` 31 | 32 | ``` 33 | Sample Output 34 | Weird 35 | Not Weird 36 | ``` 37 | 38 | #### Explanation 39 | Sample Case 0: n = 3 40 | 41 | `n` is odd and odd numbers are weird, so we print `Weird`. 42 | 43 | Sample Case 1: n = 24 44 | 45 | `n` and is even, so it isn't weird. Thus, we print `Not Weird`. 46 | 47 | #### Given Code 48 | 49 | ```python 50 | import math 51 | import os 52 | import random 53 | import re 54 | import sys 55 | 56 | 57 | 58 | if __name__ == '__main__': 59 | N = int(input()) 60 | ``` 61 | 62 | ## Solution 1 63 | 64 | ```python 65 | import math 66 | import os 67 | import random 68 | import re 69 | import sys 70 | 71 | 72 | if __name__ == '__main__': 73 | N = int(input()) 74 | if N % 2 == 0 and 2 < N < 5 : 75 | print("Not Weird") 76 | elif N % 2 == 0 and 6 < N < 20 : 77 | print("Weird") 78 | elif N % 2 == 0 and N > 20 : 79 | print("Not Weird") 80 | else : 81 | print("Weird") 82 | ``` 83 | 84 | 85 | ## Solution 2 86 | 87 | ```python 88 | import math 89 | import os 90 | import random 91 | import re 92 | import sys 93 | 94 | 95 | 96 | if __name__ == '__main__': 97 | N = int(input()) 98 | if N % 2 != 0: 99 | print("Weird") 100 | else: 101 | if N <= 5: 102 | print("Not Weird") 103 | elif N <= 20: 104 | print("Weird") 105 | else: 106 | print("Not Weird") 107 | ``` 108 | 109 | 110 | ## Solution 3 111 | 112 | ```python 113 | import math 114 | import os 115 | import random 116 | import re 117 | import sys 118 | 119 | 120 | 121 | if __name__ == '__main__': 122 | N = int(input()) 123 | if N % 2 != 0: 124 | print("Weird") 125 | else: 126 | if N in range(0,6): 127 | print("Not Weird") 128 | elif N in range(6,21): 129 | print("Weird") 130 | else: 131 | print("Not Weird") 132 | ``` 133 | 134 | 135 | ## Solution 4 136 | 137 | ```python 138 | import math 139 | import os 140 | import random 141 | import re 142 | import sys 143 | 144 | 145 | 146 | if __name__ == '__main__': 147 | N = int(input()) 148 | 149 | def isweird(num): 150 | if num % 2 != 0: 151 | print("Weird") 152 | else: 153 | if 2 <= num <= 5: 154 | print("Not Weird") 155 | elif 6 <= num <= 20: 156 | print("Weird") 157 | else: 158 | print("Not Weird") 159 | isweird(N) 160 | ``` 161 | -------------------------------------------------------------------------------- /solutions/Day_5_Loops.md: -------------------------------------------------------------------------------- 1 | # Day 5: Loops 2 | ## Problem 3 | #### Objective 4 | In this challenge, we're going to use loops to help us do some simple math. 5 | 6 | #### Task 7 | Given an integer,`n` , print its first 10 multiples. Each multiple `n x i` (where 1 <= i <= 10 ) should be printed on a new line in the form: n x i = result. 8 | 9 | #### Input Format 10 | A single integer, `n` . 11 | 12 | #### Constraints 13 | 2 <= n <= 20 14 | 15 | #### Output Format 16 | Print 10 lines of output; each line `i` (where 1 <= i <= 10 ) contains the `result` of `n x i` in the form: 17 | n x i = result. 18 | 19 | ``` 20 | -- Sample Input -- 21 | 2 22 | ``` 23 | 24 | ``` 25 | -- Sample Output -- 26 | 2 x 1 = 2 27 | 2 x 2 = 4 28 | 2 x 3 = 6 29 | 2 x 4 = 8 30 | 2 x 5 = 10 31 | 2 x 6 = 12 32 | 2 x 7 = 14 33 | 2 x 8 = 16 34 | 2 x 9 = 18 35 | 2 x 10 = 20 36 | ``` 37 | 38 | 39 | #### Given Code 40 | 41 | ```python 42 | import math 43 | import os 44 | import random 45 | import re 46 | import sys 47 | 48 | 49 | if __name__ == '__main__': 50 | n = int(input()) 51 | ``` 52 | 53 | ## Solution 1 54 | 55 | ```python 56 | import math 57 | import os 58 | import random 59 | import re 60 | import sys 61 | 62 | 63 | 64 | if __name__ == '__main__': 65 | n = int(input()) 66 | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 67 | 68 | for i in numbers : 69 | print(n, "x", i, "=", (n*i)) 70 | ``` 71 | 72 | 73 | ## Solution 2 74 | 75 | ```python 76 | import math 77 | import os 78 | import random 79 | import re 80 | import sys 81 | 82 | 83 | 84 | if __name__ == '__main__': 85 | n = int(input()) 86 | 87 | for i in range(1,11): 88 | result = n * i 89 | print("{} x {} = {}".format(n, i, result)) 90 | ``` 91 | 92 | 93 | ## Solution 3 94 | 95 | ```python 96 | import math 97 | import os 98 | import random 99 | import re 100 | import sys 101 | 102 | 103 | 104 | if __name__ == '__main__': 105 | n = int(input()) 106 | 107 | for i in range(1,11): 108 | print("{} x {} = {}".format(n, i, n * i)) 109 | ``` 110 | 111 | 112 | ## Solution 4 113 | 114 | ```python 115 | import math 116 | import os 117 | import random 118 | import re 119 | import sys 120 | 121 | 122 | 123 | if __name__ == '__main__': 124 | n = int(input()) 125 | 126 | def ten_multiple(n): 127 | for num in range(1,11): 128 | print("{} x {} = {}".format(n,num,n*num)) 129 | 130 | ten_multiple(n) 131 | ``` 132 | -------------------------------------------------------------------------------- /solutions/Day_6_Lets_Review.md: -------------------------------------------------------------------------------- 1 | # Day 6 : Let's Review 2 | ## Problem 3 | #### Objective 4 | Today we're expanding our knowledge of Strings and combining it with what we've already learned about loops. 5 | 6 | #### Task 7 | Given a string, `S`, of length `N` that is indexed from 0 to `N - 1`, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail). 8 | 9 | **Note:** 0 is considered to be an even index. 10 | 11 | #### Input Format 12 | The first line contains an integer, `T` (the number of test cases). 13 | Each line `i` of the `T` subsequent lines contain a String,`S`. 14 | 15 | #### Constraints 16 | 1 <= T <= 10 17 | 18 | 2 <= lenght of S <= 10000 19 | 20 | #### Output Format 21 | For each String Sj (where 0 <= j <= T - 1), print Sj's even-indexed characters, followed by a space, followed by Sj's odd-indexed characters. 22 | 23 | ``` 24 | Sample Input 25 | 2 26 | Hacker 27 | Rank 28 | ``` 29 | 30 | ``` 31 | Sample Output 32 | Hce akr 33 | Rn ak 34 | ``` 35 | 36 | #### Explanation 37 | Test Case 0: S = "Hacker" 38 | S[0] = "H" 39 | S[1] = "a" 40 | S[2] = "c" 41 | S[3] = "k" 42 | S[4] = "e" 43 | S[5] = "r" 44 | 45 | The even indices are 0, 2, and 4, and the odd indices are 1, 3, and 5. We then print a single line of 2 space-separated strings; the first string contains the ordered characters from S's even indices (Hce), and the second string contains the ordered characters from 's odd indices (akr). 46 | 47 | Test Case 1: S = "Rank" 48 | S[0] = "R" 49 | S[1] = "a" 50 | S[2] = "n" 51 | S[3] = "k" 52 | 53 | The even indices are 0 and 2, and the odd indices are 1 and 3. We then print a single line of 2 space-separated strings; the first string contains the ordered characters from S's even indices (Rn), and the second string contains the ordered characters from S's odd indices (ak). 54 | 55 | 56 | --- 57 | 58 | ## Given Code 59 | 60 | ```python 61 | # Enter your code here. Read input from STDIN. Print output to STDOUT 62 | ``` 63 | 64 | ## Solution 1 65 | 66 | ```python 67 | T = input() 68 | for N in range(int(T)): 69 | S = input() 70 | print(S[::2], S[1::2]) 71 | ``` 72 | 73 | ## Solution 2 74 | 75 | ```python 76 | inputs = int(input()) 77 | 78 | for n in range(inputs): 79 | user = input() 80 | evens = "" 81 | odds = "" 82 | 83 | i = 0 84 | 85 | for char in user: 86 | if i % 2 == 0: 87 | evens += char 88 | else: 89 | odds += char 90 | i += 1 91 | 92 | print("{} {}".format(evens,odds)) 93 | ``` 94 | 95 | 96 | ## Solution 3 97 | 98 | ```python 99 | N = int(input()) 100 | 101 | for i in range(0, N): 102 | string = input() 103 | for j in range(0, len(string)): 104 | if j % 2 == 0: 105 | print(string[j], end='') 106 | print(" ", end='') 107 | 108 | for j in range(0, len(string)): 109 | if j % 2 != 0: 110 | print(string[j], end='') 111 | print("") 112 | ``` 113 | -------------------------------------------------------------------------------- /solutions/Day_7_Arrays.md: -------------------------------------------------------------------------------- 1 | # Day 7 : Arrays 2 | ## Problem 3 | #### Objective 4 | Today, we're learning about the Array data structure. 5 | 6 | #### Task 7 | Given an array,`A` , of `N` integers, print `A`'s elements in reverse order as a single line of space-separated numbers. 8 | 9 | #### Input Format 10 | The first line contains an integer, `N` (the size of our array). 11 | The second line contains `N` space-separated integers describing array `A`'s elements 12 | 13 | #### Constraints 14 | 1 <= N <= 1000 15 | 16 | 1 <= Ai <= 10000 where Ai is the ith integer in the array 17 | 18 | #### Output Format 19 | Print the elements of array `A` in reverse order as a single line of space-separated numbers. 20 | 21 | ``` 22 | Sample Input 23 | 4 24 | 1 4 3 2 25 | ``` 26 | 27 | ``` 28 | Sample Output 29 | 2 3 4 1 30 | ``` 31 | 32 | #### Given Code 33 | 34 | ```python 35 | import math 36 | import os 37 | import random 38 | import re 39 | import sys 40 | 41 | 42 | if __name__ == '__main__': 43 | n = int(input()) 44 | 45 | arr = list(map(int, input().rstrip().split())) 46 | ``` 47 | 48 | 49 | ## Solution 1 50 | 51 | ```python 52 | import math 53 | import os 54 | import random 55 | import re 56 | import sys 57 | 58 | 59 | if __name__ == '__main__': 60 | n = int(input()) 61 | 62 | arr = list(map(int, input().rstrip().split())) 63 | print(*reversed(arr)) 64 | ``` 65 | 66 | 67 | ## Solution 2 68 | 69 | ```python 70 | import math 71 | import os 72 | import random 73 | import re 74 | import sys 75 | 76 | 77 | if __name__ == '__main__': 78 | n = int(input()) 79 | 80 | arr = list(map(int, input().rstrip().split())) 81 | print(*arr[::-1]) 82 | ``` 83 | 84 | 85 | 86 | ## Solution 3 87 | 88 | ```python 89 | import math 90 | import os 91 | import random 92 | import re 93 | import sys 94 | 95 | 96 | if __name__ == '__main__': 97 | n = int(input()) 98 | 99 | arr = list(map(int, input().rstrip().split())) 100 | rev = list() 101 | for i in reversed(arr): 102 | rev.append(i) 103 | A = " ".join(str(x) for x in rev) 104 | print(A) 105 | ``` 106 | -------------------------------------------------------------------------------- /solutions/Day_8_Dictionaries_and_Maps.md: -------------------------------------------------------------------------------- 1 | # Day 8: Dictionaries and Maps 2 | ## Problem 3 | #### Objective 4 | Today, we're learning about Key-Value pair mappings using a Map or Dictionary data structure. Check out the Tutorial tab for learning materials and an instructional video! 5 | 6 | #### Task 7 | Given `n` names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each `name` queried, print the associated entry from your phone book on a new line in the form `name=phoneNumber`; if an entry for `name` is not found, print `Not found` instead. 8 | 9 | **Note**: Your phone book should be a Dictionary/Map/HashMap data structure. 10 | 11 | #### Input Format 12 | The first line contains an integer, `n`, denoting the number of entries in the phone book. 13 | Each of the `n` subsequent lines describes an entry in the form of 2 space-separated values on a single line. The first value is a friend's name, and the second value is an 8-digit phone number. 14 | 15 | After the `n` lines of phone book entries, there are ***an unknown number of lines of queries***. Each line (query) contains a `name` to look up, and you must continue reading lines until there is no more input. 16 | 17 | **Note**: Names consist of lowercase English alphabetic letters and are first names only. 18 | 19 | #### Constraints 20 | 1 <= n <= 105 21 | 22 | 1 <= queries <= 105 23 | 24 | #### Output Format 25 | On a new line for each query, print `Not found` if the name has no corresponding entry in the phone book; otherwise, print the full `name` and `phoneNumber` in the format `name=phoneNumber`. 26 | 27 | ``` 28 | Sample Input 29 | 3 30 | sam 99912222 31 | tom 11122222 32 | harry 12299933 33 | sam 34 | edward 35 | harry 36 | ``` 37 | 38 | ``` 39 | Sample Output 40 | sam=99912222 41 | Not found 42 | harry=12299933 43 | ``` 44 | 45 | #### Explanation 46 | We add the following `n = 3` (Key,Value) pairs to our map so it looks like this: 47 | 48 | `phoneBook = {(sam, 99912222), (tom, 11122222), (harry, 12299933)}` 49 | 50 | We then process each query and print `key=value` if the queried `key` is found in the map; otherwise, we print `Not found`. 51 | 52 | Query 0: sam 53 | Sam is one of the keys in our dictionary, so we print sam=99912222. 54 | 55 | Query 1: edward 56 | Edward is not one of the keys in our dictionary, so we print Not found. 57 | 58 | Query 2: harry 59 | Harry is one of the keys in our dictionary, so we print harry=12299933. 60 | 61 | 62 | ## Solution 1 63 | 64 | ```python 65 | phoneBook = {} 66 | 67 | for i in range(int(input())): 68 | k,v = (tuple(map(str, input().split()))) 69 | phoneBook[k] = v 70 | 71 | 72 | for i in range(len(phoneBook)): 73 | ask = input() 74 | if ask in phoneBook: 75 | print("{}={}".format(ask, phoneBook[ask])) 76 | else: 77 | print("Not found") 78 | ``` 79 | 80 | 81 | ## Solution 2 82 | 83 | ```python 84 | n = int(input()) 85 | friends = {} 86 | 87 | for person in range(n): 88 | name, phone = map(str, input().split()) 89 | friends[name] = phone 90 | 91 | for ask in range(n): 92 | query = input() 93 | if query in friends.keys(): 94 | print("{}={}".format(query, friends[query])) 95 | else: 96 | print("Not found") 97 | ``` 98 | 99 | ## Solution 3 100 | 101 | ```python 102 | n = int(input()) 103 | friends = {} 104 | 105 | for person in range(n): 106 | name, phone = input().split() 107 | friends[name] = phone 108 | 109 | for ask in range(n): 110 | query = input() 111 | if query in friends.keys(): 112 | print("{}={}".format(query, friends[query])) 113 | else: 114 | print("Not found") 115 | ``` 116 | 117 | ## Solution 4 118 | 119 | ```python 120 | n = input("") 121 | n = int(n) 122 | friends = dict() 123 | 124 | for inp in range(n): 125 | friend = input("") 126 | inp = friend.split() 127 | name = inp[0] 128 | phone = inp[1] 129 | friends[name] = phone 130 | 131 | for ask in range(n): 132 | query = input("") 133 | if query in friends.keys(): 134 | print(query + "=" + friends[query]) 135 | else : 136 | print("Not found") 137 | ``` 138 | -------------------------------------------------------------------------------- /solutions/Day_9_Recursion_3.md: -------------------------------------------------------------------------------- 1 | # Day 9: Recursion 3 2 | ## Problem 3 | #### Objective 4 | Today, we're learning and practicing an algorithmic concept called Recursion. 5 | 6 | **Recursive Method for Calculating Factorial** 7 | 8 | ![](http://i65.tinypic.com/iefc3t.png) 9 | 10 | #### Task 11 | Write a factorial function that takes a positive integer, `N` as a parameter and prints the result of `N!` (`N` factorial). 12 | 13 | **Note**: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of `0` 14 | 15 | #### Input Format 16 | A single integer, `N` (the argument to pass to factorial). 17 | 18 | #### Constraints 19 | 2 <= N <= 12 20 | 21 | Your submission must contain a recursive function named factorial. 22 | 23 | #### Output Format 24 | On a new line for each query, print `Not found` if the name has no corresponding entry in the phone book; otherwise, print the full `name` and `phoneNumber` in the format `name=phoneNumber`. 25 | 26 | 27 | #### Sample Input 28 | 29 | ``` 30 | 3 31 | ``` 32 | 33 | #### Sample Output 34 | 35 | ``` 36 | 6 37 | ``` 38 | 39 | #### Explanation 40 | Consider the following steps: 41 | 42 | 1. factorial(3) = 3 x factorial(2) 43 | 2. factorial(2) = 2 x factorial(1) 44 | 3. factorial(1) = 1 45 | 46 | From steps 2 and 3, we can say factorial(2) = 2 x 1 = 2; then when we apply the value from factorial(2) to step 1, we get factorial(3) = 3 x 2 x 1 = 6. Thus, we print 6 as our answer. 47 | 48 | 49 | ## Given code 50 | 51 | ```python 52 | import math 53 | import os 54 | import random 55 | import re 56 | import sys 57 | 58 | # Complete the factorial function below. 59 | def factorial(n): 60 | 61 | if __name__ == '__main__': 62 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 63 | 64 | n = int(input()) 65 | 66 | result = factorial(n) 67 | 68 | fptr.write(str(result) + '\n') 69 | 70 | fptr.close() 71 | ``` 72 | 73 | ## Solution 1 74 | 75 | ```python 76 | import math 77 | import os 78 | import random 79 | import re 80 | import sys 81 | 82 | # Complete the factorial function below. 83 | def factorial(n): 84 | if n == 1: 85 | return 1 86 | else: 87 | n_fact = n * factorial(n - 1) 88 | return n_fact 89 | 90 | if __name__ == '__main__': 91 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 92 | 93 | n = int(input()) 94 | 95 | result = factorial(n) 96 | 97 | fptr.write(str(result) + '\n') 98 | 99 | fptr.close() 100 | ``` 101 | 102 | 103 | ## Solution 2 104 | 105 | ```python 106 | import math 107 | import os 108 | import random 109 | import re 110 | import sys 111 | 112 | # Complete the factorial function below. 113 | def factorial(n): 114 | return 1 if n == 1 else n * factorial(n-1) 115 | 116 | if __name__ == '__main__': 117 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 118 | 119 | n = int(input()) 120 | 121 | result = factorial(n) 122 | 123 | fptr.write(str(result) + '\n') 124 | 125 | fptr.close() 126 | ``` 127 | -------------------------------------------------------------------------------- /solutions/badges.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hevalhazalkurt/Hackerrank_Python_Solutions/88297d41e589fb8f44618913ec69550eada19dee/solutions/badges.png --------------------------------------------------------------------------------