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)
337 views
12 pages
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
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)
337 views
12 pages
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
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
Est102 Programming in C, January 2024
PDF
No ratings yet
Est102 Programming in C, January 2024
3 pages
Linear Integrated Circuits - S. Salivahanan and v. S. K. Bhaaskaran
PDF
No ratings yet
Linear Integrated Circuits - S. Salivahanan and v. S. K. Bhaaskaran
79 pages
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
CC Mod5
PDF
No ratings yet
CC Mod5
121 pages
Coding Questions
PDF
No ratings yet
Coding Questions
2 pages
CH 5 Answers
PDF
No ratings yet
CH 5 Answers
6 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
Ec3401 Networks and Security L T P C
PDF
No ratings yet
Ec3401 Networks and Security L T P C
2 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
Machine Learning
PDF
No ratings yet
Machine Learning
7 pages
Theory of Computation Long Type of Questions-1
PDF
100% (1)
Theory of Computation Long Type of Questions-1
22 pages
DSP Integrated Circuits 3
PDF
No ratings yet
DSP Integrated Circuits 3
3 pages
Ai Lab
PDF
No ratings yet
Ai Lab
48 pages
Digital 16 Marks.
PDF
No ratings yet
Digital 16 Marks.
4 pages
RTOS
PDF
0% (1)
RTOS
1 page
Addressing Modes
PDF
100% (1)
Addressing Modes
20 pages
Levitin: Introduction To The Design and Analysis of Algorithms
PDF
No ratings yet
Levitin: Introduction To The Design and Analysis of Algorithms
35 pages
6etscyll BEC613
PDF
No ratings yet
6etscyll BEC613
6 pages
COSM Question Bank
PDF
No ratings yet
COSM Question Bank
4 pages
Python Module 1 Vtu
PDF
No ratings yet
Python Module 1 Vtu
52 pages
DCLD Module 2
PDF
No ratings yet
DCLD Module 2
37 pages
Al3411 Artificial Intelligence and Machine Learning Laboratory L T P C
PDF
No ratings yet
Al3411 Artificial Intelligence and Machine Learning Laboratory L T P C
11 pages
DSP Mod1@AzDOCUMENTS - in
PDF
No ratings yet
DSP Mod1@AzDOCUMENTS - in
60 pages
Two Mark Questions and Answers
PDF
No ratings yet
Two Mark Questions and Answers
19 pages
NR 311901 Digital Systems Design
PDF
No ratings yet
NR 311901 Digital Systems Design
5 pages
BEC613A
PDF
No ratings yet
BEC613A
19 pages
Ad3351 Daa Important Questions
PDF
No ratings yet
Ad3351 Daa Important Questions
94 pages
2nd Largest No - in An Array Using 8086
PDF
No ratings yet
2nd Largest No - in An Array Using 8086
9 pages
OS - Lecture 04 - CPU Scheduling
PDF
No ratings yet
OS - Lecture 04 - CPU Scheduling
51 pages
Daa Assignment
PDF
No ratings yet
Daa Assignment
12 pages
Unit 3 - Cyclic Code MCQ
PDF
No ratings yet
Unit 3 - Cyclic Code MCQ
6 pages
DLD Workbook
PDF
No ratings yet
DLD Workbook
32 pages
Python Application Programming - 18CS752 - Syllabus
PDF
No ratings yet
Python Application Programming - 18CS752 - Syllabus
4 pages
Novel Approach For Cooperative Caching in Distributed Environment
PDF
No ratings yet
Novel Approach For Cooperative Caching in Distributed Environment
4 pages
ADA Important Questions PDF
PDF
No ratings yet
ADA Important Questions PDF
13 pages
Soft Computing
PDF
No ratings yet
Soft Computing
26 pages
Artificial Intelligence Question Bank-RICH
PDF
No ratings yet
Artificial Intelligence Question Bank-RICH
10 pages
2marks With Answer
PDF
No ratings yet
2marks With Answer
46 pages
For PPS
PDF
No ratings yet
For PPS
57 pages
Timers in 8051 - Notes
PDF
No ratings yet
Timers in 8051 - Notes
13 pages
DCDR Question Bank
PDF
No ratings yet
DCDR Question Bank
4 pages
Series1 QP CST 294
PDF
No ratings yet
Series1 QP CST 294
2 pages
MES Module 4 Notes (1) 2
PDF
No ratings yet
MES Module 4 Notes (1) 2
24 pages
Final Question Bank - DSP
PDF
No ratings yet
Final Question Bank - DSP
32 pages
Ds Solved 2021-22
PDF
No ratings yet
Ds Solved 2021-22
54 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
DSA 2022 Question Paper
PDF
100% (1)
DSA 2022 Question Paper
2 pages
IoT Module 5 IoT Case Studies and Future Trends
PDF
0% (1)
IoT Module 5 IoT Case Studies and Future Trends
48 pages
AP PGECET CS and IT (CS-2015) Question Paper & Answer Key. Download All Previous Years Computer Science & Information Technology Sample & Model Question Papers.
PDF
100% (2)
AP PGECET CS and IT (CS-2015) Question Paper & Answer Key. Download All Previous Years Computer Science & Information Technology Sample & Model Question Papers.
16 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
CS3401-ALGORITHMS QB Original
PDF
No ratings yet
CS3401-ALGORITHMS QB Original
51 pages
Multicycle Datapath PDF
PDF
No ratings yet
Multicycle Datapath PDF
22 pages
Rich Automata Solns
PDF
100% (1)
Rich Automata Solns
187 pages
Module 3 Final
PDF
No ratings yet
Module 3 Final
77 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