Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0%
(1)
0% found this document useful (1 vote)
289 views
Python Model Soultion 2
python model solutions
Uploaded by
Yasha Dhigu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Python Model Soultion 2 For Later
Download
Save
Save Python Model Soultion 2 For Later
0%
0% found this document useful, undefined
100%
, undefined
Embed
Share
Print
Report
0%
(1)
0% found this document useful (1 vote)
289 views
Python Model Soultion 2
python model solutions
Uploaded by
Yasha Dhigu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Python Model Soultion 2 For Later
Carousel Previous
Carousel Next
Download
Save
Save Python Model Soultion 2 For Later
0%
0% found this document useful, undefined
100%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 12
Search
Fullscreen
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 untilthe 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 thefance 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
Data Compression Jan 2014
PDF
No ratings yet
Data Compression Jan 2014
2 pages
Pseudo Random Sequence Generator in Verilog
PDF
No ratings yet
Pseudo Random Sequence Generator in Verilog
3 pages
Dsp12 - PP 8 Point Radix-2 Dit-Fft
PDF
No ratings yet
Dsp12 - PP 8 Point Radix-2 Dit-Fft
37 pages
Multiplexer, Demultiplexer and Encoder With Simulation and RTL Schematic
PDF
No ratings yet
Multiplexer, Demultiplexer and Encoder With Simulation and RTL Schematic
26 pages
Final Question Bank - DSP
PDF
No ratings yet
Final Question Bank - DSP
32 pages
Ad3351 Daa Important Questions
PDF
No ratings yet
Ad3351 Daa Important Questions
94 pages
DSP Mod1@AzDOCUMENTS - in
PDF
No ratings yet
DSP Mod1@AzDOCUMENTS - in
60 pages
CH 5 Answers
PDF
No ratings yet
CH 5 Answers
6 pages
Cs8351 Digital Principles and System Design
PDF
No ratings yet
Cs8351 Digital Principles and System Design
161 pages
Assignments Week08
PDF
No ratings yet
Assignments Week08
4 pages
Binary Multiplication Twos Complement Multiplication (Booths Algorithm)
PDF
100% (1)
Binary Multiplication Twos Complement Multiplication (Booths Algorithm)
9 pages
Module 1 NS Notes
PDF
100% (1)
Module 1 NS Notes
27 pages
Cse III Computer Organization (15cs34) Question Paper
PDF
No ratings yet
Cse III Computer Organization (15cs34) Question Paper
4 pages
Project #1 - Python Magic 8 Ball: Complete Python Programming Masterclass Beginner To Advanced
PDF
No ratings yet
Project #1 - Python Magic 8 Ball: Complete Python Programming Masterclass Beginner To Advanced
4 pages
Sonata Software Sample Aptitude Placement Paper Level1
PDF
No ratings yet
Sonata Software Sample Aptitude Placement Paper Level1
7 pages
STLD Bits
PDF
No ratings yet
STLD Bits
18 pages
Test-3 Solutions Subject: Advanced Computer Architecture: 1 2 3 4 5 6 7 8 S1 S2 S3 X X X X X X X X
PDF
No ratings yet
Test-3 Solutions Subject: Advanced Computer Architecture: 1 2 3 4 5 6 7 8 S1 S2 S3 X X X X X X X X
14 pages
Bidtk258 Idt Quiz
PDF
No ratings yet
Bidtk258 Idt Quiz
9 pages
STLD Question Bank
PDF
0% (1)
STLD Question Bank
6 pages
Fractal Previous Year Coding Questions Super Dream
PDF
No ratings yet
Fractal Previous Year Coding Questions Super Dream
2 pages
Baseband M Ary Transmission and Digital Subscriber Lines
PDF
100% (1)
Baseband M Ary Transmission and Digital Subscriber Lines
17 pages
Machine Learning
PDF
No ratings yet
Machine Learning
7 pages
Rabin-Karp Algorithm For Pattern Searching: Examples
PDF
No ratings yet
Rabin-Karp Algorithm For Pattern Searching: Examples
5 pages
Practice Questions CNNs Solns
PDF
No ratings yet
Practice Questions CNNs Solns
11 pages
Coding Questions
PDF
No ratings yet
Coding Questions
2 pages
Model Paper Python BCC402
PDF
No ratings yet
Model Paper Python BCC402
4 pages
Sangida Akter (ID-11608019) - Hill Cipher
PDF
No ratings yet
Sangida Akter (ID-11608019) - Hill Cipher
129 pages
ARM INstruction Set
PDF
100% (1)
ARM INstruction Set
6 pages
EC6601 VLSI Lesson Plan
PDF
No ratings yet
EC6601 VLSI Lesson Plan
7 pages
Ldco Insem Bank
PDF
No ratings yet
Ldco Insem Bank
2 pages
Experiment No.: 2: AIM: To Perform Encoding and Decoding For Hamming Code. APPARATUS: Scilab. Theory
PDF
No ratings yet
Experiment No.: 2: AIM: To Perform Encoding and Decoding For Hamming Code. APPARATUS: Scilab. Theory
4 pages
Two Mark Questions and Answers
PDF
No ratings yet
Two Mark Questions and Answers
19 pages
Dpco Important Part B Questions
PDF
No ratings yet
Dpco Important Part B Questions
1 page
6etscyll-BEC613
PDF
No ratings yet
6etscyll-BEC613
6 pages
Soft Computing
PDF
No ratings yet
Soft Computing
26 pages
DLD Workbook
PDF
No ratings yet
DLD Workbook
32 pages
Introduction To Big data-21CS753-syllabus
PDF
No ratings yet
Introduction To Big data-21CS753-syllabus
3 pages
Series1 QP CST 294
PDF
No ratings yet
Series1 QP CST 294
2 pages
Ec3401 Networks and Security L T P C
PDF
No ratings yet
Ec3401 Networks and Security L T P C
2 pages
Ec6711 Viva Questions
PDF
No ratings yet
Ec6711 Viva Questions
3 pages
Dpco Notes All Units
PDF
No ratings yet
Dpco Notes All Units
155 pages
Btech Ec 6 Sem Data Communication Networks Kec 063 2023
PDF
No ratings yet
Btech Ec 6 Sem Data Communication Networks Kec 063 2023
2 pages
Hardware Architecture of Embedded Systems
PDF
100% (1)
Hardware Architecture of Embedded Systems
68 pages
CC Mod5
PDF
No ratings yet
CC Mod5
121 pages
Unit 4 DCN Lecture Notes 46 54
PDF
No ratings yet
Unit 4 DCN Lecture Notes 46 54
21 pages
Programmable ASIC I/O Cells: Application-Specific Integrated Circuits
PDF
No ratings yet
Programmable ASIC I/O Cells: Application-Specific Integrated Circuits
39 pages
Cyclic Codes
PDF
No ratings yet
Cyclic Codes
13 pages
Application of 8051 Microcontroller
PDF
100% (1)
Application of 8051 Microcontroller
8 pages
Syllabus
PDF
No ratings yet
Syllabus
9 pages
IoT-Enabling-Technologies
PDF
No ratings yet
IoT-Enabling-Technologies
17 pages
Design and Analysis of Algorithms: Lab Manual
PDF
No ratings yet
Design and Analysis of Algorithms: Lab Manual
57 pages
MES Module 4 Notes (1) 2
PDF
No ratings yet
MES Module 4 Notes (1) 2
24 pages
Lesson Plan For GE3151
PDF
No ratings yet
Lesson Plan For GE3151
5 pages
06 Python Tutorial
PDF
No ratings yet
06 Python Tutorial
16 pages
Python 3: 1.code
PDF
No ratings yet
Python 3: 1.code
22 pages
Core Python ESD Final Draft
PDF
No ratings yet
Core Python ESD Final Draft
111 pages
Python 11
PDF
No ratings yet
Python 11
37 pages
Variables and Data Types
PDF
No ratings yet
Variables and Data Types
13 pages
Solution JUNEJULY 2018
PDF
No ratings yet
Solution JUNEJULY 2018
15 pages
DEPARTMENT: Computer Science & Engineering Module 1 - Solved Programs Semester: 6 SUBJECT: Python Application Programming SUB CODE: 15CS664
PDF
0% (1)
DEPARTMENT: Computer Science & Engineering Module 1 - Solved Programs Semester: 6 SUBJECT: Python Application Programming SUB CODE: 15CS664
4 pages
CYRPTO Model QP Solutions
PDF
No ratings yet
CYRPTO Model QP Solutions
58 pages
Python Model Soultion 1
PDF
No ratings yet
Python Model Soultion 1
20 pages
CG 15cs62 Model QP Solutions
PDF
No ratings yet
CG 15cs62 Model QP Solutions
60 pages
1.1 Introduction To Computer Graphics: Multiplex Theatre
PDF
No ratings yet
1.1 Introduction To Computer Graphics: Multiplex Theatre
24 pages
System Software and Compiler Design
PDF
No ratings yet
System Software and Compiler Design
34 pages