From a9755bd0b2bdb41573f509df1fa3f8db2cfd5e28 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Fri, 28 Jul 2017 07:12:59 +0530 Subject: [PATCH 01/15] Bug fixes --- Programs/P07_PrimeNumber.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Programs/P07_PrimeNumber.py b/Programs/P07_PrimeNumber.py index e4ba9bf..485de60 100644 --- a/Programs/P07_PrimeNumber.py +++ b/Programs/P07_PrimeNumber.py @@ -3,18 +3,20 @@ def checkPrime(number): '''This function checks for prime number''' + isPrime = False if number == 2: print(number, 'is a Prime Number') if number > 1: for i in range(2, number): if number % i == 0: print(number, 'is not a Prime Number') + isPrime = False break else: - print(number, 'is a Prime Number') - break - else: - print(number, 'is not a Prime Number') + isPrime = True + + if isPrime: + print(number, 'is a Prime Number') if __name__ == '__main__': userInput = int(input('Enter a number to check: ')) From aa3bd48c2853ffe5e828160514706a5f703f0cb6 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Sun, 30 Jul 2017 07:38:38 +0530 Subject: [PATCH 02/15] Added iterative approach --- Programs/P08_Fibonacci.py | 29 +++++++---------------------- 1 file changed, 7 insertions(+), 22 deletions(-) diff --git a/Programs/P08_Fibonacci.py b/Programs/P08_Fibonacci.py index 64b0afe..67133a1 100644 --- a/Programs/P08_Fibonacci.py +++ b/Programs/P08_Fibonacci.py @@ -8,27 +8,12 @@ def fibonacci(number): else: return (fibonacci(number - 1) + fibonacci(number - 2)) -def fibonacciFor(number): - '''This function calculates the fibonacci series for n-th term using loop''' - # first two terms - n1 = 0 - n2 = 1 - count = 2 - if number <= 0: - print("Please enter a positive integer") - elif number == 1: - print("Fibonacci sequence upto ",number,":") - print(n1) - else: - print("Fibonacci sequence upto ",number,":") - print(n1,n2,end=' ') - while count <= number: - nth = n1 + n2 - print(nth,end=' ') - # update values - n1 = n2 - n2 = nth - count += 1 +def fibonacci_without_recursion(number): + if number == 0: return 0 + fibonacci0, fibonacci1 = 0, 1 + for i in range(2, number + 1): + fibonacci1, fibonacci0 = fibonacci0 + fibonacci1, fibonacci1 + return fibonacci1 if __name__ == '__main__': userInput = int(input('Enter the number upto which you wish to calculate fibonnaci series: ')) @@ -36,4 +21,4 @@ def fibonacciFor(number): print(fibonacci(i),end=' ') print("\nUsing LOOP:") - fibonacciFor(userInput) + print(fibonacci_without_recursion(userInput)) From 1c02f15a27e249efdea8bec46b1275f0e7e9dc33 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Sun, 30 Jul 2017 07:38:47 +0530 Subject: [PATCH 03/15] Added iterative approach --- Programs/P09_Factorial.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Programs/P09_Factorial.py b/Programs/P09_Factorial.py index e9698b1..37b8dbc 100644 --- a/Programs/P09_Factorial.py +++ b/Programs/P09_Factorial.py @@ -8,6 +8,15 @@ def factorial(number): else: return number * factorial(number - 1) +def factorial_without_recursion(number): + fact = 1 + while(number > 0): + fact = fact * number + number = number - 1 + print('Factorial of', number,'is: ') + print(fact) + if __name__ == '__main__': userInput = int(input('Enter the number to find its factorial: ')) - print('Factorial of',userInput,'is:',factorial(userInput)) + print('Factorial of', userInput, 'is:', factorial(userInput)) + factorial_without_recursion(userInput) From 8e18e28056881ce472906ed1f6de9b4eb43b1a49 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Sun, 30 Jul 2017 07:38:58 +0530 Subject: [PATCH 04/15] Updated README --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 79dba69..e03e7d0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ # Python-Programs +[![GitHub stars](https://img.shields.io/github/stars/OmkarPathak/Python-Programs.svg)](https://github.com/OmkarPathak/Python-Programs/stargazers) +[![Python](https://img.shields.io/badge/Python-3.6-brightgreen.svg)] + This is my collection of Python Programs.
For python tutorials, visit my website:
http://www.omkarpathak.in From 696422734e7a9c130097e8f2e93e9db38654a5e0 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Fri, 4 Aug 2017 06:59:37 +0530 Subject: [PATCH 05/15] Script to find all IPs of devices connected in Network --- ...2_ScriptToFindDevicesConnectedInNetwork.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Scripts/P12_ScriptToFindDevicesConnectedInNetwork.py diff --git a/Scripts/P12_ScriptToFindDevicesConnectedInNetwork.py b/Scripts/P12_ScriptToFindDevicesConnectedInNetwork.py new file mode 100644 index 0000000..a46e215 --- /dev/null +++ b/Scripts/P12_ScriptToFindDevicesConnectedInNetwork.py @@ -0,0 +1,22 @@ +# Author: OMKAR PATHAK + +# This script helps to find the devices (mobiles and computers) connected to my wifi + +# This script needs python-nmap as a pre-requisite. To install: sudo pip3 install python-nmap + +import nmap +import subprocess + +# function to scan network and display IPs of conected devices +def scan_network(): + scanner = nmap.PortScanner() + myIP = subprocess.check_output(['hostname -I'], shell=True) + myIP = str(myIP, 'utf-8').split('.') + print(myIP[:3]) + scannedData = scanner.scan(hosts = '.'.join(myIP[:3]) + '.1/24', arguments = '-sP') + + # printing all the IP addresses of connected devices + for hostnames in scannedData['scan']: + print(hostnames) + +scan_network() From 643d005bcc5e6ef107ec1a1337760ba5a1da1fd9 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Fri, 4 Aug 2017 06:59:47 +0530 Subject: [PATCH 06/15] Updated README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e03e7d0..9a98c2a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Python-Programs [![GitHub stars](https://img.shields.io/github/stars/OmkarPathak/Python-Programs.svg)](https://github.com/OmkarPathak/Python-Programs/stargazers) -[![Python](https://img.shields.io/badge/Python-3.6-brightgreen.svg)] +![Python](https://img.shields.io/badge/Python-3.6-brightgreen.svg) This is my collection of Python Programs.
For python tutorials, visit my website:
From 363cfebc941d8c497e626cb4e1a592c1e5a039a1 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Sat, 12 Aug 2017 07:00:51 +0530 Subject: [PATCH 07/15] Updated README --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 9a98c2a..4f7e945 100644 --- a/README.md +++ b/README.md @@ -164,3 +164,10 @@ An example of Python Lambda function Encryption/ Decryption using RSA Algorithm * [Python ftplib](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P76_PythonFTP.py) A simple Python FTP file transfer example + +# Donation + +If you have found my softwares to be of any use to you, do consider helping me pay my internet bills. This would encourage me to create many such softwares :) + +| PayPal | Donate via PayPal! | +| ₹ (INR) | Donate via instamojo | From 4cc4cbda27cc60cb5ff8182cd278eb3d41caec0e Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Sat, 12 Aug 2017 07:02:03 +0530 Subject: [PATCH 08/15] Updated README --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4f7e945..ac9a677 100644 --- a/README.md +++ b/README.md @@ -170,4 +170,5 @@ A simple Python FTP file transfer example If you have found my softwares to be of any use to you, do consider helping me pay my internet bills. This would encourage me to create many such softwares :) | PayPal | Donate via PayPal! | -| ₹ (INR) | Donate via instamojo | +|:-------------------------------------------:|:-------------------------------------------------------------:| +| ₹ (INR) | Donate via Instamojo | From bc7d3346c445344acca91eec425566d1cd49020d Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Mon, 4 Sep 2017 07:14:11 +0530 Subject: [PATCH 09/15] Added Codechef easy problems --- .../CodeChef/P37_NDIFFPAL.py | 57 ++++++++++++++ .../CodeChef/P38_PRINCESS.py | 62 +++++++++++++++ CompetitiveProgramming/CodeChef/P39_ALATE.py | 76 +++++++++++++++++++ 3 files changed, 195 insertions(+) create mode 100644 CompetitiveProgramming/CodeChef/P37_NDIFFPAL.py create mode 100644 CompetitiveProgramming/CodeChef/P38_PRINCESS.py create mode 100644 CompetitiveProgramming/CodeChef/P39_ALATE.py diff --git a/CompetitiveProgramming/CodeChef/P37_NDIFFPAL.py b/CompetitiveProgramming/CodeChef/P37_NDIFFPAL.py new file mode 100644 index 0000000..73510e1 --- /dev/null +++ b/CompetitiveProgramming/CodeChef/P37_NDIFFPAL.py @@ -0,0 +1,57 @@ +# A palindrome is a string that reads same in both directions: forwards and backwards. For example, +# the strings radar and noon are palindromes, whereas the string chef is not a palindrome as being read +# backwards is becomes equal to fehc, which is not equal to chef. +# +# Let's say that the pair of indices (i, j) denotes a palindrome in some string S iff i ≤ j and the +# substring starting at the i-th character and ending at the j-th character of S is a palindrome. +# +# Given an integer N. Your task is to construct a string S such that there are exactly N different +# pairs (i, j) that denotes a palindrome. +# +# Input +# The first line of the input contains an integer T denoting the number of test cases. The description +# of T test cases follows. +# +# The first line of each test case contains a single integer N denoting the sought number of pairs that +# denote palindrome. +# +# Output +# For each test case, output a single line containing a string S, consisting of lowecase Latin letters, +# and having exactly N distinct palindrome-denoting pairs. If there's a few such strings, output any one. +# +# If such string S doesn't exist, output -1 instead of it. +# +# Constraints +# 1 ≤ T ≤ 100 +# 1 ≤ N ≤ 104 +# +# Example +# Input: +# 3 +# 6 +# 7 +# 2 +# +# Output: +# noon +# radar +# ab +# +# Explanation: +# Example case 1. In the string "noon", the pairs that denote a palindrome are (1-indexed): (1, 1), (1, 4), (2, 2), (2, 3), (3, 3), (4, 4). +# +# Example case 2. In the string "radar", the pairs that denote a palindrome are (1-indexed): (1, 1), (1, 5), (2, 2), (2, 4), (3, 3), (4, 4), (5, 5). +# +# Example case 3. In the string "ab", the pairs denoting a palindrome are : (1, 1), (2, 2) + +for _ in range(int(input())): + n = int(input()) + s = 'abcdefghijklmnopqrstuvwxyz' + if (n <= 26): + print(s[:n]) + else: + a = n // 26 + b = n % 26 + c = a * s + c = c + s[:b] + print (c) diff --git a/CompetitiveProgramming/CodeChef/P38_PRINCESS.py b/CompetitiveProgramming/CodeChef/P38_PRINCESS.py new file mode 100644 index 0000000..313a6a5 --- /dev/null +++ b/CompetitiveProgramming/CodeChef/P38_PRINCESS.py @@ -0,0 +1,62 @@ +# We all know that the princess is very beautiful but one day jealous from her beauty, a person asked a +# question from princess in order to check her wisdom. Since princess is not good at programming you need +# to help her in solving the problem. +# You are given a string of length N. You have to check among all the the substrings that whether a substring +# exist or not which is palindrome and having length greater than 1. If such a substring exists then print +# YES else print NO. +# +# Input +# The first line contains a single integer T, the number of test cases. Each test case is described by a +# single line containing a string. +# +# Output +# For each test case, output a single line containing the YES or NO. +# +# Constraints +# 1 ≤ T ≤ 10 +# 1 ≤ N ≤ 100000 +# +# Example +# Input: +# 2 +# ab +# babba +# +# Output: +# NO +# YES +# Explanation +# Example case 1.The only substring whose length is greater than 1 is ab, and its not a palindrome. +# +# Example case 2.abba is a substring of the string and its a palindrome thus YES. + +def manacher(string): + + string_with_bounds = '#'.join('^{}$'.format(string)) + length = len(string_with_bounds) + P = [0] * length + center = right = 0 + + for i in range(1, length - 1): + P[i] = (right > i) and min(right - i, P[2 * center - i]) + + # Attempt to expand palindrome centered at i + while string_with_bounds[i + 1 + P[i]] == string_with_bounds[i - 1 - P[i]]: + P[i] += 1 + + # If palindrome centered at i expand past R, + # adjust center based on expanded palindrome. + if i + P[i] > right: + center, right = i, i + P[i] + + # Find the maximum element in P and return the string + maxLen, centerIndex = max((n, i) for i, n in enumerate(P)) + return string[(centerIndex - maxLen)//2: (centerIndex + maxLen)//2] + +for _ in range(int(input())): + string = input() + result = manacher(string) + if len(result) > 1: + print('YES') + else: + print('NO') diff --git a/CompetitiveProgramming/CodeChef/P39_ALATE.py b/CompetitiveProgramming/CodeChef/P39_ALATE.py new file mode 100644 index 0000000..6d74eb6 --- /dev/null +++ b/CompetitiveProgramming/CodeChef/P39_ALATE.py @@ -0,0 +1,76 @@ +# Anmol always comes to class when the class is about to end. Frustrated by this behaviour of Anmol, his +# teacher has given him a special question as his homework. We all know that Anmol is very weak at computer +# science thus he came to you for help. Help Anmol in order to solve the problem. +# You are given an array A of length N(1 indexed). You have to process Q queries of two different types: +# 1 x — print func(x) +# 2 x y— change the value of A[x] to y. +# func(x) is defined as :: +# +# func(x) +# { +# sum = 0 ; +# for(i=x;i<=N;i+=x) +# sum = (sum + A[i]*A[i]) ; +# return sum ; +# } +# +# For each query of type 1 print the value of func(x) in a new line. +# Input +# The first line contains a single integer T, the number of test cases. +# Each test case is described as follows : +# The first line contains two numbers N and Q. +# In the next line N space separated numbers denoting the values of the array A. +# Each of the following Q lines contains a query of one of the above mentioned two types. +# Note :: Since the test files are large use scanf/printf for I/O. +# +# Output +# For each test case, For each query of type 1 print the required answer. +# +# +# Since the answer can be very large, output it modulo 1000000007 +# Constraints +# 1 ≤ T ≤ 10 +# 1 ≤ N ≤ 100000 +# 1 ≤ Q ≤ 100000 +# 1 ≤ A[i] ≤ 1e9 +# 1 ≤ x ≤ N +# 1 ≤ y ≤ 1e9 +# +# Subtasks +# +# Subtask #1 (20 points), Time limit : 1 sec +# 1 ≤ T<=10, N<=100 +# +# +# Subtask #2 (80 points), Time limit : 1 sec +# 1 ≤ T<=10, N<=100000 +# +# +# Example +# Input: +# 1 +# 5 3 +# 1 2 3 4 5 +# 1 1 +# 2 2 1 +# 1 2 +# Output: +# 55 +# 17 + +def func(x): + sum = 0 + for i in range(x, int(n) + 1, x): + sum = sum + array[i] * array[i] + return sum + +for _ in range(int(input())): + n, q = input().split() + array = [int(i) for i in input().split()] + array.insert(0, 0) + for _ in range(int(q)): + inputs = [int(i) for i in input().split()] + if len(inputs) == 2: + print(func(inputs[1])) + else: + array[inputs[1]] = inputs[2] From 71f7668e342ab385b84fb44f13570c65e0d06bfb Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Mon, 4 Sep 2017 07:14:38 +0530 Subject: [PATCH 10/15] Added HackerEarth Graph problems --- .../Graphs/Monk-At-The-Graph-Factory.py | 38 +++++++++++++++++++ .../Graphs/Monk-In-The-Real-Estate.py | 31 +++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/Graphs/Monk-At-The-Graph-Factory.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/Graphs/Monk-In-The-Real-Estate.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Graphs/Monk-At-The-Graph-Factory.py b/CompetitiveProgramming/HackerEarth/Algorithms/Graphs/Monk-At-The-Graph-Factory.py new file mode 100644 index 0000000..ebe2167 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Graphs/Monk-At-The-Graph-Factory.py @@ -0,0 +1,38 @@ +# Our Code Monk recently learnt about Graphs and is very excited! +# +# He went over to the Graph-making factory to watch some freshly prepared graphs. Incidentally, +# one of the workers at the factory was ill today, so Monk decided to step in and do her job. +# +# The Monk's Job is to Identify whether the incoming graph is a tree or not. He is given N, the number +# of vertices in the graph and the degree of each vertex. +# +# Find if the graph is a tree or not. +# +# Input: +# First line contains an integer N, the number of vertices. +# Second line contains N space-separated integers, the degrees of the N vertices. +# +# Output: +# Print "Yes" (without the quotes) if the graph is a tree or "No" (without the quotes) otherwise. +# +# Constraints: +# 1 ≤ N ≤ 100 +# 1 ≤ Degreei ≤ 1000 +# +# SAMPLE INPUT +# 3 +# 1 2 1 +# +# SAMPLE OUTPUT +# Yes + +n = int(input()) +degrees = [int(i) for i in input().split()] + +# Number of nodes are given thus in a tree number of edges are (n-1) and each edge has two degree +# thus in tree data structure total degree should be 2*(n-1) and this should be equal to sum of given degree + +if(2 * (n - 1) == sum(degrees)): + print('Yes') +else: + print('No') diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Graphs/Monk-In-The-Real-Estate.py b/CompetitiveProgramming/HackerEarth/Algorithms/Graphs/Monk-In-The-Real-Estate.py new file mode 100644 index 0000000..93fb5c7 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Graphs/Monk-In-The-Real-Estate.py @@ -0,0 +1,31 @@ +# The Monk wants to buy some cities. To buy two cities, he needs to buy the road connecting those two cities. +# Now, you are given a list of roads, bought by the Monk. You need to tell how many cities did the Monk buy. +# +# Input: +# First line contains an integer T, denoting the number of test cases. The first line of each test case +# contains an integer E, denoting the number of roads. The next E lines contain two space separated +# integers X and Y, denoting that there is an road between city X and city Y. +# +# Output: +# For each test case, you need to print the number of cities the Monk bought. +# +# Constraint: +# 1 <= T <= 100 +# 1 <= E <= 1000 +# 1 <= X, Y <= 10000 +# +# SAMPLE INPUT +# 1 +# 3 +# 1 2 +# 2 3 +# 1 3 + +for _ in range(int(input())): + roads = int(input()) + lst = set([]) + for i in range(roads): + node1,node2 = map(int,input().split()) + lst.add(node1) + lst.add(node2) + print(len(lst)) From 87d1ead523bc5ae8a794aeb1f4c749f21e8cdfb3 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Mon, 4 Sep 2017 07:14:46 +0530 Subject: [PATCH 11/15] Added HackerEarth Greedy problems --- .../Greedy/P01_BeingGreedyForWater.py | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/Greedy/P01_BeingGreedyForWater.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Greedy/P01_BeingGreedyForWater.py b/CompetitiveProgramming/HackerEarth/Algorithms/Greedy/P01_BeingGreedyForWater.py new file mode 100644 index 0000000..bb24158 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Greedy/P01_BeingGreedyForWater.py @@ -0,0 +1,38 @@ +# You are given container full of water. Container can have limited amount of water. You also have +# N bottles to fill. You need to find the maximum numbers of bottles you can fill. +# +# Input: +# First line contains one integer, T, number of test cases. +# First line of each test case contains two integer, N and X, number of bottles and capacity of the container. +# Second line of each test case contains +# N space separated integers, capacities of bottles. +# +# Output: +# For each test case print the maximum number of bottles you can fill. +# +# Constraints: +# 1≤T≤100 +# 1≤N≤104 +# 1≤X≤109 +# +# SAMPLE INPUT +# 1 +# 5 10 +# 8 5 4 3 2 +# +# SAMPLE OUTPUT +# 3 + +for _ in range(int(input())): + N, capacity = map(int, input().split()) + capacities = [int(bottle) for bottle in input().split()] + capacities.sort() + check, bottles = 0, 0 + for i in range(len(capacities)): + if check > capacity: + bottles -= 1 + break + bottles += 1 + check += capacities[i] + + print(bottles) From 10a305afac66ef4b031c2191ad55e96d2744e229 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 19 Sep 2017 07:41:29 +0530 Subject: [PATCH 12/15] HackerEarth String Algorithm Problems --- .../Algorithms/String/P01_SortSubtring.py | 36 +++++++++++++ .../String/P02_PrintFirstOccurence.py | 33 ++++++++++++ .../String/P03_MonkTeachesPalindrome.py | 42 +++++++++++++++ .../Algorithms/String/P04_DNAPride.py | 52 +++++++++++++++++++ .../Algorithms/String/P05_VowelPhobia.py | 28 ++++++++++ .../Algorithms/String/P06_NobitaAndString.py | 26 ++++++++++ 6 files changed, 217 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P01_SortSubtring.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P02_PrintFirstOccurence.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P03_MonkTeachesPalindrome.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P04_DNAPride.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P05_VowelPhobia.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P06_NobitaAndString.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P01_SortSubtring.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P01_SortSubtring.py new file mode 100644 index 0000000..ce0a3d4 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P01_SortSubtring.py @@ -0,0 +1,36 @@ +# Given a string S, and two numbers N, M - arrange the characters of string in between the indexes N +# and M (both inclusive) in descending order. (Indexing starts from 0). +# +# Input Format: +# First line contains T - number of test cases. +# Next T lines contains a string(S) and two numbers(N, M) separated by spaces. +# +# Output Format: +# Print the modified string for each test case in new line. +# +# Constraints: +# +# 1≤T≤1000 +# 1≤|S|≤10000 // |S| denotes the length of string. +# 0≤N≤M<|S| +# S∈[a,z] +# +# SAMPLE INPUT +# 3 +# hlleo 1 3 +# ooneefspd 0 8 +# effort 1 4 +# +# SAMPLE OUTPUT +# hlleo +# spoonfeed +# erofft + +for i in range(int(input())): + user_input = input() + user_input = user_input.split() + to_char = int(user_input[2]) + from_char = int(user_input[1]) + string = user_input[0][from_char:to_char + 1] + replace = ''.join(sorted(string)[::-1]) + print(user_input[0][:from_char] + replace + user_input[0][to_char + 1:len(user_input[0])]) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P02_PrintFirstOccurence.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P02_PrintFirstOccurence.py new file mode 100644 index 0000000..4356f04 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P02_PrintFirstOccurence.py @@ -0,0 +1,33 @@ +# Given a string containing only lower case letters ,print first occurrence of all the letters present +# in that order only. +# +# Input : +# +# Test cases, t +# string ,s +# Output : +# +# Desired Output +# +# Constraint : +# +# string length <=200 +# +# SAMPLE INPUT +# 2 +# aasdvasvavda +# sajhags +# +# SAMPLE OUTPUT +# asdv +# sajhg +# + +for _ in range(int(input())): + user_input = input() + string = [] + for i in range(len(user_input)): + if user_input[i] not in string: + string.append(user_input[i]) + + print(''.join(string)) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P03_MonkTeachesPalindrome.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P03_MonkTeachesPalindrome.py new file mode 100644 index 0000000..8699081 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P03_MonkTeachesPalindrome.py @@ -0,0 +1,42 @@ +# Monk introduces the concept of palindrome saying,"A palindrome is a sequence of characters which reads the s +# ame backward or forward." +# Now, since he loves things to be binary, he asks you to find whether the given string is palindrome or not. +# If a given string is palindrome, you need to state that it is even palindrome (palindrome with even length) +# or odd palindrome (palindrome with odd length). +# +# Input: +# The first line consists of T, denoting the number of test cases. +# Next follow T lines, each line consisting of a string of lowercase English alphabets. +# +# Output: +# For each string , you need to find whether it is palindrome or not. +# If it is not a palindrome, print NO. +# If it is a palindrome, print YES followed by a space; then print EVEN it is an even palindrome +# else print ODD. +# Output for each string should be in a separate line. +# See the sample output for clarification. +# +# Constraints: +# 1≤T≤50 +# 1≤length of string≤105 +# +# SAMPLE INPUT +# 3 +# abc +# abba +# aba +# +# SAMPLE OUTPUT +# NO +# YES EVEN +# YES ODD + +for _ in range(int(input())): + user_input = input() + if user_input == user_input[::-1]: + if len(user_input) % 2 == 0: + print('YES EVEN') + else: + print('YES ODD') + else: + print('NO') diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P04_DNAPride.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P04_DNAPride.py new file mode 100644 index 0000000..065749d --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P04_DNAPride.py @@ -0,0 +1,52 @@ +# Everyone is familiar with Pratik's obsession with DNA and how much he likes to find the correct pair for +# the nucleotide bases. One day Samim found him exaggerating about his knowledge of DNA bases. So Samim +# challenged Pratik about finding the correct base pair for the given DNA sequence and show the result. +# Also he secretly introduced some of RNA nucleotide bases to test Pratik. Now initially he accepted the +# challenge but soon found out about how big the sequence actually was, so he came to you ask him for your +# in finding the sequence and keep his pride about the knowledge of DNA molecules. +# +# You are given a string that contains the nucleotide bases of DNA and RNA, you are needed to find the +# correct pair for all the bases and print the corresponding sequence obtained. In case the sequence +# contains a RNA base, print "Error RNA nucleobases found!" (without quotes). +# +# INPUT FORMAT +# +# The first line of input contains T, the no of test cases. The next line of input contains N, the no of +# bases in each of the DNA sequence The line after that contains the DNA sequence. +# +# OUTPUT FORMAT +# +# For each test case output your answer on a new line. +# +# CONSTRAIN +# +# 1≤T≤10^4 +# 1≤N≤10^6 +# +# SAMPLE INPUT +# 3 +# 2 +# AG +# 4 +# ATGC +# 6 +# UGCACT +# +# SAMPLE OUTPUT +# TC +# TACG +# Error RNA nucleobases found! + +for _ in range(int(input())): + string_length = int(input()) + string = input() + check = {'A':'T', 'T':'A', 'G':'C', 'C':'G'} + result = [] + + if 'U' in string: + print('Error RNA nucleobases found!') + else: + for i in range(len(string)): + result.append(check[string[i]]) + + print(''.join(result)) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P05_VowelPhobia.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P05_VowelPhobia.py new file mode 100644 index 0000000..7434218 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P05_VowelPhobia.py @@ -0,0 +1,28 @@ +# Manish has got the task to frame a speech for his professor at the university at the Annual sports meet.But +# the problem is that the professor has speech dyslexia and he can't speak the words clearly which have vowels +# in them. So Manish has to avoid such words and has to minimise their usage in the speech letter. Your task +# is to help Manish mark the vowels in the words so that he can minimise their use. You are given a string S +# consisting of lower case letters only. You need to count the number of vowels in the string S. +# +# INPUT The first line will contain an integer T denoting the number of test cases. The following T lines +# will contain a string S in lower case letters only. +# +# OUTPUT Print the number the vowels in the string S. +# +# CONSTRAINTS 1<=T<=100 +# +# SAMPLE INPUT +# 1 +# hashes +# +# SAMPLE OUTPUT +# 2 + +for _ in range(int(input())): + string = input() + count = 0 + for i in range(len(string)): + if string[i] in ['a', 'e', 'i', 'o', 'u']: + count += 1 + + print(count) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P06_NobitaAndString.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P06_NobitaAndString.py new file mode 100644 index 0000000..e6f8a6f --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P06_NobitaAndString.py @@ -0,0 +1,26 @@ +# Doraemon gave Nobita a gadget that swaps words inside a string in the following manner : +# +# If there are W words, word 1 is swapped with word W, word 2 is swapped with word W-1 and so on. The +# problem is that Nobita himself cannot verify the answer for large strings. Help him write a program to do so. +# +# INPUT : +# the first line of the input contains the number of test cases. Each test case consists of a single line +# containing the string. +# +# OUTPUT : +# output the string with the words swapped as stated above. +# +# CONSTRAINTS : +# |string length| <= 100000 +# string contains english alphabets and spaces +# +# SAMPLE INPUT +# 1 +# hello world +# +# SAMPLE OUTPUT +# world hello + +for _ in range(int(input())): + string = input().split() + print(' '.join(string[::-1])) From 365f8d35aefcc9229853e75709c950281dd88ab2 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Thu, 21 Sep 2017 07:44:52 +0530 Subject: [PATCH 13/15] HackerEarth String Problems --- .../Algorithms/String/P07_SumitsString.py | 51 +++++++++++++++++++ .../String/P08_RemoveDupplicates.py | 43 ++++++++++++++++ .../Algorithms/String/P10_Conversion.py | 38 ++++++++++++++ 3 files changed, 132 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P07_SumitsString.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P08_RemoveDupplicates.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P10_Conversion.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P07_SumitsString.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P07_SumitsString.py new file mode 100644 index 0000000..831d61d --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P07_SumitsString.py @@ -0,0 +1,51 @@ +# Given a string 'S' , u need to tell whether it is 'sumit's string or not'. +# +# A string is called 'Sumit's String' , if distance between adjacent character is 1. +# +# Consider that the alphabets are arranged in cyclic manner from 'a' to 'z'. distance between any character +# 'x' and 'y' will be defined as minimum number of steps it takes 'x' to reach 'y'. Here, character 'x' can +# start moving clockwise or anti-clockwise in order to reach at position where character 'y' is placed. +# +# Print 'YES' if it is Sumit's string else print 'NO', for each yest case. +# +# Input : +# +# test cases, t +# string , s +# Output: +# +# Desired O/p +# +# Constraints : +# +# string length<=250 +# string has only lower case letters +# +# SAMPLE INPUT +# 3 +# aba +# zza +# bcd +# +# SAMPLE OUTPUT +# YES +# NO +# YES + +for _ in range(int(input())): + string = input() + sumit_string = True + check = 'abcdefghijklmnopqrstuvwxyz' + for i in range(len(string) - 1): + check_first = check.find(string[i]) + 1 + check_second = check.find(string[i + 1]) + 1 + if abs(check_second - check_first) == 1 or abs(check_second - check_first) == 25: + continue + else: + sumit_string = False + break + + if sumit_string: + print('YES') + else: + print('NO') diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P08_RemoveDupplicates.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P08_RemoveDupplicates.py new file mode 100644 index 0000000..65138f9 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P08_RemoveDupplicates.py @@ -0,0 +1,43 @@ +# Given a string S. Your task is to remove all duplicates characters from the string S +# +# NOTE: +# 1.) Order of characters in output string should be same as given in input string. +# 2.) String S contains only lowercase characters ['a'-'z']. +# +# input: +# Input contain a single string S. +# +# Output: +# Print the string S with no any duplicate characters. +# +# Constraints: +# Test Files 1 to 5: +# 1<=|S|<=100 +# Test Files 6 to 10: +# 1<=|S|<=100000 +# +# Sample Output #1 +# hacker +# +# Sample Output #1 +# hacker +# +# Sample Input #2 +# hackerearth +# +# Sample Output #2 +# hackert +# +# Sample Input #3 +# programming +# +# Sample Output #3 +# progamin + +string = list(input()) +result = [] +for i in range(len(string)): + if string[i] not in result: + result.append(string[i]) + +print(''.join(result)) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P10_Conversion.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P10_Conversion.py new file mode 100644 index 0000000..27d85b1 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P10_Conversion.py @@ -0,0 +1,38 @@ +# Given a string, convert it into its number form . +# +# A or a -> 1 +# B or b -> 2 +# C or c -> 3 +# . . . +# Z or z -> 26 +# space -> $ +# Input: +# +# test cases, t +# string , s +# Output: +# +# Desired O/p +# +# Constraints: string length <=200 +# +# SAMPLE INPUT +# 2 +# AMbuj verma +# Aaaa bBBB +# +# SAMPLE OUTPUT +# 11322110$22518131 +# 1111$2222 + +for _ in range(int(input())): + string = input() + check = 'abcdefghijklmnopqrstuvwxyz' + result = [] + for i in range(len(string)): + if string[i].lower() != ' ': + result.append(check.find(string[i].lower()) + 1) + else: + result.append('$') + + print(''.join([str(i) for i in result])) From 3436850cbac14c7da025b5955055db405255d4f6 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Thu, 21 Sep 2017 07:45:09 +0530 Subject: [PATCH 14/15] HackerEarth String Problems --- .../Algorithms/String/P11_CaesarsCipher.py | 71 ++++++++++++++++ .../Algorithms/String/P12_CompilerVersion.py | 43 ++++++++++ .../Algorithms/String/P13_NameGame.py | 85 +++++++++++++++++++ 3 files changed, 199 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P11_CaesarsCipher.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P12_CompilerVersion.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P13_NameGame.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P11_CaesarsCipher.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P11_CaesarsCipher.py new file mode 100644 index 0000000..87eb025 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P11_CaesarsCipher.py @@ -0,0 +1,71 @@ +# Caesar's Cipher is a very famous encryption technique used in cryptography. It is a type of substitution +# cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down +# the alphabet. For example, with a shift of 3, D would be replaced by G, E would become H, X would become A +# and so on. +# +# Encryption of a letter X by a shift K can be described mathematically as +# EK(X)=(X+K) % 26. +# +# Given a plaintext and it's corresponding ciphertext, output the minimum non-negative value of shift that was +# used to encrypt the plaintext or else output −1 if it is not possible to obtain the given ciphertext from +# the given plaintext using Caesar's Cipher technique. +# +# Input: +# +# The first line of the input contains Q, denoting the number of queries. +# +# The next Q lines contain two strings S and T consisting of only upper-case letters. +# +# Output: +# +# For each test-case, output a single non-negative integer denoting the minimum value of shift that was used +# to encrypt the plaintext or else print −1 if the answer doesn't exist. +# +# Constraints: +# 1≤Q≤5 +# 1≤|S|≤10^5 +# 1≤|T|≤10^5 +# |S| = |T| +# +# SAMPLE INPUT +# 2 +# ABC +# DEF +# AAA +# PQR +# +# SAMPLE OUTPUT +# 3 +# -1 + +# My Solution +for _ in range(int(input())): + string_one = input() + string_two= input() + check_one = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + # ZYXWVUTSRQPONMLKJIHGFEDCBA + check_two = check_one[::-1] + result = [] + for i in range(len(string_one)): + if(check_one.find(string_one[i]) > check_one.find(string_two[i])): + result.append(check_two.find(string_one[i]) + check_one.find(string_two[i]) + 1) + else: + result.append(check_one.find(string_two[i]) - check_one.find(string_one[i])) + + if result.count(result[0]) == len(string_one): + print(result[0]) + else: + print(-1) + +# More Efficient Solution: +tests = int(input().strip()) +for i in range(tests): + plain = input().strip() + cipher = input().strip() + shift = (ord(cipher[0])-ord(plain[0])+26)%26 + valid = True + for j in range(len(plain)): + if (ord(cipher[j])-ord(plain[j])+26)%26 != shift: + valid = False + break + print(shift) if valid else print("-1") diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P12_CompilerVersion.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P12_CompilerVersion.py new file mode 100644 index 0000000..363f4c8 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P12_CompilerVersion.py @@ -0,0 +1,43 @@ +# You are converting an old code for a new version of the compiler. +# +# In the old code we have used "->" for pointers. But now we have to replace each "->" with a ".". But this +# replacement shouldn't be done inside commments. A comment is a string that starts with "//" and terminates +# at the end of the line. +# +# Input: +# +# At max. +# 2000 +# 2000 lines of code. +# +# Each line of code consists of at maximum +# 60 +# 60 characters. +# +# Output: +# +# New code with required changes. +# +# SAMPLE INPUT +# int t; //variable t +# t->a=0; //t->a does something +# return 0; +# +# SAMPLE OUTPUT +# int t; //variable t +# t.a=0; //t->a does something +# return 0; + +import sys +import re +while True: + line = sys.stdin.readline() + if len(line) >=2 : + if '//' in line: + line = re.split("//", line) + line[0] = re.sub("->", ".", line[0]) + sys.stdout.write('//'.join(line)) + else: + sys.stdout.write(re.sub("->", ".", line)) + else: + break diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P13_NameGame.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P13_NameGame.py new file mode 100644 index 0000000..24f5260 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P13_NameGame.py @@ -0,0 +1,85 @@ +# John has recently learned about ASCII values. With his knowledge of ASCII values and character he has +# developed a special word and named it John's Magical word. +# +# A word which consists of alphabets whose ASCII values is a prime number is a John's Magical word. An +# alphabet is john's Magical alphabet if its ASCII value is prime. +# +# John's nature is to boast about the things he know or have learnt about. So just to defame his friends he +# gives few string to his friends and ask them to convert it to John's Magical word. None of his friends would +# like to get insulted. Help them to convert the given strings to John's Magical Word. +# +# Rules for converting: +# +# 1.Each character should be replaced by the nearest John's Magical alphabet. +# +# 2.If the character is equidistant with 2 Magical alphabets. The one with lower ASCII value will be considered as its replacement. +# +# Input format: +# +# First line of input contains an integer T number of test cases. Each test case contains an integer N (denoting the length of the string) and a string S. +# +# Output Format: +# +# For each test case, print John's Magical Word in a new line. +# +# Constraints: +# +# 1 <= T <= 100 +# +# 1 <= |S| <= 500 +# +# SAMPLE INPUT +# 1 +# 8 +# KINGKONG +# +# SAMPLE OUTPUT +# IIOGIOOG + +numl = [97, 101, 103, 107, 109, 113] +numu = [67, 71, 73, 79, 83, 89] +num = [67, 89, 97, 113] + +for _ in range(int(input())): + length = input() + string = input() + result = '' + + for char in string: + if char.islower() and char.isalpha(): + minimum = 200 + ascii_char = ord(char) + temp = 0 + + for j in numl: + if minimum > abs(ascii_char - j): + minimum = abs(ascii_char - j) + temp = j + + result = result + chr(temp) + + elif char.isupper() and char.isalpha(): + minimum = 200 + ascii_char = ord(char) + temp = 0 + + for j in numu: + if minimum > abs(ascii_char - j): + minimum = abs(ascii_char - j) + temp = j + + result = result + chr(temp) + + else: + minimum = 200 + ascii_char = ord(char) + temp = 0 + + for j in num: + if minimum > abs(ascii_char - j): + minimum = abs(ascii_char - j) + temp = j + + result = result + chr(temp) + + print(result) From a45d35941c9dfff921a4b4465a34cc75d00ef50d Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 26 Sep 2017 09:22:57 +0530 Subject: [PATCH 15/15] Codechef Medium Problem --- CompetitiveProgramming/CodeChef/P40_COINS.py | 46 ++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 CompetitiveProgramming/CodeChef/P40_COINS.py diff --git a/CompetitiveProgramming/CodeChef/P40_COINS.py b/CompetitiveProgramming/CodeChef/P40_COINS.py new file mode 100644 index 0000000..567985f --- /dev/null +++ b/CompetitiveProgramming/CodeChef/P40_COINS.py @@ -0,0 +1,46 @@ +# In Byteland they have a very strange monetary system. +# +# Each Bytelandian gold coin has an integer number written on it. A coin n can be exchanged in a bank into +# three coins: n/2, n/3 and n/4. But these numbers are all rounded down (the banks have to make a profit). +# +# You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy +# Bytelandian coins. +# +# You have one gold coin. What is the maximum amount of American dollars you can get for it? +# +# Input +# The input will contain several test cases (not more than 10). Each testcase is a single line with a number +# n, 0 <= n <= 1 000 000 000. It is the number written on your coin. +# +# Output +# For each test case output a single line, containing the maximum amount of American dollars you can make. +# +# Example +# Input: +# 12 +# 2 +# +# Output: +# 13 +# 2 +# You can change 12 into 6, 4 and 3, and then change these into $6+$4+$3 = $13. If you try changing the +# coin 2 into 3 smaller coins, you will get 1, 0 and 0, and later you can get no more than $1 out of them. +# It is better just to change the 2 coin directly into $2. + +import sys + +list={} +def chk(n): + if n in list.keys(): + return list[n] + if n<=2: + ans = n + else: + ans = chk(n//2) + chk(n//3) + chk(n//4) + if ans