From 9c21cb8b925ad61a153a3ead8a9548f68a4c6559 Mon Sep 17 00:00:00 2001 From: mayank Date: Thu, 15 Oct 2020 08:42:11 +0530 Subject: [PATCH] added ruby iteration code and update Readme --- ...roblems Property in Dynamic Programming.py | 106 ------ ...ructure Property in Dynamic Programming.py | 13 - Python/3-Longest Increasing Subsequence.py | 39 --- Python/4-Longest Common Subsequence.py | 327 ------------------ Python/5-EditDistance.py | 76 ---- .../6-Minimum Distance Between two points.py | 15 - Python/7-Coin Change.py | 155 --------- Python/8-Bionimal Coefficients.py | 64 ---- Python/9-0-1 Knapsack Problem.py | 70 ---- Python/ArithmeticOperators.py | 51 --- Python/BeautifulDaysAtTheMovies.py | 62 ---- Python/BubbleSort.py | 15 - Python/CalendarModule.py | 80 ----- Python/Capitalize!.py | 47 --- Python/CollectionsCounter.py | 102 ------ Python/CollectionsNamedtuple.py | 111 ------ Python/CollectionsOrderedDict.py | 102 ------ Python/Compress the String.py | 52 --- ...whose sum of digits equals to given sum.py | 18 - ...ays to reach the n\342\200\231th stair.py" | 65 ---- Python/Day-of-the-Programmer.py | 47 --- Python/DefaultDict_Tutorial.py | 71 ---- Python/DesignerDoorMat.py | 72 ---- Python/Else-If.py | 52 --- Python/ExtraLongFactorials.py | 58 ---- Python/Find a string.py | 60 ---- Python/FindDigits.py | 100 ------ Python/FindSecondRunnerUp.py | 42 --- Python/FindingThePercentage.py | 58 ---- Python/HeapsAlgorithm.py | 56 --- Python/Introduction to Sets.py | 73 ---- Python/IntroductionToSets.py | 45 --- Python/Iterables and Iterators.py | 75 ---- Python/ItertoolsCombinations.py | 72 ---- .../ItertoolsCombinations_with_replacement.py | 71 ---- Python/ItertoolsPermutations.py | 87 ----- Python/ItertoolsProduct.py | 81 ----- Python/LeapYear.py | 45 --- Python/LeftRotation.py | 43 --- Python/ListComprehensions.py | 58 ---- Python/Matrix_Script.py | 75 ---- Python/MergeTheTools.py | 89 ----- Python/MergeTwoSortedArray.py | 113 ------ Python/ModDivmod.py | 43 --- Python/Mutations.py | 81 ----- Python/NestedLists.py | 68 ---- Python/No Idea! - Find your Happiness.py | 53 --- Python/NumberToEnglish.py | 77 ----- Python/Partition problem.py | 48 --- Python/Polar Coordinates.py | 59 ---- Python/Power - Mod Power.py | 63 ---- Python/QueueUsingTwoStacks.py | 75 ---- Python/README.md | 42 --- Python/Sales by Match.py | 54 --- Python/Santa Clause.py | 56 --- Python/Set .discard(), .remove() & .pop().py | 133 ------- Python/Set.add().py | 59 ---- Python/SongOfPi.py | 75 ---- Python/Staircase.py | 87 ----- Python/String Validators.py | 111 ------ Python/String_Split_and_Join.py | 47 --- Python/StringsplitandJoin.py | 28 -- Python/SymmetricDifference.py | 143 -------- Python/Text Alignment.py | 100 ------ Python/Text Wrap.py | 52 --- Python/TheMinionGame.py | 109 ------ Python/Tiling Problem.py | 108 ------ ...of non-decreasing numbers with n digits.py | 38 -- Python/TriangleQuest.py | 36 -- Python/TriangleQuest2.py | 47 --- Python/Tuples.py | 38 -- Python/What's Your Name.py | 40 --- Python/Word Order.py | 62 ---- Python/Write_a_function.py | 36 -- Python/ZigZagSequence.py | 61 ---- Python/abbreviation.py | 39 --- Python/binarySearch.py | 31 -- Python/fast_fibonacci.py | 38 -- Python/practice.py | 4 - Python/sWAPcASE.py | 40 --- Ruby/README.md | 4 +- Ruby/string-Iteration.rb | 14 + 82 files changed, 17 insertions(+), 5395 deletions(-) delete mode 100644 Python/1-Overlapping Subproblems Property in Dynamic Programming.py delete mode 100644 Python/2-Optimal Substructure Property in Dynamic Programming.py delete mode 100644 Python/3-Longest Increasing Subsequence.py delete mode 100644 Python/4-Longest Common Subsequence.py delete mode 100644 Python/5-EditDistance.py delete mode 100644 Python/6-Minimum Distance Between two points.py delete mode 100644 Python/7-Coin Change.py delete mode 100644 Python/8-Bionimal Coefficients.py delete mode 100644 Python/9-0-1 Knapsack Problem.py delete mode 100644 Python/ArithmeticOperators.py delete mode 100644 Python/BeautifulDaysAtTheMovies.py delete mode 100644 Python/BubbleSort.py delete mode 100644 Python/CalendarModule.py delete mode 100644 Python/Capitalize!.py delete mode 100644 Python/CollectionsCounter.py delete mode 100644 Python/CollectionsNamedtuple.py delete mode 100644 Python/CollectionsOrderedDict.py delete mode 100644 Python/Compress the String.py delete mode 100644 Python/Count of n digit numbers whose sum of digits equals to given sum.py delete mode 100644 "Python/Count ways to reach the n\342\200\231th stair.py" delete mode 100644 Python/Day-of-the-Programmer.py delete mode 100644 Python/DefaultDict_Tutorial.py delete mode 100644 Python/DesignerDoorMat.py delete mode 100644 Python/Else-If.py delete mode 100644 Python/ExtraLongFactorials.py delete mode 100644 Python/Find a string.py delete mode 100644 Python/FindDigits.py delete mode 100644 Python/FindSecondRunnerUp.py delete mode 100644 Python/FindingThePercentage.py delete mode 100644 Python/HeapsAlgorithm.py delete mode 100644 Python/Introduction to Sets.py delete mode 100644 Python/IntroductionToSets.py delete mode 100644 Python/Iterables and Iterators.py delete mode 100644 Python/ItertoolsCombinations.py delete mode 100644 Python/ItertoolsCombinations_with_replacement.py delete mode 100644 Python/ItertoolsPermutations.py delete mode 100644 Python/ItertoolsProduct.py delete mode 100644 Python/LeapYear.py delete mode 100644 Python/LeftRotation.py delete mode 100644 Python/ListComprehensions.py delete mode 100644 Python/Matrix_Script.py delete mode 100644 Python/MergeTheTools.py delete mode 100644 Python/MergeTwoSortedArray.py delete mode 100644 Python/ModDivmod.py delete mode 100644 Python/Mutations.py delete mode 100644 Python/NestedLists.py delete mode 100644 Python/No Idea! - Find your Happiness.py delete mode 100644 Python/NumberToEnglish.py delete mode 100644 Python/Partition problem.py delete mode 100644 Python/Polar Coordinates.py delete mode 100644 Python/Power - Mod Power.py delete mode 100644 Python/QueueUsingTwoStacks.py delete mode 100644 Python/README.md delete mode 100644 Python/Sales by Match.py delete mode 100644 Python/Santa Clause.py delete mode 100644 Python/Set .discard(), .remove() & .pop().py delete mode 100644 Python/Set.add().py delete mode 100644 Python/SongOfPi.py delete mode 100644 Python/Staircase.py delete mode 100644 Python/String Validators.py delete mode 100644 Python/String_Split_and_Join.py delete mode 100644 Python/StringsplitandJoin.py delete mode 100644 Python/SymmetricDifference.py delete mode 100644 Python/Text Alignment.py delete mode 100644 Python/Text Wrap.py delete mode 100644 Python/TheMinionGame.py delete mode 100644 Python/Tiling Problem.py delete mode 100644 Python/Total number of non-decreasing numbers with n digits.py delete mode 100644 Python/TriangleQuest.py delete mode 100644 Python/TriangleQuest2.py delete mode 100644 Python/Tuples.py delete mode 100644 Python/What's Your Name.py delete mode 100644 Python/Word Order.py delete mode 100644 Python/Write_a_function.py delete mode 100644 Python/ZigZagSequence.py delete mode 100644 Python/abbreviation.py delete mode 100644 Python/binarySearch.py delete mode 100644 Python/fast_fibonacci.py delete mode 100644 Python/practice.py delete mode 100644 Python/sWAPcASE.py create mode 100644 Ruby/string-Iteration.rb diff --git a/Python/1-Overlapping Subproblems Property in Dynamic Programming.py b/Python/1-Overlapping Subproblems Property in Dynamic Programming.py deleted file mode 100644 index 7534ecd8..00000000 --- a/Python/1-Overlapping Subproblems Property in Dynamic Programming.py +++ /dev/null @@ -1,106 +0,0 @@ -# 1) Overlapping Subproblems: -# Like Divide and Conquer, Dynamic Programming combines solutions to -# sub-problems. Dynamic Programming is mainly used when solutions of same -# subproblems are needed again and again. In dynamic programming, computed -# solutions to subproblems are stored in a table so that these don’t have to -# be recomputed. So Dynamic Programming is not useful when there are no common -# (overlapping) subproblems because there is no point storing the solutions if -# hey are not needed again. For example, Binary Search doesn’t have common -# subproblems. If we take an example of following recursive program for -# Fibonacci Numbers, there are many subproblems which are solved again and -# again. -# Recursion tree for execution of fib(5) - - - - -# fib(5) -# / \ -# fib(4) fib(3) -# / \ / \ -# fib(3) fib(2) fib(2) fib(1) -# / \ / \ / \ -# fib(2) fib(1) fib(1) fib(0) fib(1) fib(0) -# / \ -# fib(1) fib(0) - - -# We can see that the function fib(3) is being called 2 times. If we would have -# ored the value of fib(3), then instead of computing it again, we could have -# reused the old stored value. There are following two different ways to store -# the values so that these values can be reused: -# a) Memoization (Top Down) -# b) Tabulation (Bottom Up) - -# a) Memoization (Top Down): The memoized program for a problem is similar to -# the recursive version with a small modification that it looks into a lookup -# table before computing solutions. We initialize a lookup array with all -# initial values as NIL. Whenever we need the solution to a subproblem, we -# first look into the lookup table. If the precomputed value is there then -# we return that value, otherwise, we calculate the value and put the result -# in the lookup table so that it can be reused later. - -# Following is the memoized version for nth Fibonacci Number. - -# # Function to calculate nth Fibonacci number -def fib(n, lookup): - - # Base case - if n == 0 or n == 1 : - lookup[n] = n - - # If the value is not calculated previously then calculate it - if lookup[n] is None: - lookup[n] = fib(n-1 , lookup) + fib(n-2 , lookup) - - # return the value corresponding to that value of n - return lookup[n] -# end of function - -# Driver program to test the above function -def main(): - n = 34 - # Declaration of lookup table - # Handles till n = 100 - lookup = [None]*(101) - print("Fibonacci Number is ", fib(n, lookup)) - -# main() - - -# b) Tabulation (Bottom Up): The tabulated program for a given problem builds a -# table in bottom up fashion and returns the last entry from table. -# For example, for the same Fibonacci number, we first calculate fib(0) -# then fib(1) then fib(2) then fib(3) and so on. So literally, we are building -# the solutions of subproblems bottom-up. - -# Following is the tabulated version for nth Fibonacci Number. - -# Python program Tabulated (bottom up) version -def fib(n): - - # array declaration - f = [0]*(n+1) - - # base case assignment - f[1] = 1 - - # calculating the fibonacci and storing the values - for i in range(2 , n+1): - f[i] = f[i-1] + f[i-2] - return f[n] - -# Driver program to test the above function -def main(): - n = 9 - print("Fibonacci number is " , fib(n) ) - -main() - - - - - - - -#reference:https://www.geeksforgeeks.org/overlapping-subproblems-property-in-dynamic-programming-dp-1/ \ No newline at end of file diff --git a/Python/2-Optimal Substructure Property in Dynamic Programming.py b/Python/2-Optimal Substructure Property in Dynamic Programming.py deleted file mode 100644 index 7fa78eae..00000000 --- a/Python/2-Optimal Substructure Property in Dynamic Programming.py +++ /dev/null @@ -1,13 +0,0 @@ -# 2) Optimal Substructure: A given problems has Optimal Substructure Property -# if optimal solution of the given problem can be obtained by using optimal -# solutions of its subproblems. - -# For example, the Shortest Path problem has following optimal substructure -# property: -# If a node x lies in the shortest path from a source node u to destination -# node v then the shortest path from u to v is combination of shortest path -# from u to x and shortest path from x to v. The standard All Pair Shortest -# Path algorithms like Floyd–Warshall and Bellman–Ford are typical examples -# of Dynamic Programming. - -# reference:https://www.geeksforgeeks.org/optimal-substructure-property-in-dynamic-programming-dp-2/ \ No newline at end of file diff --git a/Python/3-Longest Increasing Subsequence.py b/Python/3-Longest Increasing Subsequence.py deleted file mode 100644 index 4e7027f4..00000000 --- a/Python/3-Longest Increasing Subsequence.py +++ /dev/null @@ -1,39 +0,0 @@ -# Longest Increasing Subsequence -# We have discussed Overlapping Subproblems and Optimal Substructure properties. - -# Let us discuss Longest Increasing Subsequence (LIS) problem as an example -# problem that can be solved using Dynamic Programming. -# The Longest Increasing Subsequence (LIS) problem is to find the length of -# the longest subsequence of a given sequence such that all elements of the -# subsequence are sorted in increasing order. For example, the length of LIS -# for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS -# is {10, 22, 33, 50, 60, 80}. -# longest-increasing-subsequence - -# More Examples: - -# Input : arr[] = {3, 10, 2, 1, 20} -# Output : Length of LIS = 3 -# The longest increasing subsequence is 3, 10, 20 - -# Input : arr[] = {3, 2} -# Output : Length of LIS = 1 -# The longest increasing subsequences are {3} and {2} - -# Input : arr[] = {50, 3, 10, 7, 40, 80} -# Output : Length of LIS = 4 -# The longest increasing subsequence is {3, 7, 40, 80} - -#Method 1 :https://youtu.be/Ns4LCeeOFS4 -#(nlogn) - -def LongestIncreasingSequence(list1): - n=len(list1) - list2=[1 for i in range(n)] - for i in range(1,n): - for j in range(i): - if list1[i]>list1[j] and list2[i] 0 and j > 0: - -# # If current character in X[] and Y are same, then -# # current character is part of LCS -# if X[i-1] == Y[j-1]: -# lcs[index-1] = X[i-1] -# i-=1 -# j-=1 -# index-=1 - -# # If not same, then find the larger of two and -# # go in the direction of larger value -# elif L[i-1][j] > L[i][j-1]: -# i-=1 -# else: -# j-=1 - -# print "LCS of " + X + " and " + Y + " is " + "".join(lcs) - -#--------------------------------------------------------------------------- - - - -# Longest Common Anagram Subsequence - -# reference:https://www.geeksforgeeks.org/longest-common-anagram-subsequence/ -# Given two strings str1 and str2 of length n1 and n2 respectively. -# The problem is to find the length of the longest subsequence which is -# present in both the strings in the form of anagrams. -# Note: The strings contain only lowercase letters. -# Examples: -# Input : str1 = "abdacp", str2 = "ckamb" -# Output : 3 -# Subsequence of str1 = abc -# Subsequence of str2 = cab -# OR -# Subsequence of str1 = bac -# Subsequence of str2 = cab - -# These are longest common anagram subsequences. -# Input : str1 = "abbcfke", str2 = "fbaafbly" -# Output : 4 - -# Approach: Create two hash tables say freq1 and freq2. Store frequencies of -# each character of str1 in freq1. Likewise, store frequencies of each -# character of str2 in freq2. Initilaize len = 0. Now, for each lowercase -# letter finds its lowest frequency from the two hash tables and accumulate -# it to len. - -# Python 3 implementation to find -# the length of the longest common -# anagram subsequence -# SIZE = 26 - -# # function to find the length of the -# # longest common anagram subsequence -# def longCommomAnagramSubseq(str1, str2,n1, n2): -# # List for storing frequencies -# # of each character -# freq1 = [0] * SIZE -# freq2 = [0] * SIZE -# l = 0 -# # calculate frequency of each -# # character of 'str1[]' -# for i in range(n1): -# freq1[ord(str1[i]) - -# ord('a')] += 1 -# # calculate frequency of each -# # character of 'str2[]' -# for i in range(n2) : -# freq2[ord(str2[i]) - -# ord('a')] += 1 -# # for each character add its -# # minimum frequency out of -# # the two strings in 'len' -# for i in range(SIZE): -# l += min(freq1[i], freq2[i]) -# # required length -# return l - -# # Driver Code -# if __name__ == "__main__": - -# str1 = "abdacp" -# str2 = "ckamb" -# n1 = len(str1) -# n2 = len(str2) -# print("Length = ", -# longCommomAnagramSubseq(str1, str2, -# n1, n2)) -#--------------------------------------------------------------------------- -# LCS (Longest Common Subsequence) of three strings - -# Given 3 strings of all having length < 100,the task is to find the longest -# common sub-sequence in all three given sequences. -# Examples: -# Input : str1 = "geeks" -# str2 = "geeksfor" -# str3 = "geeksforgeeks" -# Output : 5 -# Longest common subsequence is "geeks" -# i.e., length = 5 - -# Input : str1 = "abcd1e2" -# str2 = "bc12ea" -# str3 = "bd1ea" -# Output : 3 -# Longest common subsequence is "b1e" -# i.e. length = 3. -# This problem is simply an extension of LCS - -# Let the input sequences be X[0..m-1], Y[0..n-1] and Z[0..o-1] of lengths -# m, n and o respectively. And let L(X[0..m-1], Y[0..n-1], Z[0..o-1]) be the -# lengths of LCS of the three sequences X, Y and Z. Following is the -# implementation: -# The idea is to take a 3D array to store the -# length of common subsequence in all 3 given -# sequences i. e., L[m + 1][n + 1][o + 1] - -# 1- If any of the string is empty then there -# is no common subsequence at all then -# L[i][j][k] = 0 - -# 2- If the characters of all sequences match -# (or X[i] == Y[j] ==Z[k]) then -# L[i][j][k] = 1 + L[i-1][j-1][k-1] - -# 3- If the characters of both sequences do -# not match (or X[i] != Y[j] || X[i] != Z[k] -# || Y[j] !=Z[k]) then -# L[i][j][k] = max(L[i-1][j][k], -# L[i][j-1][k], -# L[i][j][k-1]) -#--------------------------------------------------------------------------- -# Longest common subsequence with permutations allowed - -# Given two strings in lowercase, find the longest string whose permutations -# are subsequences of given two strings. The output longest string must be -# sorted. - -# Examples: -# Input : str1 = "pink", str2 = "kite" -# Output : "ik" -# The string "ik" is the longest sorted string -# whose one permutation "ik" is subsequence of -# "pink" and another permutation "ki" is -# subsequence of "kite". - -# Input : str1 = "working", str2 = "women" -# Output : "now" - -# Input : str1 = "geeks" , str2 = "cake" -# Output : "ek" - -# Input : str1 = "aaaa" , str2 = "baba" -# Output : "aa" - -# The idea is to count characters in both strings. -# calculate frequency of characters for each string and store them in their -# respective count arrays, say count1[] for str1 and count2[] for str2. -# Now we have count arrays for 26 characters. So traverse count1[] and for any -# index ‘i’ append character (‘a’+i) in resultant string ‘result’ by -# min(count1[i], count2[i]) times. -# Since we traverse count array in ascending order, our final string -# characters will be in sorted order. - -# Python 3 program to find LCS -# with permutations allowed - -# Function to calculate longest string -# str1 --> first string -# str2 --> second string -# count1[] --> hash array to calculate frequency -# of characters in str1 -# count[2] --> hash array to calculate frequency -# of characters in str2 -# result --> resultant longest string whose -# permutations are sub-sequence -# of given two strings -def longestString(str1, str2): - - count1 = [0] * 26 - count2 = [0] * 26 - - # calculate frequency of characters - for i in range( len(str1)): - count1[ord(str1[i]) - ord('a')] += 1 - for i in range(len(str2)): - count2[ord(str2[i]) - ord('a')] += 1 - - # Now traverse hash array - result = "" - for i in range(26): - - # append character ('a'+i) in - # resultant string 'result' by - # min(count1[i],count2i]) times - for j in range(1, min(count1[i], - count2[i]) + 1): - result = result + chr(ord('a') + i) - - print(result) - -# Driver Code -# if __name__ == "__main__": - -# str1 = "geeks" -# str2 = "cake" -# longestString(str1, str2) - -#--------------------------------------------------------------------------- -# Longest Subsequence with at least one common digit in every element - -# Given an array. The task is to find the length of the longest subsequence -# in which all elements must have at least one digit in common. - -# Examples: - -# Input : arr[] = { 11, 12, 23, 74, 13 } -# Output : 3 -# Explanation: The elements 11, 12, and 13 have the digit ‘1’ as common. -# So it is the required longest sub-sequence. - - - -# Input : arr[] = { 12, 90, 67, 78, 45 } -# Output : 2 - -# Normal Approach: Find all the subsequences of the array and find the -# subsequence in which every element must have a common digit. Then we -# have to find the longest such subsequence and print the length of that -# subsequence. This method will take exponential time complexity. - -# reference:https://www.geeksforgeeks.org/longest-subsequence-with-at-least-one-common-digit-in-every-element/ -#--------------------------------------------------------------------------- \ No newline at end of file diff --git a/Python/5-EditDistance.py b/Python/5-EditDistance.py deleted file mode 100644 index 40be2beb..00000000 --- a/Python/5-EditDistance.py +++ /dev/null @@ -1,76 +0,0 @@ -# 5-EditDistance - -# Edit Distance -# Given two strings str1 and str2 and below operations that can performed on -# str1. Find minimum number of edits (operations) required to convert ‘str1’ -# into ‘str2’. - -# Insert -# Remove -# Replace -# All of the above operations are of equal cost. - -# Examples: - -# Input: str1 = "geek", str2 = "gesek" -# Output: 1 -# We can convert str1 into str2 by inserting a 's'. - -# Input: str1 = "cat", str2 = "cut" -# Output: 1 -# We can convert str1 into str2 by replacing 'a' with 'u'. - -# Input: str1 = "sunday", str2 = "saturday" -# Output: 3 -# Last three and first characters are same. We basically -# need to convert "un" to "atur". This can be done using -# below three operations. -# Replace 'n' with 'r', insert t, insert a - - -# What are the subproblems in this case? -# The idea is process all characters one by one staring from either from left -# or right sides of both strings. -# Let us traverse from right corner, there are two possibilities for every pair -# of character being traversed. - -# m: Length of str1 (first string) -# n: Length of str2 (second string) -# If last characters of two strings are same, nothing much to do. Ignore last -# characters and get count for remaining strings. So we recur for lengths m-1 -# and n-1. -# Else (If last characters are not same), we consider all operations on -# ‘str1’, consider all three operations on last character of first string, -# recursively compute minimum cost for all three operations and take minimum -# of three values. -# Insert: Recur for m and n-1 -# Remove: Recur for m-1 and n -# Replace: Recur for m-1 and n-1 - -def EditDistance(str1,str2,m,n): - # If first string is empty, the only option is to - # insert all characters of second string into first - if m==0 : - return n - - # If second string is empty, the only option is to - # remove all characters of first string - if n==0: - return m - - # If last characters of two strings are same, nothing - # much to do. Ignore last characters and get count for - # remaining strings. - elif str1[m-1]==str2[n-1]: - return EditDistance(str1,str2,m-1,n-1) - - # If last characters are not same, consider all three - # operations on last character of first string, recursively - # compute minimum cost for all three operations and take - # minimum of three values. - else: - return 1+min(EditDistance(str1,str2,m,n-1),EditDistance(str1,str2,m-1,n),EditDistance(str1,str2,m-1,n-1)) - -str1 = "sunday" -str2 = "saturday" -print (EditDistance(str1, str2, len(str1), len(str2)) ) \ No newline at end of file diff --git a/Python/6-Minimum Distance Between two points.py b/Python/6-Minimum Distance Between two points.py deleted file mode 100644 index a7f263f9..00000000 --- a/Python/6-Minimum Distance Between two points.py +++ /dev/null @@ -1,15 +0,0 @@ -import sys -def mincost(cost , m , n): - if m < 0 or n <0: - return sys.maxsize - if m == 0 and n ==0: - return cost[m][n] - else: - return cost[m][n] +min(mincost(cost,m-1,n-1), mincost(cost,m-1,n), mincost(cost,m,n-1)) -def min(x,y,z): - if x < y: - return x if x < z else z - else: - return y if y < z else z -list1=[[1,2,3,8],[2,8,2,42],[4,5,6,68],[52,62,68,72]] -print(mincost(list1,3,2)) \ No newline at end of file diff --git a/Python/7-Coin Change.py b/Python/7-Coin Change.py deleted file mode 100644 index bd46279d..00000000 --- a/Python/7-Coin Change.py +++ /dev/null @@ -1,155 +0,0 @@ -# Given a value N, if we want to make change for N cents, and we -# have infinite supply of each of S = { S1, S2, .. , Sm} valued -# coins, how many ways can we make the change? The order of coins -# doesn’t matter. - -# For example, for N = 4 and S = {1,2,3}, there are four -# solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should -# be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: -# {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output -# should be 5. - - -# Recursive Python3 program for -# coin change problem. - -# Returns the count of ways we can sum -# S[0...m-1] coins to get sum n -def count(S, m, n ): - - # If n is 0 then there is 1 - # solution (do not include any coin) - if (n == 0): - return 1 - - # If n is less than 0 then no - # solution exists - if (n < 0): - return 0; - - # If there are no coins and n - # is greater than 0, then no - # solution exist - if (m <=0 and n >= 1): - return 0 - - # count is sum of solutions (i) - # including S[m-1] (ii) excluding S[m-1] - return count( S, m - 1, n ) + count( S, m, n-S[m-1] ); - -# Driver program to test above function -arr = [1, 2, 3] -m = len(arr) -print(count(arr, m, 4)) - -# This code is contributed by Smitha Dinesh Semwal - - -# It should be noted that the above function computes the same -# subproblems again and again. - -# Dynamic Programming Python implementation of Coin -# Change problem -def count(S, m, n): - # We need n+1 rows as the table is constructed - # in bottom up manner using the base case 0 value - # case (n = 0) - table = [[0 for x in range(m)] for x in range(n+1)] - - # Fill the entries for 0 value case (n = 0) - for i in range(m): - table[0][i] = 1 - - # Fill rest of the table entries in bottom up manner - for i in range(1, n+1): - for j in range(m): - - # Count of solutions including S[j] - x = table[i - S[j]][j] if i-S[j] >= 0 else 0 - - # Count of solutions excluding S[j] - y = table[i][j-1] if j >= 1 else 0 - - # total count - table[i][j] = x + y - - return table[n][m-1] - -# Driver program to test above function -arr = [1, 2, 3] -m = len(arr) -n = 4 -print(count(arr, m, n)) - - - -# references:https://www.geeksforgeeks.org/coin-change-dp-7/ -# https://www.youtube.com/watch?v=L27_JpN6Z1Q - -#-------------------------------------------------------------------- - -# Given two coins of denominations “X” and “Y” respectively, find the -# largest amount that cannot be obtained using these two coins -# (assuming infinite supply of coins) followed by the total number -# of such non obtainable amounts, if no such value exists print “NA”. - -# Examples : - -# Input : X=2, Y=5 -# Output: Largest amount = 3 -# Total count = 2 -# We cannot represent 1 and 3 from infinite supply -# of given two coins. The largest among these 2 is 3. -# We can represent all other amounts for example 13 -# can be represented 2*4 + 5. - -# Input : X=5, Y=10 -# Output: NA -# There are infinite number of amounts that cannot -# be represented by these two coins. - - - -# This general problem for n coins is known as classic Forbenius coin -# problem. - -# When the number of coins is two, there is -# explicit formula if GCD is not 1. The formula -# is: -# Largest amount A = (X * Y) - (X + Y) -# Total amount = (X -1) * (Y - 1) /2 - -def gcd(a, b): - while (a != 0): - c = a; - a = b % a; - b = c; - - return b; - -# Function to print the desired output -def forbenius(X, Y): - - # Solution doesn't exist - # if GCD is not 1 - if (gcd(X, Y) != 1): - print("NA"); - return; - - # Else apply the formula - A = (X * Y) - (X + Y); - N = (X - 1) * (Y - 1) // 2; - - print("Largest Amount =", A); - print("Total Count =", N); - -# Driver Code -X = 2; -Y = 5; -forbenius(X, Y); - -X = 5; -Y = 10; -print(""); -forbenius(X, Y); -#-------------------------------------------------------------------- \ No newline at end of file diff --git a/Python/8-Bionimal Coefficients.py b/Python/8-Bionimal Coefficients.py deleted file mode 100644 index 6f8614af..00000000 --- a/Python/8-Bionimal Coefficients.py +++ /dev/null @@ -1,64 +0,0 @@ -# Problem -# Write a function that takes two parameters n and k and returns the -# value of Binomial Coefficient C(n, k). For example, your function -# should return 6 for n = 4 and k = 2, and it should return 10 for -# n = 5 and k = 2. - - -# def bio(n,k): -# if k == 0 or k == n: -# return 1 -# else: -# return bio(n-1,k-1) + bio(n-1,k) - -# print(bio(4,2)) - -# Using Overlapping Structure - - -# MY TRY -# def Bionomial(n,k): -# if n == k or k == 0: -# lookup[[n,k]]=1 -# return lookup[(n,k)] -# if lookup[[n,k]] == None: -# return Bionomial(n-1,k-1) + Bionomial(n-1,k) -# lookup = [None]*101 -# print(Bionomial(4,2)) - -# ACTUAL ONCE IS THIS ONE - - -# print(Bionimal(4,2)) - - - -# def binomialCoef(n, k): -# C = [[0 for x in range(k+1)] for x in range(n+1)] - -# # Calculate value of Binomial Coefficient in bottom up manner -# for i in range(n+1): -# for j in range(min(i, k)+1): -# # Base Cases -# if j == 0 or j == i: -# C[i][j] = 1 - -# # Calculate value using previously stored values -# else: -# C[i][j] = C[i-1][j-1] + C[i-1][j] - -# return C[n][k] - -# print(binomialCoef(4,2)) - - - - -def BionimalCoefficient(n,k): - if k==n or k==0: - return 1 - else: - return BionimalCoefficient(n-1,k-1)+BionimalCoefficient(n-1,k) -print(BionimalCoefficient(4,2)) - -# reference:https://www.geeksforgeeks.org/binomial-coefficient-dp-9/ \ No newline at end of file diff --git a/Python/9-0-1 Knapsack Problem.py b/Python/9-0-1 Knapsack Problem.py deleted file mode 100644 index 17f8f62c..00000000 --- a/Python/9-0-1 Knapsack Problem.py +++ /dev/null @@ -1,70 +0,0 @@ -# Given weights and values of n items, put these items in a knapsack -# of capacity W to get the maximum total value in the knapsack. In -# other words, given two integer arrays val[0..n-1] and wt[0..n-1] -# which represent values and weights associated with n items -# respectively. Also given an integer W which represents knapsack -# capacity, find out the maximum value subset of val[] such that -# sum of the weights of this subset is smaller than or equal to W. -# You cannot break an item, either pick the complete item, or -# don’t pick it (0-1 property). - -#A naive recursive implementation of 0-1 Knapsack Problem - -# Returns the maximum value that can be put in a knapsack of -# capacity W -# def knapSack(W , wt , val , n): - -# # Base Case -# if n == 0 or W == 0 : -# return 0 - -# # If weight of the nth item is more than Knapsack of capacity -# # W, then this item cannot be included in the optimal solution -# if (wt[n-1] > W): -# return knapSack(W , wt , val , n-1) - -# # return the maximum of two cases: -# # (1) nth item included -# # (2) not included -# else: -# return max(val[n-1] + knapSack(W-wt[n-1] , wt , val , n-1), -# knapSack(W , wt , val , n-1)) - -# # end of function knapSack - -# # To test above function -# val = [60, 100, 120] -# wt = [10, 20, 30] -# W = 50 -# n = len(val) -# print knapSack(W , wt , val , n) - - - - -# Returns the maximum value that can be put in a knapsack of capacity W -def knapSack(W, wt, val, n): - K = [[0 for x in range(W+1)] for x in range(n+1)] - - # Build table K[][] in bottom up manner - for i in range(n+1): - for w in range(W+1): - if i==0 or w==0: - K[i][w] = 0 - elif wt[i-1] <= w: - K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) - else: - K[i][w] = K[i-1][w] - - return K[n][W] - -# Driver program to test above function -val = [60, 100, 120] -wt = [10, 20, 30] -W = 50 -n = len(val) -print(knapSack(W, wt, val, n)) - - -# reference:https://www.youtube.com/watch?v=PfkBS9qIMRE&t=63s -# https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/ \ No newline at end of file diff --git a/Python/ArithmeticOperators.py b/Python/ArithmeticOperators.py deleted file mode 100644 index ddcb02e9..00000000 --- a/Python/ArithmeticOperators.py +++ /dev/null @@ -1,51 +0,0 @@ -''' -Task -The provided code stub reads two integers from STDIN, and . Add code to print three lines where: - -1.The first line contains the sum of the two numbers. -2.The second line contains the difference of the two numbers (first - second). -3.The third line contains the product of the two numbers. - -Example -a = 3 -b = 5 - -Print the following: -8 --2 -15 - -Input Format - -The first line contains the first integer, a -The second line contains the second integer, b - -Constraints -1 <= a <= 10^10 -1 <= b <= 10^10 - -Output format -Print the three lines as explained above. - -Sample Input 0 -3 -2 - -Sample Output 0 -5 -1 -6 - -Explanation 0 -3+2 = 5 -3-2 = 1 -3*2 = 6 -''' - -if __name__ == '__main__': - a = int(input()) - b = int(input()) - - print(a+b) - print(a-b) - print(a*b) diff --git a/Python/BeautifulDaysAtTheMovies.py b/Python/BeautifulDaysAtTheMovies.py deleted file mode 100644 index 3eaca447..00000000 --- a/Python/BeautifulDaysAtTheMovies.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/bin/python3 - -''' -Problem Link: https://www.hackerrank.com/challenges/beautiful-days-at-the-movies/problem - -Problem Description: - -Lily likes to play games with integers. She has created a new game where she determines the difference between a number and its reverse. For instance, given the number 12 , its reverse is 21. Their difference is 9. The number 120 reversed is 21, and their difference is 99. - -She decides to apply her game to decision making. She will look at a numbered range of days and will only go to a movie on a beautiful day. - -Given a range of numbered days, [i...j] and a number k, determine the number of days in the range that are beautiful. Beautiful numbers are defined as numbers where |i-reverse(i)| is evenly divisible by k. If a day's value is a beautiful number, it is a beautiful day. Print the number of beautiful days in the range. - -Function Description: -Complete the beautifulDays function in the editor below. It must return the number of beautiful days in the range. - -beautifulDays has the following parameter(s): - -i: the starting day number -j: the ending day number -k: the divisor - -Input Format: -A single line of three space-separated integers describing the respective values of i, j, and k. - -Constraints: -1) 1<=j<=j<=2*10^6 -2) 1<=k<=2*10^9 - -Output Format: -Print the number of beautiful days in the inclusive range between i and j. - -Sample Input: -20 23 6 - -Sample Output: -2 -''' - - -def reverse(x): - n = 0 - while(x!=0): - n = x%10 + n*10 - x = x//10 - return n - -def beautifulDays(i, j, k): - c = 0 #c: counter - for d in range(i,j+1): - n = reverse(d) - if abs(d-n)%k == 0: - c+=1 - return c - -if __name__ == '__main__': - ijk = input().split() - i = int(ijk[0]) #i: starting day number - j = int(ijk[1]) #j: ending day number - k = int(ijk[2]) #k: divisor - result = beautifulDays(i, j, k) - print(result) diff --git a/Python/BubbleSort.py b/Python/BubbleSort.py deleted file mode 100644 index 177f2009..00000000 --- a/Python/BubbleSort.py +++ /dev/null @@ -1,15 +0,0 @@ -#Python program for implementation og Bubble Sort -#Making Function to perform bubbleSort -def bubbleSort(arrays): - for passnum in range(len(arrays)-1,0,-1): - for i in range(passnum): - if arrays[i]>arrays[i+1]: - temp = arrays[i] - arrays[i] = arrays[i+1] - arrays[i+1] = temp -#initialize the array -arrays = [5,2,9,1,7,3,4,505,200] -#Performing bubbleSort Function -bubbleSort(arrays) -#Printing array after bubble sort -print(arrays) diff --git a/Python/CalendarModule.py b/Python/CalendarModule.py deleted file mode 100644 index ad6d7a0f..00000000 --- a/Python/CalendarModule.py +++ /dev/null @@ -1,80 +0,0 @@ -''' -Calendar Module -The calendar module allows you to output calendars and provides additional useful functions for them. - -class calendar.TextCalendar([firstweekday]) - -This class can be used to generate plain text calendars. - -Sample Code - ->>> import calendar ->>> ->>> print calendar.TextCalendar(firstweekday=6).formatyear(2015) - 2015 - - January February March -Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa - 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 6 7 - 4 5 6 7 8 9 10 8 9 10 11 12 13 14 8 9 10 11 12 13 14 -11 12 13 14 15 16 17 15 16 17 18 19 20 21 15 16 17 18 19 20 21 -18 19 20 21 22 23 24 22 23 24 25 26 27 28 22 23 24 25 26 27 28 -25 26 27 28 29 30 31 29 30 31 - - April May June -Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa - 1 2 3 4 1 2 1 2 3 4 5 6 - 5 6 7 8 9 10 11 3 4 5 6 7 8 9 7 8 9 10 11 12 13 -12 13 14 15 16 17 18 10 11 12 13 14 15 16 14 15 16 17 18 19 20 -19 20 21 22 23 24 25 17 18 19 20 21 22 23 21 22 23 24 25 26 27 -26 27 28 29 30 24 25 26 27 28 29 30 28 29 30 - 31 - - July August September -Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa - 1 2 3 4 1 1 2 3 4 5 - 5 6 7 8 9 10 11 2 3 4 5 6 7 8 6 7 8 9 10 11 12 -12 13 14 15 16 17 18 9 10 11 12 13 14 15 13 14 15 16 17 18 19 -19 20 21 22 23 24 25 16 17 18 19 20 21 22 20 21 22 23 24 25 26 -26 27 28 29 30 31 23 24 25 26 27 28 29 27 28 29 30 - 30 31 - - October November December -Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa - 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 - 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 -11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 -18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 -25 26 27 28 29 30 31 29 30 27 28 29 30 31 -To learn more about different calendar functions, click here. - -Task - -You are given a date. Your task is to find what the day is on that date. - -Input Format - -A single line of input containing the space separated month, day and year, respectively, in format. - -Constraints - -Output Format - -Output the correct day in capital letters. - -Sample Input - -08 05 2015 -Sample Output - -WEDNESDAY -Explanation - -The day on August th was WEDNESDAY. -''' - -if __name__ == "__main__": - import calendar - - month, day, year = map(int, input().split()) - print(calendar.day_name[calendar.weekday(year, month, day)].upper()) \ No newline at end of file diff --git a/Python/Capitalize!.py b/Python/Capitalize!.py deleted file mode 100644 index c2d4f48e..00000000 --- a/Python/Capitalize!.py +++ /dev/null @@ -1,47 +0,0 @@ -''' -You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck. - -Given a full name, your task is to capitalize the name appropriately. - -Input Format - -A single line of input containing the full name, - -. - -Constraints - - The string consists of alphanumeric characters and spaces. - -Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc. - -Output Format - -Print the capitalized string, - -. - -Sample Input - -chris alan - -Sample Output - -Chris Alan - -''' - -def solve(s): - return s.title() - -if __name__ == '__main__': - import os - fptr = open(os.environ['OUTPUT_PATH'], 'w') - - s = input() - - result = solve(s) - - fptr.write(result + '\n') - - fptr.close() diff --git a/Python/CollectionsCounter.py b/Python/CollectionsCounter.py deleted file mode 100644 index d8fc05ee..00000000 --- a/Python/CollectionsCounter.py +++ /dev/null @@ -1,102 +0,0 @@ -''' -collections.Counter() -A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values. - -Sample Code - ->>> from collections import Counter ->>> ->>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3] ->>> print Counter(myList) -Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1}) ->>> ->>> print Counter(myList).items() -[(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)] ->>> ->>> print Counter(myList).keys() -[1, 2, 3, 4, 5] ->>> ->>> print Counter(myList).values() -[3, 4, 4, 2, 1] - -Task - -is a shoe shop owner. His shop has number of shoes. -He has a list containing the size of each shoe he has in his shop. -There are number of customers who are willing to pay - -amount of money only if they get the shoe of their desired size. - -Your task is to compute how much money - -earned. - -Input Format - -The first line contains -, the number of shoes. -The second line contains the space separated list of all the shoe sizes in the shop. -The third line contains , the number of customers. -The next lines contain the space separated values of the desired by the customer and - -, the price of the shoe. - -Constraints - - - - -Output Format - -Print the amount of money earned by - -. - -Sample Input - -10 -2 3 4 5 6 8 7 6 5 18 -6 -6 55 -6 45 -6 55 -4 40 -18 60 -10 50 - -Sample Output - -200 - -Explanation - -Customer 1: Purchased size 6 shoe for $55. -Customer 2: Purchased size 6 shoe for $45. -Customer 3: Size 6 no longer available, so no purchase. -Customer 4: Purchased size 4 shoe for $40. -Customer 5: Purchased size 18 shoe for $60. -Customer 6: Size 10 not available, so no purchase. - -Total money earned = - -''' - -from collections import Counter -if __name__ == '__main__': - n = int(input()) - l = list(map(lambda x: int(x),input().split())) - t = int(input()) - tup=list() - for i in range(t): - tup.append(tuple(map(lambda x: int(x),input().split()))) -total=0 -c=dict(Counter(l).items()) -for item in tup: - try: - if c[item[0]]>0: - c[item[0]]-=1 - total+=item[-1] - except: - pass - -print(total) \ No newline at end of file diff --git a/Python/CollectionsNamedtuple.py b/Python/CollectionsNamedtuple.py deleted file mode 100644 index 9efaae41..00000000 --- a/Python/CollectionsNamedtuple.py +++ /dev/null @@ -1,111 +0,0 @@ -''' -collections.namedtuple() - -Basically, namedtuples are easy to create, lightweight object types. -They turn tuples into convenient containers for simple tasks. -With namedtuples, you don’t have to use integer indices for accessing members of a tuple. - -Example - -Code 01 - ->>> from collections import namedtuple ->>> Point = namedtuple('Point','x,y') ->>> pt1 = Point(1,2) ->>> pt2 = Point(3,4) ->>> dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y ) ->>> print dot_product -11 - -Code 02 - ->>> from collections import namedtuple ->>> Car = namedtuple('Car','Price Mileage Colour Class') ->>> xyz = Car(Price = 100000, Mileage = 30, Colour = 'Cyan', Class = 'Y') ->>> print xyz -Car(Price=100000, Mileage=30, Colour='Cyan', Class='Y') ->>> print xyz.Class -Y - -Task - -Dr. John Wesley has a spreadsheet containing a list of student's -, , and - -. - -Your task is to help Dr. Wesley calculate the average marks of the students. - -Note: -1. Columns can be in any order. IDs, marks, class and name can be written in any order in the spreadsheet. -2. Column names are ID, MARKS, CLASS and NAME. (The spelling and case type of these names won't change.) - -Input Format - -The first line contains an integer -, the total number of students. -The second line contains the names of the columns in any order. -The next lines contains the , , and - -, under their respective column names. - -Constraints - -Output Format - -Print the average marks of the list corrected to 2 decimal places. - -Sample Input - -TESTCASE 01 - -5 -ID MARKS NAME CLASS -1 97 Raymond 7 -2 50 Steven 4 -3 91 Adrian 9 -4 72 Stewart 5 -5 80 Peter 6 - -TESTCASE 02 - -5 -MARKS CLASS NAME ID -92 2 Calum 1 -82 5 Scott 2 -94 2 Jason 3 -55 8 Glenn 4 -82 2 Fergus 5 - -Sample Output - -TESTCASE 01 - -78.00 - -TESTCASE 02 - -81.00 - -Explanation - -TESTCASE 01 - -Average = -Can you solve this challenge in 4 lines of code or less? -NOTE: There is no penalty for solutions that are correct but have more than 4 lines. -''' - -from collections import namedtuple -if __name__ == '__main__': - n = int(input()) - Student=namedtuple('Student',input()) - Slist=list() - for i in range(n): - d=input().split() - Slist.append(Student(*d)) -total=0 -for S in Slist: - total+=int(S.MARKS) - -print('{:.2f}'.format(total/n)) \ No newline at end of file diff --git a/Python/CollectionsOrderedDict.py b/Python/CollectionsOrderedDict.py deleted file mode 100644 index 67425806..00000000 --- a/Python/CollectionsOrderedDict.py +++ /dev/null @@ -1,102 +0,0 @@ -''' -collections.OrderedDict - -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. - -Example - -Code - ->>> from collections import OrderedDict ->>> ->>> ordinary_dictionary = {} ->>> ordinary_dictionary['a'] = 1 ->>> ordinary_dictionary['b'] = 2 ->>> ordinary_dictionary['c'] = 3 ->>> ordinary_dictionary['d'] = 4 ->>> ordinary_dictionary['e'] = 5 ->>> ->>> print ordinary_dictionary -{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} ->>> ->>> ordered_dictionary = OrderedDict() ->>> ordered_dictionary['a'] = 1 ->>> ordered_dictionary['b'] = 2 ->>> ordered_dictionary['c'] = 3 ->>> ordered_dictionary['d'] = 4 ->>> ordered_dictionary['e'] = 5 ->>> ->>> print ordered_dictionary -OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) - -Task - -You are the manager of a supermarket. -You have a list of - -items together with their prices that consumers bought on a particular day. -Your task is to print each item_name and net_price in order of its first occurrence. - -item_name = Name of the item. -net_price = Quantity of the item sold multiplied by the price of each item. - -Input Format - -The first line contains the number of items, -. -The next - -lines contains the item's name and price, separated by a space. - -Constraints - -Output Format - -Print the item_name and net_price in order of its first occurrence. - -Sample Input - -9 -BANANA FRIES 12 -POTATO CHIPS 30 -APPLE JUICE 10 -CANDY 5 -APPLE JUICE 10 -CANDY 5 -CANDY 5 -CANDY 5 -POTATO CHIPS 30 - -Sample Output - -BANANA FRIES 12 -POTATO CHIPS 60 -APPLE JUICE 20 -CANDY 20 - -Explanation - -BANANA FRIES: Quantity bought: -, Price: -Net Price: -POTATO CHIPS: Quantity bought: , Price: -Net Price: -APPLE JUICE: Quantity bought: , Price: -Net Price: -CANDY: Quantity bought: , Price: -Net Price: -''' - -from collections import OrderedDict -if __name__ == '__main__': - n = int(input()) - l=OrderedDict() - for i in range(n): - d=input().split() - c=d[:-1] - try: - l[' '.join(c)]+=int(d[-1]) - except: - l[' '.join(c)]=int(d[-1]) -for i in l.keys(): - print(i,l[i]) \ No newline at end of file diff --git a/Python/Compress the String.py b/Python/Compress the String.py deleted file mode 100644 index 925a98be..00000000 --- a/Python/Compress the String.py +++ /dev/null @@ -1,52 +0,0 @@ -''' -In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools . To read more about this function, Check this out . - -You are given a string -. Suppose a character '' occurs consecutively times in the string. Replace these consecutive occurrences of the character '' with - -in the string. - -For a better understanding of the problem, check the explanation. - -Input Format - -A single line of input consisting of the string - -. - -Output Format - -A single line of output consisting of the modified string. - -Constraints - -All the characters of -denote integers between and - -. - -Sample Input - -1222311 - -Sample Output - -(1, 1) (3, 2) (1, 3) (2, 1) - -Explanation - -First, the character -occurs only once. It is replaced by . Then the character occurs three times, and it is replaced by - -and so on. - -Also, note the single space within each compression and between the compressions. -''' - -from itertools import groupby -if __name__ == '__main__': - l = list(map(lambda x: int(x),list(input()))) - -r=[(len(list(g)),k) for k,g in groupby(l)] -for _ in r: - print(_,end=' ') \ No newline at end of file diff --git a/Python/Count of n digit numbers whose sum of digits equals to given sum.py b/Python/Count of n digit numbers whose sum of digits equals to given sum.py deleted file mode 100644 index bf8e22d8..00000000 --- a/Python/Count of n digit numbers whose sum of digits equals to given sum.py +++ /dev/null @@ -1,18 +0,0 @@ -def sumofdigits(n): - sum=0 - temp=0 - while n>0: - num=n%10 - n=n//10 - sum=sum+num - return sum - -def count(n,sum): - count=0 - for i in range(10,10**n+1): - if sumofdigits(i) == sum: - count+=1 - return count - -print(count(2,5)) -# print(sumofdigits(14)) \ No newline at end of file diff --git "a/Python/Count ways to reach the n\342\200\231th stair.py" "b/Python/Count ways to reach the n\342\200\231th stair.py" deleted file mode 100644 index 67d39dd3..00000000 --- "a/Python/Count ways to reach the n\342\200\231th stair.py" +++ /dev/null @@ -1,65 +0,0 @@ - -""" -Question: - -Distinct ways to climb a n step staircase where -each time you can either climb 1 or 2 steps. -""" - -""" -Solution 1: -We can easily find recursive nature in above problem. -The person can reach n’th stair from either (n-1)’th stair or from (n-2)’th stair. -Let the total number of ways to reach n’t stair be ‘ways(n)’. -The value of ‘ways(n)’ can be written as following. -ways(n)=ways(n-1)+ways(n-2) - -The above expression is actually the expression for Fibonacci numbers, but there is one thing to notice, the value of ways(n) is equal to fibonacci(n+1). - -ways(1) = fib(2) = 1 -ways(2) = fib(3) = 2 -ways(3) = fib(4) = 3 -""" - -def fibo(n:int) -> int: - return n if n<=1 else fibo(n-1)+fibo(n-2) - -def ways(n:int) -> int: - fmt = "n needs to be positive integer, your input {}" - assert isinstance(n, int) and n > 0, fmt.format(n) - return fibo(n+1) - -# print(ways(4)) - -""" -Solution 2: -This uses bottom to top approach , in tabular method , -We use table to store the previous values in list. -""" -def climb_stairs(n: int) -> int: - """ - Args: - n: number of steps of staircase - Returns: - Distinct ways to climb a n step staircase - Raises: - AssertionError: n not positive integer - """ - fmt = "n needs to be positive integer, your input {}" - assert isinstance(n, int) and n > 0, fmt.format(n) - if n == 1: - return 1 - dp = [0] * (n + 1) - dp[0], dp[1] = (1, 1) - for i in range(2, n + 1): - dp[i] = dp[i - 1] + dp[i - 2] - return dp[n] - -# climb_stairs(3) -# 3 -# climb_stairs(1) -# 1 -# climb_stairs(-7) -# Traceback (most recent call last): -# ... -# AssertionError: n needs to be positive integer, your input -7 \ No newline at end of file diff --git a/Python/Day-of-the-Programmer.py b/Python/Day-of-the-Programmer.py deleted file mode 100644 index bd02626c..00000000 --- a/Python/Day-of-the-Programmer.py +++ /dev/null @@ -1,47 +0,0 @@ -''' -Day - of - the - Programmer - -Short Problem Definition: -Marie invented a Time Machine and wants to test it by time-traveling to visit Russia on the Day of the Programmer (the 256th day of the year) during a year in the inclusive range from 1700 to 2700. - -Link -Day of The Programmer - -Complexity: -time complexity is O(-1) - -space complexity is O(-1) - -Execution: -As I have pointed out in the past, no engineer should ever implement any calendar related functions. It should be done natively by the language or by a library. - -''' - -# Solution: -#!/bin/python3 - -import math -import os -import random -import re -import sys - -# Complete the solve function below. -def solve(year): - if (year == 1918): - return '26.09.1918' - elif ((year <= 1917) & (year%4 == 0)) or ((year > 1918) & (year%400 == 0 or ((year%4 == 0) & (year%100 != 0)))): - return '12.09.%s' %year - else: - return '13.09.%s' %year - -if __name__ == '__main__': - fptr = open(os.environ['OUTPUT_PATH'], 'w') - - year = int(input()) - - result = solve(year) - - fptr.write(result + '\n') - - fptr.close() \ No newline at end of file diff --git a/Python/DefaultDict_Tutorial.py b/Python/DefaultDict_Tutorial.py deleted file mode 100644 index 41ea4506..00000000 --- a/Python/DefaultDict_Tutorial.py +++ /dev/null @@ -1,71 +0,0 @@ -# https://www.hackerrank.com/challenges/defaultdict-tutorial/problem - -# The default dict 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. -# For example: - -#from collections import defaultdict -#d = defaultdict(list) -# d['python'].append("awesome") -#d['something-else'].append("not relevant") -# d['python'].append("language") -# for i in d.items(): -# print i - -# This prints : - -#('python', ['awesome', 'language']) -#('something-else', ['not relevant']) - -# In this challenge, you will be given 2 integers, n and m. There are n words, which might repeat, in word group . 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 occurance of m in group A. If it does not appear , print -1. - -# Constrainst : - -#1 <= n <= 10000 -#1 <= n <= 100 -# 1 <= length of each word in the input <=100 - -# Input Format :- - -# The first line contains integers, n and m separated by a space. -# The next n lines contains the words belonging to group A. -# The next m lines contains the words belonging to group B.\ - -# Output formats: -# Output m lines -# The ith line should contain 1-indexed positions of the occurance of the ith word separated by spaces. - -# Sample input: - -# 5 2 -# a -# a -# b -# a -# b -# a -# b - -# Sample Output : -# 1 2 4 -# 3 5 - -# Explanation - -# 'a' appeared 3 times in positions 1,2 and 4 -# 'b' appeared 2 times in positions 3 and 5. -# In the sample problem, if 'c' also appeared in word group B, you would print -1 - -from collections import defaultdict -d = defaultdict(list) - -n, m = map(int, input().split()) - -for i in range(1, n + 1): - d[input()].append(i) - -for i in range(0, m): - list_of_indices = d[input()] - if len(list_of_indices) == 0: - print(-1) - else: - print(*list_of_indices, sep=' ') diff --git a/Python/DesignerDoorMat.py b/Python/DesignerDoorMat.py deleted file mode 100644 index 1c9609c7..00000000 --- a/Python/DesignerDoorMat.py +++ /dev/null @@ -1,72 +0,0 @@ -''' -Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications: - -Mat size must be X. ( is an odd natural number, and is times .) -The design should have 'WELCOME' written in the center. -The design pattern should only use |, . and - characters. -Sample Designs - - Size: 7 x 21 - ---------.|.--------- - ------.|..|..|.------ - ---.|..|..|..|..|.--- - -------WELCOME------- - ---.|..|..|..|..|.--- - ------.|..|..|.------ - ---------.|.--------- - - Size: 11 x 33 - ---------------.|.--------------- - ------------.|..|..|.------------ - ---------.|..|..|..|..|.--------- - ------.|..|..|..|..|..|..|.------ - ---.|..|..|..|..|..|..|..|..|.--- - -------------WELCOME------------- - ---.|..|..|..|..|..|..|..|..|.--- - ------.|..|..|..|..|..|..|.------ - ---------.|..|..|..|..|.--------- - ------------.|..|..|.------------ - ---------------.|.--------------- -Input Format - -A single line containing the space separated values of and . - -Constraints - -Output Format - -Output the design pattern. - -Sample Input - -9 27 -Sample Output - -------------.|.------------ ----------.|..|..|.--------- -------.|..|..|..|..|.------ ----.|..|..|..|..|..|..|.--- -----------WELCOME---------- ----.|..|..|..|..|..|..|.--- -------.|..|..|..|..|.------ ----------.|..|..|.--------- -------------.|.------------ - - -''' - -n,m = map(int,input().split(" ")) -str = "WELCOME" -symbol = ".|." - -for i in range(0,n): - if i % 2 != 0: - print((symbol*i).center(m,"-")) - -print(str.center(m,"-")) - -i = n-1 -while i>=0: - if i % 2 != 0: - print((symbol*i).center(m,"-")) - i-=1 diff --git a/Python/Else-If.py b/Python/Else-If.py deleted file mode 100644 index 9e2a6db9..00000000 --- a/Python/Else-If.py +++ /dev/null @@ -1,52 +0,0 @@ -''' -Task -Given an integer, -, perform the following conditional actions: - If -is odd, print Weird -If -is even and in the inclusive range of to -, print Not Weird -If -is even and in the inclusive range of to -, print Weird -If -is even and greater than - , print Not Weird -Input Format -A single line containing a positive integer, -. -Constraints -Output Format -Print Weird if the number is weird; otherwise, print Not Weird. -Sample Input 0 -3 -Sample Output 0 -Weird -Explanation 0 -is odd and odd numbers are weird, so we print Weird. -Sample Input 1 -24 -Sample Output 1 -Not Weird -Explanation 1 -and is even, so it isn't weird. Thus, we print Not Weird. -''' - -try: - raw_input -except NameError: - raw_input = input - - -if __name__ == '__main__': - n = int(raw_input().strip()) - if n%2==0 and n<=5: - print("Not Weird") - elif n%2!=0: - print("Weird") - elif n%2==0 and n<=20: - print("Weird") - else: - print("Not Weird") - diff --git a/Python/ExtraLongFactorials.py b/Python/ExtraLongFactorials.py deleted file mode 100644 index 0aa23385..00000000 --- a/Python/ExtraLongFactorials.py +++ /dev/null @@ -1,58 +0,0 @@ -""" -File: ExtraLongFactorials.py -Description: A solution for ExtraLongFactorials -Author: Nuttaphat Arunoprayoch -Date: 06-Oct-2020 - -# Information -Link: https://www.hackerrank.com/challenges/extra-long-factorials - -The factorial of the integer , written , is defined as: -n! = n * (n-1) * (n-2) * .... 1 -Calculate and print the factorial of a given integer. -For example, if n=30, we calculate 30*29*28*....*1 - -# Function Description -Complete the extraLongFactorials function in the editor below. It should print the result and return. -extraLongFactorials has the following parameter(s): - * n -> int - -Note: Factorials of can't be stored even in a long long variable. Big integers must be used for such calculations. -Languages like Java, Python, Ruby etc. can handle big integers, but we need to write additional code in C/C++ to handle huge values. -We recommend solving this challenge using BigIntegers. - -# Input Format -Input consists of a single integer - -# Constraints -1 <= n <= 100 - -# Output Format -Print the factorial of n. - -# Sample Input -25 - -# Sample Output -15511210043330985984000000 -""" -# Import libraries -import math -import os -import random -import re -import sys -from functools import reduce - - -# Complete the extraLongFactorials function below. -def extraLongFactorials(n): - all_nums = [i for i in range(1, n+1)] - res = reduce(lambda x,y: x*y, all_nums) - print(res) - return res - - -if __name__ == '__main__': - n = int(input()) - extraLongFactorials(n) diff --git a/Python/Find a string.py b/Python/Find a string.py deleted file mode 100644 index 75bba414..00000000 --- a/Python/Find a string.py +++ /dev/null @@ -1,60 +0,0 @@ -''' -In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left. - -NOTE: String letters are case-sensitive. - -Input Format - -The first line of input contains the original string. The next line contains the substring. - -Constraints - - -Each character in the string is an ascii character. - -Output Format - -Output the integer number indicating the total number of occurrences of the substring in the original string. - -Sample Input - -ABCDCDC -CDC - -Sample Output - -2 - -Concept - -Some string processing examples, such as these, might be useful. -There are a couple of new concepts: -In Python, the length of a string is found by the function len(s), where - -is the string. -To traverse through the length of a string, use a for loop: - -for i in range(0, len(s)): - print (s[i]) - -A range function is used to loop over some length: - -range (0, 5) - -Here, the range loops over -to . is excluded. -''' - -def count_substring(string, sub_string): - count=0 - for i in range(0,len(string)-len(sub_string)+1): - if string[i:i+len(sub_string)] == sub_string: - count+=1 - return count - -if __name__ == '__main__': - string = input().strip() - sub_string = input().strip() - - count = count_substring(string, sub_string) - print(count) \ No newline at end of file diff --git a/Python/FindDigits.py b/Python/FindDigits.py deleted file mode 100644 index 1923f5ca..00000000 --- a/Python/FindDigits.py +++ /dev/null @@ -1,100 +0,0 @@ -''' -An integer d is a divisor of an integer n if the remainder of n % d = 0. - -Given an integer, for each digit that makes up the integer determine whether it is a divisor. Count the number of divisors occurring within the integer. - -Note: Each digit is considered to be unique, so each occurrence of the same digit should be counted (e.g. for n = 111, 1 ,is a divisor of 111 each time it occurs so the answer is 3). - -Function Description - -Complete the findDigits function in the editor below. It should return an integer representing the number of digits of that are divisors of d. - -findDigits has the following parameter(s): - -* n: an integer to analyze - -Input Format - -The first line is an integer, t, indicating the number of test cases. -The t subsequent lines each contain an integer, n. - -Constraints - -1<= t <= 15 -0< n< 10^9 - -Output Format - -For every test case, count the number of digits in n that are divisors of n. Print each answer on a new line. - -Sample Input - -2 -12 -1012 - -Sample Output - -2 -3 - -Explanation - -The number 12 is broken into two digits,1 and 2. When 12 is divided by either of those two digits, the remainder is 0 so they are both divisors. - -The number 1012 is broken into four digits,1 ,0 , 1 and 2. 1012 is evenly divisible by its digits 1, 1, and 2, but it is not divisible by 0 as division by zero is undefined. - -''' - -import os -import random -import re -import sys - -# Complete the findDigits function below. -def findDigits(n): - count = 0 - print(list(str(n))) - for i in list(str(n)): - if int(i) != 0 and n % int(i) == 0: - count += 1 - return count - -if __name__ == '__main__': - fptr = open(os.environ['OUTPUT_PATH'], 'w') - - t = int(input()) - - for t_itr in range(t): - n = int(input()) - - result = findDigits(n) - - fptr.write(str(result) + '\n') - - fptr.close() - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Python/FindSecondRunnerUp.py b/Python/FindSecondRunnerUp.py deleted file mode 100644 index 254aa4d8..00000000 --- a/Python/FindSecondRunnerUp.py +++ /dev/null @@ -1,42 +0,0 @@ -''' -Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given - -scores. Store them in a list and find the score of the runner-up. - -Input Format - -The first line contains -. The second line contains an array of - -integers each separated by a space. - -Constraints - -Output Format - -Print the runner-up score. - -Sample Input 0 - -5 -2 3 6 6 5 - -Sample Output 0 - -5 - -Explanation 0 - -Given list is -. The maximum score is , second maximum is . Hence, we print as the runner-up score. -''' - -if __name__ == '__main__': - n = int(input()) - arr = list(map(int, input().split())) - -s,f=0,max(arr) -for i in range(arr.count(f)): - arr.remove(f) -s=max(arr) -print(s) \ No newline at end of file diff --git a/Python/FindingThePercentage.py b/Python/FindingThePercentage.py deleted file mode 100644 index 699c2502..00000000 --- a/Python/FindingThePercentage.py +++ /dev/null @@ -1,58 +0,0 @@ -''' -You have a record of 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 followed by the names and marks for - -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. - -Input Format - -The first line contains the integer -, the number of students. The next - -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. - -Constraints - -Output Format - -Print one line: The average of the marks obtained by the particular student correct to 2 decimal places. - -Sample Input 0 - -3 -Krishna 67 68 69 -Arjun 70 98 63 -Malika 52 56 60 -Malika - -Sample Output 0 - -56.00 - -Explanation 0 - -Marks for Malika are -whose average is - -Sample Input 1 - -2 -Harsh 25 26.5 28 -Anurag 26 28 30 -Harsh - -Sample Output 1 - -26.50 - - -''' - -if __name__ == '__main__': - n = int(input()) - student_marks = {} - for _ in range(n): - name, *line = input().split() - scores = list(map(float, line)) - student_marks[name] = scores - query_name = input() -print('{:.2f}'.format(sum(student_marks[query_name])/len(student_marks[query_name]))) \ No newline at end of file diff --git a/Python/HeapsAlgorithm.py b/Python/HeapsAlgorithm.py deleted file mode 100644 index af30ad66..00000000 --- a/Python/HeapsAlgorithm.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -Heap's algorithm returns the list of all permutations possible from a list. -It minimizes movement by generating each permutation from the previous one -by swapping only two elements. -More information: -https://en.wikipedia.org/wiki/Heap%27s_algorithm. -""" - - -def heaps(arr: list) -> list: - """ - Pure python implementation of the Heap's algorithm (recursive version), - returning all permutations of a list. - >>> heaps([]) - [()] - >>> heaps([0]) - [(0,)] - >>> heaps([-1, 1]) - [(-1, 1), (1, -1)] - >>> heaps([1, 2, 3]) - [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] - >>> from itertools import permutations - >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) - True - >>> all(sorted(heaps(x)) == sorted(permutations(x)) - ... for x in ([], [0], [-1, 1], [1, 2, 3])) - True - """ - - if len(arr) <= 1: - return [tuple(arr)] - - res = [] - - def generate(k: int, arr: list): - if k == 1: - res.append(tuple(arr[:])) - return - - generate(k - 1, arr) - - for i in range(k - 1): - if k % 2 == 0: # k is even - arr[i], arr[k - 1] = arr[k - 1], arr[i] - else: # k is odd - arr[0], arr[k - 1] = arr[k - 1], arr[0] - generate(k - 1, arr) - - generate(len(arr), arr) - return res - - -if __name__ == "__main__": - user_input = input("Enter numbers separated by a comma:\n").strip() - arr = [int(item) for item in user_input.split(",")] - print(heaps(arr)) diff --git a/Python/Introduction to Sets.py b/Python/Introduction to Sets.py deleted file mode 100644 index 779eefe3..00000000 --- a/Python/Introduction to Sets.py +++ /dev/null @@ -1,73 +0,0 @@ -''' -A set is an unordered collection of elements without duplicate entries. -When printed, iterated or converted into a sequence, its elements will appear in an arbitrary order. - -Example - ->>> print set() -set([]) - ->>> print set('HackerRank') -set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R']) - ->>> print set([1,2,1,2,3,4,5,6,0,9,12,22,3]) -set([0, 1, 2, 3, 4, 5, 6, 9, 12, 22]) - ->>> print set((1,2,3,4,5,5)) -set([1, 2, 3, 4, 5]) - ->>> print set(set(['H','a','c','k','e','r','r','a','n','k'])) -set(['a', 'c', 'r', 'e', 'H', 'k', 'n']) - ->>> print set({'Hacker' : 'DOSHI', 'Rank' : 616 }) -set(['Hacker', 'Rank']) - ->>> print set(enumerate(['H','a','c','k','e','r','r','a','n','k'])) -set([(6, 'r'), (7, 'a'), (3, 'k'), (4, 'e'), (5, 'r'), (9, 'k'), (2, 'c'), (0, 'H'), (1, 'a'), (8, 'n')]) -Basically, sets are used for membership testing and eliminating duplicate entries. - -Task - -Now, let's use our knowledge of sets and help Mickey. - -Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse. - -Formula used: - -Input Format - -The first line contains the integer, , the total number of plants. -The second line contains the space separated heights of the plants. - -Constraints - - -Output Format - -Output the average height value on a single line. - -Sample Input - -10 -161 182 161 154 176 170 167 171 170 174 -Sample Output - -169.375 -Explanation - -Here, set is the set containing the distinct heights. Using the sum() and len() functions, we can compute the average. -''' - - -def average(arr): - arr = set(arr) - percentage = 0.0 - for item in arr: - percentage+=item - percentage = percentage/len(arr) - return(percentage) -if __name__ == '__main__': - n = int(input()) - arr = list(map(int, input().split())) - result = average(arr) - print(result) diff --git a/Python/IntroductionToSets.py b/Python/IntroductionToSets.py deleted file mode 100644 index f9945318..00000000 --- a/Python/IntroductionToSets.py +++ /dev/null @@ -1,45 +0,0 @@ -''' - -Link to problem: https://www.hackerrank.com/challenges/py-introduction-to-sets/problem - -Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse. - -Formula used: - Average = (Sum of Distinct Heights) / (Total number of distinct heights) - -Input Format: - The first line contains the integer, N, the total number of plants. - The second line contains the N space separated heights of the plants. - -Constraints: - 0 < N <= 100 - -Output Format: - Output the average height value on a single line. - -Sample Input: - 10 - 161 182 161 154 176 170 167 171 170 174 - -Sample Output: - 169.375 - -Explanation: - Here, set ([154, 161, 167, 170, 171, 174, 176, 182]) is the set containing the distinct heights. - Using the sum() and len() functions, we can compute the average. - Average = 1355 / 8 = 169.375 -''' - -def average(array): - # your code goes here - sumOfHeights = 0 - heightSet = set(array) - for height in heightSet: - sumOfHeights += height - return sumOfHeights / len(heightSet) - -if __name__ == '__main__': - n = int(input()) - arr = list(map(int, input().split())) - result = average(arr) - print(result) \ No newline at end of file diff --git a/Python/Iterables and Iterators.py b/Python/Iterables and Iterators.py deleted file mode 100644 index e7fd8691..00000000 --- a/Python/Iterables and Iterators.py +++ /dev/null @@ -1,75 +0,0 @@ -''' -The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python. - -To read more about the functions in this module, check out their documentation here. - -You are given a list of -lowercase English letters. For a given integer , you can select any indices (assume - --based indexing) with a uniform probability from the list. - -Find the probability that at least one of the -indices selected will contain the letter: ' - -'. - -Input Format - -The input consists of three lines. The first line contains the integer -, denoting the length of the list. The next line consists of - -space-separated lowercase English letters, denoting the elements of the list. - -The third and the last line of input contains the integer - -, denoting the number of indices to be selected. - -Output Format - -Output a single line consisting of the probability that at least one of the -indices selected contains the letter:' - -'. - -Note: The answer must be correct up to 3 decimal places. - -Constraints - -All the letters in the list are lowercase English letters. - -Sample Input - -4 -a a c d -2 - -Sample Output - -0.8333 - -Explanation - -All possible unordered tuples of length -comprising of indices from to - -are: - -Out of these combinations, of them contain either index or index which are the indices that contain the letter ' - -'. - -Hence, the answer is -. -''' - -from itertools import combinations -if __name__ == '__main__': - n = int(input()) - l = input().split() - t = int(input()) -p=0 -com=list(combinations(l,t)) -for tup in com: - if 'a' in tup: - p+=1 -print('{:.3f}'.format(p/len(com))) \ No newline at end of file diff --git a/Python/ItertoolsCombinations.py b/Python/ItertoolsCombinations.py deleted file mode 100644 index bac8509b..00000000 --- a/Python/ItertoolsCombinations.py +++ /dev/null @@ -1,72 +0,0 @@ -''' -itertools.combinations(iterable, r) -This tool returns the - -length subsequences of elements from the input iterable. - -Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order. - -Sample Code - ->>> from itertools import combinations ->>> ->>> print list(combinations('12345',2)) -[('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '4'), ('3', '5'), ('4', '5')] ->>> ->>> A = [1,1,3,3,3] ->>> print list(combinations(A,4)) -[(1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3), (1, 3, 3, 3), (1, 3, 3, 3)] - -Task - -You are given a string -. -Your task is to print all possible combinations, up to size - -, of the string in lexicographic sorted order. - -Input Format - -A single line containing the string -and integer value - -separated by a space. - -Constraints - - -The string contains only UPPERCASE characters. - -Output Format - -Print the different combinations of string - -on separate lines. - -Sample Input - -HACK 2 - -Sample Output - -A -C -H -K -AC -AH -AK -CH -CK -HK - -''' - -from itertools import combinations -if __name__ == '__main__': - s = input() - word,r = s.split() - -for i in range(1,int(r)+1): - for p in sorted(list(combinations(sorted(word),i))): - print(''.join(p)) \ No newline at end of file diff --git a/Python/ItertoolsCombinations_with_replacement.py b/Python/ItertoolsCombinations_with_replacement.py deleted file mode 100644 index 517d9652..00000000 --- a/Python/ItertoolsCombinations_with_replacement.py +++ /dev/null @@ -1,71 +0,0 @@ -''' -itertools.combinations_with_replacement(iterable, r) -This tool returns - -length subsequences of elements from the input iterable allowing individual elements to be repeated more than once. - -Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order. - -Sample Code - ->>> from itertools import combinations_with_replacement ->>> ->>> print list(combinations_with_replacement('12345',2)) -[('1', '1'), ('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '2'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '3'), ('3', '4'), ('3', '5'), ('4', '4'), ('4', '5'), ('5', '5')] ->>> ->>> A = [1,1,3,3,3] ->>> print list(combinations(A,2)) -[(1, 1), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (3, 3), (3, 3), (3, 3)] - -Task - -You are given a string -. -Your task is to print all possible size - -replacement combinations of the string in lexicographic sorted order. - -Input Format - -A single line containing the string -and integer value - -separated by a space. - -Constraints - - -The string contains only UPPERCASE characters. - -Output Format - -Print the combinations with their replacements of string - -on separate lines. - -Sample Input - -HACK 2 - -Sample Output - -AA -AC -AH -AK -CC -CH -CK -HH -HK -KK - -''' - -from itertools import combinations_with_replacement -if __name__ == '__main__': - s = input() - word,r = s.split() - -for p in sorted(list(combinations_with_replacement(sorted(word),int(r)))): - print(''.join(p)) \ No newline at end of file diff --git a/Python/ItertoolsPermutations.py b/Python/ItertoolsPermutations.py deleted file mode 100644 index f476713b..00000000 --- a/Python/ItertoolsPermutations.py +++ /dev/null @@ -1,87 +0,0 @@ -''' -itertools.permutations(iterable[, r]) - -This tool returns successive - -length permutations of elements in an iterable. - -If -is not specified or is None, then - -defaults to the length of the iterable, and all possible full length permutations are generated. - -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. - -Sample Code - ->>> from itertools import permutations ->>> print permutations(['1','2','3']) - ->>> ->>> print list(permutations(['1','2','3'])) -[('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')] ->>> ->>> print list(permutations(['1','2','3'],2)) -[('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')] ->>> ->>> print list(permutations('abc',3)) -[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')] - -Task - -You are given a string -. -Your task is to print all possible permutations of size - -of the string in lexicographic sorted order. - -Input Format - -A single line containing the space separated string -and the integer value - -. - -Constraints - - -The string contains only UPPERCASE characters. - -Output Format - -Print the permutations of the string - -on separate lines. - -Sample Input - -HACK 2 - -Sample Output - -AC -AH -AK -CA -CH -CK -HA -HC -HK -KA -KC -KH - -Explanation - -All possible size -permutations of the string "HACK" are printed in lexicographic sorted order. -''' - -from itertools import permutations -if __name__ == '__main__': - s = input() - word,r = s.split() - -for p in sorted(list(permutations(word,int(r)))): - print(''.join(p)) \ No newline at end of file diff --git a/Python/ItertoolsProduct.py b/Python/ItertoolsProduct.py deleted file mode 100644 index 06df25bc..00000000 --- a/Python/ItertoolsProduct.py +++ /dev/null @@ -1,81 +0,0 @@ -''' -itertools.product() - -This tool computes the cartesian product of input iterables. -It is equivalent to nested for-loops. -For example, product(A, B) returns the same as ((x,y) for x in A for y in B). - -Sample Code - ->>> from itertools import product ->>> ->>> print list(product([1,2,3],repeat = 2)) -[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)] ->>> ->>> print list(product([1,2,3],[3,4])) -[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)] ->>> ->>> A = [[1,2,3],[3,4,5]] ->>> print list(product(*A)) -[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5)] ->>> ->>> B = [[1,2,3],[3,4,5],[7,8]] ->>> print list(product(*B)) -[(1, 3, 7), (1, 3, 8), (1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 3, 7), (2, 3, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 3, 7), (3, 3, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)] - -Task - -You are given a two lists -and . Your task is to compute their cartesian product X - -. - -Example - -A = [1, 2] -B = [3, 4] - -AxB = [(1, 3), (1, 4), (2, 3), (2, 4)] - -Note: -and - -are sorted lists, and the cartesian product's tuples should be output in sorted order. - -Input Format - -The first line contains the space separated elements of list -. -The second line contains the space separated elements of list - -. - -Both lists have no duplicate integer elements. - -Constraints - - -Output Format - -Output the space separated tuples of the cartesian product. - -Sample Input - - 1 2 - 3 4 - -Sample Output - - (1, 3) (1, 4) (2, 3) (2, 4) - -''' - -from itertools import product -if __name__ == '__main__': - l1 = input() - l2 = input() - A= list(map(lambda x: int(x),l1.split())) - B= list(map(lambda x: int(x),l2.split())) - -for r in list(product(A,B)): - print(r,end=" ") \ No newline at end of file diff --git a/Python/LeapYear.py b/Python/LeapYear.py deleted file mode 100644 index 5dfad3af..00000000 --- a/Python/LeapYear.py +++ /dev/null @@ -1,45 +0,0 @@ -''' -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. -In the Gregorian calendar three criteria must be taken into account to identify leap years: - - The year can be evenly divided by 4, is a leap year, unless: - The year can be evenly divided by 100, it is NOT a leap year, unless: - The year is also evenly divisible by 400. Then it is a leap year. - -This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years.Source - -Task -You are given the year, and you have to write a function to check if the year is leap or not. - -Note that you have to complete the function and remaining code is given as template. - -Input Format - -Read y, the year that needs to be checked. - -Constraints - -Output Format - -Output is taken care of by the template. Your function must return a boolean value (True/False) - -Sample Input 0 - -1990 - -Sample Output 0 - -False - -Explanation 0 - -1990 is not a multiple of 4 hence it's not a leap year. -''' -def is_leap(year): - leap = False - if ((year%4==0 and year%100!=0) or year%400==0) and year>=1900: - leap=True - return leap - -year = int(input()) -print(is_leap(year)) \ No newline at end of file diff --git a/Python/LeftRotation.py b/Python/LeftRotation.py deleted file mode 100644 index 69292177..00000000 --- a/Python/LeftRotation.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Created on Sun Oct 4 15:15:37 2020 - -@author: Tanmoyee -""" - -''' A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. - -Example - -d=2 -arr=[1,2,3,4,5] -after 2 rotations, arr'=[3,4,5,1,2] -''' - - - - - - -#!/bin/python3 - -import math -import os -import random -import re -import sys - -def left_rotate(a,d): - l=a[d:] + a[:d] - print(" ".join(list(map(str,l)))) - -if __name__ == '__main__': - nd = input().split() - - n = int(nd[0]) - - d = int(nd[1]) - - a = list(map(int, input().rstrip().split())) - result=left_rotate(a,d) - diff --git a/Python/ListComprehensions.py b/Python/ListComprehensions.py deleted file mode 100644 index cf06b394..00000000 --- a/Python/ListComprehensions.py +++ /dev/null @@ -1,58 +0,0 @@ -''' -Let's learn about list comprehensions! You are given three integers and representing the dimensions of a cuboid along with an integer . You have to print a list of all possible coordinates given by on a 3D grid where the sum of is not equal to . Here, - -Input Format - -Four integers -and - -each on four separate lines, respectively. - -Constraints - -Print the list in lexicographic increasing order. - -Sample Input 0 - -1 -1 -1 -2 - -Sample Output 0 - -[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]] - -Explanation 0 - -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. - -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. - -python x = int ( raw_input()) y = int ( raw_input()) n = int ( raw_input()) ar = [] p = 0 for i in range ( x + 1 ) : for j in range( y + 1): if i+j != n: ar.append([]) ar[p] = [ i , j ] p+=1 print ar -Other smaller codes may also exist, but using list comprehensions is always a good option. Code using list comprehensions: - -python x = int ( raw_input()) y = int ( raw_input()) n = int ( raw_input()) print [ [ i, j] for i in range( x + 1) for j in range( y + 1) if ( ( i + j ) != n )] - -Sample Input 1 - -2 -2 -2 -2 - -Sample Output 1 - -[[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]] - - -''' -if __name__ == '__main__': - x = int(input()) - y = int(input()) - z = int(input()) - n = int(input()) - -print([[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]) \ No newline at end of file diff --git a/Python/Matrix_Script.py b/Python/Matrix_Script.py deleted file mode 100644 index f1224fd4..00000000 --- a/Python/Matrix_Script.py +++ /dev/null @@ -1,75 +0,0 @@ -'''Neo has a complex matrix script. The matrix script is a X grid of strings. It consists of alphanumeric characters, spaces and symbols (!,@,#,$,%,&). - -Capture.JPG - -To decode the script, Neo needs to read each column and select only the alphanumeric characters and connect them. Neo reads the column from top to bottom and starts reading from the leftmost column. - -If there are symbols or spaces between two alphanumeric characters of the decoded script, then Neo replaces them with a single space '' for better readability. - -Neo feels that there is no need to use 'if' conditions for decoding. - -Alphanumeric characters consist of: [A-Z, a-z, and 0-9]. - -Input Format - -The first line contains space-separated integers (rows) and (columns) respectively. -The next lines contain the row elements of the matrix script. - -Constraints - - -Note: A score will be awarded for using 'if' conditions in your code. - -Output Format - -Print the decoded matrix script. - -Sample Input 0 - -7 3 -Tsi -h%x -i # -sM -$a -#t% -ir! -Sample Output 0 - -This is Matrix# %! -Explanation 0 - -The decoded script is: - -This$#is% Matrix# %! -Neo replaces the symbols or spaces between two alphanumeric characters with a single space ' ' for better readability. - -So, the final decoded script is: - -This is Matrix# %! -''' - -#Program - - -#!/bin/python3 - -import math -import os -import random -import re -import sys - - - - - -n, m = map(int, input().split()) -a, b = [], "" -for _ in range(n): - a.append(input()) - -for z in zip(*a): - b += "".join(z) - -print(re.sub(r"(?<=\w)([^\w]+)(?=\w)", " ", b)) diff --git a/Python/MergeTheTools.py b/Python/MergeTheTools.py deleted file mode 100644 index 9bb465d4..00000000 --- a/Python/MergeTheTools.py +++ /dev/null @@ -1,89 +0,0 @@ -''' - -Consider the following: - - A string, - -, of length where -. -An integer, -, where is a factor of - - . - -We can split -into subsegments where each subsegment, , consists of a contiguous block of characters in . Then, use each to create string - -such that: - - The characters in - -are a subsequence of the characters in -. -Any repeat occurrence of a character is removed from the string such that each character in -occurs exactly once. In other words, if the character at some index in occurs at a previous index in , then do not include the character in string - - . - -Given -and , print lines where each line denotes string - -. - -Input Format - -The first line contains a single string denoting -. -The second line contains an integer, - -, denoting the length of each subsegment. - -Constraints - -, where is the length of It is guaranteed that is a multiple of - - . - -Output Format - -Print -lines where each line contains string - -. - -Sample Input - -AABCAAADA -3 - -Sample Output - -AB -CA -AD - -Explanation - -String -is split into equal parts of length . We convert each to by removing any subsequent occurrences non-distinct characters in - -: - -We then print each on a new line. -''' - -def merge_the_tools(string, k): - # your code goes here - lst=list(string[i:i+k] for i in range(0,len(string),k)) - #print(lst) - for s in lst: - l=[] - for i in s: - if not i in l: - l.append(i) - #print(i) - print(''.join(l)) - -if __name__ == '__main__': - string, k = input(), int(input()) - merge_the_tools(string, k) diff --git a/Python/MergeTwoSortedArray.py b/Python/MergeTwoSortedArray.py deleted file mode 100644 index d40adb42..00000000 --- a/Python/MergeTwoSortedArray.py +++ /dev/null @@ -1,113 +0,0 @@ -""" -You have been given two sorted arrays/lists(ARR1 and ARR2) of size N and M respectively, merge them into a third array/list such that the third array is also sorted. -Input Format : - -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -First line of each test case or query contains an integer 'N' representing the size of the first array/list. - -Second line contains 'N' single space separated integers representing the elements of the first array/list. - -Third line contains an integer 'M' representing the size of the second array/list. - -Fourth line contains 'M' single space separated integers representing the elements of the second array/list. - -Output Format : - -For each test case, print the sorted array/list(of size N + M) in a single row, separated by a single space. - -Output for every test case will be printed in a separate line. - -Constraints : - -1 <= t <= 10^2 -0 <= N <= 10^5 -0 <= M <= 10^5 -Time Limit: 1 sec - -Sample Input 1 : - -1 -5 -1 3 4 7 11 -4 -2 4 6 13 - -Sample Output 1 : - -1 2 3 4 4 6 7 11 13 - -Sample Input 2 : - -2 -3 -10 100 500 -7 -4 7 9 25 30 300 450 -4 -7 45 89 90 -0 - -Sample Output 2 : - -4 7 9 10 25 30 100 300 450 500 -7 45 89 90 -""" - - - - - -from sys import stdin - -def merge(arr1, n, arr2, m) : - i,j=0,0 - arr=[] - while i 0 : - - arr1, n = takeInput() - arr2, m = takeInput() - - ans = merge(arr1, n, arr2, m) - printList(ans, (n + m)) - - t -= 1 diff --git a/Python/ModDivmod.py b/Python/ModDivmod.py deleted file mode 100644 index 8c2a513d..00000000 --- a/Python/ModDivmod.py +++ /dev/null @@ -1,43 +0,0 @@ -''' -One of the built-in functions of Python is divmod, which takes two arguments and and returns a tuple containing the quotient of a/b first and then the remainder a. - -For example: - ->>> print divmod(177,10) -(17, 7) -Here, the integer division is 177/10 => 17 and the modulo operator is 177%10 => 7. - -Task -Read in two integers, a and b, and print three lines. -The first line is the integer division a//b (While using Python2 remember to import division from __future__). -The second line is the result of the modulo operator: a%b. -The third line prints the divmod of a and b. - -Input Format -The first line contains the first integer, , and the second line contains the second integer, . - -Output Format -Print the result as described above. - -Sample Input - -177 -10 -Sample Output - -17 -7 -(17, 7) -''' - - -if __name__ == '__main__': - a = int(input()) - b = int(input()) - - int_div = a//b - modulo = a%b - - print(int_div) - print(modulo) - print(tuple([int_div, modulo])) \ No newline at end of file diff --git a/Python/Mutations.py b/Python/Mutations.py deleted file mode 100644 index ad10c49c..00000000 --- a/Python/Mutations.py +++ /dev/null @@ -1,81 +0,0 @@ -''' -We have seen that lists are mutable (they can be changed), and tuples are immutable (they cannot be changed). - -Let's try to understand this with an example. - -You are given an immutable string, and you want to make changes to it. - -Example - ->>> string = "abracadabra" - -You can access an index by: - ->>> print string[5] -a - -What if you would like to assign a value? - ->>> string[5] = 'k' -Traceback (most recent call last): - File "", line 1, in -TypeError: 'str' object does not support item assignment - -How would you approach this? - - One solution is to convert the string to a list and then change the value. - -Example - ->>> string = "abracadabra" ->>> l = list(string) ->>> l[5] = 'k' ->>> string = ''.join(l) ->>> print string -abrackdabra - - Another approach is to slice the string and join it back. - -Example - ->>> string = string[:5] + "k" + string[6:] ->>> print string -abrackdabra - -Task -Read a given string, change the character at a given index and then print the modified string. - -Input Format -The first line contains a string, -. -The next line contains an integer , denoting the index location and a character - -separated by a space. - -Output Format -Using any of the methods explained above, replace the character at index -with character - -. - -Sample Input - -abracadabra -5 k - -Sample Output - -abrackdabra - -''' - -def mutate_string(string, position, character): - stl=list(string) - stl[position]=character - return ''.join(stl) - -if __name__ == '__main__': - s = input() - i, c = input().split() - s_new = mutate_string(s, int(i), c) - print(s_new) \ No newline at end of file diff --git a/Python/NestedLists.py b/Python/NestedLists.py deleted file mode 100644 index a72da32b..00000000 --- a/Python/NestedLists.py +++ /dev/null @@ -1,68 +0,0 @@ -''' -Given the names and grades for each student in a Physics class of - -students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. - -Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. - -Input Format - -The first line contains an integer, -, the number of students. -The subsequent lines describe each student over - -lines; the first line contains a student's name, and the second line contains their grade. - -Constraints - - There will always be one or more students having the second lowest grade. - -Output Format - -Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line. - -Sample Input 0 - -5 -Harry -37.21 -Berry -37.21 -Tina -37.2 -Akriti -41 -Harsh -39 - -Sample Output 0 - -Berry -Harry - -Explanation 0 - -There are - -students in this class whose names and grades are assembled to build the following list: - -python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] - -The lowest grade of -belongs to Tina. The second lowest grade of belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line. -''' - -students,names=list(),list() -if __name__ == '__main__': - for _ in range(int(input())): - name = input() - score = float(input()) - students.append([name, score]) -numlist=[i[1] for i in students] -mi=min(numlist) -while min(numlist)==mi: - numlist.remove(mi) -secondlast=min(numlist) -names=[name[0] for name in students if name[1]==secondlast] -for i in sorted(names): - print(i) \ No newline at end of file diff --git a/Python/No Idea! - Find your Happiness.py b/Python/No Idea! - Find your Happiness.py deleted file mode 100644 index 1cb42d81..00000000 --- a/Python/No Idea! - Find your Happiness.py +++ /dev/null @@ -1,53 +0,0 @@ -''' -There is an array of n integers. There are also 2 disjoint sets, A and B, each containing m integers. You like all the integers in set A and dislike all the integers in set B. Your initial happiness is 0. For each i integer in the array, if i ∈ A, you add 1 to your happiness. If i ∈ B, you add -1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end. - -Note: Since A and B are sets, they have no repeated elements. However, the array might contain duplicate elements. - -Constraints - -1 <= n <= 10^5 -1 <= n <= 10^5 -1 <= Any integer in the inputs <= 10^9 - -Input Format - -The first line contains integers n and m separated by a space. -The second line contains n integers, the elements of the array. -The third and fourth lines contain m integers, A and B, respectively. - -Output Format - -Output a single integer, your total happiness. - -Sample Input - -3 2 -1 5 3 -3 1 -5 7 - -Sample Output - -1 - -Explanation - -You gain 1 unit of happiness for elements 3 and 1 in set A. You lose 1 unit for 5 in set B. The element 7 in set B does not exist in the array so it is not included in the calculation. -Hence, the total happiness is 2 - 1 = 1. -''' - -if __name__ == '__main__': - n,m=[int(i) for i in input().split(" ")] - - n1=[int(i) for i in input().split(" ")] - - a=set([int(i) for i in input().split(" ")]) - - b=set([int(i) for i in input().split(" ")]) - happiness=0 - for j in n1: - if j in a: - happiness+=1 - if j in b: - happiness-=1 -print(happiness) diff --git a/Python/NumberToEnglish.py b/Python/NumberToEnglish.py deleted file mode 100644 index 43fe19c3..00000000 --- a/Python/NumberToEnglish.py +++ /dev/null @@ -1,77 +0,0 @@ -# -''' - Problem task: Write a function that accepts a positive integer between 0 and 999 inclusive and returns a string representation of that integer written in English. - Problem Link: https://edabit.com/challenge/mZqMnS3FsL2MPyFMg -''' - -""" -Working -Takes input from Function FormattingNumber() [eg: 123 (type: )] -The input number is converted into String type for better String Manupulation -We intial a result string (String), and a initial string (Dictionary) that contains reference numbers in english - -We check if the user input already exists in our dictionary, if so we return the english version [eg: 14 --> fourteen] -### --Taking example as 569-- #### - -Otherwise, we first divide all digits in 3 parts that is for (0 - 999) in this case [5 6 9] -We now start from the MSP(Most Significant Place [eg: 5 is MSP in 569]) -We get value of 5 from dictionary and append it with string "hundred" and update it in result string -Using dict.get(5) - -We do the same for other digits -Keeping in mind the case for occurance of zero -Keeping in mind the case like [519] in which you have to return the value from dictionary itself -""" - -def NumToEnglish(num): - num = str(num) - - resulted_string = "" - initial_dict = {0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", - 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen", - 16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen", 20: "twenty", 30: "thirty", - 40: "forty", 50: "fifty", 60: "sixty", 70: "seventy", 80: "eighty", 90: "ninety", 100: "hundred"} - - if int(num) in initial_dict.keys(): - return initial_dict.get(int(num)) - else: - length_of_number = len(num) - for i in range(length_of_number): - if i == 0 and int(num[i]) > 0: - resulted_string = str(initial_dict.get(int(num[i]))) + " " + str(initial_dict.get(100)) - elif i == 1 and int(num[1]) == 1: - resulted_string = resulted_string + " " + str(initial_dict.get(int(num[1:3]))) - elif i == 1 and int(num[1]) > 1: - resulted_string = resulted_string + " " + str(initial_dict.get(int(num[1]) * 10)) - elif i == 2 and int(num[1]) != 1 and int(num[i]) > 0: - resulted_string = resulted_string + " " + str(initial_dict.get(int(num[i]))) - - return resulted_string.strip() - -""" -converting all the input number in 3 digit numbers [eg: 13 --> 013, 189 --> 189] - -working -If the number is of 2 digit add 0 in start of number -No need to code of case (number od digit = 1 ie 0 to 9) as this case will already be added in the dictionary -after conversion the formatted number is passed to Function NumToEnglish() -""" - -def FormattingNumber(num): - num = str(num) - if len(num) == 2: - num = "0" + num - return num - -""" -# 't' takes number of test cases as input -# Num is the number input given by the user [eg: 132 (type: )] - -# working -# The code takes input (Num) from user and passes it to Function (FormattingNumber() for formatting all number in format abc) [eg: 13 --> 013, 189 --> 189] -""" -if __name__ == "__main__": - t = int(input()) - for _ in range(t): - Num = int(input()) - print(NumToEnglish(FormattingNumber(Num))) diff --git a/Python/Partition problem.py b/Python/Partition problem.py deleted file mode 100644 index 4be6d473..00000000 --- a/Python/Partition problem.py +++ /dev/null @@ -1,48 +0,0 @@ -""" -Partition problem -Partition problem is to determine whether a given set can be partitioned into two -subsets such that the sum of elements in both subsets is same. - -arr[] = {1, 5, 11, 5} -Output: true -The array can be partitioned as {1, 5, 5} and {11} - -arr[] = {1, 5, 3} -Output: false -The array cannot be partitioned into equal sum sets. -""" - -def isSubsetSum (arr, n, sum): - # Base Cases - if sum == 0: - return True - if n == 0 and sum != 0: - return False - - # If last element is greater than sum, then - # ignore it - if arr[n-1] > sum: - return isSubsetSum (arr, n-1, sum) - - ''' else, check if sum can be obtained by any of - the following - (a) including the last element - (b) excluding the last element''' - - return isSubsetSum (arr, n-1, sum) or isSubsetSum (arr, n-1, sum-arr[n-1]) - -# Returns true if arr[] can be partitioned in two -# subsets of equal sum, otherwise false -def findPartion (arr, n): - # Calculate sum of the elements in array - sum = 0 - for i in range(0, n): - sum += arr[i] - # If sum is odd, there cannot be two subsets - # with equal sum - if sum % 2 != 0: - return False - - # Find if there is subset with sum equal to - # half of total sum - return isSubsetSum (arr, n, sum // 2) \ No newline at end of file diff --git a/Python/Polar Coordinates.py b/Python/Polar Coordinates.py deleted file mode 100644 index 13942808..00000000 --- a/Python/Polar Coordinates.py +++ /dev/null @@ -1,59 +0,0 @@ -''' -Polar coordinates are an alternative way of representing Cartesian coordinates or Complex Numbers. - -A complex number Capture.PNG -is completely determined by its real part and imaginary part . -Here, is the imaginary unit. -A polar coordinate ()Capture.PNG - -is completely determined by modulus and phase angle . - -If we convert complex number to its polar coordinate, we find: -: Distance from to origin, i.e., -: Counter clockwise angle measured from the positive -axis to the line segment that joins to the origin. - -Python's cmath module provides access to the mathematical functions for complex numbers. - - -This tool returns the phase of complex number (also known as the argument of ). - ->>> phase(complex(-1.0, 0.0)) -3.1415926535897931 - -This tool returns the modulus (absolute value) of complex number . - ->>> abs(complex(-1.0, 0.0)) -1.0 -Task -You are given a complex . Your task is to convert it to polar coordinates. - -Input Format - -A single line containing the complex number . Note: complex() function can be used in python to convert the input as a complex number. - -Constraints - -Given number is a valid complex number - -Output Format - -Output two lines: -The first line should contain the value of . -The second line should contain the value of . - -Sample Input - - 1+2j -Sample Output - - 2.23606797749979 - 1.1071487177940904 -Note: The output should be correct up to 3 decimal places. -''' - -if __name__ == '__main__': - import cmath - - z = complex(input()) - print(abs(z)) - print(cmath.phase(z)) \ No newline at end of file diff --git a/Python/Power - Mod Power.py b/Python/Power - Mod Power.py deleted file mode 100644 index fd25e325..00000000 --- a/Python/Power - Mod Power.py +++ /dev/null @@ -1,63 +0,0 @@ -''' -So far, we have only heard of Python's powers. Now, we will witness them! - -Powers or exponents in Python can be calculated using the built-in power function. Call the power function - -as shown below: - ->>> pow(a,b) - -or - ->>> a**b - -It's also possible to calculate - -. - ->>> pow(a,b,m) - -This is very helpful in computations where you have to print the resultant % mod. - -Note: Here, -and can be floats or negatives, but, if a third argument is present, - -cannot be negative. - -Note: Python has a math module that has its own pow(). It takes two arguments and returns a float. Frankly speaking, we will never use math.pow(). - -Task -You are given three integers: -, , and - -, respectively. Print two lines. -The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m). - -Input Format -The first line contains -, the second line contains , and the third line contains - -. - -Constraints - - -Sample Input - -3 -4 -5 - -Sample Output - -81 -1 - -''' - -if __name__ == '__main__': - a=int(input()) - b=int(input()) - m=int(input()) -print(pow(a,b)) -print(pow(a,b,m)) \ No newline at end of file diff --git a/Python/QueueUsingTwoStacks.py b/Python/QueueUsingTwoStacks.py deleted file mode 100644 index 739938e9..00000000 --- a/Python/QueueUsingTwoStacks.py +++ /dev/null @@ -1,75 +0,0 @@ -''' - A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest - elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) - data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. - - A basic queue has the following operations: - - Enqueue: add a new element to the end of the queue. - Dequeue: remove the element from the front of the queue and return it. - In this challenge, you must first implement a queue using two stacks. Then process queries, where each query is one of the following types: - - 1 x: Enqueue element into the end of the queue. - 2: Dequeue the element at the front of the queue. - 3: Print the element at the front of the queue. - Input Format - - The first line contains a single integer, , denoting the number of queries. - Each line of the subsequent lines contains a single query in the form described in the problem statement above. - All three queries start with an integer denoting the query , but only query is followed by an additional space-separated value, x, - denoting the value to be enqueued. - - It is guaranteed that a valid answer always exists for each query of type . - Output Format - - For each query of type , print the value of the element at the front of the queue on a new line. - - Sample Input - 10 - 1 42 - 2 - 1 14 - 3 - 1 28 - 3 - 1 60 - 1 78 - 2 - 2 -''' -class Queue: - def __init__(self): - self.in_stack = list() - self.out_stack = list() - - def enqueue(self, data): - self.in_stack.append(data) - - def dequeue(self): - if not self.out_stack: - while self.in_stack: - self.out_stack.append(self.in_stack.pop()) - return self.out_stack.pop() - - def peek(self): - if not self.out_stack: - while self.in_stack: - self.out_stack.append(self.in_stack.pop()) - return self.out_stack[-1] - -def main(): - n = int(input()) - q1 = Queue() - - for i in range(n): - query = [int(i) for i in input().split()] - - if query[0] == 1: - q1.enqueue(query[1]) - if query[0] == 2: - q1.dequeue() - if query[0] == 3: - print(q1.peek()) - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/Python/README.md b/Python/README.md deleted file mode 100644 index c5d36267..00000000 --- a/Python/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Python Hackerrank Codes - -**Following Codes are Present** - -* [Arithmetic Operators](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ArithmeticOperators.py) -* [Beautiful Days at the Movies](https://www.hackerrank.com/challenges/beautiful-days-at-the-movies/problem) -* [Calendar](https://github.com/wanda15tw/Hackerrank-Codes/blob/Python/CalendarModule/Python/CalendarModule.py) -* [Capitalize](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Capitalize!.py) -* [Collections Counter](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/CollectionsCounter.py) -* [Collections Namedtuple](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/CollectionsNamedtuple.py) -* [Collections OrderedDict](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/CollectionsOrderedDict.py) -* [Compress the String](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Compress%20the%20String.py) -* [Day of the Programmer](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Day-of-the-Programmer.py) -* [Else-If](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Else-If.py) -* [Extra Long Factorials](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ExtraLongFactorials.py) -* [Find a string](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Find%20a%20string.py) -* [Finding The Percentage](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/FindingThePercentage.py) -* [Find Second RunnerUp](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/FindSecondRunnerUp.py) -* [Iterables and Iterators](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Iterables%20and%20Iterators.py) -* [Itertools Combinations](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ItertoolsCombinations.py) -* [Itertools Combinations with Replacecment](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ItertoolsCombinations_with_replacement.py) -* [Itertools Permutation](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ItertoolsPermutations.py) -* [Itertools Product](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ItertoolsProduct.py) -* [Leap Year](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/LeapYear.py) -* [List Comprehension](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ListComprehensions.py) -* [Mod Divmod](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ModDivmod.py) -* [Mutations](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Mutations.py) -* [NestedLists](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/NestedLists.py) -* [Mod Power](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Power%20-%20Mod%20Power.py) -* [Polar Coordinates](https://github.com/wanda15tw/Hackerrank-Codes/blob/Python/CalendarModule/Python/Polar%20Coordinates.py) -* [Queue using Two Stacks](https://github.com/bolajixi/Hackerrank-Codes/blob/Add_Queue-DoubleStack/Python/QueueUsingTwoStacks.py) -* [Set discard remove and copy](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Set%20.discard()%2C%20.remove()%20%26%20.pop().py) -* [String Validators](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/String%20Validators.py) -* [swapcase](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/sWAPcASE.py) -* [Symmetric Difference](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/SymmetricDifference.py) -* [Text Alignment](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Text%20Alignment.py) -* [Text Wrap](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Text%20Wrap.pyv) -* [Tuples](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Tuples.py) -* [What's your name](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/What's%20Your%20Name.py) -* [Word Order](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Word%20Order.py) -* [Introduction To Sets] (https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/IntroductionToSets.py) -* [Triangle Quest 2](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/TriangleQuest2.py) \ No newline at end of file diff --git a/Python/Sales by Match.py b/Python/Sales by Match.py deleted file mode 100644 index 25fc20d0..00000000 --- a/Python/Sales by Match.py +++ /dev/null @@ -1,54 +0,0 @@ -#problem hackerrank.com/challenges/sock-merchant/problem -#points 10 -'''Alex works at a clothing store. There is a large pile of socks that must be paired 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. - -For example, there are socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is . - -Function Description - -Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available. - -sockMerchant has the following parameter(s): - -n: the number of socks in the pile -ar: the colors of each sock -Input Format - -The first line contains an integer , the number of socks represented in . -The second line contains space-separated integers describing the colors of the socks in the pile. - -Constraints -Output Format - -Return the total number of matching pairs of socks that Alex can sell. - -Sample Input - -9 -10 20 20 10 10 30 50 10 20 -Sample Output - -3 -Explanation - -sock.png - -Alex can match three pairs of socks''' - -#solution -def sockMerchant(n, ar): - return sum([ar.count(i)//2 for i in set(ar)]) - -if __name__ == '__main__': - import os - fptr = open(os.environ['OUTPUT_PATH'], 'w') - - n = int(input()) - - ar = list(map(int, input().rstrip().split())) - - result = sockMerchant(n, ar) - - fptr.write(str(result) + '\n') - - fptr.close() diff --git a/Python/Santa Clause.py b/Python/Santa Clause.py deleted file mode 100644 index 2c5fb007..00000000 --- a/Python/Santa Clause.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -Have you ever wondered how Christmas presents are delivered? -I sure have, and I believe Santa Claus has a list of houses he loops through. -He goes to a house, drops off the presents, eats the cookies and milk, and moves on to the next house on the list. -Since this algorithm for delivering presents is based on an explicit loop construction, it is called an iterative algorithm. -""" -houses = ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"] - -def deliver_presents_iteratively(): - for house in houses: - print("Delivering presents to", house) - - -""" -But I feel for Santa. At his age, he shouldn’t have to deliver all the presents by himself. -I propose an algorithm with which he can divide the work of delivering presents among his elves: - - - -1-Appoint an elf and give all the work to him -2-Assign titles and responsibilities to the elves based on the number of houses for which they are responsible: - > 1 He is a manager and can appoint two elves and divide his work among them - = 1 He is a worker and has to deliver the presents to the house assigned to him - - -This is the typical structure of a recursive algorithm. -If the current problem represents a simple case, solve it. -If not, divide it into subproblems and apply the same strategy to them. - -The algorithm for recursive present delivery implemented in Python: -""" - -houses = ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"] - -# Each function call represents an elf doing his work -def deliver_presents_recursively(houses): - # Worker elf doing his work - if len(houses) == 1: - house = houses[0] - print("Delivering presents to", house) - - # Manager elf doing his work - else: - mid = len(houses) // 2 - first_half = houses[:mid] - second_half = houses[mid:] - - # Divides his work among two elves - deliver_presents_recursively(first_half) - deliver_presents_recursively(second_half) - -""" -Many people ask where we use the algorithms in real life, For them -This is not any new algorithm , this is binary search Algorithm -which we learn and this helped use sloving a real life Dynamic Programming Solution -""" \ No newline at end of file diff --git a/Python/Set .discard(), .remove() & .pop().py b/Python/Set .discard(), .remove() & .pop().py deleted file mode 100644 index c3ce1a83..00000000 --- a/Python/Set .discard(), .remove() & .pop().py +++ /dev/null @@ -1,133 +0,0 @@ -''' -.remove(x) - -This operation removes element -from the set. -If element - -does not exist, it raises a KeyError. -The .remove(x) operation returns None. - -Example - ->>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) ->>> s.remove(5) ->>> print s -set([1, 2, 3, 4, 6, 7, 8, 9]) ->>> print s.remove(4) -None ->>> print s -set([1, 2, 3, 6, 7, 8, 9]) ->>> s.remove(0) -KeyError: 0 - -.discard(x) - -This operation also removes element -from the set. -If element - -does not exist, it does not raise a KeyError. -The .discard(x) operation returns None. - -Example - ->>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) ->>> s.discard(5) ->>> print s -set([1, 2, 3, 4, 6, 7, 8, 9]) ->>> print s.discard(4) -None ->>> print s -set([1, 2, 3, 6, 7, 8, 9]) ->>> s.discard(0) ->>> print s -set([1, 2, 3, 6, 7, 8, 9]) - -.pop() - -This operation removes and return an arbitrary element from the set. -If there are no elements to remove, it raises a KeyError. - -Example - ->>> s = set([1]) ->>> print s.pop() -1 ->>> print s -set([]) ->>> print s.pop() -KeyError: pop from an empty set - -Task - -You have a non-empty set -, and you have to execute commands given in - -lines. - -The commands will be pop, remove and discard. - -Input Format - -The first line contains integer -, the number of elements in the set . -The second line contains space separated elements of set . All of the elements are non-negative integers, less than or equal to 9. -The third line contains integer , the number of commands. -The next - -lines contains either pop, remove and/or discard commands followed by their associated value. - -Constraints - - -Output Format - -Print the sum of the elements of set - -on a single line. - -Sample Input - -9 -1 2 3 4 5 6 7 8 9 -10 -pop -remove 9 -discard 9 -discard 8 -remove 7 -pop -discard 6 -remove 5 -pop -discard 5 - -Sample Output - -4 - -Explanation - -After completing these -operations on the set, we get set. Hence, the sum is - -. - -Note: Convert the elements of set s to integers while you are assigning them. To ensure the proper input of the set, we have added the first two lines of code to the editor. -''' - -n = int(input()) -s = set(map(int, input().split())) -inst=int(input()) -for i in range(inst): - ist=input() - if ist.startswith('pop'): - s.pop() - elif ist.startswith('remove'): - s.remove(int(ist.split()[-1])) - elif ist.startswith('discard'): - s.discard(int(ist.split()[-1])) - else: - pass -print(sum(s)) \ No newline at end of file diff --git a/Python/Set.add().py b/Python/Set.add().py deleted file mode 100644 index 37bd6ad5..00000000 --- a/Python/Set.add().py +++ /dev/null @@ -1,59 +0,0 @@ -""" -Task - -Apply your knowledge of the .add() operation to help your friend Rupal. - -Rupal has a huge collection of country stamps. -She decided to count the total number of distinct country stamps in her collection. -She asked for your help. You pick the stamps one by one from a stack of -n country stamps - -Input Format - -The first line contains an integer n, the total number of country stamps. -The next n lines contains the name of the country where the stamp is from. - -Input Format - -The first line contains an integer , the total number of country stamps. -The next lines contains the name of the country where the stamp is from. - -Constraints -0>> print 'ab123'.isalnum() -True ->>> print 'ab123#'.isalnum() -False - -str.isalpha() -This method checks if all the characters of a string are alphabetical (a-z and A-Z). - ->>> print 'abcD'.isalpha() -True ->>> print 'abcd1'.isalpha() -False - -str.isdigit() -This method checks if all the characters of a string are digits (0-9). - ->>> print '1234'.isdigit() -True ->>> print '123edsd'.isdigit() -False - -str.islower() -This method checks if all the characters of a string are lowercase characters (a-z). - ->>> print 'abcd123#'.islower() -True ->>> print 'Abcd123#'.islower() -False - -str.isupper() -This method checks if all the characters of a string are uppercase characters (A-Z). - ->>> print 'ABCD123#'.isupper() -True ->>> print 'Abcd123#'.isupper() -False - -Task - -You are given a string -. -Your task is to find out if the string - -contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters. - -Input Format - -A single line containing a string - -. - -Constraints - -Output Format - -In the first line, print True if -has any alphanumeric characters. Otherwise, print False. -In the second line, print True if has any alphabetical characters. Otherwise, print False. -In the third line, print True if has any digits. Otherwise, print False. -In the fourth line, print True if has any lowercase characters. Otherwise, print False. -In the fifth line, print True if - -has any uppercase characters. Otherwise, print False. - -Sample Input - -qA2 - -Sample Output - -True -True -True -True -True - -''' - -if __name__ == '__main__': - s = input() -v=False -for n in s: - if n.isalnum(): - v=True -print(v) -v=False -for n in s: - if n.isalpha(): - v=True -print(v) -v=False -for n in s: - if n.isdigit(): - v=True -print(v) -v=False -for n in s: - if n.islower(): - v=True -print(v) -v=False -for n in s: - if n.isupper(): - v=True -print(v) \ No newline at end of file diff --git a/Python/String_Split_and_Join.py b/Python/String_Split_and_Join.py deleted file mode 100644 index 0f7bc00e..00000000 --- a/Python/String_Split_and_Join.py +++ /dev/null @@ -1,47 +0,0 @@ -""" -In Python, a string can be split on a delimiter. - -Example: - ->>> a = "this is a string" ->>> a = a.split(" ") # a is converted to a list of strings. ->>> print a -['this', 'is', 'a', 'string'] - -Joining a string is simple: - ->>> a = "-".join(a) ->>> print a -this-is-a-string - -Task -You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen. - -Input Format -The first line contains a string consisting of space separated words. - -Output Format -Print the formatted string as explained above. - -Sample Input - -this is a string - -Sample Output - -this-is-a-string - -""" - -try: - raw_input -except NameError: - raw_input = input - -def split_and_join(line): - return "-".join(line.split(" ")) - -if __name__ == '__main__': - line = raw_input() - result = split_and_join(line) - print(result) diff --git a/Python/StringsplitandJoin.py b/Python/StringsplitandJoin.py deleted file mode 100644 index 5c582046..00000000 --- a/Python/StringsplitandJoin.py +++ /dev/null @@ -1,28 +0,0 @@ -#Answer to the challenge "String split and Join" in Python3 - -#In Python, a string can be split on a delimeter. Example -#>>> a = "this is a string" -#>>> a = a.split(" ") # a is converted to a list of strings. -#>>> print a -#['this', 'is', 'a', 'string'] - -#joining a string is simple : - -#>>> a = "-".join(a) -#>>> print a -#this-is-a-string - -#Task :- You are given a string. Split the string on a " "(space)delimeter and join using a - hyphen - -#input Format :- The first line contains a string consisting of space separated words. - -#output Format:- Print the formatted string as explained above - -#Sample input :- this is a string. - -#sample output:- this-is-a-string - -#the code to be written directly in a compiler. - -print('-'.join(input().split())) - diff --git a/Python/SymmetricDifference.py b/Python/SymmetricDifference.py deleted file mode 100644 index 142a55ca..00000000 --- a/Python/SymmetricDifference.py +++ /dev/null @@ -1,143 +0,0 @@ -''' -Objective -Today, we're learning about a new data type: sets. - -Concept - -If the inputs are given on one line separated by a space character, use split() to get the separate values in the form of a list: - ->> a = raw_input() -5 4 3 2 ->> lis = a.split() ->> print (lis) -['5', '4', '3', '2'] - -If the list values are all integer types, use the map() method to convert all the strings to integers. - ->> newlis = list(map(int, lis)) ->> print (newlis) -[5, 4, 3, 2] - -Sets are an unordered bag of unique values. A single set contains values of any immutable data type. - -CREATING SETS - ->> myset = {1, 2} # Directly assigning values to a set ->> myset = set() # Initializing a set ->> myset = set(['a', 'b']) # Creating a set from a list ->> myset -{'a', 'b'} - - -MODIFYING SETS - -Using the add() function: - ->> myset.add('c') ->> myset -{'a', 'c', 'b'} ->> myset.add('a') # As 'a' already exists in the set, nothing happens ->> myset.add((5, 4)) ->> myset -{'a', 'c', 'b', (5, 4)} - - -Using the update() function: - ->> myset.update([1, 2, 3, 4]) # update() only works for iterable objects ->> myset -{'a', 1, 'c', 'b', 4, 2, (5, 4), 3} ->> myset.update({1, 7, 8}) ->> myset -{'a', 1, 'c', 'b', 4, 7, 8, 2, (5, 4), 3} ->> myset.update({1, 6}, [5, 13]) ->> myset -{'a', 1, 'c', 'b', 4, 5, 6, 7, 8, 2, (5, 4), 13, 3} - - -REMOVING ITEMS - -Both the discard() and remove() functions take a single value as an argument and removes that value from the set. If that value is not present, discard() does nothing, but remove() will raise a KeyError exception. - ->> myset.discard(10) ->> myset -{'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 13, 11, 3} ->> myset.remove(13) ->> myset -{'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 11, 3} - - -COMMON SET OPERATIONS Using union(), intersection() and difference() functions. - ->> a = {2, 4, 5, 9} ->> b = {2, 4, 11, 12} ->> a.union(b) # Values which exist in a or b -{2, 4, 5, 9, 11, 12} ->> a.intersection(b) # Values which exist in a and b -{2, 4} ->> a.difference(b) # Values which exist in a but not in b -{9, 5} - - -The union() and intersection() functions are symmetric methods: - ->> a.union(b) == b.union(a) -True ->> a.intersection(b) == b.intersection(a) -True ->> a.difference(b) == b.difference(a) -False - -These other built-in data structures in Python are also useful. - -Task -Given -sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or - -but do not exist in both. - -Input Format - -The first line of input contains an integer, -. -The second line contains space-separated integers. -The third line contains an integer, . -The fourth line contains - -space-separated integers. - -Output Format - -Output the symmetric difference integers in ascending order, one per line. - -Sample Input - -4 -2 4 5 9 -4 -2 4 11 12 - -Sample Output - -5 -9 -11 -12 - -''' -if __name__=='__main__': - n=int(input()) - a=input().split() - m=int(input()) - b=input().split() - a=[int(i) for i in a] - b=[int(i) for i in b] - -a=set(a) -b=set(b) -ad=a.difference(b) -bd=b.difference(a) -d=ad.union(bd) -d=list(d) -for i in sorted(d): - print(i) \ No newline at end of file diff --git a/Python/Text Alignment.py b/Python/Text Alignment.py deleted file mode 100644 index b54fbebe..00000000 --- a/Python/Text Alignment.py +++ /dev/null @@ -1,100 +0,0 @@ -''' -In Python, a string of text can be aligned left, right and center. - -.ljust(width) - -This method returns a left aligned string of length width. - ->>> width = 20 ->>> print 'HackerRank'.ljust(width,'-') -HackerRank---------- - -.center(width) - -This method returns a centered string of length width. - ->>> width = 20 ->>> print 'HackerRank'.center(width,'-') ------HackerRank----- - -.rjust(width) - -This method returns a right aligned string of length width. - ->>> width = 20 ->>> print 'HackerRank'.rjust(width,'-') -----------HackerRank - -Task - -You are given a partial code that is used for generating the HackerRank Logo of variable thickness. -Your task is to replace the blank (______) with rjust, ljust or center. - -Input Format - -A single line containing the thickness value for the logo. - -Constraints - -The thickness must be an odd number. - -Output Format - -Output the desired logo. - -Sample Input - -5 - -Sample Output - - H - HHH - HHHHH - HHHHHHH -HHHHHHHHH - HHHHH HHHHH - HHHHH HHHHH - HHHHH HHHHH - HHHHH HHHHH - HHHHH HHHHH - HHHHH HHHHH - HHHHHHHHHHHHHHHHHHHHHHHHH - HHHHHHHHHHHHHHHHHHHHHHHHH - HHHHHHHHHHHHHHHHHHHHHHHHH - HHHHH HHHHH - HHHHH HHHHH - HHHHH HHHHH - HHHHH HHHHH - HHHHH HHHHH - HHHHH HHHHH - HHHHHHHHH - HHHHHHH - HHHHH - HHH - H - -''' - -thickness = int(input()) #This must be an odd number -c = 'H' - -#Top Cone -for i in range(thickness): - print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1)) - -#Top Pillars -for i in range(thickness+1): - print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) - -#Middle Belt -for i in range((thickness+1)//2): - print((c*thickness*5).center(thickness*6)) - -#Bottom Pillars -for i in range(thickness+1): - print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) - -#Bottom Cone -for i in range(thickness): - print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6)) \ No newline at end of file diff --git a/Python/Text Wrap.py b/Python/Text Wrap.py deleted file mode 100644 index 9da4db2c..00000000 --- a/Python/Text Wrap.py +++ /dev/null @@ -1,52 +0,0 @@ -''' -You are given a string and width . -Your task is to wrap the string into a paragraph of width - -. - -Input Format - -The first line contains a string, -. -The second line contains the width, - -. - -Constraints - -Output Format - -Print the text wrapped paragraph. - -Sample Input 0 - -ABCDEFGHIJKLIMNOQRSTUVWXYZ -4 - -Sample Output 0 - -ABCD -EFGH -IJKL -IMNO -QRST -UVWX -YZ - - -''' - -import textwrap - -def wrap(string, max_width): - result='' - while len(string)>=max_width: - result+=string[0:max_width]+'\n' - string=string[max_width:] - result+=string - return result - -if __name__ == '__main__': - string, max_width = input(), int(input()) - result = wrap(string, max_width) - print(result) \ No newline at end of file diff --git a/Python/TheMinionGame.py b/Python/TheMinionGame.py deleted file mode 100644 index 3ce21167..00000000 --- a/Python/TheMinionGame.py +++ /dev/null @@ -1,109 +0,0 @@ -#Type 1 -#Kevin and Stuart want to play 'The Minion Game' - -#Game Rules - -#1) Both players are given the same string, S -#2) Both players have to make substrings using the letters of the string . -#3) Stuart has to make words starting with consonants. -#4) Kevin has to make words starting with vowels. -#5) The game ends when both players have made all possible substrings. - -#Scoring :- A player gets +1 points for each occurance of the substring in the string S - -#For Example :- String S = BANANA -#Kevin's vowel beginning word = ANA -#Here's ANA occurs twice in BANANA. Hence, Kevin will get 2 points. - -#Input Format :- A single line of input containing the string S. Also, The string S will contain only uppercase letters [A-Z] - -#Constratints :- 0 < len(S) < 10 to the power 6 - -#Output :- Print one line: the name of the winner and their score separated by a space. If the game is a draw, print Draw. - -#Sample Input :- BANANA -#Sample Output :- Stuart 12 - -def minion_game(string): - vowel =['A','E','I','O','U'] - S=0 - K=0 - for i in range(len(string)): - if string[i] in vowel: - K+= len(string)-i - else: - S+=len(string)-i - if S>K: - print("Stuart"+" "+ "%d" % S) - elif K>S: - print("Kevin"+" "+'%d' % K) - else: - print("Draw") - -#Note :- The Answer is to put directly in the compiler (Any Python compiler) -# ======= -#Type 2 -''' - Kevin and Stuart want to play the 'The Minion Game'. - -Game Rules - -Both players are given the same string, S. -Both players have to make substrings using the letters of the string S. -Stuart has to make words starting with consonants. -Kevin has to make words starting with vowels. -The game ends when both players have made all possible substrings. - -Scoring -A player gets +1 point for each occurrence of the substring in the string S. - -For Example: -String S = BANANA -Kevin's vowel beginning word = ANA -Here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points. - -Your task is to determine the winner of the game and their score. - -Input Format - -A single line of input containing the string S. -Note: The string will contain only uppercase letters: [A - Z]. - -Constraints - 0 < len(S) < 10^6 - -Output Format - -Print one line: the name of the winner and their score separated by a space. - -If the game is a draw, print Draw. - -Sample Input -BANANA - -Sample Output -Stuart 12 - -Note : -Vowels are only defined as AEIOU. In this problem,Y is not considered a vowel. -''' - -def minion_game(string): - vowels = {'A', 'E', 'I', 'O', 'U'} - kevin = 0 # vowels - stuart = 0 # consonants - for i in range(len(string)): - if string[i] in vowels: - kevin += len(string) - i - else: - stuart += len(string) - i - if kevin > stuart: - print('Kevin', kevin) - elif stuart > kevin: - print('Stuart', stuart) - else: - print('Draw') -if __name__ == '__main__': - s = input() - minion_game(s) - diff --git a/Python/Tiling Problem.py b/Python/Tiling Problem.py deleted file mode 100644 index 8b3b8d70..00000000 --- a/Python/Tiling Problem.py +++ /dev/null @@ -1,108 +0,0 @@ -""" -Count the number of ways to tile the floor of size n x m using 1 x m size tiles -Given a floor of size n x m and tiles of size 1 x m. The problem is to count the number of ways to tile the -given floor using 1 x m tiles. A tile can either be placed horizontally or vertically. -Both n and m are positive integers and 2 < = m. - -Examples: - -Input : n = 2, m = 3 -Output : 1 -Only one combination to place -two tiles of size 1 x 3 horizontally -on the floor of size 2 x 3. - -Input : n = 4, m = 4 -Output : 2 -1st combination: -All tiles are placed horizontally -2nd combination: -All tiles are placed vertically. -""" - -""" -This problem is mainly a more generalized approach to the Tiling Problem. -Approach: For a given value of n and m, the number of ways to tile the -floor can be obtained from the following relation. - - - | 1, 1 < = n < m - count(n) = | 2, n = m - | count(n-1) + count(n-m), m < n -""" -def tiling(n,m): - count=[] - for i in range(n+2): - count.append(0) - count[0]=0 - for i in range(1,n+1): - # recurssive cases - if i > m: - count[i]=count[i-1]+count[i-m] - #base cases - elif i 0: - temp1=num%10 - num=num//10 - if temp1<=temp2: - temp2=temp1 - else: - return False - return True \ No newline at end of file diff --git a/Python/TriangleQuest.py b/Python/TriangleQuest.py deleted file mode 100644 index 4cb88741..00000000 --- a/Python/TriangleQuest.py +++ /dev/null @@ -1,36 +0,0 @@ -''' -You are given a positive integer . Print a numerical triangle of height like the one below: - -1 -22 -333 -4444 -55555 -...... -Can you do it using only arithmetic operations, a single for loop and print statement? - -Use no more than two lines. The first line (the for statement) is already written for you. You have to complete the print statement. - -Note: Using anything related to strings will give a score of . - -Input Format -A single line containing integer, . - -Constraints - -Output Format -Print lines as explained above. - -Sample Input - -5 -Sample Output - -1 -22 -333 -4444 -''' - -for i in range(1,int(input())): - print((10**(i)//9)*i) diff --git a/Python/TriangleQuest2.py b/Python/TriangleQuest2.py deleted file mode 100644 index b7c8bbd0..00000000 --- a/Python/TriangleQuest2.py +++ /dev/null @@ -1,47 +0,0 @@ -""" -You are given a positive integer N. -Your task is to print a palindromic triangle of size N. - -For example, a palindromic triangle of size 5 is: -1 -121 -12321 -1234321 -123454321 - - -You can't take more than two lines. The first line (a for-statement) is already written for you. -You have to complete the code using exactly one print statement. - - -Note: -Using anything related to strings will give a score of 0. -Using more than one for-statement will give a score of 0. - - -Input Format -A single line of input containing the integer N. - - -Constraints -• 0=1900): - leapyear=True - return leapyear - -year = int(input()) -print(is_leap(year)) \ No newline at end of file diff --git a/Python/ZigZagSequence.py b/Python/ZigZagSequence.py deleted file mode 100644 index 6acd751c..00000000 --- a/Python/ZigZagSequence.py +++ /dev/null @@ -1,61 +0,0 @@ -''' -Problem Link: https://www.hackerrank.com/challenges/zig-zag-sequence/problem - -In this challenge, the task is to debug the existing code to successfully execute all provided test files. - -Given an array of n distinct integers, transform the array into a zig zag sequence by permuting the array elements. A sequence will be called a zig zag sequence if the first k elements in the sequence are in increasing order and the last k elements are in decreasing order, where k=(n+1)/2. You need to find the lexicographically smallest zig zag sequence of the given array. - -For example let's say a=[2,3,5,1,4]. Now if we permute the array as [1,4,5,3,2], the result is a zig zag sequence. - -Debug the given function findZigZagSequence to return the appropriate zig zag sequence for the given input array. - -Note: You can modify at most three lines in the given code and you cannot add or remove lines to the code. - -To restore the original code in the editor, create a new buffer by clicking on the top left icon in the editor. - -Input Format: -The first line contains t the number of test cases. The first line of each test case contains an integer n, denoting the number of array elements. The next line of the test case contains n elements of array a. - -Constraints: -1<=t<=20 -1<=n<=10000 (n is always odd) -1<=a[i]<=10^9 - -Output Format: -For each test cases, print the elements of the transformed zig zag sequence in a single line. - -Sample Input: -1 -7 -1 2 3 4 5 6 7 -Sample Output: -1 2 3 7 6 5 4 - -''' - - -def findZigZagSequence(a, n): - a.sort() - mid = int((n)/2) - a[mid], a[n-1] = a[n-1], a[mid] - - st = mid + 1 - ed = n - 2 - while(st <= ed): - a[st], a[ed] = a[ed], a[st] - st = st + 1 - ed = ed - 1 - - for i in range (n): - if i == n-1: - print(a[i]) - else: - print(a[i], end = ' ') - return - -test_cases = int(input()) -for cs in range (test_cases): - n = int(input()) - a = list(map(int, input().split())) - findZigZagSequence(a, n) - diff --git a/Python/abbreviation.py b/Python/abbreviation.py deleted file mode 100644 index 5175aa9e..00000000 --- a/Python/abbreviation.py +++ /dev/null @@ -1,39 +0,0 @@ -""" -https://www.hackerrank.com/challenges/abbr/problem -You can perform the following operation on some string, : - -1. Capitalize zero or more of 's lowercase letters at some index i - (i.e., make them uppercase). -2. Delete all of the remaining lowercase letters in . - -Example: -a=daBcd and b="ABC" -daBcd -> capitalize a and c(dABCd) -> remove d (ABC) -""" - - -def abbr(a: str, b: str) -> bool: - """ - >>> abbr("daBcd", "ABC") - True - >>> abbr("dBcd", "ABC") - False - """ - n = len(a) - m = len(b) - dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] - dp[0][0] = True - for i in range(n): - for j in range(m + 1): - if dp[i][j]: - if j < m and a[i].upper() == b[j]: - dp[i + 1][j + 1] = True - if a[i].islower(): - dp[i + 1][j] = True - return dp[n][m] - - -if __name__ == "__main__": - import doctest - - doctest.testmod() diff --git a/Python/binarySearch.py b/Python/binarySearch.py deleted file mode 100644 index 0f033a36..00000000 --- a/Python/binarySearch.py +++ /dev/null @@ -1,31 +0,0 @@ -# @author: Jorge Reyes - -""" -The binary search algorithm works by splitting the array recursively. Keep in mind that this algorithm needs an already sorted array. -""" - -def binarySearch(arr, n): - # Base Case - if (len(arr) == 1 and n != arr[0]): - return False - - # Get the middle item of the array - half = len(arr)//2 - - # Check if the middle item is equal to 'n' - if (arr[half] == n): - return True - else: - # If 'n' is smaller than the number in the middle of the array, search the left part - if (n < arr[half]): - return binarySearch(arr[0:half], n) - else: - # If 'n' is greater than the number in the middle of the arrau, search the right part - return binarySearch(arr[half:len(arr)], n) - - -# Example -arr = [293, 394, 598, 829, 4000] - -print(binarySearch(arr, 293)) -print(binarySearch(arr, 100)) \ No newline at end of file diff --git a/Python/fast_fibonacci.py b/Python/fast_fibonacci.py deleted file mode 100644 index f48186a3..00000000 --- a/Python/fast_fibonacci.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python3 - -""" -This program calculates the nth Fibonacci number in O(log(n)). -It's possible to calculate F(1_000_000) in less than a second. -""" -from __future__ import annotations - -import sys - - -def fibonacci(n: int) -> int: - """ - return F(n) - >>> [fibonacci(i) for i in range(13)] - [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] - """ - if n < 0: - raise ValueError("Negative arguments are not supported") - return _fib(n)[0] - - -# returns (F(n), F(n-1)) -def _fib(n: int) -> tuple[int, int]: - if n == 0: # (F(0), F(1)) - return (0, 1) - - # F(2n) = F(n)[2F(n+1) − F(n)] - # F(2n+1) = F(n+1)^2+F(n)^2 - a, b = _fib(n // 2) - c = a * (b * 2 - a) - d = a * a + b * b - return (d, c + d) if n % 2 else (c, d) - - -if __name__ == "__main__": - n = int(sys.argv[1]) - print(f"fibonacci({n}) is {fibonacci(n)}") diff --git a/Python/practice.py b/Python/practice.py deleted file mode 100644 index 1929c244..00000000 --- a/Python/practice.py +++ /dev/null @@ -1,4 +0,0 @@ -""" -This File is dedicated For Ur Practise Only , -Nothing Can be obtained without Practice so Start it now, as its never too late -""" \ No newline at end of file diff --git a/Python/sWAPcASE.py b/Python/sWAPcASE.py deleted file mode 100644 index f25d3c46..00000000 --- a/Python/sWAPcASE.py +++ /dev/null @@ -1,40 +0,0 @@ -''' -You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. - -For Example: - -Www.HackerRank.com → wWW.hACKERrANK.COM -Pythonist 2 → pYTHONIST 2 - -Input Format - -A single line containing a string - -. - -Constraints - -Output Format - -Print the modified string - -. - -Sample Input 0 - -HackerRank.com presents "Pythonist 2". - -Sample Output 0 - -hACKERrANK.COM PRESENTS "pYTHONIST 2". - - -''' -def swap_case(s): - s=s.swapcase() - return s - -if __name__ == '__main__': - s = input() - result = swap_case(s) - print(result) diff --git a/Ruby/README.md b/Ruby/README.md index cf37b208..45c55939 100644 --- a/Ruby/README.md +++ b/Ruby/README.md @@ -1 +1,3 @@ -# Ruby \ No newline at end of file +# Ruby + +* String-Iteration \ No newline at end of file diff --git a/Ruby/string-Iteration.rb b/Ruby/string-Iteration.rb new file mode 100644 index 00000000..b522951f --- /dev/null +++ b/Ruby/string-Iteration.rb @@ -0,0 +1,14 @@ +=begin +https://www.hackerrank.com/challenges/ruby-strings-iteration/problem +Write the method count_multibyte_char which takes a string as input and returns the number of multibyte characters (byte size > 1) in it. +=end + +def count_multibyte_char(str) + char_count = 0 + + str.each_char do |character| + char_count += 1 if character.bytesize > 1 + end + + return char_count +end \ No newline at end of file