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/CompetitiveProgramming/CodeChef/P36_SUBGCD.py b/CompetitiveProgramming/CodeChef/P36_SUBGCD.py index a4d503a..5087b84 100644 --- a/CompetitiveProgramming/CodeChef/P36_SUBGCD.py +++ b/CompetitiveProgramming/CodeChef/P36_SUBGCD.py @@ -60,11 +60,11 @@ def gcd(firstNumber, secondNumber): flag = 0 size = 0 for i in array: - currentGCD = gcd(i, currentGCD) - if currentGCD == 1: - flag = 1 - print(count) - break + currentGCD = gcd(i, currentGCD) + if currentGCD == 1: + flag = 1 + print(count) + break if flag == 0: - print(-1) + print(-1) \ No newline at end of file diff --git a/CompetitiveProgramming/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 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/P11_JumpOut.py b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P11_JumpOut.py index 4da7dc1..acda653 100644 --- a/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P11_JumpOut.py +++ b/CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P11_JumpOut.py @@ -27,7 +27,7 @@ array = input().split() array = [int(i) for i in array] array.insert(0,0) -count = +count = 0 for i in range(0, check + 1): pos = array[i] + i if pos > check: diff --git a/CompetitiveProgramming/SPOJ/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/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/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/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/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/P72_PythonLambda.py b/Programs/P72_PythonLambda.py index 77b2da4..67fc881 100644 --- a/Programs/P72_PythonLambda.py +++ b/Programs/P72_PythonLambda.py @@ -10,14 +10,24 @@ # expression using these arguments. You can assign the function to a variable to give it a name. # The following example of a lambda function returns the sum of its two arguments: -myFunc = lambda x, y: x * y -# returns 6 -print(myFunc(2, 3)) +myFunc = lambda x, y: x * y -# example to find squares of all numbers from a list +print(myFunc(2, 3)) #output: 6 + +#Here we are directly creating the function and passing the arguments +print((lambda x, y: x * y)(2, 3)) #same output i.e 6 + +print(type(lambda x, y: x * y)) #Output: + +# example to find squares of all numbers of a list myList = [i for i in range(10)] + # returns square of each number -myFunc = lambda x: x * x +myFunc2 = lambda x: x * x + +squares = list(map(myFunc2, myList)) +print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + +print(list(map(lambda x: x * x, myList))) #same as above + -squares = list(map(myFunc, myList)) -print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 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/README.md b/README.md index ac9a677..c79a6c5 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,8 @@ Pune, Maharashtra, India.
9. [Birthday Reminder](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P09_ReminderApplication.py) 10. [Script to download tutorial from tutorials point](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P10_SciptToDownloadPDF.py) 11. [Script to check email in your terminal](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P11_CheckEmail.py) +12. [Script to find devices connected to Network](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P12_ScriptToFindDevicesConnectedInNetwork.py) +13. [Script to create metadata for a file](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P13_Python_Create_File_With_Metadata.py) ## Python Concepts @@ -164,6 +166,8 @@ An example of Python Lambda function Encryption/ Decryption using RSA Algorithm * [Python ftplib](https://github.com/OmkarPathak/Python-Programs/blob/master/Programs/P76_PythonFTP.py) A simple Python FTP file transfer example +* [Python Django Project (beginner)](https://github.com/modernwarfareuplink/fyleBanksApi) +A simple Django Project with two endpoints to show IFSC and bank details # Donation 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/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 +