Posts

Practice Exercise 8

 ''' Python Practice problem 8 (Easy, 10 points) Rohan Das Is A Fraud Rohan das is a fraud by nature. Rohan Das wrote a python function to print a multiplication table of a given number and put one of the values (randomly generated) as wrong. Rohan Das did this to fool his classmates and make them commit a mistake in a test. You cannot tolerate this! So you decided to use your python skills to counter Rohan’s actions by writing a python program that validates Rohan’s multiplication table. Your function should be able to find out the wrong values in Rohan’s table and expose Rohan Das as a fraud. Note: Rohan’s function returns a list of numbers like this Rohan Das’s Function Input: rohanMultiplication(6) Rohan’s function returns this output: [6, 12, 18, 26, …., 60] You have to write a function isCorrect(table, number) and return the index where rohan’s function is wrong and print it to the screen! If the table is correct, your function returns None. ''' import ran...

Practice Exercise 7

 ''' You are given few sentences as a list (Python list of sentences). Take a query string as an input from the user. You have to pull out the sentences matching this query inputted by the user in decreasing order of relevance after converting every word in the query and the sentence to lowercase. Most relevant sentence is the one with the maximum number of matching words with the query. Sentences = [“This is good”, “python is good”, “python is not python snake”] Input: Please input your query string “Python is” Output: 3 results found: 1. python is not python snake 2. python is good 3. This is good ''' def mathingWords(sentence1, sentence2):     words1 = sentence1.strip().split(" ")     words2 = sentence2.strip().split(" ")     score = 0     for word1 in words1:         for word2 in words2:             # print(f"Matching {word1} with {word2}")             i...

Practice Exercise 6

 # Problem Statement:- # Generate a random integer from a to b. You and your friend have to guess a number # between two numbers a and b. a and b are inputs taken from the user. Your friend is # player 1 and plays first. He will have to keep choosing the number and your program # must tell whether the number is greater than the actual number or less than the actual # number. Log the number of trials it took your friend to arrive at the number. # You play the same game and then the person with minimum number of trials wins! # Randomly generate a number after taking a and b as input and don’t show that to the user. # Input: # Enter the value of a # 4 # Enter the value of b # 13 # Output: # Player1 : # Please guess the number between 4 and 13 # 5 # Wrong guess a greater number again # 8 # Wrong guess a smaller number again # 6 #Correct you took 3 trials to guess the number # Player 2: # Correct you took 7 trials to guess the number # Player 1 wins! ''' Author :  Aryan Sonone D...

Practice Exercise 5

  # Problem Statement:- # You are given a list that contains some numbers. You have to print a list of next # palindromes only if the number is greater than 10; otherwise, you will print that number. # # Input: # [1, 6, 87, 43] # # Output: # [1, 6, 88, 44] def next_palindrome (n): n = n+ 1 while not is_palindrome(n): n += 1 return n def is_palindrome (n): return str (n) == str (n)[::- 1 ] if __name__ == "__main__" : size = int ( input ( "Enter the size of your list \n " )) num_list = [] for i in range (size): num_list.append( int ( input ( "Enter the number of the list \n " ))) print ( f"You have entered { num_list } " ) new_list = [] for element in num_list: if element > 10 : n = next_palindrome(element) new_list.append(n) else : new_list.append(element) print ( f"Output List: { new_list } " )

Practice Exercise 4

 # Problem Statement:- # A palindrome is a string that, when reversed, is equal to itself. Example of the palindrome includes: # # 676, 616, mom, 100001. # # You have to take a number as an input from the user. You have to find the next palindrome corresponding to that number. Your first input should be the number of test cases and then take all the cases as input from the user. # # Input: # 3 # # 451 # # 10 # # 2133 # # Output: # Next palindrome for 451 is 454 # # Next palindrome for 10 is 11 # # Next palindrome for 2311 is 2222 ''' Author: Harry Date: 15 April 2019 Purpose: Practice Problem For CodeWithHarry Channel ''' def next_palindrome(n):     n = n+1     while not is_palindrome(n):         n += 1     return n def is_palindrome(n):     return str(n) == str(n)[::-1] if __name__ == "__main__":     n = int(input("Enter the number of test cases\n"))     numbers = []     for i in range(n): ...

