From 87d1ead523bc5ae8a794aeb1f4c749f21e8cdfb3 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Mon, 4 Sep 2017 07:14:46 +0530 Subject: [PATCH 01/13] Added HackerEarth Greedy problems --- .../Greedy/P01_BeingGreedyForWater.py | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/Greedy/P01_BeingGreedyForWater.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/Greedy/P01_BeingGreedyForWater.py b/CompetitiveProgramming/HackerEarth/Algorithms/Greedy/P01_BeingGreedyForWater.py new file mode 100644 index 0000000..bb24158 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/Greedy/P01_BeingGreedyForWater.py @@ -0,0 +1,38 @@ +# You are given container full of water. Container can have limited amount of water. You also have +# N bottles to fill. You need to find the maximum numbers of bottles you can fill. +# +# Input: +# First line contains one integer, T, number of test cases. +# First line of each test case contains two integer, N and X, number of bottles and capacity of the container. +# Second line of each test case contains +# N space separated integers, capacities of bottles. +# +# Output: +# For each test case print the maximum number of bottles you can fill. +# +# Constraints: +# 1≤T≤100 +# 1≤N≤104 +# 1≤X≤109 +# +# SAMPLE INPUT +# 1 +# 5 10 +# 8 5 4 3 2 +# +# SAMPLE OUTPUT +# 3 + +for _ in range(int(input())): + N, capacity = map(int, input().split()) + capacities = [int(bottle) for bottle in input().split()] + capacities.sort() + check, bottles = 0, 0 + for i in range(len(capacities)): + if check > capacity: + bottles -= 1 + break + bottles += 1 + check += capacities[i] + + print(bottles) From 10a305afac66ef4b031c2191ad55e96d2744e229 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 19 Sep 2017 07:41:29 +0530 Subject: [PATCH 02/13] HackerEarth String Algorithm Problems --- .../Algorithms/String/P01_SortSubtring.py | 36 +++++++++++++ .../String/P02_PrintFirstOccurence.py | 33 ++++++++++++ .../String/P03_MonkTeachesPalindrome.py | 42 +++++++++++++++ .../Algorithms/String/P04_DNAPride.py | 52 +++++++++++++++++++ .../Algorithms/String/P05_VowelPhobia.py | 28 ++++++++++ .../Algorithms/String/P06_NobitaAndString.py | 26 ++++++++++ 6 files changed, 217 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P01_SortSubtring.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P02_PrintFirstOccurence.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P03_MonkTeachesPalindrome.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P04_DNAPride.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P05_VowelPhobia.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P06_NobitaAndString.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P01_SortSubtring.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P01_SortSubtring.py new file mode 100644 index 0000000..ce0a3d4 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P01_SortSubtring.py @@ -0,0 +1,36 @@ +# Given a string S, and two numbers N, M - arrange the characters of string in between the indexes N +# and M (both inclusive) in descending order. (Indexing starts from 0). +# +# Input Format: +# First line contains T - number of test cases. +# Next T lines contains a string(S) and two numbers(N, M) separated by spaces. +# +# Output Format: +# Print the modified string for each test case in new line. +# +# Constraints: +# +# 1≤T≤1000 +# 1≤|S|≤10000 // |S| denotes the length of string. +# 0≤N≤M<|S| +# S∈[a,z] +# +# SAMPLE INPUT +# 3 +# hlleo 1 3 +# ooneefspd 0 8 +# effort 1 4 +# +# SAMPLE OUTPUT +# hlleo +# spoonfeed +# erofft + +for i in range(int(input())): + user_input = input() + user_input = user_input.split() + to_char = int(user_input[2]) + from_char = int(user_input[1]) + string = user_input[0][from_char:to_char + 1] + replace = ''.join(sorted(string)[::-1]) + print(user_input[0][:from_char] + replace + user_input[0][to_char + 1:len(user_input[0])]) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P02_PrintFirstOccurence.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P02_PrintFirstOccurence.py new file mode 100644 index 0000000..4356f04 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P02_PrintFirstOccurence.py @@ -0,0 +1,33 @@ +# Given a string containing only lower case letters ,print first occurrence of all the letters present +# in that order only. +# +# Input : +# +# Test cases, t +# string ,s +# Output : +# +# Desired Output +# +# Constraint : +# +# string length <=200 +# +# SAMPLE INPUT +# 2 +# aasdvasvavda +# sajhags +# +# SAMPLE OUTPUT +# asdv +# sajhg +# + +for _ in range(int(input())): + user_input = input() + string = [] + for i in range(len(user_input)): + if user_input[i] not in string: + string.append(user_input[i]) + + print(''.join(string)) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P03_MonkTeachesPalindrome.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P03_MonkTeachesPalindrome.py new file mode 100644 index 0000000..8699081 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P03_MonkTeachesPalindrome.py @@ -0,0 +1,42 @@ +# Monk introduces the concept of palindrome saying,"A palindrome is a sequence of characters which reads the s +# ame backward or forward." +# Now, since he loves things to be binary, he asks you to find whether the given string is palindrome or not. +# If a given string is palindrome, you need to state that it is even palindrome (palindrome with even length) +# or odd palindrome (palindrome with odd length). +# +# Input: +# The first line consists of T, denoting the number of test cases. +# Next follow T lines, each line consisting of a string of lowercase English alphabets. +# +# Output: +# For each string , you need to find whether it is palindrome or not. +# If it is not a palindrome, print NO. +# If it is a palindrome, print YES followed by a space; then print EVEN it is an even palindrome +# else print ODD. +# Output for each string should be in a separate line. +# See the sample output for clarification. +# +# Constraints: +# 1≤T≤50 +# 1≤length of string≤105 +# +# SAMPLE INPUT +# 3 +# abc +# abba +# aba +# +# SAMPLE OUTPUT +# NO +# YES EVEN +# YES ODD + +for _ in range(int(input())): + user_input = input() + if user_input == user_input[::-1]: + if len(user_input) % 2 == 0: + print('YES EVEN') + else: + print('YES ODD') + else: + print('NO') diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P04_DNAPride.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P04_DNAPride.py new file mode 100644 index 0000000..065749d --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P04_DNAPride.py @@ -0,0 +1,52 @@ +# Everyone is familiar with Pratik's obsession with DNA and how much he likes to find the correct pair for +# the nucleotide bases. One day Samim found him exaggerating about his knowledge of DNA bases. So Samim +# challenged Pratik about finding the correct base pair for the given DNA sequence and show the result. +# Also he secretly introduced some of RNA nucleotide bases to test Pratik. Now initially he accepted the +# challenge but soon found out about how big the sequence actually was, so he came to you ask him for your +# in finding the sequence and keep his pride about the knowledge of DNA molecules. +# +# You are given a string that contains the nucleotide bases of DNA and RNA, you are needed to find the +# correct pair for all the bases and print the corresponding sequence obtained. In case the sequence +# contains a RNA base, print "Error RNA nucleobases found!" (without quotes). +# +# INPUT FORMAT +# +# The first line of input contains T, the no of test cases. The next line of input contains N, the no of +# bases in each of the DNA sequence The line after that contains the DNA sequence. +# +# OUTPUT FORMAT +# +# For each test case output your answer on a new line. +# +# CONSTRAIN +# +# 1≤T≤10^4 +# 1≤N≤10^6 +# +# SAMPLE INPUT +# 3 +# 2 +# AG +# 4 +# ATGC +# 6 +# UGCACT +# +# SAMPLE OUTPUT +# TC +# TACG +# Error RNA nucleobases found! + +for _ in range(int(input())): + string_length = int(input()) + string = input() + check = {'A':'T', 'T':'A', 'G':'C', 'C':'G'} + result = [] + + if 'U' in string: + print('Error RNA nucleobases found!') + else: + for i in range(len(string)): + result.append(check[string[i]]) + + print(''.join(result)) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P05_VowelPhobia.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P05_VowelPhobia.py new file mode 100644 index 0000000..7434218 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P05_VowelPhobia.py @@ -0,0 +1,28 @@ +# Manish has got the task to frame a speech for his professor at the university at the Annual sports meet.But +# the problem is that the professor has speech dyslexia and he can't speak the words clearly which have vowels +# in them. So Manish has to avoid such words and has to minimise their usage in the speech letter. Your task +# is to help Manish mark the vowels in the words so that he can minimise their use. You are given a string S +# consisting of lower case letters only. You need to count the number of vowels in the string S. +# +# INPUT The first line will contain an integer T denoting the number of test cases. The following T lines +# will contain a string S in lower case letters only. +# +# OUTPUT Print the number the vowels in the string S. +# +# CONSTRAINTS 1<=T<=100 +# +# SAMPLE INPUT +# 1 +# hashes +# +# SAMPLE OUTPUT +# 2 + +for _ in range(int(input())): + string = input() + count = 0 + for i in range(len(string)): + if string[i] in ['a', 'e', 'i', 'o', 'u']: + count += 1 + + print(count) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P06_NobitaAndString.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P06_NobitaAndString.py new file mode 100644 index 0000000..e6f8a6f --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P06_NobitaAndString.py @@ -0,0 +1,26 @@ +# Doraemon gave Nobita a gadget that swaps words inside a string in the following manner : +# +# If there are W words, word 1 is swapped with word W, word 2 is swapped with word W-1 and so on. The +# problem is that Nobita himself cannot verify the answer for large strings. Help him write a program to do so. +# +# INPUT : +# the first line of the input contains the number of test cases. Each test case consists of a single line +# containing the string. +# +# OUTPUT : +# output the string with the words swapped as stated above. +# +# CONSTRAINTS : +# |string length| <= 100000 +# string contains english alphabets and spaces +# +# SAMPLE INPUT +# 1 +# hello world +# +# SAMPLE OUTPUT +# world hello + +for _ in range(int(input())): + string = input().split() + print(' '.join(string[::-1])) From 365f8d35aefcc9229853e75709c950281dd88ab2 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Thu, 21 Sep 2017 07:44:52 +0530 Subject: [PATCH 03/13] HackerEarth String Problems --- .../Algorithms/String/P07_SumitsString.py | 51 +++++++++++++++++++ .../String/P08_RemoveDupplicates.py | 43 ++++++++++++++++ .../Algorithms/String/P10_Conversion.py | 38 ++++++++++++++ 3 files changed, 132 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P07_SumitsString.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P08_RemoveDupplicates.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P10_Conversion.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P07_SumitsString.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P07_SumitsString.py new file mode 100644 index 0000000..831d61d --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P07_SumitsString.py @@ -0,0 +1,51 @@ +# Given a string 'S' , u need to tell whether it is 'sumit's string or not'. +# +# A string is called 'Sumit's String' , if distance between adjacent character is 1. +# +# Consider that the alphabets are arranged in cyclic manner from 'a' to 'z'. distance between any character +# 'x' and 'y' will be defined as minimum number of steps it takes 'x' to reach 'y'. Here, character 'x' can +# start moving clockwise or anti-clockwise in order to reach at position where character 'y' is placed. +# +# Print 'YES' if it is Sumit's string else print 'NO', for each yest case. +# +# Input : +# +# test cases, t +# string , s +# Output: +# +# Desired O/p +# +# Constraints : +# +# string length<=250 +# string has only lower case letters +# +# SAMPLE INPUT +# 3 +# aba +# zza +# bcd +# +# SAMPLE OUTPUT +# YES +# NO +# YES + +for _ in range(int(input())): + string = input() + sumit_string = True + check = 'abcdefghijklmnopqrstuvwxyz' + for i in range(len(string) - 1): + check_first = check.find(string[i]) + 1 + check_second = check.find(string[i + 1]) + 1 + if abs(check_second - check_first) == 1 or abs(check_second - check_first) == 25: + continue + else: + sumit_string = False + break + + if sumit_string: + print('YES') + else: + print('NO') diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P08_RemoveDupplicates.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P08_RemoveDupplicates.py new file mode 100644 index 0000000..65138f9 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P08_RemoveDupplicates.py @@ -0,0 +1,43 @@ +# Given a string S. Your task is to remove all duplicates characters from the string S +# +# NOTE: +# 1.) Order of characters in output string should be same as given in input string. +# 2.) String S contains only lowercase characters ['a'-'z']. +# +# input: +# Input contain a single string S. +# +# Output: +# Print the string S with no any duplicate characters. +# +# Constraints: +# Test Files 1 to 5: +# 1<=|S|<=100 +# Test Files 6 to 10: +# 1<=|S|<=100000 +# +# Sample Output #1 +# hacker +# +# Sample Output #1 +# hacker +# +# Sample Input #2 +# hackerearth +# +# Sample Output #2 +# hackert +# +# Sample Input #3 +# programming +# +# Sample Output #3 +# progamin + +string = list(input()) +result = [] +for i in range(len(string)): + if string[i] not in result: + result.append(string[i]) + +print(''.join(result)) diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P10_Conversion.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P10_Conversion.py new file mode 100644 index 0000000..27d85b1 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P10_Conversion.py @@ -0,0 +1,38 @@ +# Given a string, convert it into its number form . +# +# A or a -> 1 +# B or b -> 2 +# C or c -> 3 +# . . . +# Z or z -> 26 +# space -> $ +# Input: +# +# test cases, t +# string , s +# Output: +# +# Desired O/p +# +# Constraints: string length <=200 +# +# SAMPLE INPUT +# 2 +# AMbuj verma +# Aaaa bBBB +# +# SAMPLE OUTPUT +# 11322110$22518131 +# 1111$2222 + +for _ in range(int(input())): + string = input() + check = 'abcdefghijklmnopqrstuvwxyz' + result = [] + for i in range(len(string)): + if string[i].lower() != ' ': + result.append(check.find(string[i].lower()) + 1) + else: + result.append('$') + + print(''.join([str(i) for i in result])) From 3436850cbac14c7da025b5955055db405255d4f6 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Thu, 21 Sep 2017 07:45:09 +0530 Subject: [PATCH 04/13] HackerEarth String Problems --- .../Algorithms/String/P11_CaesarsCipher.py | 71 ++++++++++++++++ .../Algorithms/String/P12_CompilerVersion.py | 43 ++++++++++ .../Algorithms/String/P13_NameGame.py | 85 +++++++++++++++++++ 3 files changed, 199 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P11_CaesarsCipher.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P12_CompilerVersion.py create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P13_NameGame.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P11_CaesarsCipher.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P11_CaesarsCipher.py new file mode 100644 index 0000000..87eb025 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P11_CaesarsCipher.py @@ -0,0 +1,71 @@ +# Caesar's Cipher is a very famous encryption technique used in cryptography. It is a type of substitution +# cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down +# the alphabet. For example, with a shift of 3, D would be replaced by G, E would become H, X would become A +# and so on. +# +# Encryption of a letter X by a shift K can be described mathematically as +# EK(X)=(X+K) % 26. +# +# Given a plaintext and it's corresponding ciphertext, output the minimum non-negative value of shift that was +# used to encrypt the plaintext or else output −1 if it is not possible to obtain the given ciphertext from +# the given plaintext using Caesar's Cipher technique. +# +# Input: +# +# The first line of the input contains Q, denoting the number of queries. +# +# The next Q lines contain two strings S and T consisting of only upper-case letters. +# +# Output: +# +# For each test-case, output a single non-negative integer denoting the minimum value of shift that was used +# to encrypt the plaintext or else print −1 if the answer doesn't exist. +# +# Constraints: +# 1≤Q≤5 +# 1≤|S|≤10^5 +# 1≤|T|≤10^5 +# |S| = |T| +# +# SAMPLE INPUT +# 2 +# ABC +# DEF +# AAA +# PQR +# +# SAMPLE OUTPUT +# 3 +# -1 + +# My Solution +for _ in range(int(input())): + string_one = input() + string_two= input() + check_one = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + # ZYXWVUTSRQPONMLKJIHGFEDCBA + check_two = check_one[::-1] + result = [] + for i in range(len(string_one)): + if(check_one.find(string_one[i]) > check_one.find(string_two[i])): + result.append(check_two.find(string_one[i]) + check_one.find(string_two[i]) + 1) + else: + result.append(check_one.find(string_two[i]) - check_one.find(string_one[i])) + + if result.count(result[0]) == len(string_one): + print(result[0]) + else: + print(-1) + +# More Efficient Solution: +tests = int(input().strip()) +for i in range(tests): + plain = input().strip() + cipher = input().strip() + shift = (ord(cipher[0])-ord(plain[0])+26)%26 + valid = True + for j in range(len(plain)): + if (ord(cipher[j])-ord(plain[j])+26)%26 != shift: + valid = False + break + print(shift) if valid else print("-1") diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P12_CompilerVersion.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P12_CompilerVersion.py new file mode 100644 index 0000000..363f4c8 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P12_CompilerVersion.py @@ -0,0 +1,43 @@ +# You are converting an old code for a new version of the compiler. +# +# In the old code we have used "->" for pointers. But now we have to replace each "->" with a ".". But this +# replacement shouldn't be done inside commments. A comment is a string that starts with "//" and terminates +# at the end of the line. +# +# Input: +# +# At max. +# 2000 +# 2000 lines of code. +# +# Each line of code consists of at maximum +# 60 +# 60 characters. +# +# Output: +# +# New code with required changes. +# +# SAMPLE INPUT +# int t; //variable t +# t->a=0; //t->a does something +# return 0; +# +# SAMPLE OUTPUT +# int t; //variable t +# t.a=0; //t->a does something +# return 0; + +import sys +import re +while True: + line = sys.stdin.readline() + if len(line) >=2 : + if '//' in line: + line = re.split("//", line) + line[0] = re.sub("->", ".", line[0]) + sys.stdout.write('//'.join(line)) + else: + sys.stdout.write(re.sub("->", ".", line)) + else: + break diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P13_NameGame.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P13_NameGame.py new file mode 100644 index 0000000..24f5260 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P13_NameGame.py @@ -0,0 +1,85 @@ +# John has recently learned about ASCII values. With his knowledge of ASCII values and character he has +# developed a special word and named it John's Magical word. +# +# A word which consists of alphabets whose ASCII values is a prime number is a John's Magical word. An +# alphabet is john's Magical alphabet if its ASCII value is prime. +# +# John's nature is to boast about the things he know or have learnt about. So just to defame his friends he +# gives few string to his friends and ask them to convert it to John's Magical word. None of his friends would +# like to get insulted. Help them to convert the given strings to John's Magical Word. +# +# Rules for converting: +# +# 1.Each character should be replaced by the nearest John's Magical alphabet. +# +# 2.If the character is equidistant with 2 Magical alphabets. The one with lower ASCII value will be considered as its replacement. +# +# Input format: +# +# First line of input contains an integer T number of test cases. Each test case contains an integer N (denoting the length of the string) and a string S. +# +# Output Format: +# +# For each test case, print John's Magical Word in a new line. +# +# Constraints: +# +# 1 <= T <= 100 +# +# 1 <= |S| <= 500 +# +# SAMPLE INPUT +# 1 +# 8 +# KINGKONG +# +# SAMPLE OUTPUT +# IIOGIOOG + +numl = [97, 101, 103, 107, 109, 113] +numu = [67, 71, 73, 79, 83, 89] +num = [67, 89, 97, 113] + +for _ in range(int(input())): + length = input() + string = input() + result = '' + + for char in string: + if char.islower() and char.isalpha(): + minimum = 200 + ascii_char = ord(char) + temp = 0 + + for j in numl: + if minimum > abs(ascii_char - j): + minimum = abs(ascii_char - j) + temp = j + + result = result + chr(temp) + + elif char.isupper() and char.isalpha(): + minimum = 200 + ascii_char = ord(char) + temp = 0 + + for j in numu: + if minimum > abs(ascii_char - j): + minimum = abs(ascii_char - j) + temp = j + + result = result + chr(temp) + + else: + minimum = 200 + ascii_char = ord(char) + temp = 0 + + for j in num: + if minimum > abs(ascii_char - j): + minimum = abs(ascii_char - j) + temp = j + + result = result + chr(temp) + + print(result) From a45d35941c9dfff921a4b4465a34cc75d00ef50d Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 26 Sep 2017 09:22:57 +0530 Subject: [PATCH 05/13] Codechef Medium Problem --- CompetitiveProgramming/CodeChef/P40_COINS.py | 46 ++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 CompetitiveProgramming/CodeChef/P40_COINS.py diff --git a/CompetitiveProgramming/CodeChef/P40_COINS.py b/CompetitiveProgramming/CodeChef/P40_COINS.py new file mode 100644 index 0000000..567985f --- /dev/null +++ b/CompetitiveProgramming/CodeChef/P40_COINS.py @@ -0,0 +1,46 @@ +# In Byteland they have a very strange monetary system. +# +# Each Bytelandian gold coin has an integer number written on it. A coin n can be exchanged in a bank into +# three coins: n/2, n/3 and n/4. But these numbers are all rounded down (the banks have to make a profit). +# +# You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy +# Bytelandian coins. +# +# You have one gold coin. What is the maximum amount of American dollars you can get for it? +# +# Input +# The input will contain several test cases (not more than 10). Each testcase is a single line with a number +# n, 0 <= n <= 1 000 000 000. It is the number written on your coin. +# +# Output +# For each test case output a single line, containing the maximum amount of American dollars you can make. +# +# Example +# Input: +# 12 +# 2 +# +# Output: +# 13 +# 2 +# You can change 12 into 6, 4 and 3, and then change these into $6+$4+$3 = $13. If you try changing the +# coin 2 into 3 smaller coins, you will get 1, 0 and 0, and later you can get no more than $1 out of them. +# It is better just to change the 2 coin directly into $2. + +import sys + +list={} +def chk(n): + if n in list.keys(): + return list[n] + if n<=2: + ans = n + else: + ans = chk(n//2) + chk(n//3) + chk(n//4) + if ans Date: Tue, 26 Sep 2017 09:23:17 +0530 Subject: [PATCH 06/13] HackerEarth String Problem --- .../P14_XennyAndPartiallySortedStrings.py | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P14_XennyAndPartiallySortedStrings.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P14_XennyAndPartiallySortedStrings.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P14_XennyAndPartiallySortedStrings.py new file mode 100644 index 0000000..2621a45 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P14_XennyAndPartiallySortedStrings.py @@ -0,0 +1,50 @@ +# Xenny had a list of N strings of equal length. He wanted to sort them by the first M characters only. That +# means, while sorting the list of strings, he only wanted to consider the first M characters of each string. +# Help Xenny to find out the Kth string in the list after he sorts them. +# +# Note: Xenny wanted to perform stable sorting. +# Stable sorting algorithms maintain the relative order of records with equal keys (i.e. values). That is, a +# sorting algorithm is stable if whenever there are two records R and S with the same key and with R +# appearing before S in the original list, R will appear before S in the sorted list. +# +# Input +# +# First line contains a single integer - T, which represents the number of testcases. +# T testcases follow. +# Each testcase is of the following format: +# First line contains 3 space-separated integers - N, K and M. +# N is the total number of strings Xenny has. +# K is the index of the string in the list after sorting, which Xenny has to find. +# M is the number of characters based on which sorting will be done by Xenny. +# Then next N lines contain N strings ( each line will contain one string ) . +# +# Output +# +# For each testcase, print the Kth string in the sorted list in a new line. +# +# Constraints +# +# 1 ≤ T ≤ 50 +# 1 ≤ N ≤ 103 +# 1 ≤ Max Length of each String ≤ 103 +# 1 ≤ M ≤ Max Length +# M ≤ Max Length of each String ≤ 103 +# +# SAMPLE INPUT +# 1 +# 3 1 3 +# abcdef +# abcaaa +# aabaaa +# +# SAMPLE OUTPUT +# aabaaa + +for _ in range(int(input())): + n, k, m = input().split() + strings = [] + for i in range(int(n)): + strings.append(input()) + + array = sorted(strings, key = lambda x: x[:int(m)]) + print(array[int(k) - 1]) From d1a2e33858e66748e5dd885e8b3bdd98b6a90801 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 26 Sep 2017 09:23:22 +0530 Subject: [PATCH 07/13] HackerEarth String Problem --- .../Algorithms/String/P15_SortedString.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P15_SortedString.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P15_SortedString.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P15_SortedString.py new file mode 100644 index 0000000..6c199b1 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P15_SortedString.py @@ -0,0 +1,43 @@ +# Little Ashish got a lot of strings as his birthday gift. He does not mind getting so many strings for +# free; in fact, he loves them. But, on noticing all the strings he received as a gift, Little Ashish, who's +# also a snob and a bit OCD kind of a guy, realizes that he does not like the way in which the strings are +# arranged. +# +# He likes his strings sorted, in a different kind of a way. He wants his strings to be sorted based on the +# count of characters present in the string. For instance, if the string is: "aaabbc", then the desired +# string would be: cbbaaa. In case where the count of two characters is same, then the lexicographically +# smaller one will be printed first. For instance: "aabbcc" then, the output will be: "aabbcc". +# +# Input: +# First line of input contains number of test cases T. Each test case contains a single string S. +# +# Output: +# For each test cases print the sorted string. +# +# Constraints: +# 1<=T<=100 +# 1<=|S|<=100 +# +# Note: +# String contains only lowercase characters ['a' to 'z']. +# +# SAMPLE INPUT +# 3 +# aabbccdd +# aabcc +# hackerearth +# +# SAMPLE OUTPUT +# aabbccdd +# baacc +# cktaaeehhrr + +from collections import Counter + +for _ in range(int(input())): + string = Counter(input()) + sorted_array = sorted(string.items(), key=lambda x: (x[1], x[0])) + result = '' + for items in sorted_array: + result += items[0] * items[1] + print(result) From 0b695e41109e343ea2cc6bc35f27af71db6ebc54 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 26 Sep 2017 09:23:29 +0530 Subject: [PATCH 08/13] HackerEarth String Problem --- .../Algorithms/String/P16_SecretMessages.py | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/String/P16_SecretMessages.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/String/P16_SecretMessages.py b/CompetitiveProgramming/HackerEarth/Algorithms/String/P16_SecretMessages.py new file mode 100644 index 0000000..80a1fea --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/String/P16_SecretMessages.py @@ -0,0 +1,57 @@ +# X and Y are best friends and they love to chat with each other. But their recent concerns about the privacy +# of their messages has distant them. So they decided to encrypt their messages with a key, K, such that the +# character of their messages are now shifted K times towards right of their initial value. Their techniques +# only convert numbers and alphabets while leaving special characters as it is. +# +# Provided the value K you are required to encrypt the messages using their idea of encryption. +# +# INPUT FORMAT +# +# The first line of the input contains, T, the number of messages. The next line contains N, and K, no of +# characters in the message and key for encryption. The next line contains the message. +# +# OUTPUT FORMAT +# +# Output the encrypted messages on a new line for all the test cases. +# +# CONSTRAINS +# +# 1≤T≤100 +# 1≤N≤106 +# 0≤K≤106 +# +# SAMPLE INPUT +# 2 +# 12 4 +# Hello-World! +# 16 50 +# Aarambh@1800-hrs +# +# SAMPLE OUTPUT +# Lipps-Asvph! +# Yypykzf@1800-fpq + +myString = 'abcdefghijklmnopqrstuvwxyz' +myStringU = myString.upper() +nums = '0123456789' + +def access_char(string, i): + return string[i % len(string)] + +for _ in range(int(input())): + n, k = map(int, input().split()) + string = input() + result = [] + + for char in string: + if char.islower() and char.isalpha(): + result.append(access_char(myString, myString.find(char) + k)) + elif char.isupper() and char.isalpha(): + result.append(access_char(myStringU, myStringU.find(char) + k)) + elif char.isnumeric(): + result.append(access_char(nums, nums.find(str(char)) + k)) + else: + result.append(char) + + print(''.join([str(i) for i in result])) + From 104c5ffaadc5c98b811f8d1129457676c24c485e Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 26 Sep 2017 09:23:56 +0530 Subject: [PATCH 09/13] SQLAlchemy beginner tutorial --- Programs/P80_SQLAlchemyTutorial.py | 61 +++++++++++++++++++++++++++++ Programs/example.db | Bin 0 -> 8192 bytes 2 files changed, 61 insertions(+) create mode 100644 Programs/P80_SQLAlchemyTutorial.py create mode 100644 Programs/example.db diff --git a/Programs/P80_SQLAlchemyTutorial.py b/Programs/P80_SQLAlchemyTutorial.py new file mode 100644 index 0000000..f031635 --- /dev/null +++ b/Programs/P80_SQLAlchemyTutorial.py @@ -0,0 +1,61 @@ +# Author: OMKAR PATHAK +# This is a simple tutorial on usinng SQLAlchemy as ORM (Object Relational Mapping) + +# Make sure you have installed SQLAlchemy using: pip3 install sqlalchemy + +from sqlalchemy import ( + create_engine, + Column, + Integer, + String +) + +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker +import os + + +# create a sqlite db +engine = create_engine('sqlite:///example.db', echo=True) +Base = declarative_base() + + +class Student(Base): + __tablename__ = "student" + + id = Column(Integer, primary_key=True) + username = Column(String) + firstname = Column(String) + lastname = Column(String) + university = Column(String) + + def __init__(self, username, firstname, lastname, university): + self.username = username + self.firstname = firstname + self.lastname = lastname + self.university = university + + +def create_tables(): + # create tables + Base.metadata.create_all(engine) + + +if __name__ == '__main__': + sqlite_file = 'example.db' + file_exists = os.path.isfile(sqlite_file) + if not file_exists: + create_tables() + Session = sessionmaker(bind=engine) + session = Session() + + # Create objects + user = Student('OmkarPathak', 'Omkar', 'Pathak', 'MIT') + session.add(user) + + # commit the record the database + session.commit() + + # Select objects + for student in session.query(Student).order_by(Student.id): + print (student.firstname, student.lastname) diff --git a/Programs/example.db b/Programs/example.db new file mode 100644 index 0000000000000000000000000000000000000000..633be46bae2e500a878bba2d1761763d3d0eae89 GIT binary patch literal 8192 zcmeI#u}Z^090u^av?vWo1cxFW`UjU56bErPmY~5jt!ETEp5%&0n+VB8aMa0{@Kt;j zpTo@yv`}=&<{;n49e4Nf&+^-Ha~)};X#QAa($ERpWt_7!BF0$TZpZF*xV_ZfI`z9L zZFcnawqvKb7c;vM2tWV=5P$##AOHafKmY;|fWSWxcsb_V-CmEso*H?-RHdm>m7CS! zj6~ok0VV!<6ws=qf!on3g>e#G1cKs8Lh)@B9g^FrN>$`CQ*`Hx(WNiyZmx^c{4AI9 zcUR^5Nfo6w&zql5ML71wjIM$i4RktmhxNaC%X??ur}tqG1OgC%00bZa0SG_<0uX=z l1Rwx`zZU4Xw%9>;e{Yg4WHFWIK`u6~<1pzvO#{4P;2SE+U9bQE literal 0 HcmV?d00001 From e511b2677129f32e6106ab1b2e6e1f06aa98485a Mon Sep 17 00:00:00 2001 From: chinya07 Date: Thu, 23 Aug 2018 14:48:24 +0530 Subject: [PATCH 10/13] updations in pattern programs --- Programs/P05_Pattern.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Programs/P05_Pattern.py b/Programs/P05_Pattern.py index b4da517..0289826 100644 --- a/Programs/P05_Pattern.py +++ b/Programs/P05_Pattern.py @@ -88,3 +88,24 @@ def pattern5(level): print() pattern5(userInput) print() + +''' +following is the another approach to solve pattern problems with reduced time complexity + +for + +* +** +*** +**** +***** +''' + +num = int(input('Enter number for pattern')) +pattern = '*' +string = pattern * num +x = 0 + +for i in string: + x = x + 1 + print(string[0:x]) From 8d764797422bed31951ae5619334f06418e12ce9 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Thu, 23 Aug 2018 16:20:12 +0530 Subject: [PATCH 11/13] More efficient way to solve Pattern Program --- Programs/P05_Pattern.py | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/Programs/P05_Pattern.py b/Programs/P05_Pattern.py index 0289826..db988a0 100644 --- a/Programs/P05_Pattern.py +++ b/Programs/P05_Pattern.py @@ -89,23 +89,24 @@ def pattern5(level): pattern5(userInput) print() -''' -following is the another approach to solve pattern problems with reduced time complexity - -for - -* -** -*** -**** -***** -''' - -num = int(input('Enter number for pattern')) -pattern = '*' -string = pattern * num -x = 0 - -for i in string: - x = x + 1 - print(string[0:x]) + def pattern6(userInput): + ''' + following is the another approach to solve pattern problems with reduced time complexity + + for + + * + ** + *** + **** + ***** + ''' + + num = int(input('Enter number for pattern')) + pattern = '*' + string = pattern * num + x = 0 + + for i in string: + x = x + 1 + print(string[0:x]) From e3f7414790499f8f3b7bd1d20cbc8c2dc78b078b Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Fri, 7 Sep 2018 20:52:47 +0530 Subject: [PATCH 12/13] Added new script --- README.md | 2 ++ .../P13_Python_Create_File_With_Metadata.py | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 Scripts/P13_Python_Create_File_With_Metadata.py diff --git a/README.md b/README.md index ac9a677..ab3fef9 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,8 @@ Pune, Maharashtra, India.
9. [Birthday Reminder](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P09_ReminderApplication.py) 10. [Script to download tutorial from tutorials point](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P10_SciptToDownloadPDF.py) 11. [Script to check email in your terminal](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P11_CheckEmail.py) +12. [Script to find devices connected to Network](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P12_ScriptToFindDevicesConnectedInNetwork.py) +13. [Script to create metadata for a file](https://github.com/OmkarPathak/Python-Programs/blob/master/Scripts/P13_Python_Create_File_With_Metadata.py) ## Python Concepts diff --git a/Scripts/P13_Python_Create_File_With_Metadata.py b/Scripts/P13_Python_Create_File_With_Metadata.py new file mode 100644 index 0000000..d0b70ad --- /dev/null +++ b/Scripts/P13_Python_Create_File_With_Metadata.py @@ -0,0 +1,36 @@ +#!/usr/bin/python3.6 +import sys, os, datetime + +def create_file(file_name): + ''' + Create a flat file based on underlying Operating System + ''' + if sys.platform == 'linux' or sys.platform == 'darwin': + os.system('touch ' + file_name) + elif sys.platform == 'win32': + os.system('echo . > ' + file_name) + +def write_data_in_file(file_name): + ''' + Write the metadata into the file + ''' + if sys.argv[3]: + if len(sys.argv[3]) <= 15: + length = 15 + else: + length = len(sys.argv[3]) + else: + length = 15 + with open(file_name, 'w') as fd: + fd.write('#' * (length + 16)) + fd.write('\n# Author: ' + sys.argv[2]) + fd.write('\n# Description: ' + sys.argv[3]) + fd.write('\n# Created at: ' + datetime.datetime.today().strftime('%d %b %Y') + '\n') + fd.write('#' * (length + 16)) + +if __name__ == '__main__': + if len(sys.argv) <= 3: + print('You need to provide three arguments [File Name] [Author Name] [Description]') + exit() + create_file(sys.argv[1]) + write_data_in_file(sys.argv[1]) \ No newline at end of file From 386bed49278ae55522175393cf8019ea97adde47 Mon Sep 17 00:00:00 2001 From: Tarun Kumar Dixit <43788843+tarun-sharma03@users.noreply.github.com> Date: Tue, 1 Oct 2019 01:19:26 +0530 Subject: [PATCH 13/13] Added new script --- Scripts/P14_ScriptToPlaySongs.py | 54 ++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Scripts/P14_ScriptToPlaySongs.py diff --git a/Scripts/P14_ScriptToPlaySongs.py b/Scripts/P14_ScriptToPlaySongs.py new file mode 100644 index 0000000..147e417 --- /dev/null +++ b/Scripts/P14_ScriptToPlaySongs.py @@ -0,0 +1,54 @@ +# This program upon execution will take your command to play music randomly. +import pyttsx3 #pip install pyttsx3 +import speech_recognition as sr #pip install speech recognition +import os +import datetime +import random + +engine = pyttsx3.init('sapi5') +voices = engine.getProperty('voices') +engine.setProperty('voice',voices[0].id) #voices[1].id for female assistant + +#speak function to speak the string passed to it. +def speak(audio): + engine.say(audio) + engine.runAndWait() +#function to listen your command and process them +def takedata(): + r= sr.Recognizer() + with sr.Microphone() as source: + print("Listening....") + audio = r.listen(source) + try: + print("Recognizing...") + query = r.recognize_google(audio,language='en-in') #language set is Indian English + print("The user said ",query) + except Exception : + print("Sorry i was unable to catch that. Please try speaking that again.") + return 'None' + return query + +def wishme(): + hours = datetime.datetime.now().hour + + if hours>=0 and hours <12: + speak("good morning") + elif hours>=12 and hours <18: + speak("good afternoon") + else: + speak("good evening") + speak("sir i am your personal assistant. tell me how can i help you ") + +wishme() +query = takedata() +if 'play music' or 'play songs' in query: + music_dir = "F:\\Songs" #put the location of the folder where you store your songs + songs = os.listdir(music_dir) + l = len(songs) + num = random.randrange(0,l,1) + os.startfile(os.path.join(music_dir,songs[num])) + speak("Thank you for using my sevices. All improvements on my github repository are welcome.") + print("www.github.com/tarun-sharma03") + exit() +else: + speak("Query type not supported") \ No newline at end of file