0% found this document useful (0 votes)
3 views9 pages

Unit II To V Python Programs With Answers

The document provides a collection of Python programming exercises and solutions, covering various topics such as problem-solving techniques, basic programming constructs, data types, and functions. Each unit includes multiple programming tasks with corresponding code snippets and explanations. This resource serves as a guide for learning and practicing Python programming skills.

Uploaded by

eirikrozar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views9 pages

Unit II To V Python Programs With Answers

The document provides a collection of Python programming exercises and solutions, covering various topics such as problem-solving techniques, basic programming constructs, data types, and functions. Each unit includes multiple programming tasks with corresponding code snippets and explanations. This resource serves as a guide for learning and practicing Python programming skills.

Uploaded by

eirikrozar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Algorithmic Thinking and Problem Solving

UNIT II – UNIT V
Python Programs with Answer Key
UNIT II – Problem Solving Techniques & Algorithmic Thinking
1. Even or Odd
n=int(input())
print("Even" if n%2==0 else "Odd")

2. Largest of three numbers


a,b,c=map(int,input().split())
print(max(a,b,c))

3. Positive, Negative or Zero


n=int(input())
if n>0: print("Positive")
elif n<0: print("Negative")
else: print("Zero")

4. Sum of N natural numbers


n=int(input())
print(n*(n+1)//2)

5. Fibonacci series
n=int(input())
a,b=0,1
for i in range(n):
print(a,end=" ")
a,b=b,a+b

6. Prime number check


n=int(input())
flag=True
for i in range(2,n):
if n%i==0:
flag=False
break
print("Prime" if flag and n>1 else "Not Prime")

7. Factorial
n=int(input())
f=1
for i in range(1,n+1):
f*=i
print(f)

8. Reverse a number
n=input()
print(n[::-1])

9. Palindrome number
n=input()
print("Palindrome" if n==n[::-1] else "Not Palindrome")

10. Count digits


n=input()
print(len(n))

11. GCD
import math
a,b=map(int,input().split())
print([Link](a,b))

12. LCM
a,b=map(int,input().split())
lcm=(a*b)//__import__('math').gcd(a,b)
print(lcm)

13. Average of numbers


nums=list(map(int,input().split()))
print(sum(nums)/len(nums))

14. Star pattern


n=int(input())
for i in range(1,n+1):
print("*"*i)

15. Power of number


a,b=map(int,input().split())
print(a**b)
UNIT III – Introduction to Python Programming
1. Simple Calculator
a,b=map(int,input().split())
print(a+b,a-b,a*b,a/b)

2. Swap two numbers


a,b=map(int,input().split())
a,b=b,a
print(a,b)

3. Leap year
y=int(input())
print("Leap Year" if y%4==0 and (y%100!=0 or y%400==0) else "Not Leap Year")

4. Multiplication table
n=int(input())
for i in range(1,11):
print(n,"x",i,"=",n*i)

5. Sum of digits
n=input()
print(sum(map(int,n)))

6. Smallest in list
lst=list(map(int,input().split()))
print(min(lst))

7. Count vowels
s=input().lower()
print(sum(1 for c in s if c in 'aeiou'))

8. Reverse string
s=input()
print(s[::-1])

9. While loop demo


i=1
while i<=5:
print(i)
i+=1

10. For loop demo


for i in range(1,6):
print(i)

11. Break statement


for i in range(10):
if i==5: break
print(i)

12. Continue statement


for i in range(5):
if i==2: continue
print(i)

13. Nested if
a,b=map(int,input().split())
if a>0:
if b>0: print("Both positive")
14. Nested loop
for i in range(3):
for j in range(3):
print(i,j)

15. Menu driven


print("[Link] [Link]")
ch=int(input())
a,b=map(int,input().split())
print(a+b if ch==1 else a-b)
UNIT IV – Python Data Types
1. List creation
lst=[1,2,3]
print(lst)

2. List methods
lst=[1,2,3]
[Link](4)
print(lst)

3. Nested list
lst=[[1,2],[3,4]]
print(lst[0][1])

4. String slicing
s="Python"
print(s[1:4])

5. Character count
s=input()
print(len(s))

6. Tuple access
t=(10,20,30)
print(t[1])

7. List to tuple
lst=[1,2,3]
print(tuple(lst))

8. Set operations
a={1,2,3}
b={3,4}
print(a-b)

9. Set vs List
print("Set removes duplicates")

10. Dictionary creation


d={'a':1,'b':2}
print(d)

11. Access dictionary


d={'x':10}
print(d['x'])

12. Update dictionary


d={'a':1}
d['a']=5
print(d)

13. Nested dictionary


d={'s1':{'m':90}}
print(d['s1']['m'])

14. Length of data types


print(len([1,2,3]),len("abc"))

15. Type conversion


print(int("10"),str(10))
UNIT V – Functions
1. Simple function
def show():
print("Hello")
show()

2. Function with arguments


def add(a,b):
return a+b
print(add(2,3))

3. Return value
def square(x):
return x*x
print(square(4))

4. Factorial function
def fact(n):
return 1 if n==0 else n*fact(n-1)
print(fact(5))

5. Prime function
def prime(n):
return n>1 and all(n%i for i in range(2,n))
print(prime(7))

6. Max function
def max2(a,b):
return a if a>b else b
print(max2(3,5))

7. Default argument
def greet(name="User"):
print(name)
greet()

8. Keyword arguments
def info(name,age):
print(name,age)
info(age=20,name="Ram")

9. Recursive function
def sum_n(n):
return n+sum_n(n-1) if n>0 else 0
print(sum_n(5))

10. Lambda function


sq=lambda x:x*x
print(sq(4))

11. Reverse string function


def rev(s):
return s[::-1]
print(rev("abc"))

12. Sum function


def total(lst):
return sum(lst)
print(total([1,2,3]))

13. Global variable


x=10
def f():
global x
x=5
f()
print(x)

14. Local variable


def f():
x=10
print(x)
f()

15. Menu driven function


def add(a,b): return a+b
def sub(a,b): return a-b
ch=int(input())
a,b=map(int,input().split())
print(add(a,b) if ch==1 else sub(a,b))

Common questions

Powered by AI

Number reversal in Python can be achieved using string slicing. By converting the number to a string, slicing syntax allows for reversal. The expression `s[::-1]` creates a new string that is the reverse of `s`. For example, with `n=input()`, calling `n[::-1]` returns the reversed string, effectively reversing the digits of the number .

Default arguments provide a mechanism to define functions with optional parameter values, making function calls more versatile. For instance, `def greet(name='User'):` defaults the parameter `name` to 'User' if no argument is passed during the function call, allowing flexible use of the function `greet()`, which will simply print 'User', but if a name is provided, it will print the given name. This feature supports user-friendly API design by decreasing the need for function overloading .

The algorithm uses modulo operation to determine if a number is even or odd. Specifically, it checks the remainder of the number when divided by 2; if the remainder is 0, the number is even, otherwise it's odd. This logic is encapsulated in the Python expression `n%2==0`, which evaluates to True for even numbers and False for odd numbers .

List comprehensions provide a compact way of generating lists. To create a list of squares of integers from 1 to n inclusive, one can use the syntax `[i*i for i in range(1, n+1)]`. This expression iteratively computes the square of each integer i in the specified range and collects them into a new list. This approach is not only concise but also more efficient and readable compared to the traditional loop-based list creation .

A nested loop can be used to iterate over different rows and columns to construct the multiplication table. The outer loop iterates over the multiplicand (typically from 1 to n), while the inner loop iterates over a static range (e.g., 1 to 10) representing the multiplier. For example, `for i in range(1, 11): print(n, 'x', i, '=', n*i)` effectively calculates and prints `n` times each number `i`, forming a structured table. This systematic approach leverages the repetitive nature of the task .

To check and count vowels in a string, Python's comprehension and built-in functions are utilized. The string is first converted to lowercase to ensure uniformity during checks. Using a generator expression, the program iterates over the string and sums instances where a letter matches any vowel ('a', 'e', 'i', 'o', 'u'). This is expressed as `sum(1 for c in s if c in 'aeiou')`, which counts each occurrence efficiently .

Recursive functions handle repetitive tasks by breaking down the problem into smaller instances of the same problem. In summing natural numbers, recursion is employed by defining a function that returns the sum of `n` plus the sum of `n-1`. The base case is `n=0`, which returns 0, ending the recursion. This method elegantly captures the natural reduction of the problem and is succinctly expressed with `def sum_n(n): return n+sum_n(n-1) if n > 0 else 0` .

Python dictionaries are versatile for storing hierarchical information due to their key-value structure. A nested dictionary can encapsulate multiple layers of data, resembling complex datasets. For example, a student score record could be organized as `d={'s1':{'math':90, 'science':95}}`, where 's1' is the student ID, and the nested dictionary stores scores in subjects. Accessing `d['s1']['math']` retrieves the math score, demonstrating easy access and storage of related data through keys .

Python utilizes the built-in `max()` function to compare values and determine the largest one. Given three numbers, a, b, and c, the expression `max(a, b, c)` evaluates these numbers and returns the one with the maximum value using simple comparison internally, which is efficient for this task .

Lambda functions in Python serve as a concise way to define anonymous functions used for simple tasks. Unlike regular functions created with `def`, lambda functions do not require naming and are limited to a single expression which is evaluated and returned. For example, `sq=lambda x: x*x` quickly defines a square function without additional structure. Lambda functions favor brevity and are often used for short-term purposes like inline function arguments due to their simplicity and speed in being defined and executed .

You might also like