Practice Execise 3

  # You visited a restaurant called CodeWithHarry, and the food items in that restaurant are sorted, based on their amount of calories. You have to reserve this list of food items containing calories. # # You have to use the following three methods to reserve a list: # # Inbuild method of python # List name [::-1] slicing trick # Swapping the first element with the last one and second element with second last one and so on like, # [6 7 8 34 5] -> [5 34 8 7 6] # # Input: # Take a list as an input from the user # # [5, 4, 1] # # Output: # [1, 4, 5] # # [1, 4, 5] # # [1, 4, 5] # # All three methods give the same results! print ( "Welcome To Our Program \n " "Foods and Calories" ) # Take the size of the list from the user print ( "Enter the numbers of the list one by one \n " ) size = int ( input ( "Enter size of list \n " )) # Initialize a blank list mylist = [] # Take the input from the user one by one for i in range (size): mylist.app...

Practice Exercise 2

  #Divide The Apples # Harry Potter has got the “n” number of apples. Harry has some students among whom # he wants to distribute the apples. # These “n” number of apples is provided to harry by his friends, and he can request for # few more or few less apples. # # You need to print whether a number is in range mn to mx, is a divisor of “n” or not. # # Input: # # Take input n, mn, and mx from the user. # # Output: # Print whether the numbers between mn and mx are divisor of “n” or not. If mn=mx, # show that this is not a range, and mn is equal to mx. Show the result for that number. # # Example: # If n is 20 and mn=2 and mx=5 # # 2 is a divisor of20 # # 3 is not a divisor of 20 # # … # # 5 is a divisor of 20 # print("Welcome To Our Programme\n"       "Divide The Apples\n") apples = int(input("Please Enter the number of apples harry has got :\n")) mn = int(input("What is the minimum number in this case?\n")) mx = int(input("What is the maximu...

Practice Exercise 1

# Take age or year of birth as an input from the user. Store the input in one variable. Your program should detect whether the entered input is age or year of birth and tell the user when they will turn 100 years old. (5 points). # # Here are a few instructions that you must have to follow: # # Do not use any type of modules like DateTime or date utils. (-5 points) # Users can optionally provide a year, and your program must tell their age in that particular year. (3points) # Your code should handle all sort of errors like:                       (2 points) # You are not yet born # You seem to be the oldest person alive # You can also handle any other errors, if possible! print("Welcome To Our Programme") aorb = input("To Enter your age Enter a, To enter your year of birth press b and\n"              "To enter a year and want to check your age in that year press c\n") if aorb=="a":   ...

Exercise 11 Regex Email Extractor

  import re print ( "Welcome To Exerise 11 \n " "Email Collector \n " ) # strin = # Email Collector # email1 # email2 # email3 str = """ Email:enquiry@alliance.edu.in Helpline: +91 80 3093 8100 / 8200 / 4619 9100 Media Library News Webmail Careers Alliance University Conferences Admissions Open Select Language UPDATES: ABOUT US WHY AU COLLEGES FACULTY INTERNATIONAL PROGRAMS PROGRAMS RESEARCH ADMISSIONS PLACEMENTS CONTACT US Contact UsHome Contact Us Contact Us Back Vice-Chancellor Dr. Pavana Dibbur : vc@alliance.edu.in : +91 80 3093 8100/4619 9100 Pro Vice-Chancellor (Academics, Research & Strategy) Dr. Anubha Singh : anubha@alliance.edu.in : +91 80 3093 8102 Registrar Mr. Madhu Sudan Mishra : registrar@alliance.edu.in : +91 80 3093 8100/4619 9100 Registrar (Examination & Evaluation) Dr. Sajan Mathew : registrar.exams@alliance.edu.in : +91 80 3093 8141 Director (Placements) Mr. Mathew Thankachan : placement@alliance....

