From 363cfebc941d8c497e626cb4e1a592c1e5a039a1 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Sat, 12 Aug 2017 07:00:51 +0530 Subject: [PATCH 01/37] 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 02/37] 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 03/37] 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 04/37] 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 05/37] 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 06/37] 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 07/37] 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 08/37] 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 09/37] 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 Date: Tue, 26 Sep 2017 09:23:17 +0530 Subject: [PATCH 10/37] HackerEarth String Problem --- .../P14_XennyAndPartiallySortedStrings.py | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P14_XennyAndPartiallySortedStrings.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P14_XennyAndPartiallySortedStrings.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P14_XennyAndPartiallySortedStrings.py new file mode 100644 index 0000000..2621a45 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P14_XennyAndPartiallySortedStrings.py @@ -0,0 +1,50 @@ +# Xenny had a list of N strings of equal length. He wanted to sort them by the first M characters only. That +# means, while sorting the list of strings, he only wanted to consider the first M characters of each string. +# Help Xenny to find out the Kth string in the list after he sorts them. +# +# Note: Xenny wanted to perform stable sorting. +# Stable sorting algorithms maintain the relative order of records with equal keys (i.e. values). That is, a +# sorting algorithm is stable if whenever there are two records R and S with the same key and with R +# appearing before S in the original list, R will appear before S in the sorted list. +# +# Input +# +# First line contains a single integer - T, which represents the number of testcases. +# T testcases follow. +# Each testcase is of the following format: +# First line contains 3 space-separated integers - N, K and M. +# N is the total number of strings Xenny has. +# K is the index of the string in the list after sorting, which Xenny has to find. +# M is the number of characters based on which sorting will be done by Xenny. +# Then next N lines contain N strings ( each line will contain one string ) . +# +# Output +# +# For each testcase, print the Kth string in the sorted list in a new line. +# +# Constraints +# +# 1 ≤ T ≤ 50 +# 1 ≤ N ≤ 103 +# 1 ≤ Max Length of each String ≤ 103 +# 1 ≤ M ≤ Max Length +# M ≤ Max Length of each String ≤ 103 +# +# SAMPLE INPUT +# 1 +# 3 1 3 +# abcdef +# abcaaa +# aabaaa +# +# SAMPLE OUTPUT +# aabaaa + +for _ in range(int(input())): + n, k, m = input().split() + strings = [] + for i in range(int(n)): + strings.append(input()) + + array = sorted(strings, key = lambda x: x[:int(m)]) + print(array[int(k) - 1]) From d1a2e33858e66748e5dd885e8b3bdd98b6a90801 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 26 Sep 2017 09:23:22 +0530 Subject: [PATCH 11/37] HackerEarth String Problem --- .../Algorithms/String/P15_SortedString.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P15_SortedString.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P15_SortedString.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P15_SortedString.py new file mode 100644 index 0000000..6c199b1 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P15_SortedString.py @@ -0,0 +1,43 @@ +# Little Ashish got a lot of strings as his birthday gift. He does not mind getting so many strings for +# free; in fact, he loves them. But, on noticing all the strings he received as a gift, Little Ashish, who's +# also a snob and a bit OCD kind of a guy, realizes that he does not like the way in which the strings are +# arranged. +# +# He likes his strings sorted, in a different kind of a way. He wants his strings to be sorted based on the +# count of characters present in the string. For instance, if the string is: "aaabbc", then the desired +# string would be: cbbaaa. In case where the count of two characters is same, then the lexicographically +# smaller one will be printed first. For instance: "aabbcc" then, the output will be: "aabbcc". +# +# Input: +# First line of input contains number of test cases T. Each test case contains a single string S. +# +# Output: +# For each test cases print the sorted string. +# +# Constraints: +# 1<=T<=100 +# 1<=|S|<=100 +# +# Note: +# String contains only lowercase characters ['a' to 'z']. +# +# SAMPLE INPUT +# 3 +# aabbccdd +# aabcc +# hackerearth +# +# SAMPLE OUTPUT +# aabbccdd +# baacc +# cktaaeehhrr + +from collections import Counter + +for _ in range(int(input())): + string = Counter(input()) + sorted_array = sorted(string.items(), key=lambda x: (x[1], x[0])) + result = '' + for items in sorted_array: + result += items[0] * items[1] + print(result) From 0b695e41109e343ea2cc6bc35f27af71db6ebc54 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 26 Sep 2017 09:23:29 +0530 Subject: [PATCH 12/37] HackerEarth String Problem --- .../Algorithms/String/P16_SecretMessages.py | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P16_SecretMessages.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P16_SecretMessages.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P16_SecretMessages.py new file mode 100644 index 0000000..80a1fea --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P16_SecretMessages.py @@ -0,0 +1,57 @@ +# X and Y are best friends and they love to chat with each other. But their recent concerns about the privacy +# of their messages has distant them. So they decided to encrypt their messages with a key, K, such that the +# character of their messages are now shifted K times towards right of their initial value. Their techniques +# only convert numbers and alphabets while leaving special characters as it is. +# +# Provided the value K you are required to encrypt the messages using their idea of encryption. +# +# INPUT FORMAT +# +# The first line of the input contains, T, the number of messages. The next line contains N, and K, no of +# characters in the message and key for encryption. The next line contains the message. +# +# OUTPUT FORMAT +# +# Output the encrypted messages on a new line for all the test cases. +# +# CONSTRAINS +# +# 1≤T≤100 +# 1≤N≤106 +# 0≤K≤106 +# +# SAMPLE INPUT +# 2 +# 12 4 +# Hello-World! +# 16 50 +# Aarambh@1800-hrs +# +# SAMPLE OUTPUT +# Lipps-Asvph! +# Yypykzf@1800-fpq + +myString = 'abcdefghijklmnopqrstuvwxyz' +myStringU = myString.upper() +nums = '0123456789' + +def access_char(string, i): + return string[i % len(string)] + +for _ in range(int(input())): + n, k = map(int, input().split()) + string = input() + result = [] + + for char in string: + if char.islower() and char.isalpha(): + result.append(access_char(myString, myString.find(char) + k)) + elif char.isupper() and char.isalpha(): + result.append(access_char(myStringU, myStringU.find(char) + k)) + elif char.isnumeric(): + result.append(access_char(nums, nums.find(str(char)) + k)) + else: + result.append(char) + + print(''.join([str(i) for i in result])) + From 104c5ffaadc5c98b811f8d1129457676c24c485e Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 26 Sep 2017 09:23:56 +0530 Subject: [PATCH 13/37] SQLAlchemy beginner tutorial --- Programs/P80_SQLAlchemyTutorial.py | 61 +++++++++++++++++++++++++++++ Programs/example.db | Bin 0 -> 8192 bytes 2 files changed, 61 insertions(+) create mode 100644 Programs/P80_SQLAlchemyTutorial.py create mode 100644 Programs/example.db diff --git a/Programs/P80_SQLAlchemyTutorial.py b/Programs/P80_SQLAlchemyTutorial.py new file mode 100644 index 0000000..f031635 --- /dev/null +++ b/Programs/P80_SQLAlchemyTutorial.py @@ -0,0 +1,61 @@ +# Author: OMKAR PATHAK +# This is a simple tutorial on usinng SQLAlchemy as ORM (Object Relational Mapping) + +# Make sure you have installed SQLAlchemy using: pip3 install sqlalchemy + +from sqlalchemy import ( + create_engine, + Column, + Integer, + String +) + +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker +import os + + +# create a sqlite db +engine = create_engine('sqlite:///example.db', echo=True) +Base = declarative_base() + + +class Student(Base): + __tablename__ = "student" + + id = Column(Integer, primary_key=True) + username = Column(String) + firstname = Column(String) + lastname = Column(String) + university = Column(String) + + def __init__(self, username, firstname, lastname, university): + self.username = username + self.firstname = firstname + self.lastname = lastname + self.university = university + + +def create_tables(): + # create tables + Base.metadata.create_all(engine) + + +if __name__ == '__main__': + sqlite_file = 'example.db' + file_exists = os.path.isfile(sqlite_file) + if not file_exists: + create_tables() + Session = sessionmaker(bind=engine) + session = Session() + + # Create objects + user = Student('OmkarPathak', 'Omkar', 'Pathak', 'MIT') + session.add(user) + + # commit the record the database + session.commit() + + # Select objects + for student in session.query(Student).order_by(Student.id): + print (student.firstname, student.lastname) diff --git a/Programs/example.db b/Programs/example.db new file mode 100644 index 0000000000000000000000000000000000000000..633be46bae2e500a878bba2d1761763d3d0eae89 GIT binary patch literal 8192 zcmeI#u}Z^090u^av?vWo1cxFW`UjU56bErPmY~5jt!ETEp5%&0n+VB8aMa0{@Kt;j zpTo@yv`}=&<{;n49e4Nf&+^-Ha~)};X#QAa($ERpWt_7!BF0$TZpZF*xV_ZfI`z9L zZFcnawqvKb7c;vM2tWV=5P$##AOHafKmY;|fWSWxcsb_V-CmEso*H?-RHdm>m7CS! zj6~ok0VV!<6ws=qf!on3g>e#G1cKs8Lh)@B9g^FrN>$`CQ*`Hx(WNiyZmx^c{4AI9 zcUR^5Nfo6w&zql5ML71wjIM$i4RktmhxNaC%X??ur}tqG1OgC%00bZa0SG_<0uX=z l1Rwx`zZU4Xw%9>;e{Yg4WHFWIK`u6~<1pzvO#{4P;2SE+U9bQE literal 0 HcmV?d00001 From e511b2677129f32e6106ab1b2e6e1f06aa98485a Mon Sep 17 00:00:00 2001 From: chinya07 Date: Thu, 23 Aug 2018 14:48:24 +0530 Subject: [PATCH 14/37] updations in pattern programs --- Programs/P05_Pattern.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Programs/P05_Pattern.py b/Programs/P05_Pattern.py index b4da517..0289826 100644 --- a/Programs/P05_Pattern.py +++ b/Programs/P05_Pattern.py @@ -88,3 +88,24 @@ def pattern5(level): print() pattern5(userInput) print() + +''' +following is the another approach to solve pattern problems with reduced time complexity + +for + +* +** +*** +**** +***** +''' + +num = int(input('Enter number for pattern')) +pattern = '*' +string = pattern * num +x = 0 + +for i in string: + x = x + 1 + print(string[0:x]) From 8d764797422bed31951ae5619334f06418e12ce9 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Thu, 23 Aug 2018 16:20:12 +0530 Subject: [PATCH 15/37] More efficient way to solve Pattern Program --- Programs/P05_Pattern.py | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/Programs/P05_Pattern.py b/Programs/P05_Pattern.py index 0289826..db988a0 100644 --- a/Programs/P05_Pattern.py +++ b/Programs/P05_Pattern.py @@ -89,23 +89,24 @@ def pattern5(level): pattern5(userInput) print() -''' -following is the another approach to solve pattern problems with reduced time complexity - -for - -* -** -*** -**** -***** -''' - -num = int(input('Enter number for pattern')) -pattern = '*' -string = pattern * num -x = 0 - -for i in string: - x = x + 1 - print(string[0:x]) + def pattern6(userInput): + ''' + following is the another approach to solve pattern problems with reduced time complexity + + for + + * + ** + *** + **** + ***** + ''' + + num = int(input('Enter number for pattern')) + pattern = '*' + string = pattern * num + x = 0 + + for i in string: + x = x + 1 + print(string[0:x]) From e3f7414790499f8f3b7bd1d20cbc8c2dc78b078b Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Fri, 7 Sep 2018 20:52:47 +0530 Subject: [PATCH 16/37] Added new script --- README.md | 2 ++ .../P13_Python_Create_File_With_Metadata.py | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 Scripts/P13_Python_Create_File_With_Metadata.py diff --git a/README.md b/README.md index ac9a677..ab3fef9 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,8 @@ Pune, Maharashtra, India.
9. [Birthday Reminder](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P09_ReminderApplication.py) 10. [Script to download tutorial from tutorials point](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P10_SciptToDownloadPDF.py) 11. [Script to check email in your terminal](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P11_CheckEmail.py) +12. [Script to find devices connected to Network](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P12_ScriptToFindDevicesConnectedInNetwork.py) +13. [Script to create metadata for a file](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P13_Python_Create_File_With_Metadata.py) ## Python Concepts diff --git a/Scripts/P13_Python_Create_File_With_Metadata.py b/Scripts/P13_Python_Create_File_With_Metadata.py new file mode 100644 index 0000000..d0b70ad --- /dev/null +++ b/Scripts/P13_Python_Create_File_With_Metadata.py @@ -0,0 +1,36 @@ +#!/usr/bin/python3.6 +import sys, os, datetime + +def create_file(file_name): + ''' + Create a flat file based on underlying Operating System + ''' + if sys.platform == 'linux' or sys.platform == 'darwin': + os.system('touch ' + file_name) + elif sys.platform == 'win32': + os.system('echo . > ' + file_name) + +def write_data_in_file(file_name): + ''' + Write the metadata into the file + ''' + if sys.argv[3]: + if len(sys.argv[3]) <= 15: + length = 15 + else: + length = len(sys.argv[3]) + else: + length = 15 + with open(file_name, 'w') as fd: + fd.write('#' * (length + 16)) + fd.write('\n# Author: ' + sys.argv[2]) + fd.write('\n# Description: ' + sys.argv[3]) + fd.write('\n# Created at: ' + datetime.datetime.today().strftime('%d %b %Y') + '\n') + fd.write('#' * (length + 16)) + +if __name__ == '__main__': + if len(sys.argv) <= 3: + print('You need to provide three arguments [File Name] [Author Name] [Description]') + exit() + create_file(sys.argv[1]) + write_data_in_file(sys.argv[1]) \ No newline at end of file From 386bed49278ae55522175393cf8019ea97adde47 Mon Sep 17 00:00:00 2001 From: Tarun Kumar Dixit <43788843+tarun-sharma03@users.noreply.github.com> Date: Tue, 1 Oct 2019 01:19:26 +0530 Subject: [PATCH 17/37] Added new script --- Scripts/P14_ScriptToPlaySongs.py | 54 ++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Scripts/P14_ScriptToPlaySongs.py diff --git a/Scripts/P14_ScriptToPlaySongs.py b/Scripts/P14_ScriptToPlaySongs.py new file mode 100644 index 0000000..147e417 --- /dev/null +++ b/Scripts/P14_ScriptToPlaySongs.py @@ -0,0 +1,54 @@ +# This program upon execution will take your command to play music randomly. +import pyttsx3 #pip install pyttsx3 +import speech_recognition as sr #pip install speech recognition +import os +import datetime +import random + +engine = pyttsx3.init('sapi5') +voices = engine.getProperty('voices') +engine.setProperty('voice',voices[0].id) #voices[1].id for female assistant + +#speak function to speak the string passed to it. +def speak(audio): + engine.say(audio) + engine.runAndWait() +#function to listen your command and process them +def takedata(): + r= sr.Recognizer() + with sr.Microphone() as source: + print("Listening....") + audio = r.listen(source) + try: + print("Recognizing...") + query = r.recognize_google(audio,language='en-in') #language set is Indian English + print("The user said ",query) + except Exception : + print("Sorry i was unable to catch that. Please try speaking that again.") + return 'None' + return query + +def wishme(): + hours = datetime.datetime.now().hour + + if hours>=0 and hours <12: + speak("good morning") + elif hours>=12 and hours <18: + speak("good afternoon") + else: + speak("good evening") + speak("sir i am your personal assistant. tell me how can i help you ") + +wishme() +query = takedata() +if 'play music' or 'play songs' in query: + music_dir = "F:\\Songs" #put the location of the folder where you store your songs + songs = os.listdir(music_dir) + l = len(songs) + num = random.randrange(0,l,1) + os.startfile(os.path.join(music_dir,songs[num])) + speak("Thank you for using my sevices. All improvements on my github repository are welcome.") + print("www.github.com/tarun-sharma03") + exit() +else: + speak("Query type not supported") \ No newline at end of file From 750ad1f311836583f1724e2de03b25c6d5a891c3 Mon Sep 17 00:00:00 2001 From: Abhishek Jha <44729252+abhishek-kehsihba@users.noreply.github.com> Date: Thu, 3 Oct 2019 19:44:22 +0530 Subject: [PATCH 18/37] Added problems in BIT Manipulation in Hackerearth section (#5) * Created P04_Mystery.py BIT MANIPULATION: Hackearth-Mystery * Created P05_HihiAndCrazyBits * Created P06_RajanAndOddFrequencyNumber.py * Created P07_SherlockAndXOR.py * Created P08_XorAndProject.py * Created P09_LuckyNumbers.py --- .../Bit_Manipulation/P04_Mystery.py | 44 +++++++++++++++++++ .../Bit_Manipulation/P05_HihiAndCrazyBits.py | 37 ++++++++++++++++ .../P06_RajanAndOddFrequencyNumber.py | 25 +++++++++++ .../Bit_Manipulation/P07_SherlockAndXOR.py | 36 +++++++++++++++ .../Bit_Manipulation/P08_XorAndProject.py | 42 ++++++++++++++++++ .../Bit_Manipulation/P09_LuckyNumbers.py | 44 +++++++++++++++++++ 6 files changed, 228 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Bit_Manipulation/P04_Mystery.py create mode 100644 CompetitiveProgramming/HackerEarth/Bit_Manipulation/P05_HihiAndCrazyBits.py create mode 100644 CompetitiveProgramming/HackerEarth/Bit_Manipulation/P06_RajanAndOddFrequencyNumber.py create mode 100644 CompetitiveProgramming/HackerEarth/Bit_Manipulation/P07_SherlockAndXOR.py create mode 100644 CompetitiveProgramming/HackerEarth/Bit_Manipulation/P08_XorAndProject.py create mode 100644 CompetitiveProgramming/HackerEarth/Bit_Manipulation/P09_LuckyNumbers.py diff --git a/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P04_Mystery.py b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P04_Mystery.py new file mode 100644 index 0000000..4f3735d --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P04_Mystery.py @@ -0,0 +1,44 @@ +# In the world of dragon ball, Goku has been the greatest rival of Vegeta. Vegeta wants to surpass goku but never succeeds. Now that he +# knows he cant beat goku in physical strength, he wants to be satisfied by beating goku in mental strength. He gives certain inputs and +# outputs , Goku needs to find the logic and predict the output for the next inputs. Goku is struggling with the challenge, your task is +# to find the logic and and help him win the challenge. + +# INPUT : + +# Given a series of numbers(inputs) and each number(N) on a newline. + +# OUTPUT : + +# For the given input , Output the required ans. + +# NOTE : + +# No. of test cases are unknown. + +# Use Faster I/O Techniques. + +# CONSTRAINTS : + +# 0<= N <= 10^18 + +# SAMPLE INPUT +# 0 +# 1 +# 5 +# 12 +# 22 +# 1424 +# SAMPLE OUTPUT +# 0 +# 1 +# 2 +# 2 +# 3 +# 4 + +while(1): + try: + r=bin(int(input())) + print(r.count('1')) + except: + break diff --git a/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P05_HihiAndCrazyBits.py b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P05_HihiAndCrazyBits.py new file mode 100644 index 0000000..39f7340 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P05_HihiAndCrazyBits.py @@ -0,0 +1,37 @@ +# Hihi is the grandfather of all geeks in IIITA. He and his crazy ideas.....Huh..... Currently, hihi is working on his most famous project +# named 21 Lane, but he is stuck at a tricky segment of his code. + +# Hihi wants to assign some random IP addresses to users, but he won't use rand(). He wants to change the current IP of the user's computer +# to the IP such that its hash is next hash greater than the hash of original IP and differs by only 1 bit from the hash of original IP. + +# Smart Hihi already hashed the IP to some integer using his personal hash function. What he wants from you is to convert the given hashed +# IP to the required IP X as mentioned above. + +# OK, just find the find the smallest number greater than n with exactly 1 bit different from n in binary form + +# Input : + +# First line contains single integer T ( 1 <= T <= 10^6)- number of test cases. Second line contains hashed IP N ( 1 <= N <= 10^18) + +# Output : + +# Print T lines, each containing an integer X, the required IP.(don't worry Hihi will decode X to obtain final IP address) + +# SAMPLE INPUT +# 5 +# 6 +# 4 +# 10 +# 12 +# 14 +# SAMPLE OUTPUT +# 7 +# 5 +# 11 +# 13 +# 15 + + +for _ in range(int(input())): + a=int(input()) + print(a|a+1) diff --git a/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P06_RajanAndOddFrequencyNumber.py b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P06_RajanAndOddFrequencyNumber.py new file mode 100644 index 0000000..924380a --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P06_RajanAndOddFrequencyNumber.py @@ -0,0 +1,25 @@ +# Given an array of numbers of size (2*n+1).Raja is unable to find the number which is present odd number of times.It is guaranteed that only one such number exists.Can you help Raja in finding the number which is present odd number of times? + +# Input +# First line contains value of n. +# Second line contains (2*n+1) array elements. +# Output +# Print the required number. +# Constraints +# 1≤ n ≤ +# 1≤ a[i] ≤ + +# SAMPLE INPUT +# 2 +# 1 2 3 2 1 +# SAMPLE OUTPUT +# 3 +# Explanation +# For first input only 3 is the number which is present odd number of times. + +a=int(input()) +b=list(map(int,input().split())) +d=b[0] +for i in range(1,len(b)): + d=d^b[i] +print(d) diff --git a/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P07_SherlockAndXOR.py b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P07_SherlockAndXOR.py new file mode 100644 index 0000000..56f5d4d --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P07_SherlockAndXOR.py @@ -0,0 +1,36 @@ +# You are given an array A1,A2...AN. You have to tell how many pairs (i, j) exist such that 1 ≤ i < j ≤ N and Ai XOR Aj is odd. + +# Input and Output +# First line T, the number of testcases. Each testcase: first line N, followed by N integers in next line. For each testcase, print the +# required answer in one line. + +# Constraints +# 1 ≤ T ≤ 10 +# 1 ≤ N ≤ 105 +# 0 ≤ Ai ≤ 109 + +# SAMPLE INPUT +# 2 +# 3 +# 1 2 3 +# 4 +# 1 2 3 4 +# SAMPLE OUTPUT +# 2 +# 4 +# Explanation +# For first testcase: 1 XOR 2 is 3 and 2 XOR 3 is 1. So, 2 valid pairs. For second testcase: 1 XOR 2 is 3 and 2 XOR 3 is 1 and 1 XOR 4 is 5 +# and 3 XOR 4 is 7. So, 4 valid pairs. + +for _ in range (int(input())): + a=int(input()) + b=list(map(int,input().split())) + ans=0 + a2=0 + for i in range(0,a): + if(b[i]&1): + ans+=1 + else: + a2+=1 + + print(ans*a2) diff --git a/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P08_XorAndProject.py b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P08_XorAndProject.py new file mode 100644 index 0000000..bbecdba --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P08_XorAndProject.py @@ -0,0 +1,42 @@ +# A project was going on related to image processing and to perform experiments and get desired result the image needs to be converted to +# Gray-Scale using a parameter 'x' and the function P(x) represented the Gray-Code and calculated via x xor (x div 2) where xor stands for +# bitwise exclusive OR (bitwise modulo 2 addition), and div means integer division. + +# It is interesting to note that function P(x) is invertible, which means it is always possible to uniquely restore x given the value of +# P(x). + +# So the group working on the project forgot to keep the original data related to parameter 'x'. Write a program to restore number x from +# the given value of P(x). + +# INPUT: +# The input file contains an integer number y, the value of G(x). + +# OUTPUT: +# The output file should contain a single integer x such that G(x) = y. + +# CONSTRAINTS: +# 0 ≤ x,P(x) ≤ . + +# SAMPLE INPUT +# 15 +# SAMPLE OUTPUT +# 10 + +a=int(input()) +a=bin(a).replace("0b","") +c=[int(i) for i in str(a)] +d=[] +e=c[0] +for i in range(0,len(a)): + if(i==0): + d.append(c[i]) + else: + f=c[i]^e + d.append(f) + e=f +e=1 +g=0 +for i in range(0,len(a)): + g=g+d[len(a)-i-1]*e + e=e*2 +print(g) diff --git a/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P09_LuckyNumbers.py b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P09_LuckyNumbers.py new file mode 100644 index 0000000..20378c2 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P09_LuckyNumbers.py @@ -0,0 +1,44 @@ +# Golu wants to find out the sum of Lucky numbers.Lucky numbers are those numbers which contain exactly two set bits.This task is very +# diffcult for him.So Help Golu to find sum of those numbers which exactly contain two set bits upto a given number N. + +# 3 5 10 are lucky numbers where 7 14 are not. + +# INPUT +# First line contain number of test cases T.Each test case contains a single number N. +# OUTPUT +# Print sum of all Lucky Numbers upto N.Output may be large so take modulo with 1000000007. + +# Constraints +# 1<=T<=105 +# 1<=N<=1018 + +# NOTE: Since value of test cases and n is really large, please use fast I/O optimization techniques. + +# SAMPLE INPUT +# 1 +# 5 +# SAMPLE OUTPUT +# 8 + +import collections +for _ in range(int(input())): + + sum = 0 + mod = 1000000007 + n = int(input()) + j = bin(n) + bl = len(j) - 2 + + + while bl > 0: + lo = bl - 2 + + while lo >= 0: + i = '1' + ('0' * lo) + ('1' ) + ('0' * (bl - lo - 2)) + + if int(i,2) <= n : + sum = (sum + int(i,2)) + lo -= 1 + + bl -= 1 + print(sum % mod) From a118f4a28423ba1182608da62ca3b31f1cde426c Mon Sep 17 00:00:00 2001 From: Avinash Kumar Jha <41112044+avinashjha11@users.noreply.github.com> Date: Sun, 6 Oct 2019 21:33:49 +0530 Subject: [PATCH 19/37] Added problems in SPOJ section. (#6) * SPOJ Problems * SPOJ Problems * SPOJ Problems --- CompetitiveProgramming/SPOJ/P13_AVRG.py | 5 +++++ CompetitiveProgramming/SPOJ/P14_MUL.py | 5 +++++ CompetitiveProgramming/SPOJ/P15_PRADIPSUM.py | 19 +++++++++++++++++++ 3 files changed, 29 insertions(+) create mode 100644 CompetitiveProgramming/SPOJ/P13_AVRG.py create mode 100644 CompetitiveProgramming/SPOJ/P14_MUL.py create mode 100644 CompetitiveProgramming/SPOJ/P15_PRADIPSUM.py diff --git a/CompetitiveProgramming/SPOJ/P13_AVRG.py b/CompetitiveProgramming/SPOJ/P13_AVRG.py new file mode 100644 index 0000000..1c4f21c --- /dev/null +++ b/CompetitiveProgramming/SPOJ/P13_AVRG.py @@ -0,0 +1,5 @@ +sum=0 +for i in range (0,6): + a=int(input()) + sum+=a +print(sum/6) diff --git a/CompetitiveProgramming/SPOJ/P14_MUL.py b/CompetitiveProgramming/SPOJ/P14_MUL.py new file mode 100644 index 0000000..e114106 --- /dev/null +++ b/CompetitiveProgramming/SPOJ/P14_MUL.py @@ -0,0 +1,5 @@ +t = int(input()) +while t>0: + t-=1 + n1, n2 = map(int, raw_input().split()) + print n1*n2 diff --git a/CompetitiveProgramming/SPOJ/P15_PRADIPSUM.py b/CompetitiveProgramming/SPOJ/P15_PRADIPSUM.py new file mode 100644 index 0000000..a4b78da --- /dev/null +++ b/CompetitiveProgramming/SPOJ/P15_PRADIPSUM.py @@ -0,0 +1,19 @@ +def sum(x): + if x < 0: + return -(-x * (-x + 1) // 2) + else: + return x * (x + 1) // 2 + +while True: + try: + a, b = map(int, input().split()) + if a > b: + a, b = b, a + if b < 0: + print(sum(a) - sum(b + 1)) + elif a <= 0: + print(sum(b) + sum(a)) + else: + print(sum(b) - sum(a - 1)) + except EOFError: + exit(0) From 8906b98bb7a0770b2c5faf42fac90f84742dfadd Mon Sep 17 00:00:00 2001 From: Pulkit-100 <40335208+Pulkit-100@users.noreply.github.com> Date: Sun, 6 Oct 2019 21:34:27 +0530 Subject: [PATCH 20/37] Added Magic Methods (#7) --- OOP/P11_MagicMethods.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/OOP/P11_MagicMethods.py b/OOP/P11_MagicMethods.py index caebf85..751b7db 100644 --- a/OOP/P11_MagicMethods.py +++ b/OOP/P11_MagicMethods.py @@ -13,6 +13,14 @@ def __init__(self, firstname, lastname, salary = 0): def __str__(self): return 'Full Name: ' + self.firstname + ' ' + self.lastname + # Implements behaviour for built in type comparison to int + def __int__(self): + return self.salary + + # For overloading the (==) + def __eq__(self,other): + return self.salary==other.salary + # For overloading the (+) def __add__(self, other): return self.salary + other.salary @@ -28,3 +36,6 @@ def __mul__(self, other): print(Jagdish) # Full Name: Jagdish Pathak print(Omkar + Jagdish) # 3000 (This output because of __add__ method overloading) print(Omkar * Jagdish) # 2000000 (__mul__) + print(int(Omkar)) # 1000 (__int__) + print(int(Jagdish)) # 2000 (__int__) + print(Omkar==Jagdish) From 3e41fbe9d5d9c0314cc9a7d92fb353540e09a23e Mon Sep 17 00:00:00 2001 From: AthaSSiN <56124496+AthaSSiN@users.noreply.github.com> Date: Fri, 11 Oct 2019 20:41:48 +0530 Subject: [PATCH 21/37] Added an efficient method to find primes (#8) --- .../HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py b/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py index 28d4de9..050e516 100644 --- a/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py +++ b/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py @@ -12,10 +12,12 @@ # Constraints # 1 <= N <=1000 +import math + userInput = int(input()) -for i in range(2, userInput): +for i in range(2, userInput + 1): check = 0 - for j in range(2, i): + for j in range(2, int(math.sqrt(i))+ 1): if i % j == 0: check = 1 break From 38f7b664a356d64b3e19acbf73ef39c0ee6a9609 Mon Sep 17 00:00:00 2001 From: Subrhamanya <36793516+Subrhamanya@users.noreply.github.com> Date: Tue, 15 Oct 2019 20:38:34 +0530 Subject: [PATCH 22/37] Efficient program to check given number is a perfect square of 2 (#12) --- .../Algorithms/logics/perfectsquareof2.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/logics/perfectsquareof2.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/logics/perfectsquareof2.py b/CompetitiveProgramming/HackerEarth/Algorithms/logics/perfectsquareof2.py new file mode 100644 index 0000000..87b79a9 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/logics/perfectsquareof2.py @@ -0,0 +1,12 @@ +# Efficient Python program to check entered number is a perfect square of 2 or not +# Example +# 8 +# Its a perfect square of 2 + + + +n = int(input("Enter a number")) +if n & (n - 1) == 0: + print("Its a perfect square of 2") +else: + print("Its not perfect square") From 377cf550531c86bae88a2e3805c6db2b063fd5d9 Mon Sep 17 00:00:00 2001 From: namangup <32638824+namangup@users.noreply.github.com> Date: Wed, 16 Oct 2019 08:59:31 +0530 Subject: [PATCH 23/37] Modified the algorithm to take half of the previous time (#13) --- .../HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py b/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py index 050e516..c491dfd 100644 --- a/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py +++ b/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py @@ -15,7 +15,9 @@ import math userInput = int(input()) -for i in range(2, userInput + 1): +if userInput>2 + print("2",end = ' ') +for i in range(3, userInput + 2): check = 0 for j in range(2, int(math.sqrt(i))+ 1): if i % j == 0: From 0c09f366f9d652d0c2dd83dc07006eb5f2e806e0 Mon Sep 17 00:00:00 2001 From: Sudhi Mohan Date: Sat, 26 Oct 2019 09:49:53 +0530 Subject: [PATCH 24/37] Added machine learning program (#15) * created folder machine learning * Added gradient descent program * Delete file1 --- MachineLearning/gradient_descent.py | 102 ++++++++++++++++++++++++++ MachineLearning/readme.txt | 30 ++++++++ MachineLearning/version_list.txt | 109 ++++++++++++++++++++++++++++ 3 files changed, 241 insertions(+) create mode 100644 MachineLearning/gradient_descent.py create mode 100644 MachineLearning/readme.txt create mode 100644 MachineLearning/version_list.txt diff --git a/MachineLearning/gradient_descent.py b/MachineLearning/gradient_descent.py new file mode 100644 index 0000000..6c89d92 --- /dev/null +++ b/MachineLearning/gradient_descent.py @@ -0,0 +1,102 @@ +#################################################################################### +## PROBLEM1: Gradient Descent +## Gradient descent is a popular optimization technique to solve many +## machine learning problems. In this case, we will explore the gradient +## descent algorithm to fit a line for the given set of 2-D points. +## ref: https://tinyurl.com/yc4jbjzs +## ref: https://spin.atomicobject.com/2014/06/24/gradient-descent-linear-regression/ +## +## +## input: directory of faces in ./data/1_points.csv/ +## function for reading points is provided +## +## +## your task: fill the following functions: +## evaluate_cost +## evaluate_gradient +## udpate_params +## NOTE: do NOT change values of 'init_params' and 'max_iterations' in optimizer +## +## +## output: cost after convergence (rmse, lower the better) +## +## +## NOTE: all required modules are imported. DO NOT import new modules. +## NOTE: references are given intline +## tested on Ubuntu14.04, 22Oct2017, Abhilash Srikantha +#################################################################################### + +import numpy as np +import matplotlib.pyplot as plt +import time + +def load_data(fname): + points = np.loadtxt(fname, delimiter=',') + y_ = points[:,1] + # append '1' to account for the intercept + x_ = np.ones([len(y_),2]) + x_[:,0] = points[:,0] + # display plot + #plt.plot(x_[:,0], y_, 'ro') + #plt.xlabel('x-axis') + #plt.ylabel('y-axis') + #plt.show() + print('data loaded. x:{} y:{}'.format(x_.shape, y_.shape)) + return x_, y_ + +def evaluate_cost(x_,y_,params): + tempcost = 0 + for i in range(len(y_)): + tempcost += (y_[i] - ((params[0] * x_[i,0]) + params[1])) ** 2 + return tempcost / float(10000) + +def evaluate_gradient(x_,y_,params): + m_gradient = 0 + b_gradient = 0 + N = float(len(y_)) + for i in range(len(y_)): + m_gradient += -(2/N) * (x_[i,0] * (y_[i] - ((params[0] * x_[i,0]) + params[1]))) + b_gradient += -(2/N) * (y_[i] - ((params[0] * x_[i,0]) + params[1])) + return [m_gradient,b_gradient] + +def update_params(old_params, grad, alpha): + new_m = old_params[0] - (alpha * grad[0]) + new_b = old_params[1] - (alpha * grad[1]) + return [new_m,new_b] + +# initialize the optimizer +optimizer = {'init_params':np.array([4.5,2.0]) , + 'max_iterations':10000, + 'alpha':0.69908, + 'eps':0.0000001, + 'inf':1e10} + +# load data +x_, y_ = load_data("./data/1_points.csv") + +# time stamp +start = time.time() + +try: + # gradient descent + params = optimizer['init_params'] + old_cost = 1e10 + for iter_ in range(optimizer['max_iterations']): + # evaluate cost and gradient + cost = evaluate_cost(x_,y_,params) + grad = evaluate_gradient(x_,y_,params) + # display + if(iter_ % 10 == 0): + print('iter: {} cost: {} params: {}'.format(iter_, cost, params)) + # check convergence + if(abs(old_cost - cost) < optimizer['eps']): + break + # udpate parameters + params = update_params(params,grad,optimizer['alpha']) + old_cost = cost +except: + cost = optimizer['inf'] + +# final output +print('time elapsed: {}'.format(time.time() - start)) +print('cost at convergence: {} (lower the better)'.format(cost)) diff --git a/MachineLearning/readme.txt b/MachineLearning/readme.txt new file mode 100644 index 0000000..590f033 --- /dev/null +++ b/MachineLearning/readme.txt @@ -0,0 +1,30 @@ +The assignment consists of three problems based on basic machine learning and computer vision. +Numerous problems in these areas are well studied in statistics and applied mathematics. +Solutions are to be implemented in python by filling out required functions in each python file. +A basic framework for data i/o and evaluation is already provided (see header comments in each python file). +Please note that all required libraries are already imported so please DO NOT import anything new. + +The four problems are briefly discussed below. + +1. Gradient Descent: This is a popular optimization problem to find solutions to differentiable equations. +Typically, learning problems involve minimizing a cost function by appropriately setting model parameters. +In this task, we are given a set of (noisy) points on a line and we wish to retrieve model parameters (intercept and slope) through gradient descent. +Please refer to 'gradient_descent.py' and inline comments for further details. + +2. Eigenfaces: This is a popular application of learning a basis representation of input data. +The application of this technique is the basis for simple recognition/compression algorithms. +In this task, we want to learn orthonormal basis using PCA of images that correspond to faces. +Please refer to 'eigenfaces.py' and inline comments for further details. + +3. Classification: This is among the basic tasks of machine learning problems. +Here, we will learn a classifier to using groundtruth labels on the training data to be able to distinguish between two object classes. +You will use the scikit library to learn two classifiers (svm and random forest). +Feel free to explore the parameters of both models to maximize classifier performance. +Please refer to 'classification.py' and inline comments for further details. + +4. Disparity map: This is among the basic tasks of 3D computer vision +Here, given two differnce perspectives of the same scene, we will reconstruct an approximate of the depth map. +This is called the disparity map (higher disparity is similar to lower depth). +You will use the scikit library to implement the module. Feel free to explore the parameters 'downsample' and 'patchsize' +Please refer to disparity.py and inline comments for further details. + diff --git a/MachineLearning/version_list.txt b/MachineLearning/version_list.txt new file mode 100644 index 0000000..146455c --- /dev/null +++ b/MachineLearning/version_list.txt @@ -0,0 +1,109 @@ +alabaster==0.7.10 +angles==1.9.11 +astroid==1.5.3 +Babel==2.5.0 +backports.weakref==1.0rc1 +bleach==1.5.0 +chardet==3.0.4 +configparser==3.5.0 +cycler==0.10.0 +decorator==4.1.2 +docutils==0.14 +entrypoints==0.2.3 +html5lib==0.9999999 +imagesize==0.7.1 +imutils==0.4.3 +ipykernel==4.6.1 +ipython==6.1.0 +ipython-genutils==0.2.0 +ipywidgets==6.0.0 +isort==4.2.15 +jedi==0.10.2 +Jinja2==2.9.6 +jsonschema==2.6.0 +jupyter==1.0.0 +jupyter-client==5.1.0 +jupyter-console==5.2.0 +jupyter-core==4.3.0 +lazy-object-proxy==1.3.1 +lxml==3.8.0 +Mako==1.0.6 +Markdown==2.6.9 +MarkupSafe==1.0 +matplotlib==2.0.2 +mistune==0.7.4 +mock==2.0.0 +mpmath==0.19 +nbconvert==5.2.1 +nbformat==4.4.0 +networkx==1.11 +nose==1.3.7 +notebook==5.0.0 +numpy==1.13.1 +numpydoc==0.7.0 +olefile==0.44 +opencv==1.0.1 +pandas==0.20.3 +pandocfilters==1.4.2 +pbr==3.1.1 +pexpect==4.2.1 +pickleshare==0.7.4 +Pillow==3.4.2 +prompt-toolkit==1.0.15 +protobuf==3.4.0 +psutil==5.2.2 +ptyprocess==0.5.2 +pycodestyle==2.3.1 +pyflakes==1.6.0 +Pygments==2.2.0 +pygpu==0.6.9 +pylint==1.7.2 +pyparsing==2.2.0 +python-dateutil==2.6.1 +python-qt-binding==0.2.19 +pytz==2017.2 +PyWavelets==0.5.2 +pyzmq==16.0.2 +qt-dotgraph==0.2.32 +qt-gui==0.2.32 +qt-gui-py-common==0.2.32 +QtAwesome==0.4.4 +qtconsole==4.3.1 +QtPy==1.3.1 +requests==2.14.2 +rope-py3k==0.9.4.post1 +rosboost-cfg==1.11.14 +rosclean==1.11.14 +roscreate==1.11.14 +rosgraph==1.11.21 +roslint==0.10.0 +roslz4==1.11.21 +rosmaster==1.11.21 +rosparam==1.11.21 +scikit-image==0.13.0 +scikit-learn==0.19.0 +scipy==0.19.1 +simplegeneric==0.8.1 +singledispatch==3.4.0.3 +six==1.10.0 +sklearn-theano==0.0.1 +smach==2.0.1 +smclib==1.7.19 +snowballstemmer==1.2.1 +Sphinx==1.6.3 +sphinxcontrib-websupport==1.0.1 +spyder==3.2.3 +sympy==1.1.1 +tensorflow==1.3.0 +tensorflow-tensorboard==0.1.5 +terminado==0.6 +testpath==0.3 +Theano==0.9.0 +tornado==4.5.2 +traitlets==4.3.2 +wcwidth==0.1.7 +webencodings==0.5 +Werkzeug==0.12.2 +widgetsnbextension==3.0.1 +wrapt==1.10.11 +xdot==2.0.1 From be26cc5c5c00b30160f390533fc633ca5d7c45c3 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 5 Nov 2019 11:27:24 +0530 Subject: [PATCH 25/37] Added github actions --- .github/workflows/pythonapp.yml | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 .github/workflows/pythonapp.yml diff --git a/.github/workflows/pythonapp.yml b/.github/workflows/pythonapp.yml new file mode 100644 index 0000000..52a8b87 --- /dev/null +++ b/.github/workflows/pythonapp.yml @@ -0,0 +1,29 @@ +name: Python application + +on: [push, pull_request] +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + - name: Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + - name: Lint with flake8 + run: | + pip install flake8 + # stop the build if there are Python syntax errors or undefined names + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics + - name: Test with pytest + run: | + pip install pytest + pytest From aadc4546d4d22e47c105815f80095ca3b251dc7e Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 5 Nov 2019 11:28:24 +0530 Subject: [PATCH 26/37] Update pythonapp.yml --- .github/workflows/pythonapp.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pythonapp.yml b/.github/workflows/pythonapp.yml index 52a8b87..d01da42 100644 --- a/.github/workflows/pythonapp.yml +++ b/.github/workflows/pythonapp.yml @@ -15,7 +15,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - pip install -r requirements.txt + # pip install -r requirements.txt - name: Lint with flake8 run: | pip install flake8 From d20faf6c77a8c94fe414655b6f306ea508e09cf6 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 5 Nov 2019 11:36:01 +0530 Subject: [PATCH 27/37] Fixed syntax changes --- CompetitiveProgramming/CodeChef/P36_SUBGCD.py | 12 ++++++------ .../Basics_Of_Input_Output/P04_PrimeNumber.py | 2 +- .../HackerEarth/DataStructures/Arrays/P11_JumpOut.py | 2 +- CompetitiveProgramming/SPOJ/P14_MUL.py | 4 ++-- Programs/P40_CipherText.py | 4 ---- Programs/P56_Pangram.py | 2 +- 6 files changed, 11 insertions(+), 15 deletions(-) diff --git a/CompetitiveProgramming/CodeChef/P36_SUBGCD.py b/CompetitiveProgramming/CodeChef/P36_SUBGCD.py index a4d503a..5087b84 100644 --- a/CompetitiveProgramming/CodeChef/P36_SUBGCD.py +++ b/CompetitiveProgramming/CodeChef/P36_SUBGCD.py @@ -60,11 +60,11 @@ def gcd(firstNumber, secondNumber): flag = 0 size = 0 for i in array: - currentGCD = gcd(i, currentGCD) - if currentGCD == 1: - flag = 1 - print(count) - break + currentGCD = gcd(i, currentGCD) + if currentGCD == 1: + flag = 1 + print(count) + break if flag == 0: - print(-1) + print(-1) \ No newline at end of file diff --git a/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py b/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py index c491dfd..9fa2418 100644 --- a/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py +++ b/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py @@ -15,7 +15,7 @@ import math userInput = int(input()) -if userInput>2 +if userInput > 2: print("2",end = ' ') for i in range(3, userInput + 2): check = 0 diff --git a/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P11_JumpOut.py b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P11_JumpOut.py index 4da7dc1..acda653 100644 --- a/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P11_JumpOut.py +++ b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P11_JumpOut.py @@ -27,7 +27,7 @@ array = input().split() array = [int(i) for i in array] array.insert(0,0) -count = +count = 0 for i in range(0, check + 1): pos = array[i] + i if pos > check: diff --git a/CompetitiveProgramming/SPOJ/P14_MUL.py b/CompetitiveProgramming/SPOJ/P14_MUL.py index e114106..735e492 100644 --- a/CompetitiveProgramming/SPOJ/P14_MUL.py +++ b/CompetitiveProgramming/SPOJ/P14_MUL.py @@ -1,5 +1,5 @@ t = int(input()) while t>0: t-=1 - n1, n2 = map(int, raw_input().split()) - print n1*n2 + n1, n2 = map(int, input().split()) + print(n1*n2) diff --git a/Programs/P40_CipherText.py b/Programs/P40_CipherText.py index af4b2c1..3733f43 100644 --- a/Programs/P40_CipherText.py +++ b/Programs/P40_CipherText.py @@ -12,8 +12,6 @@ def encrypt(message, key): num = LETTERS.find(chars) num += key encrypted += LETTERS[num] - else: - encrypted += symbol return encrypted @@ -25,8 +23,6 @@ def decrypt(message, key): num = LETTERS.find(chars) num -= key decrypted += LETTERS[num] - else: - decrypted += symbol return decrypted diff --git a/Programs/P56_Pangram.py b/Programs/P56_Pangram.py index 2e6ff3c..be2f31d 100644 --- a/Programs/P56_Pangram.py +++ b/Programs/P56_Pangram.py @@ -24,7 +24,7 @@ def pangram(sentence): # A short version of above function: def pangram2(sentence): alphabet = list(map(chr, range(97, 123))) - formattedString = ''.join(c for c in string if c.isalpha()).lower() + formattedString = ''.join(c for c in sentence if c.isalpha()).lower() return set(alphabet) == set(formattedString) if __name__ == '__main__': From 1cf984af807c090154556fdf023d8c13ef33b3f2 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 5 Nov 2019 11:38:11 +0530 Subject: [PATCH 28/37] Update pythonapp.yml --- .github/workflows/pythonapp.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pythonapp.yml b/.github/workflows/pythonapp.yml index d01da42..63612d1 100644 --- a/.github/workflows/pythonapp.yml +++ b/.github/workflows/pythonapp.yml @@ -26,4 +26,4 @@ jobs: - name: Test with pytest run: | pip install pytest - pytest + # pytest From 53f95064ee2302c9f2f26c01192e7e4a1e3e0ef1 Mon Sep 17 00:00:00 2001 From: Hanif Ali Date: Sun, 10 Nov 2019 07:25:12 +0500 Subject: [PATCH 29/37] Added Pretty Printing feature to Binary Tree Programs (#17) * Added some more functions to BinarySearchTree. -> Defining intial elements of newly created Trees -> Prettyprinting trees with left-right order and * representing null nodes. * Added pretty print to BinaryTree.py * Fixed flake8 Linting --- Programs/P43_BinarySearchTree.py | 23 ++++++++++++++++++++++- Programs/P62_BinaryTree.py | 21 +++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/Programs/P43_BinarySearchTree.py b/Programs/P43_BinarySearchTree.py index d82b433..eac303f 100644 --- a/Programs/P43_BinarySearchTree.py +++ b/Programs/P43_BinarySearchTree.py @@ -72,9 +72,13 @@ def postorder(self): print(str(self.data), end = ' ') class Tree(object): - def __init__(self): + def __init__(self, initial_data = []): self.root = None + # If provided, add initial data + for data in initial_data: + self.insert(data) + def insert(self, data): if self.root: return self.root.insert(data) @@ -106,6 +110,22 @@ def postorder(self): print('Postorder: ') self.root.postorder() + + def pprint(self, head_node=0, _pre="", _last=True, term=False): + + head_node = self.root if head_node == 0 else head_node + + data = "*" if head_node is None else head_node.data + + print(_pre, "`- " if _last else "|- ", data, sep="") + _pre += " " if _last else "| " + + if term: return + + for i, child in enumerate([head_node.leftChild, head_node.rightChild]): + self.pprint(child, _pre, bool(i) ,term=not(bool(child))) + + if __name__ == '__main__': tree = Tree() tree.insert(10) @@ -117,6 +137,7 @@ def postorder(self): tree.insert(7) tree.insert(15) tree.insert(13) + tree.pprint() print(tree.find(1)) print(tree.find(12)) tree.preorder() diff --git a/Programs/P62_BinaryTree.py b/Programs/P62_BinaryTree.py index fe29b3a..56a3bc1 100644 --- a/Programs/P62_BinaryTree.py +++ b/Programs/P62_BinaryTree.py @@ -38,18 +38,39 @@ def insertLeft(self,newnodeData): tree.left = self.left + + def printTree(tree): if tree != None: printTree(tree.getLeftChild()) print(tree.getnodeDataValue()) printTree(tree.getRightChild()) + +def pprint(head_node, _pre="", _last=True, term=False): + data = "*" if head_node is None else head_node.nodeData + + print(_pre, "`- " if _last else "|- ", data, sep="") + _pre += " " if _last else "| " + + if term: return + + left = head_node.getLeftChild() + right = head_node.getRightChild() + + for i, child in enumerate([left, right]): + pprint(child, _pre, bool(i) ,term=not(bool(child))) + + + + def testTree(): myTree = BinaryTree("1") myTree.insertLeft("2") myTree.insertRight("3") myTree.insertRight("4") printTree(myTree) + pprint(myTree) if __name__ == '__main__': testTree() From d968c4dcdf6f308b0276c74b796a9aaa6cbf46f7 Mon Sep 17 00:00:00 2001 From: Jayasree77 <41224416+Jayasree77@users.noreply.github.com> Date: Sun, 19 Apr 2020 19:51:11 +0530 Subject: [PATCH 30/37] Create Property_decoraters.py (#19) --- OOP/P11_Property decorators.py | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 OOP/P11_Property decorators.py diff --git a/OOP/P11_Property decorators.py b/OOP/P11_Property decorators.py new file mode 100644 index 0000000..2489bff --- /dev/null +++ b/OOP/P11_Property decorators.py @@ -0,0 +1,38 @@ +#This shows the usage of property decorators + +#Python @property is one of the built-in decorators. The main purpose of any decorator is to change your class methods or attributes in such a way so that the users neeed not make any additional changes in their code. + +#Without property decorators + +class BankAccount: + def __init__(self,name,balance): + self.name=name + self.balance=balance + self.total= self.name+ " has "+self.balance+ " dollars in the account" + +user1=BankAccount("Elon Musk","10000") +user1.name="Tim cook" +print(user1.name) +print(user1.total) + +# Output: Tim cook +# Elon Musk has 10000 dollars in the account + + +#With property decorators + +class BankAccount: + def __init__(self,name,balance): + self.name=name + self.balance=balance + @property + def total(self): + return self.name+ " has "+self.balance+ " dollars in the account" + +user1=BankAccount("Elon Musk","10000") +user1.name="Tim cook" +print(user1.name) +print(user1.total) + +#Output: Tim cook +# Tim cook has 10000 dollars in the account From 5c0e4b2f140f0103f004e035d57b13348ca25c99 Mon Sep 17 00:00:00 2001 From: arun tvs Date: Thu, 7 May 2020 13:57:41 +0530 Subject: [PATCH 31/37] Add simple django project (#16) --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index ab3fef9..c79a6c5 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,8 @@ 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 +* [Python Django Project (beginner)](https://github.com/modernwarfareuplink/fyleBanksApi) +A simple Django Project with two endpoints to show IFSC and bank details # Donation From 2029a5ecfe7162e3cbd42ff4c75df019a23d7791 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Thu, 7 May 2020 15:01:02 +0530 Subject: [PATCH 32/37] Add files via upload --- Untitled (1).py | 174 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 Untitled (1).py diff --git a/Untitled (1).py b/Untitled (1).py new file mode 100644 index 0000000..318a38e --- /dev/null +++ b/Untitled (1).py @@ -0,0 +1,174 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # File Handling using Python + +# In[1]: + + +# open(filename, mode) + +# r - reading +# w - writing +# a - appending + + +# In[7]: + + +file = open('social.txt', 'r') +data = file.read() + +# if for + +file.close() + +print(file.closed) + + +# In[11]: + + +# context manager + +with open('social.txt', 'r') as file: + data = file.read() + +print(file.closed) + + +# In[15]: + + +with open('something.txt', 'a') as file: + file.write('MMCOE - yethe bahutanche hith!') + + +# In[18]: + + +with open('social.txt', 'r') as fd: + data = fd.read(6) # how many bytes or characters you have to read + +print(data) + + +# In[21]: + + +import os + +print(os.getcwd()) + + +# In[22]: + + +print('Original Directory:', os.getcwd()) +os.chdir('/home/omkarpathak/Documents/Notebooks') +print('Current Directory:', os.getcwd()) + + +# In[24]: + + +print(os.listdir()) + + +# In[30]: + + +files = [] + +files = os.listdir() + +# os.path.isfile(filename) # return True is it is a file, else it returns False + +for file in files: + if os.path.isfile(os.path.abspath(file)): + print('File:', file) + +for file in files: + if os.path.isdir(os.path.abspath(file)): + print('Dir:', file) + + +# In[68]: + + +os.chdir('/home/omkarpathak/Documents/PythonLecture/Naruto/Directory0') + +for i in range(10): + os.mkdir('Directory' + str(i) + str(i)) # creating a folder + os.chdir('Directory' + str(i) + str(i)) # Directory0 -> Directory1 + with open('something.txt', 'w') as file: + file.write('Text') + os.chdir('/home/omkarpathak/Documents/PythonLecture/Naruto/Directory0') + + +# In[47]: + + +os.chdir('/home/omkarpathak/Documents/PythonLecture/') + + +# In[44]: + + +mylist = ['omkar', 1, 3, 4.0] +print(mylist) + + +# In[53]: + + +word_to_check = 'hilarious' + +with open('social.txt', 'r') as file: + data = file.read() + +for line in data.split('\n'): + if word_to_check in line: + print('True') + print(line) + +print(len(data.split('\n'))) + + +# In[72]: + + +os.chdir('/home/omkarpathak/Documents/PythonLecture') +with open('social.txt', 'r') as file: + data = file.read() + +char = 'M' +# print(data.lower()) +print(data.lower().count(char.lower())) + + +# In[60]: + + +with open('social.txt', 'r') as file: + data = file.read() + +char = input('Enter a character of your choice:') + +print(data.lower().count(char)) + + +# In[76]: + + +string = 'My namename is Omkar' +print(string.count('name')) # fuzzy search + + +# In[ ]: + + +import numpy +import scipy +import matplotlib + From e0eb3f767207598895a8e86e583cf7cf1f1e60a0 Mon Sep 17 00:00:00 2001 From: Vishal Naik <59202862+Monsieurvishal@users.noreply.github.com> Date: Sun, 21 Jun 2020 11:19:28 +0530 Subject: [PATCH 33/37] alternate program update (#21) Press enter to start and stop the watch --- Programs/P19_SimpleStopWatch.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Programs/P19_SimpleStopWatch.py b/Programs/P19_SimpleStopWatch.py index 59eec6b..bbbff67 100644 --- a/Programs/P19_SimpleStopWatch.py +++ b/Programs/P19_SimpleStopWatch.py @@ -14,3 +14,32 @@ endtime = time.time() print('Total Time:', round(endtime - starttime, 2),'secs') break +# Press enter to start and stop the watch +""" +import time + +print('Press Enter to begin, Press Enter again to stop') +if input()=='': + starttime = time.time() + print('Started') + while True: + val=input() #For ENTER + if val=='': + print('Stopped') + endtime = time.time() + print('Total Time:', round(endtime - starttime, 2),'secs') + break + +""" + +""" +Output: +Press Enter to begin, Press Enter again to stop + +Started + +Stopped +Total Time: 1.05 secs + +""" + From 1b303377aa3a484dd1cbdaeaa94f719cd6d40dea Mon Sep 17 00:00:00 2001 From: Vishal Naik <59202862+Monsieurvishal@users.noreply.github.com> Date: Tue, 23 Jun 2020 14:37:39 +0530 Subject: [PATCH 34/37] fixed indexing error (#23) Enter your message: vishal Enter you key [1 - 26]: 7 Encrypt or Decrypt? [E/D]: e --------------------------------------------------------------------------- IndexError Traceback (most recent call last) in 35 36 if __name__ == '__main__': ---> 37 main() in main() 30 31 if choice.lower().startswith('e'): ---> 32 print(encrypt(message, key)) 33 else: 34 print(decrypt(message, key)) in encrypt(message, key) 9 num = LETTERS.find(chars) 10 num += key ---> 11 encrypted += LETTERS[num] 12 13 return encrypted IndexError: string index out of range ______________________________________________ Above issue was solved --- Programs/P40_CipherText.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Programs/P40_CipherText.py b/Programs/P40_CipherText.py index 3733f43..e092f31 100644 --- a/Programs/P40_CipherText.py +++ b/Programs/P40_CipherText.py @@ -11,7 +11,10 @@ def encrypt(message, key): if chars in LETTERS: num = LETTERS.find(chars) num += key - encrypted += LETTERS[num] + if num>25: + num=num%25 + num=num-1 + encrypted =encrypted + LETTERS[num] return encrypted @@ -21,8 +24,11 @@ def decrypt(message, key): for chars in message: if chars in LETTERS: num = LETTERS.find(chars) - num -= key - decrypted += LETTERS[num] + if num>25: + num=num%25 + num=num-1 + num = num -key + decrypted =decrypted+LETTERS[num] return decrypted From 5893eca078094623e6f8e37c4958d5ec01d8dac7 Mon Sep 17 00:00:00 2001 From: Tej Pratap Yadav <60545022+tyadav4268@users.noreply.github.com> Date: Fri, 2 Oct 2020 08:56:15 +0530 Subject: [PATCH 35/37] Update P72_PythonLambda.py (#41) Added some lines to demonstrate the use of lambda function in a more compact way. for example directly passing the arguments to lambda function. --- Programs/P72_PythonLambda.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/Programs/P72_PythonLambda.py b/Programs/P72_PythonLambda.py index 77b2da4..67fc881 100644 --- a/Programs/P72_PythonLambda.py +++ b/Programs/P72_PythonLambda.py @@ -10,14 +10,24 @@ # expression using these arguments. You can assign the function to a variable to give it a name. # The following example of a lambda function returns the sum of its two arguments: -myFunc = lambda x, y: x * y -# returns 6 -print(myFunc(2, 3)) +myFunc = lambda x, y: x * y -# example to find squares of all numbers from a list +print(myFunc(2, 3)) #output: 6 + +#Here we are directly creating the function and passing the arguments +print((lambda x, y: x * y)(2, 3)) #same output i.e 6 + +print(type(lambda x, y: x * y)) #Output: + +# example to find squares of all numbers of a list myList = [i for i in range(10)] + # returns square of each number -myFunc = lambda x: x * x +myFunc2 = lambda x: x * x + +squares = list(map(myFunc2, myList)) +print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + +print(list(map(lambda x: x * x, myList))) #same as above + -squares = list(map(myFunc, myList)) -print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] From 6039e35b51696cbe7c71cc4a5cfdc743b1bdef1b Mon Sep 17 00:00:00 2001 From: Yash <33280486+yash-odint@users.noreply.github.com> Date: Fri, 2 Oct 2020 09:04:58 +0530 Subject: [PATCH 36/37] Update P04_Factorial.py (#28) --- Programs/P04_Factorial.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Programs/P04_Factorial.py b/Programs/P04_Factorial.py index 5798ccf..fb29789 100644 --- a/Programs/P04_Factorial.py +++ b/Programs/P04_Factorial.py @@ -1,5 +1,6 @@ #Author: OMKAR PATHAK #This program finds the favtorial of the specified numbers +#For example, factorial of 5 = 5*4*3*2*1 = 120 def factorial(number): '''This function finds the factorial of the number passed as argument''' From ed96a4f7b2ddcad5be6c6a0f13cff89975731b77 Mon Sep 17 00:00:00 2001 From: Gunjan Kadel <86482290+GunjanKadel@users.noreply.github.com> Date: Sun, 12 Sep 2021 17:02:13 +0530 Subject: [PATCH 37/37] Added a Basic Chatbot program using Python (#76) --- Programs/Chatbot.py | 145 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 Programs/Chatbot.py diff --git a/Programs/Chatbot.py b/Programs/Chatbot.py new file mode 100644 index 0000000..7c35e98 --- /dev/null +++ b/Programs/Chatbot.py @@ -0,0 +1,145 @@ +# -*- coding: utf-8 -*- +import nltk +from nltk.chat.util import Chat, reflections + +reflections = { + "i am" : "you are", + "i was" : "you were", + "i" : "you", + "i'm" : "you are", + "i'd" : "you would", + "i've" : "you have", + "i'll" : "you will", + "my" : "your", + "you are" : "I am", + "you were" : "I was", + "you've" : "I have", + "you'll" : "I will", + "your" : "my", + "yours" : "mine", + "you" : "me", + "me" : "you", + +} +pairs = [ + [ + r"my name is (.*)", + ["Hello %1, How are you today ?",] + ], + [ + r"hi|hey|hello", + ["Hello", "Hey there",] + ], + [ + r"what is your name ?|your name|name please", + ["I am Y2K. You can call me crazy individual!",] + ], + [ + r"how are you ?|how you doing|what about you|how about you ?", + ["I'm doing good. How can I help you ?",] + ], + [ + r"sorry (.*)", + ["Its alright","Its OK, never mind",] + ], + [ + r"I am fine", + ["Great to hear that, How can I help you?",] + ], + [ + r"(.*) continents", + ["Asia, Africa, North America, South America, Antarctica, Europe, and Australia ",] + ], + [ + r"(.*) (english|hollywood) movie", + ["The Shawshank Redemption", " The Lord of the Rings: The Return of the King","Inception", "Interstellar", "Parasite", "Twilight", "Fast & Furious", "Lucky one","A walk to remember", "The Last Song", "The Notebook","The Fault in Our Stars", "Joker", "Me Before You", "All the boys have met before","Kissing booth", "Titanic",] + ], + [ + r"i'm (.*) doing good", + ["Nice to hear that","How can I help you?:)",] + ], + [ + r"(.*) age?|are you an (idiot|stupid)|what do you think you are", + ["I'm a computer program dude....Seriously you are asking me this?",] + ], + [ + r"(.*) (online|free) courses", + ["Udemy","Udacity","Great Learning","Google Digital Garage","Swayam",] + ], + [ + r"(.*) (news channel|news)", + ["BCC World News","Fox News","Cable News Network (CNN)","Sky News","MSNCB","Republic World","ZEE News","ABP News",] + ], + [ + r"(.*) (horror|spooky) movie", + ["The Nun", "Annabelle", "The conjuring", "Sinister", "The cabin in the wood", "insidious", "IT","Ouija", "Train to Busan", "The Ring", "Hush", "Evil Dead", "Oculus",] + ], + [ + r"(.*) (bollywood|hindi) movie", + ["War", "My name is Khan", "Happy new year", "Dilwale", "Uri", "Don", "Don 2", "Raees","Raazi", "Kalank", "Kalank", "Dangal", "LUDO", "Good Newz", "PK", "Jab Tak Hai Jaan","Cocktail", "Bahubali", "M.S.Dhoni", "Aashiqui 2","Dear Zindagi","Anand", "Mughal-E-Azam", "Mother India", "Don ", " Parinda", "Mr. India","Mera Naam Joker", "Amar, Akbar and Anthony", " Agneepath ", "Sahib Bibi Aur Ghulam","Sholay",] + ], + [ + r"(.*) (webseries|series)", + ["You", "Lucifer", "Cursed", "Mismatched", "Money Heist", "Stranger Things", "Merlin","The Protector", "Sabrina", "Dark", "Friends", "The Big Bang Theory", "Little Things","Lock & Key", "Sherlock", "Sweet Tooth", "The Witcher", "Shadow and Bones","Never Have i ever", "Brooklyn Nine-Nine", "Ragnarok", "Originals", "Vampire Diaries","The Order", "The Boss Baby", "The Haunting of Hill House", "Pup Academy", "Mary Queen of Scots","Bitten", "Titans", "Warrior Nun","The Haunting of bly Manor",] + ], + [ + r"(.*) k-drama", + ["descendants of the sun","busted", "her private life", "whats wrong with secretary kim","its okay to not be okay", "hospital playlist", "crash landing on you","weightlifting fairy kim bok joo", "my first first love", "beauty inside", "was it love",] + ], + [ + r"(.*) (novel|book)", + ["Harry Potter", "Twilight", "Alchemist", "Angel And Demon", "Dead Beautiful", "Lost Symbol", "The Vinche Code", "Hunger Games",] + ], + [ + r"(.*) created ?", + ["I am created using Python's NLTK library ","top secret",] + ], + [ + r"(.*) band", + ["BTS", "The Beatles", "The rolling stones", "Maroon 5", "One Direction", "No Doubt","Black Pink", "EXO", "MonstaX", "Stray Kids","The chainsmokers",] + ], + [ + r"(.*) actress", + ["Scarlett Johansson", "Jennifer Lawrence", "Emma Watson", " Margot Robbie","Angelina Jolie", "Kristen Stewart", "Rachel McAdams","Deepika Padukone", "Priyanka Chopra", "Alia Bhatt", "Kareena Kapoor","Nora Fatehi", "Jacqueline Fernandez", "Aishwarya Rai", "Sara Ali Khan", "Shraddha Kapoor","Anushka Sharma", "Disha Patani",] + ], + [ + r"(.*) (game|sport)", + ["Cricket","Hockey", "Basketball", "Football", "Baseball","Badminton", "Tennis", "Swimming", "Archery","Skates", "Volleyball", "Table Tennis", "Golf",] + ], + [ + r"(.*) (sports person|player)", + ["Lionel Messi","Sania Mirza", "Sachin Tendulkar", "Virat Kohli", "Kevin Durant","Hardik Pandya", "Rohit Sharma", "P. V. Sindhu", "Parupalli Kashyap","Sania Mirza", "Dhyan Chand", "Cristiano Ronaldo", "Robert Lewandowski","Chris Gayle", "Steve Smith", "David Warner", "Ricky Ponting","Stephen Curry", "LeBron James", "M.S.Dhoni", "Chris Paul",] + ], + [ + r"(.*) actor", + ["Robert Downey, Jr.", "Chris Hemsworth", "Tom Holland", "Brad Pitt","Tom Hiddleston", "Tom Cruise", "Chris Evans", "Benedict Cumberbatch","Paul Rudd", "Jeremy Renner", "Ian Somerhalder ","Paul Wesley", "Aamir Khan", "Amitabh Bachchan","Anil Kapoor", "Ranveer Singh", "Ranbir Kapoor", "Salman Khan","Sanjay Dutt", "Shah Rukh Khan", "Tiger Shroff", "Varun Dhawan",] + ], + [ + r"(.*) dialogue", + ["Mere paas maa hai.","Pushpa, I hate tears…","Kitne aadmi the!","Babumoshai, zindagi badi honi chahiye, lambi nahi.","Rishtey mein toh hum tumhare baap lagte hai, naam hai Shahenshaah!","Dosti ka ek usool hai madam – no sorry, no thank you.","Mogambo khush hua!","Hum jahan khade hote hain line yahi se shuru hoti hai.","Bade bade deshon mein aisi choti-choti baatein hoti rehti hai, Senorita.","Haar kar jeetne wale ko baazigar kehte hai.","Mere Karan Arjun aayenge.","Agar maa ka doodh piya hai toh samne aa!","Uska to na bad luck hi kharab hai.","Crime Master Gogo naam hai mera, aankhen nikal ke gotiyan khelta hun main.","Tareekh pe tareekh, tareekh pe tareekh, tareekh pe tareekh milti gayi My Lord, par insaaf nahi mila","Rahul, naam toh suna hi hoga.","Mein apni favourite hoon!","Picture abhi baaki hai mere dost!","How’s the josh?","Thappad se darr nahi lagta sahab, pyaar se lagta hai.","Filmein sirf teen cheezo ke wajah se chalti hai…entertainment, entertainment, entertainment…aur main entertainment hoon.","All izz well",] + ], + [ + r"quit", + ["Bye take care. See you soon :) ","It was nice talking to you. See you soon :)",] + ], + [ + r"(.*) joke", + ["Why did the tomato blush? Because it saw the salad dressing.","What do you call bears with no ears? B","What do dentists call X-rays? Tooth pics.","Did you hear about the first restaurant to open on the moon? It had great food, but no atmosphere.","What did one wall say to the other wall? I’ll meet you at the corner.","When does a joke become a “dad” joke? When the punchline is apparent.","What did the paper say to the pencil? Write on!","How did the bullet lose its job? It got fired.","Why should you never trust stairs? They are always up to something.","Sometimes I tuck my knees into my chest and lean forward.That’s just how I roll.","What do you call a cheese that’s not yours? Nacho cheese!","Did you hear about the cheese factory that exploded in France?There was nothing left but de Brie.",] + ], + [ + r"even me", + ["That's great"] + ], + [ + r"thank you", + ["Your welcome , would you like to know something else if no then please type in QUIT to exit",] + ], +] +def chat(): + print("Hi! I am Y2K..") + chat = Chat(pairs, reflections) + chat.converse() + +#initiate the conversation +if __name__ == "__main__": + chat() \ No newline at end of file