From 1bdec39e104fd64ef8268391463d16769404b545 Mon Sep 17 00:00:00 2001 From: Omkar Pathak Date: Tue, 26 Sep 2017 09:23:17 +0530 Subject: [PATCH 01/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 02/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 03/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 04/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 05/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 06/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 07/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 08/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 From 750ad1f311836583f1724e2de03b25c6d5a891c3 Mon Sep 17 00:00:00 2001 From: Abhishek Jha <44729252+abhishek-kehsihba@users.noreply.github.com> Date: Thu, 3 Oct 2019 19:44:22 +0530 Subject: [PATCH 09/13] Added problems in BIT Manipulation in Hackerearth section (#5) * Created P04_Mystery.py BIT MANIPULATION: Hackearth-Mystery * Created P05_HihiAndCrazyBits * Created P06_RajanAndOddFrequencyNumber.py * Created P07_SherlockAndXOR.py * Created P08_XorAndProject.py * Created P09_LuckyNumbers.py --- .../Bit_Manipulation/P04_Mystery.py | 44 +++++++++++++++++++ .../Bit_Manipulation/P05_HihiAndCrazyBits.py | 37 ++++++++++++++++ .../P06_RajanAndOddFrequencyNumber.py | 25 +++++++++++ .../Bit_Manipulation/P07_SherlockAndXOR.py | 36 +++++++++++++++ .../Bit_Manipulation/P08_XorAndProject.py | 42 ++++++++++++++++++ .../Bit_Manipulation/P09_LuckyNumbers.py | 44 +++++++++++++++++++ 6 files changed, 228 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Bit_Manipulation/P04_Mystery.py create mode 100644 CompetitiveProgramming/HackerEarth/Bit_Manipulation/P05_HihiAndCrazyBits.py create mode 100644 CompetitiveProgramming/HackerEarth/Bit_Manipulation/P06_RajanAndOddFrequencyNumber.py create mode 100644 CompetitiveProgramming/HackerEarth/Bit_Manipulation/P07_SherlockAndXOR.py create mode 100644 CompetitiveProgramming/HackerEarth/Bit_Manipulation/P08_XorAndProject.py create mode 100644 CompetitiveProgramming/HackerEarth/Bit_Manipulation/P09_LuckyNumbers.py diff --git a/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P04_Mystery.py b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P04_Mystery.py new file mode 100644 index 0000000..4f3735d --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P04_Mystery.py @@ -0,0 +1,44 @@ +# In the world of dragon ball, Goku has been the greatest rival of Vegeta. Vegeta wants to surpass goku but never succeeds. Now that he +# knows he cant beat goku in physical strength, he wants to be satisfied by beating goku in mental strength. He gives certain inputs and +# outputs , Goku needs to find the logic and predict the output for the next inputs. Goku is struggling with the challenge, your task is +# to find the logic and and help him win the challenge. + +# INPUT : + +# Given a series of numbers(inputs) and each number(N) on a newline. + +# OUTPUT : + +# For the given input , Output the required ans. + +# NOTE : + +# No. of test cases are unknown. + +# Use Faster I/O Techniques. + +# CONSTRAINTS : + +# 0<= N <= 10^18 + +# SAMPLE INPUT +# 0 +# 1 +# 5 +# 12 +# 22 +# 1424 +# SAMPLE OUTPUT +# 0 +# 1 +# 2 +# 2 +# 3 +# 4 + +while(1): + try: + r=bin(int(input())) + print(r.count('1')) + except: + break diff --git a/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P05_HihiAndCrazyBits.py b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P05_HihiAndCrazyBits.py new file mode 100644 index 0000000..39f7340 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P05_HihiAndCrazyBits.py @@ -0,0 +1,37 @@ +# Hihi is the grandfather of all geeks in IIITA. He and his crazy ideas.....Huh..... Currently, hihi is working on his most famous project +# named 21 Lane, but he is stuck at a tricky segment of his code. + +# Hihi wants to assign some random IP addresses to users, but he won't use rand(). He wants to change the current IP of the user's computer +# to the IP such that its hash is next hash greater than the hash of original IP and differs by only 1 bit from the hash of original IP. + +# Smart Hihi already hashed the IP to some integer using his personal hash function. What he wants from you is to convert the given hashed +# IP to the required IP X as mentioned above. + +# OK, just find the find the smallest number greater than n with exactly 1 bit different from n in binary form + +# Input : + +# First line contains single integer T ( 1 <= T <= 10^6)- number of test cases. Second line contains hashed IP N ( 1 <= N <= 10^18) + +# Output : + +# Print T lines, each containing an integer X, the required IP.(don't worry Hihi will decode X to obtain final IP address) + +# SAMPLE INPUT +# 5 +# 6 +# 4 +# 10 +# 12 +# 14 +# SAMPLE OUTPUT +# 7 +# 5 +# 11 +# 13 +# 15 + + +for _ in range(int(input())): + a=int(input()) + print(a|a+1) diff --git a/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P06_RajanAndOddFrequencyNumber.py b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P06_RajanAndOddFrequencyNumber.py new file mode 100644 index 0000000..924380a --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P06_RajanAndOddFrequencyNumber.py @@ -0,0 +1,25 @@ +# Given an array of numbers of size (2*n+1).Raja is unable to find the number which is present odd number of times.It is guaranteed that only one such number exists.Can you help Raja in finding the number which is present odd number of times? + +# Input +# First line contains value of n. +# Second line contains (2*n+1) array elements. +# Output +# Print the required number. +# Constraints +# 1≤ n ≤ +# 1≤ a[i] ≤ + +# SAMPLE INPUT +# 2 +# 1 2 3 2 1 +# SAMPLE OUTPUT +# 3 +# Explanation +# For first input only 3 is the number which is present odd number of times. + +a=int(input()) +b=list(map(int,input().split())) +d=b[0] +for i in range(1,len(b)): + d=d^b[i] +print(d) diff --git a/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P07_SherlockAndXOR.py b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P07_SherlockAndXOR.py new file mode 100644 index 0000000..56f5d4d --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P07_SherlockAndXOR.py @@ -0,0 +1,36 @@ +# You are given an array A1,A2...AN. You have to tell how many pairs (i, j) exist such that 1 ≤ i < j ≤ N and Ai XOR Aj is odd. + +# Input and Output +# First line T, the number of testcases. Each testcase: first line N, followed by N integers in next line. For each testcase, print the +# required answer in one line. + +# Constraints +# 1 ≤ T ≤ 10 +# 1 ≤ N ≤ 105 +# 0 ≤ Ai ≤ 109 + +# SAMPLE INPUT +# 2 +# 3 +# 1 2 3 +# 4 +# 1 2 3 4 +# SAMPLE OUTPUT +# 2 +# 4 +# Explanation +# For first testcase: 1 XOR 2 is 3 and 2 XOR 3 is 1. So, 2 valid pairs. For second testcase: 1 XOR 2 is 3 and 2 XOR 3 is 1 and 1 XOR 4 is 5 +# and 3 XOR 4 is 7. So, 4 valid pairs. + +for _ in range (int(input())): + a=int(input()) + b=list(map(int,input().split())) + ans=0 + a2=0 + for i in range(0,a): + if(b[i]&1): + ans+=1 + else: + a2+=1 + + print(ans*a2) diff --git a/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P08_XorAndProject.py b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P08_XorAndProject.py new file mode 100644 index 0000000..bbecdba --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P08_XorAndProject.py @@ -0,0 +1,42 @@ +# A project was going on related to image processing and to perform experiments and get desired result the image needs to be converted to +# Gray-Scale using a parameter 'x' and the function P(x) represented the Gray-Code and calculated via x xor (x div 2) where xor stands for +# bitwise exclusive OR (bitwise modulo 2 addition), and div means integer division. + +# It is interesting to note that function P(x) is invertible, which means it is always possible to uniquely restore x given the value of +# P(x). + +# So the group working on the project forgot to keep the original data related to parameter 'x'. Write a program to restore number x from +# the given value of P(x). + +# INPUT: +# The input file contains an integer number y, the value of G(x). + +# OUTPUT: +# The output file should contain a single integer x such that G(x) = y. + +# CONSTRAINTS: +# 0 ≤ x,P(x) ≤ . + +# SAMPLE INPUT +# 15 +# SAMPLE OUTPUT +# 10 + +a=int(input()) +a=bin(a).replace("0b","") +c=[int(i) for i in str(a)] +d=[] +e=c[0] +for i in range(0,len(a)): + if(i==0): + d.append(c[i]) + else: + f=c[i]^e + d.append(f) + e=f +e=1 +g=0 +for i in range(0,len(a)): + g=g+d[len(a)-i-1]*e + e=e*2 +print(g) diff --git a/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P09_LuckyNumbers.py b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P09_LuckyNumbers.py new file mode 100644 index 0000000..20378c2 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Bit_Manipulation/P09_LuckyNumbers.py @@ -0,0 +1,44 @@ +# Golu wants to find out the sum of Lucky numbers.Lucky numbers are those numbers which contain exactly two set bits.This task is very +# diffcult for him.So Help Golu to find sum of those numbers which exactly contain two set bits upto a given number N. + +# 3 5 10 are lucky numbers where 7 14 are not. + +# INPUT +# First line contain number of test cases T.Each test case contains a single number N. +# OUTPUT +# Print sum of all Lucky Numbers upto N.Output may be large so take modulo with 1000000007. + +# Constraints +# 1<=T<=105 +# 1<=N<=1018 + +# NOTE: Since value of test cases and n is really large, please use fast I/O optimization techniques. + +# SAMPLE INPUT +# 1 +# 5 +# SAMPLE OUTPUT +# 8 + +import collections +for _ in range(int(input())): + + sum = 0 + mod = 1000000007 + n = int(input()) + j = bin(n) + bl = len(j) - 2 + + + while bl > 0: + lo = bl - 2 + + while lo >= 0: + i = '1' + ('0' * lo) + ('1' ) + ('0' * (bl - lo - 2)) + + if int(i,2) <= n : + sum = (sum + int(i,2)) + lo -= 1 + + bl -= 1 + print(sum % mod) From a118f4a28423ba1182608da62ca3b31f1cde426c Mon Sep 17 00:00:00 2001 From: Avinash Kumar Jha <41112044+avinashjha11@users.noreply.github.com> Date: Sun, 6 Oct 2019 21:33:49 +0530 Subject: [PATCH 10/13] Added problems in SPOJ section. (#6) * SPOJ Problems * SPOJ Problems * SPOJ Problems --- CompetitiveProgramming/SPOJ/P13_AVRG.py | 5 +++++ CompetitiveProgramming/SPOJ/P14_MUL.py | 5 +++++ CompetitiveProgramming/SPOJ/P15_PRADIPSUM.py | 19 +++++++++++++++++++ 3 files changed, 29 insertions(+) create mode 100644 CompetitiveProgramming/SPOJ/P13_AVRG.py create mode 100644 CompetitiveProgramming/SPOJ/P14_MUL.py create mode 100644 CompetitiveProgramming/SPOJ/P15_PRADIPSUM.py diff --git a/CompetitiveProgramming/SPOJ/P13_AVRG.py b/CompetitiveProgramming/SPOJ/P13_AVRG.py new file mode 100644 index 0000000..1c4f21c --- /dev/null +++ b/CompetitiveProgramming/SPOJ/P13_AVRG.py @@ -0,0 +1,5 @@ +sum=0 +for i in range (0,6): + a=int(input()) + sum+=a +print(sum/6) diff --git a/CompetitiveProgramming/SPOJ/P14_MUL.py b/CompetitiveProgramming/SPOJ/P14_MUL.py new file mode 100644 index 0000000..e114106 --- /dev/null +++ b/CompetitiveProgramming/SPOJ/P14_MUL.py @@ -0,0 +1,5 @@ +t = int(input()) +while t>0: + t-=1 + n1, n2 = map(int, raw_input().split()) + print n1*n2 diff --git a/CompetitiveProgramming/SPOJ/P15_PRADIPSUM.py b/CompetitiveProgramming/SPOJ/P15_PRADIPSUM.py new file mode 100644 index 0000000..a4b78da --- /dev/null +++ b/CompetitiveProgramming/SPOJ/P15_PRADIPSUM.py @@ -0,0 +1,19 @@ +def sum(x): + if x < 0: + return -(-x * (-x + 1) // 2) + else: + return x * (x + 1) // 2 + +while True: + try: + a, b = map(int, input().split()) + if a > b: + a, b = b, a + if b < 0: + print(sum(a) - sum(b + 1)) + elif a <= 0: + print(sum(b) + sum(a)) + else: + print(sum(b) - sum(a - 1)) + except EOFError: + exit(0) From 8906b98bb7a0770b2c5faf42fac90f84742dfadd Mon Sep 17 00:00:00 2001 From: Pulkit-100 <40335208+Pulkit-100@users.noreply.github.com> Date: Sun, 6 Oct 2019 21:34:27 +0530 Subject: [PATCH 11/13] Added Magic Methods (#7) --- OOP/P11_MagicMethods.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/OOP/P11_MagicMethods.py b/OOP/P11_MagicMethods.py index caebf85..751b7db 100644 --- a/OOP/P11_MagicMethods.py +++ b/OOP/P11_MagicMethods.py @@ -13,6 +13,14 @@ def __init__(self, firstname, lastname, salary = 0): def __str__(self): return 'Full Name: ' + self.firstname + ' ' + self.lastname + # Implements behaviour for built in type comparison to int + def __int__(self): + return self.salary + + # For overloading the (==) + def __eq__(self,other): + return self.salary==other.salary + # For overloading the (+) def __add__(self, other): return self.salary + other.salary @@ -28,3 +36,6 @@ def __mul__(self, other): print(Jagdish) # Full Name: Jagdish Pathak print(Omkar + Jagdish) # 3000 (This output because of __add__ method overloading) print(Omkar * Jagdish) # 2000000 (__mul__) + print(int(Omkar)) # 1000 (__int__) + print(int(Jagdish)) # 2000 (__int__) + print(Omkar==Jagdish) From 3e41fbe9d5d9c0314cc9a7d92fb353540e09a23e Mon Sep 17 00:00:00 2001 From: AthaSSiN <56124496+AthaSSiN@users.noreply.github.com> Date: Fri, 11 Oct 2019 20:41:48 +0530 Subject: [PATCH 12/13] Added an efficient method to find primes (#8) --- .../HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py b/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py index 28d4de9..050e516 100644 --- a/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py +++ b/CompetitiveProgramming/HackerEarth/Basics_Of_Input_Output/P04_PrimeNumber.py @@ -12,10 +12,12 @@ # Constraints # 1 <= N <=1000 +import math + userInput = int(input()) -for i in range(2, userInput): +for i in range(2, userInput + 1): check = 0 - for j in range(2, i): + for j in range(2, int(math.sqrt(i))+ 1): if i % j == 0: check = 1 break From 38f7b664a356d64b3e19acbf73ef39c0ee6a9609 Mon Sep 17 00:00:00 2001 From: Subrhamanya <36793516+Subrhamanya@users.noreply.github.com> Date: Tue, 15 Oct 2019 20:38:34 +0530 Subject: [PATCH 13/13] Efficient program to check given number is a perfect square of 2 (#12) --- .../Algorithms/logics/perfectsquareof2.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 CompetitiveProgramming/HackerEarth/Algorithms/logics/perfectsquareof2.py diff --git a/CompetitiveProgramming/HackerEarth/Algorithms/logics/perfectsquareof2.py b/CompetitiveProgramming/HackerEarth/Algorithms/logics/perfectsquareof2.py new file mode 100644 index 0000000..87b79a9 --- /dev/null +++ b/CompetitiveProgramming/HackerEarth/Algorithms/logics/perfectsquareof2.py @@ -0,0 +1,12 @@ +# Efficient Python program to check entered number is a perfect square of 2 or not +# Example +# 8 +# Its a perfect square of 2 + + + +n = int(input("Enter a number")) +if n & (n - 1) == 0: + print("Its a perfect square of 2") +else: + print("Its not perfect square")