Creating a Command Line Utility In Python

  import argparse import sys def calc(args):     if args.o == 'add':         return args.x + args.y     elif args.o == 'mul':         return args.x * args.y     elif args.o == 'sub':         return args.x - args.y     elif args.o == 'div':         return args.x / args.y     else:         return "Something went wrong" if __name__ == '__main__':     parser = argparse.ArgumentParser()     parser.add_argument('--x', type=float, default=1.0,                         help="Enter first number. This is a utility for calculation. Please contact harry bhai")     parser.add_argument('--y', type=float, default=3.0,                         help="Enter second number. This is a utility for calculation. ...

Creating a Python Package Using Setuptools

  from setuptools import setup setup(name="packageharry", version="0.3", description="This is code with harry package", long_description = "This is a very very long description", author="Harry", packages=['packageharry'], install_requires=[]) class Achha:     def __init__(self):         print("Constructor ban gaya")     def achhafunc(self, number):         print("This is a function")         return number

Raise In Python

  # a = input("What is your name") # b = input("How much do you earn") # if int(b)==0: #     raise ZeroDivisionError("b is 0 so stopping the program") # if a.isnumeric(): #     raise Exception("Numbers are not allowed") # # print(f"Hello {a}") # 1000 lines taking 1 hour # Task - Write about 2 built in exception c = input("Enter your name") try:     print(a) except Exception as e:     if c =="harry":         raise ValueError("Harry is blocked he is not allowed")     print("Exception handled")

Regular Expressions Quiz

 pattern = re.compile(r"91 \d{10}").finditer(mystr) for match in pattern:     print(match)

Regular Expressions

 # pickle # Use requests module to download the iris dataset import re mystr = '''Tata Limited Dr. David Landsman, executive director 18, Grosvenor Place London SW1X 7HSc Phone: +44 (20) 7235 8281 Fax: +44 (20) 7235 8727 Email: tata@tata.co.uk Website: www.europe.tata.com Directions: View map Tata Sons, North America 1700 North Moore St, Suite 1520 Arlington, VA 22209-1911 USA Phone: +1 (703) 243 9787 Fax: +1 (703) 243 9791 66-66 455-4545 Email: northamerica@tata.com  Website: www.northamerica.tata.com Directions: View map fass harry bhai lekin bahut hi badia aadmi haiaiinaiiiiiiiiiiii''' # findall, search, split, sub, finditer # patt = re.compile(r'fass') # patt = re.compile(r'.adm') # patt = re.compile(r'^Tata') # patt = re.compile(r'iin$') # patt = re.compile(r'ai{2}') # patt = re.compile(r'(ai){1}') # patt = re.compile(r'ai{1}|Fax') # Special Sequences # patt = re.compile(r'Fax\b') # patt = re.c...

Pickle Module

  import pickle # Pickling a python object # cars = ["Audi", "BMW", "Maruti Suzuki", "Harryti Tuzuki"] # file = "mycar.pkl" # fileobj = open(file, 'wb') # pickle.dump(cars, fileobj) # fileobj.close() file = "mycar.pkl" fileobj = open(file, 'rb') mycar = pickle.load(fileobj) print(mycar) print(type(mycar)) # pickle.loads = ?

Akhbaar padhke sunaao

 # Akhbaar padhke sunaao # Attempt it yourself and watch the series for solution and shoutouts for this lecture! import requests def speak(str):     from win32com.client import Dispatch     speak = Dispatch("SAPI.SpVoice")     speak.Speak(str) # # # if __name__ == '__main__': #     speak("Hello Sir,\n" #           "I am Edith ,\n" #           "Always a your service sir !!") if __name__ == '__main__':     print("Hello Welcome To Exercise 9 \n"           "Akhbaar padhke sunaao")     print("Please Enter 'ent' for Entertainment news\n"           "Please Enter 'hea' for Health-related news\n"           "Please Enter 'bus' for Business news\n"           "Please Enter 'sci' for Science news\n"           "Please Enter 'tech' for Technology news...

Json Module

  # Json = Java script object notation # The json. load() is used to read the JSON document from file and The json. # loads() is used to convert the JSON String document into the Python dictionary. # fp file pointer used to read a text file, binary file or a JSON file that contains a JSON document. import json data = '{"Aryan": "Sonone" , "Vidhan": "Laddha"}' print (data) parsed = json.loads(data) print (parsed[ 'Aryan' ]) data2 = { "channel_name" : "CodeWithHarry" , "cars" : [ 'bmw' , 'audi a8' , 'ferrari' ], "fridge" : ( 'roti' , 540 ), "isbad" : False } jacomp = json.dumps(data2) print (jacomp) import json x = { "name" : "Aryan" , "age" : 14 , "married" : False , "pets" : "Cats" , "cars" : [ { "model" : "BMW 230" , "mpg...

Requests Module For HTTP Requests

import requests # This will get the source code of the url mentioned r = requests.get("https://aryansonone1.blogspot.com/2020/09/blog-post.html") print(r.text) #This will give the status of the code print(r.status_code) # To post request to the server # url = "www.something.com" # data = { #     "p1":4, #     "p2":8 # } # r2 = requests.post(url=url, data=data)  

Oh soldier Prettify my Folder

  # # # Oh soldier Prettify my Folder # # # path, dictionary file, format # # # def soldier("C://", "harry.txt", "jpg") # # # if __name__ == '__main__': # # # # import os # def soldier(path, dictionary_file, format): # os.chdir(path) # i = 1 # files = os.listdir(path) # # # with open(dictionary_file) as f : # filelist = f.read().split("\n") # # for dictionary_file in files : # if dictionary_file not in filelist: # os.rename(dictionary_file, files.capitalize()) # # if os.path.splitext(dictionary_file)[1] == format: # os.rename((dictionary_file, f"{i}{format}")) # i = i + 1 # # # need = str(input("Please Enter the three things here each seperated by a (,) symbol\n" # "Order Should be like this : path, dictionary file, format\n")) # # # names = need.split(",")[0] ...

OS Module

 import os # print(dir(os)) # This os.getcwd will get the current working directory's path and will print that # print(os.getcwd()) # This will change the current directory to th specified in the brackets # print(os.chdir("C://")) # print(os.getcwd()) # This will display all the folders and file present at the cwd as a list # print(os.listdir()) # This will make a new folder in the directory # os.mkdir("Oho") # This will make folders inside folder in the directory # os.makedirs("This/that") # This will rename a file # os.rename("aryan1.txt", "aryan2.txt") # This will give us an environment # print(os.environ.get('Path')) # This will join 2 paths and make into 1 # print(os.path.join("C://", "/   Aryan.txt")) # This will tell whether a directory mentioned existes or not as True Or False # print(os.path.exists("C://")) # This will tell whether a directory mentioned existes or not as True Or False #...

Coroutines Quiz Answer

def searcher():     import time     book = "aryan mansi rushikesh sarvesh siddhi vedant vidhan"     # book = open("coroutines.txt")     # content = book.read()     time.sleep(1)     while True:         text = (yield)         if text in book:             print("Your text is in the book")         else:             print("Text is not in the book") search = searcher() print("Search started") next(search) print("Next method wil run now ") search.send("aryan")

Coroutines

  def searcher():     import time     # Some 4 seconds time consuming task     book = "This is a book on harry and code with harry and good"     time.sleep(4)     while True:         text = (yield)         if text in book:             print("Your text is in the book")         else:             print("Text is not in the book") search = searcher() print("search started") next(search) print("Next method run") search.send("harry") search.close()

Else & Finally In Try Except

 f1 = open("aryan.txt") try:     f = open("does2.txt") except EOFError as e:     print("Print eof error aa gaya hai", e) except IOError as e:     print("Print IO error aa gaya hai", e) else:     print("This will run only if except is not running") finally:     print("Run this anyway...")         # f.close()     f1.close() print("Important stuff")

Function Caching Quiz

if __name__ == '__main__' : n = input ( "Please Enter How many time do you want to run Max Size \n " ) @lru_cache ( maxsize = 9 ) def tt_not (n): time.sleep(n) return n print ( "Runing Now" ) tt_not( 2 ) tt_not( 4 ) print ( "Again Running Wait Na" ) tt_not( 4 ) print ( "Done" )

Function Caching In Python

  import time from functools import lru_cache # @lru_cache(maxsize=32) # def some_work(n): # #Some task taking n seconds # time.sleep(n) # return n # # if __name__ == '__main__': # print("Now running some work") # some_work(3) # some_work(1) # some_work(1) # some_work(1) # print("Done... Calling again") # input() # some_work(3) # print("Called again")

Python Comprehension Quiz Answer

  itemsno = int ( input ( "Enter the number of items you want to print \n " )) choice = str ( input ( "Enter l for List, s for Set, and d for Dictionary \n " )) list= [ i for i in range (itemsno) if choice== "l" ] if choice== "l" : print (list) dict= {i: f"item { i } " for i in range (itemsno) if choice== "d" } if choice== "d" : print (dict) set= (i for i in range (itemsno) if choice== "s" ) if choice== "s" : print (set)

Python Comprehensions

  # ls = [] # for i in range(100): #     if i%3==0: #         ls.append(i) # ls = [i for i in range(100) if i%3==0] # # print(ls) # dict1 = {i:f"item {i}" for i in range(1, 10001) if i%100==0} # dict1 = {i:f"Item {i}" for i in range(5)} # # dict2 = {value:key for key,value in dict1.items()} # print(dict1,"\n", dict2) # dresses = [dress for dress in ["dress1", "dress2","dress1", #                                "dress2","dress1", "dress2"]] # print(type(dresses)) evens = (i for i in range(100) if i%2==0) # print(evens.__next__()) # for item in evens: #     print(item)

Generators In Python

  # def gen(n): # for i in range(n): # yield (i) # # g = gen(123456789) # # print(g) def genrt (): n = int ( input ( "enter number - " )) i = 1 for i in range (n): i = i * (i+ 1 ) yield i print (genrt()) """ Iterable - __iter__() or __getitem__() Iterator - __next__() Iteration - """ def gen (n): for i in range (n): yield i g = gen( 3 ) # print(g.__next__()) # print(g.__next__()) # print(g.__next__()) # print(g.__next__()) # for i in g: # print(i) h = "harry" ier = iter (h) print (ier. __next__ ()) print (ier. __next__ ()) print (ier. __next__ ()) # for c in h: # print(c)

Mini Project

  #Question # Create a library class # display book # lend book - (who owns the book if not present) # add book # return book # HarryLibrary = Library(listofbooks, library_name) #dictionary (books-nameofperson) # create a main function and run an infinite while loop asking # users for their input # Plan # Make a class named libary. It should have 4 functions # display book # lend book - (who owns the book if not present) # add book # return book # Add book and make a list display books if asked and check the avibility of the book asked # if anyone wants to add a book so take his/her name and name of book and if anyone lends a # book so ask name of person, name of book and save the time at which book was witdrawed and # make a .txt file to save that details. I anyone returns the book take name of person, book # and save time for the same !! # Program: import time class Libary (): def displaybook ( self ): with open ( "books.txt" ) as op: for i in op: ...

Object Introspection

  # Types to inspect an object are : # type(object) # id(object) # Next 2 line are on function only !! # o = MyClass() # print(dir(o)) # Main Code: class Employee : def __init__ ( self , fname, lname): self .fname = fname self .lname = lname # self.email = f"{fname}.{lname}@codewithharry.com" def explain ( self ): return f"This employee is { self .fname } { self .lname } " @property def email ( self ): if self .fname== None or self .lname == None : return "Email is not set. Please set it using setter" return f" { self .fname } . { self .lname } @codewithharry.com" @email.setter def email ( self , string): print ( "Setting now..." ) names = string.split( "@" )[ 0 ] self .fname = names.split( "." )[ 0 ] self .lname = names.split( "." )[ 1 ] @email.deleter def email ( self ): self...