0% found this document useful (1 vote)
192 views

Python Model Soultion 2

python model solutions

Uploaded by

Yasha Dhigu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (1 vote)
192 views

Python Model Soultion 2

python model solutions

Uploaded by

Yasha Dhigu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
PYTHON APPLICATION PROGRAMMING MODEL QUESTION PAPER-2__ Write python program to swap two numbers using functions. (write without using intermediate/temporary variables). Prompt the user for input. def swapla,b): print (‘Before swapping a=%s b=%s' s6(a,b)) print "After swapping a=%s b=%s" %(a,b)} ainput("Enter a:") beinput( "Enter swapla,b) Find the area and perimeter of a circle using functions. Prompt the user for input, defealc(r): import math areazmath.pitr**2 perimeter=2*math.pi*r return area,perimeter print(*to find loat(input(" abecale(r) print(“area:",a) print("perimeter:",b) rimeter and area of circle") enter radius:")) Explain variable names, Keywords, operators, operands and order of operations with examples. Variable Names: © Avariable is a name that refers to value. © The value is assigned to variable using equal sign(=). ‘© Variable names can be arbitrarily long. They can contain both letters and ‘aumbers, but they cannot start with a number. © Legal to use uppercase letters, but itis a good idea to begin variable names with 2 lowercase letter. ‘© Underscore character(_) can appear in name © Eg:name=’CBIT’ Keywords: Python interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names, Python reserves 31 keywords. Like... and.as assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, if, is not, pass, print, while etc,, * Eg: word="mango’ for word in words: Print word Operators: © Operators are special symbols that represent computations like addition and subtraction. ‘¢ The values the operator is applied to are called Operands ‘= The operators +, ,*, 7, and ** performs addition subtraction, multiplication, division and exponentiation * 8: 20432 hour*60+minute hour minute/60 52 (549)*(15-7) Order of operations: ‘+ When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence + For mathematical operations, python follows mathematical convention, ‘Acronym PEDMAS is 2 useful way to remember the rules: ¥ Parantheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expression in parantheses are evaluated first, 2*(3-1) is 4 ¥-_Exponentiation has the next highest precedence, so 2**141 is 3 not 4, ¥ Multiplication and division have same precedence ehich is higher than addition and subtraction which also have same precedence. So 2*3-1 is S and 6+4/2 is 8. Y Operators with same precedence are evaluated from left to right, So the expression 5-3-1 is 1 ‘Write pythonic code to solve the quadratic equation ax**2+bxe=0 by getting input for coefficients from the user. Solution: import emath ##To take coefficient input from the users a= float{input(‘Enter a: ) b= float(input(*Enter b: )) c= float(input{'Enterc:')) # calculate the discriminant d= (b**2}-(4*atc} find two solutions solt = (-b-emath.sart(d))/(2*a) sol2 = (-b+cmath.sqrt(d)}/(2*a) print("The solution are {0} and {1} format(sol1,sol2)) | Write a function called is_palindrome that takes a string argument and returns True ifitis a palindrome and False otherwise. Use builtin function to check the length of a string. Prompt the user for input. Solution ‘word = raw_input(‘Want to see if itis a palindrome?\n') def is_palindrome(word} iflen(word) <= 2 and word(0} print "rue! elif word{0} == word!-2} is_palindrome(word{1:-1) else: print ‘False’ is_palindrome(word) ‘wordl-1]: b) print "factorial is” fact) | checkethe length of string | >>>Words=input(‘enter a string’:) | >>len(word) | Explain syntax errors and logic errors. Write pythonic code which prompts the user for a | Celsius temperature. Convert the temperature to Fahrenheit and print out the converted temperature. Use try and except so that your program handles non-numeric input gracefully by printing a message and exit the program. | solution: | Syntax errors: Syntax error means that violated the grammar rules of python. Python does its best to point right at the line and character where it noticed it was confused. it indicates in a syntax error may just be a starting point for investigation. Logic errors: ‘logic eror is when program has good syntax but there is a mistake in the order of the statements or perhaps 2 mistake in how the statements relate to one another. Celcius to Fahrenheit inp=input(Enter celcius temperature: try: celsius=float(inp) fahrenheit = (celsius * 1.8) + 32 print(fahrenheit) except: print( please enter a number) Strings in python are immtable”. Explain this statement with example. Write pythoniccode to find the factorial of any number entered through the keyboard. Solution: >o>greeting="Hello, world!” ogreetinglO}= The above expression gives typeerror: object does not support item assignment The reason for error is immutable, which means existing strings cant be changed. The best can be done is create a new string that is a variation on the original >>> greeting="Hello, world!” >oonew_greeting="'+ greeting [1:] >>> print new_greetin, Jello, world! This example concatenates a new frst letter onto a slice of greeting, It has no effect on the original string, Factorial of number: number=int(input(‘enter a number to calculate the fact’) fact=1 while number>0: fact=fact*number number=number-1 ‘Anumber with more than one digit is input through the keyboard. Write pythonie code to reverse the digits in the number and find the sum of all the digits in the reversed number. Solution: Number=int(input(‘please enter number:’)) | [| TReverse=0 While(aumber>0): | Remainder=numbers10 Reverse=(Reverse* 10}+Remainder Number=Number/10 | Print("\n reverse of entered number is = ¥4" %Reverse) _ - <)___| Explain the following string methods in detail a) upper() and b) find(). Write a python program to check whether a number is prime or not using while loop and print appropriate messages, Solution: Upper(): It takes a string and returns a new string with all uppercase letters >peword= ‘banana’ >ponew=word.upper() >>>print{new) Find(): searches for the position of one string within another jord find(‘a’) >>>printlindex) umber=int(input(‘enter a number’) prime=True while ic=int{math.sart(number)} if number%i==0: prime=False break isis if number>> camels=42 >>>'%d" % camels, ae >>>'l have spotted %éd camels.’ % camels ‘have spotted 42 camels’ ‘Write pythonic code that iteratively prompts the user for input. It should continue until the user enters ‘done’ and return the average value. count=0 average=0 while(True}: put(‘enter a number’) done’) except print("invalid input") print(‘Ave’,average) ‘Why do you need regular expressions in python? Consider a file “ait.txt”. Write a python program to read the file and look for lines of the form X-DSPAM-Confidence:0.8475 X-DSPAM-Probability:0.458 Extract the number from each of the lines using a regular expression. Compute the average of the numbers and print out the average. Solution: import re hand=open(‘ait.txt’) for line in hand: line=line.rstrip() ifre.findall(’*X\S*; ({0-9.}+)',ine) print(line) average of numbers: sum=0 count: average=0 while (True): input(‘enter a number‘) except print(“invalid input”) print (sum, count,average) ae How are dictionaries and tuples used together? Demonstrate the use of tuple assignment with dictionaries to traverse the keys and values of dictionary. Solution: Dictionaries have a method called items that returns a list of tuples, where each tuple is a key value pair. {a’,10),('e':22),('b',1)) tuple assignment with dictionaries to traverse the keys and values i=(a':10, >eated.items( } 22) for key,val in d.items{): print val,key ouput: 10a 2 1b ‘Write pythonic code to create a function called most_frequent that takes a string and prints the letters in decreasing order of frequency using dictionary. Solution: defmost_frequent(string): for key in string: it key not in a dfkey|: else: dlkey}+=1 return d print (most_frequent(‘aabbbc’)) Consider the string ‘brontosaurus’. Write pythonic code that implements and returns the functionality of histogram using dictionaries for the given string. Also, write the function. print_hist to print the keys and their values in alphabetical order from the values returned by the histogram function. Solution: for ¢ in word: iftenot in d: dfe}=1 else: d{c}=1 print(d) >>> L=‘abracadabra’ >>> histogram(L) {fa 5, "bi 2, c' 1'r:2} def histogram(L) d={} for x in Le if x ind: lx] + else’ a) ‘write an —init_ method for the point cass that takes xand yas optional parametres and assigns them to corresponding attributes. Write an add method for Ponts that works with either a Point object or a tuple. If the second operand is a Point, the method should. return anew Point whose x coordinate isthe sum of the x coordinates ofthe operands, and likewise forthe y coordinates. I the second operands a tuple, the method should add the first element of the tuple to the x coordinate and the second element to the y Coordinate, and return 3 new Point withthe resu Solution: def _add__(self, other): point_ roint() if isinstance(other, Point): point_x += selfx+ other-x oint_y 4=selfy + other:y return elif type(other) == point_x += self.x + other{0] point_y += self.y + other[1] return point_ det _radd_(self, other): return self._add_(other) def _str_(self return "(%s, Xs)" % (sex, self-y) point point2 point3 point4 = point2 + point print point3, point b) Write a function called distance that takes two points as arguments and returns the fance between them. Solution: import math class Point( object): point_one = Point() point_two= Point() point_one.x, point_one.y = 6.0, 1.0 oint_two.x, point_two.y = 2.0, 6.0 def distance(p1, p2): delta_x=p2.x-pl.x delia_y=p2y-ply return math sqrt(delta_x ** 2 + delta_y ** 2) print "The distance between point one at (%%g,%g)" % (point_one.x, point_one.y) print "and point two at (%g,%g)" % (point_two.x, point_two.y) al print "is %3f" % distance(point_one, point two) Write pythonic code to compute the end time of movie by specifying the start time and duration by considering all relevant conditions. Solution import time start_time = time.time() # your script elapsed_time = time.time() - start_time time strftime("%H:%M:%S", time.gmtime(elapsed_time)) ‘What is operator overloading? Write a pythonic code to overload "+","-" and operators by providing the methods _add_,__sub__and_mul_. Solution: By defining other special methods, you can specify the behavior of | operators on p# Hinside class Time: def _add__(self, other): seconds = self.time to int() + other-time_to_int() return int_to_time(seconds) def_sub__(selfother) seconds = self:time_to_int() ~ other.time_to_int() return int_to_time(seconds) def__mul__(self,other): seconds = selftime_to_int() * other.time_to_int() return int_to_time(seconds) ‘And here is how you could use it: >>> start = Time(9, 45) >>> duration = Time(1, 35) >>> print(start + duration) >>> print(start - duration) >>>print(start * duration) When you apply the + operator to Time obj 4s, Python invokes _add_. When you print the result, Python invokes _str_ So there is a lot happening behind the scenest Changing the behavior of an operator so that it works with programmer-defined types is called operator overloading, b) State a need for urlib in python. Explain why data is retrieved in blocks. Write pythonic code to read any sized binary file using urlip without using up all of the memory you have in your computer. Solution: iflen{info}chuck loop through XML nodes in the document import xmletree.ElementTree as ET 001 chuck

You might also like