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)
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
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)
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
Download now
Download
Save Python Model Soultion 2 For Later
Carousel Previous
Carousel Next
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
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6125)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (627)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brene Brown
4/5 (1148)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (932)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8214)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (631)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1253)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (8365)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (860)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (877)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (954)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (2922)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (484)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (277)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4972)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (444)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4281)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Tóibín
3.5/5 (2061)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (447)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1068)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1987)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (1993)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2641)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (1936)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (125)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (692)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4074)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (75)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (901)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2530)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (790)
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
Solution JUNEJULY 2018
PDF
No ratings yet
Solution JUNEJULY 2018
15 pages
Python Model Soultion 1
PDF
No ratings yet
Python Model Soultion 1
20 pages
CYRPTO Model QP Solutions
PDF
No ratings yet
CYRPTO Model QP Solutions
58 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
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4/5 (105)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
3.5/5 (109)
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Principles: Life and Work
From Everand
Principles: Life and Work
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Steve Jobs
From Everand
Steve Jobs
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Yes Please
From Everand
Yes Please
The Outsider: A Novel
From Everand
The Outsider: A Novel
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
John Adams
From Everand
John Adams
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
DEPARTMENT: Computer Science & Engineering Module 1 - Solved Programs Semester: 6 SUBJECT: Python Application Programming SUB CODE: 15CS664
PDF
DEPARTMENT: Computer Science & Engineering Module 1 - Solved Programs Semester: 6 SUBJECT: Python Application Programming SUB CODE: 15CS664
Solution JUNEJULY 2018
PDF
Solution JUNEJULY 2018
Python Model Soultion 1
PDF
Python Model Soultion 1
CYRPTO Model QP Solutions
PDF
CYRPTO Model QP Solutions
CG 15cs62 Model QP Solutions
PDF
CG 15cs62 Model QP Solutions
1.1 Introduction To Computer Graphics: Multiplex Theatre
PDF
1.1 Introduction To Computer Graphics: Multiplex Theatre
System Software and Compiler Design
PDF
System Software and Compiler Design
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
Little Women
From Everand
Little Women
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel