Value1 Value2 Value3 Value4 Value5
1 I Algorithm Define Algorithm An algorithm is a finite sequence of well-defined, computer-implementable instructions, typically to solve a class of problems or to perform a computation. Algorithms re unambiguous specifications for performing calculation, data processing, automated reasoning, and other tasks.
2 I Control Flow Define Control flow statement with an example. A program's control flow is the order in which the program's code executes. The control flow of a Python program is regulated by conditional statements, loops, and function calls. ... Raising and handling exceptions also affects control flow; Control flow example if x < 0: print "x is negative" elif x % 2: print "x is positive and odd" else: print "x is even and non-negative
3 I Recursion Define Recursion A recursive function is a function defined in terms of itself via self-referential expressions. This means that the function will continue to call itself and repeat its behavior until some condition is met to return a result. def factorial(x): if x==1: return 1 else: return x*factorial(x-1) f=factorial(5) print ("factorial of 5 is ",f) The result is factorial of 5 is 120
4 I Procedure Write an algorithm to accept two numbers, compute the sum and print the result. a = int(input("enter first number: ")) b = int(input("enter second number: ")) sum = a + b print("sum:", sum)
5 I Code Develop an algorithm to convert Temperature in Celsius to Fahrenheit and vice versa. # Python Program to convert temperature in celsius to fahrenheit # change this value for a different result celsius = 37.5 # calculate fahrenheit fahrenheit = (celsius * 1.8) + 32
6 I Code Examine a simple program to print the integer number from 1 to 50. # Sum of natural numbers up to 50 num = 50 if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate until zero while(num > 0): sum += num num -= 1 print("The sum is", sum)
7 I Code Discuss with suitable examples: i) Find minimum in a list ii) Find maximum in a list def smallest_num_in_list( list ): min = list[ 0 ] for a in list: if a < min: min = a return min print(smallest_num_in_list([1, 2, -8, 0])) Sample Output: -8 i) Find maximum in a list def max_num_in_list( list ): max = list[ 0 ] for a in list: if a > max: max = a return max print(max_num_in_list([1, 2, -8, 0]))
8 II CODE Function call with arguments # A simple Python function to check # whether x is even or odd def evenOdd( x ): if (x % 2 == 0): print "even" else: print "odd" # Driver code evenOdd(2) evenOdd(3) Output: even odd
9 II CODE Define the special syntax *args for passing arguments The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list. • Example for usage of *arg: # Python program to illustrate # *args with first extra argument def myFun(arg1, *argv): print ("First argument :", arg1) for arg in argv: print("Next argument through *argv :", arg) myFun('Hello', 'Welcome', 'to', 'World of Python') Output: First argument : Hello Next argument through *argv : Welcome Next argument through *argv : to Next argument through *argv : World of Python
10 II CODE What are the two parts of function definition. Give its syntax. '''Function definition and invocation.''' def happyBirthdayEmily(): print("Happy Birthday to you!") print("Happy Birthday to you!") print("Happy Birthday, dear Emily.") print("Happy Birthday to you!") happyBirthdayEmily() happyBirthdayEmily()
11 II CODE Explain a Python function with arguments with an example. '''Function with parameter called in main''' def happyBirthday(person): print("Happy Birthday to you!") print("Happy Birthday to you!") print("Happy Birthday, dear " + person + ".") print("Happy Birthday to you!") def main(): happyBirthday('Emily') happyBirthday('Andre') main()
12 II CODE Point out the difference between recursive and iterative technique with examples Iterative Approach # iterative Function (Returns the result of: 1 +2+3+4+5+...+n) def iterativeSum(n): total=0 for i in range(1,n+1): total += i return total The Recursive Approach The following code uses a function that calls itself. This is the main characteristic of a recursive approach. # Recursive Function (Returns the result of: 1 +2+3+4+5+...+n) def recursiveSum(n): if (n > 1): return n + recursiveSum(n - 1) else: return n OUTPUT Using an interative approach 1+2+3+4+...+99+100= 5050 Using a recursive approach 1+2+3+4+...+99+100= 5050
13 II CODE Give the syntax for variable length arguments. Python *args Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.The arguments are passed as a tuple and these passed arguments make tuple inside the function with same name as the parameter excluding asterisk *. Example : Using *args to pass the variable length arguments to the function 1. def adder(*num): 2. sum = 0 3. 4. for n in num: 5. sum = sum + n 6. 7. print("Sum:",sum) 8. 9. adder(3,5) 10. adder(4,5,6,7) 11. adder(1,2,3,5,6) When we run the above program, the output will be Sum: 8 Sum: 22 Sum: 17
14 II CODE Differentiate append() and extend() operations of a List. Explain with sntax and examples append(): Used for appending and adding elements to List.It is used to add elements to the last position of List. Syntax: list.append (element) extend(): Adds contents to List2 to the end of List1. Syntax: List1.extend(List2) # Adds List Element as value of List. List = ['Mathematics', 'chemistry', 1997, 2000] List.append(20544) print(List) Output: ['Mathematics', 'chemistry', 1997, 2000, 20544] List1 = [1, 2, 3] List2 = [2, 3, 4, 5] # Add List2 to List1 List1.extend(List2) print(List1) #Add List1 to List2 now List2.extend(List1) print(List2) Output: [1, 2, 3, 2, 3, 4, 5] [2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
15 II CODE i) Write a function which returns the average of given list of numbers # Python program to get average of a list # Using reduce() and lambda # importing reduce() from functools import reduce def Average(lst): return reduce(lambda a, b: a + b, lst) / len(lst) # Driver Code lst = [15, 9, 55, 41, 35, 20, 62, 49] average = Average(lst) # Printing average of the list print("Average of the list =", round(average, 2)) Output: Average of the list = 35.75
16 II CODE ii) Write a Python program to exchange the value of two variables 1. # Python program to swap two variables 2. 3. x = 5 4. y = 10 5. 6. # To take inputs from the user 7. #x = input('Enter value of x: ') 8. #y = input('Enter value of y: ') 9. 10. # create a temporary variable and swap the values 11. temp = x 12. x = y 13. y = temp 14. 15. print('The value of x after swapping: {}'.format(x)) 16. print('The value of y after swapping: {}'.format(y))
17 II CODE ii) Write a Python function to find the sum of first ā€˜n’ even numbers. #sum of Even numbers in python #Python program to get input n and calculate the sum of even numbers till n Solution n=int(input("Enter n value:")) sum=0 for i in range(2,n+1,2): sum+=i print(sum)
18 III CODE Give syntax and an example of for loop in Python >>> languages = ["C", "C++", "Perl", "Python"] >>> for x in languages: ... print(x) ... C C++ Perl Python >>>
19 III CODE Write a Python program to accept two numbers, multiply them and print the result. 1. a = int(input("enter first number: ")) 2. b = int(input("enter second number: ")) 3. result = a * b. 4. print("result :", result) OUTPUT enter first number: 4 enter second number: 5 result : 20
20 III CODE How to access the elements of an array using index. How to access array elements? We use indices to access elements of an array: 1. import array as arr 2. a = arr.array('i', [2, 4, 6, 8]) 3. 4. print("First element:", a[0]) 5. print("Second element:", a[1]) 6. print("Last element:", a[-1]) OUTPUT First element: 2 Second element: 4 Last element: 8
21 III CODE What is the use of pass statement? Illustrate with an example. The pass Statement: The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example): Example: #!/usr/bin/python for letter in 'Python': if letter == 'h': pass print 'This is pass block' print 'Current Letter :', letter print "Good bye!" OUTPUT Current Letter : P Current Letter : y Current Letter : t This is pass block Current Letter : h Current Letter : o Current Letter : n Good bye!
22 III CODE Write a program for binary search using Arrays. Python Program for Binary Search (Recursive and Iterative) We basically ignore half of the elements just after one comparison. 1. Compare x with the middle element. 2. If x matches with middle element, we return the mid index. 3. Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. 4. Else (x is smaller) recur for the left half. Iterative: # Iterative Binary Search Function # It returns location of x in given array arr if present, # else returns -1 def binarySearch(arr, l, r, x): while l <= r: mid = l + (r - l)/2; # Check if x is present at mid if arr[mid] == x: return mid # If x is greater, ignore left half elif arr[mid] < x: l = mid + 1 # If x is smaller, ignore right half else: r = mid - 1 # If we reach here, then the element was not present return -1 # Test array arr = [ 2, 3, 4, 10, 40 ] x = 10 # Function call result = binarySearch(arr, 0, len(arr)-1, x) if result != -1: print "Element is present at index %d" % result else: print "Element is not present in array"
23 III CODE Write a Python program to count the number of vowels in a string provided by the user. # Python code to count and display number of vowels # Simply using for and comparing it with a # string containg all vowels def Check_Vow(string, vowels): final = [each for each in string if each in vowels] print(len(final)) print(final) # Driver Code string = "I wandered lonely as a cloud" vowels = "AaeEeIiOoUu" Check_Vow(string, vowels); Output: 10 ['I', 'a', 'e', 'e', 'o', 'e', 'a', 'a', 'o', 'u']
24 III CODE Write syntax for while loop in python and give an example # Syntax of while Loop in Python while test_expression: Body of while # Example: Python while Loop # Program to add natural numbers upto n # sum = 1+2+3+...+n # To take input from the user, # n = int(input("Enter n: ")) n = 10 # initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # update counter # print the sum print("The sum is", sum) OUTPUT Enter n: 10 The sum is 55
25 III CODE Create a Python program to find the given year is leap year or not. # Python program to check if year is a leap year or not. # To get year (integer input) from the user. year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year". format(year)) if (year % 4) is not 0: print("{0} is NOT a leap year". format(year)) OUTPUT Enter a year: 2019 2019 is NOT a leap year Enter a year: 2000 2000 is a leap year