Docsity

Learn functions in python with 30+problems with solution, Study notes of Computer Science

Toggle sidebar
bg1
Python Functions: A Complete Notes
1. Defining and Calling Functions
A function in Python is defined using the def keyword. Functions help organize code
into reusable blocks.
Example:
def greet(name): # Defining the function
print(f"Hello, {name}!")
# Calling the function
greet("Alice")
2. Parameters and Return Values
Functions can take parameters (inputs) and return values (outputs).
Example with Parameters and Return Value:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
3. Recursion in Python
Recursion is when a function calls itself to solve a problem.
Example: Factorial using Recursion
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Example: Fibonacci using Recursion
def fibonacci(n):
if n <= 0:
return "Invalid Input"
elif n == 1:
return 0
elif n == 2:
return 1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17

Partial preview of the text

Download Learn functions in python with 30+problems with solution and more Study notes Computer Science in PDF only on Docsity!

Python Functions: A Complete Notes

1. Defining and Calling Functions A function in Python is defined using the def keyword. Functions help organize code into reusable blocks. Example: def greet(name): # Defining the function print(f"Hello, {name}!")

Calling the function

greet("Alice") 2. Parameters and Return Values Functions can take parameters (inputs) and return values (outputs). Example with Parameters and Return Value: def add(a, b): return a + b result = add(5, 3 ) print(result) # Output: 8 3. Recursion in Python Recursion is when a function calls itself to solve a problem. Example: Factorial using Recursion def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n - 1) print(factorial( 5 )) # Output: 120 Example: Fibonacci using Recursion def fibonacci(n): if n <= 0: return "Invalid Input" elif n == 1: return 0 elif n == 2: return 1

else: return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci( 6 )) # Output: 5 Key Takeaways: ļ‚· Functions improve code reusability and readability. ļ‚· Parameters allow passing values to functions. ļ‚· Return values allow functions to output results. ļ‚· Recursion is useful for problems like factorial, Fibonacci, and tree traversal.

1. A circular prime is a prime number that remains prime under all rotations of its digits. For example, 197 is a circular prime because all its rotations (197, 971, 719 ) are prime. Output: 197 197 is a Circular Prime Code: def is_prime(n): #Check if a number is prime if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True def get_rotations(n): #Generate all rotations of a number str_n = str(n) return [int(str_n[i:] + str_n[:i]) for i in range(len(str_n))] def is_circular_prime(n): #Check if a number is a circular prime return all(is_prime(rot) for rot in get_rotations(n)) num = 197 if is_circular_prime(num): print(f"{num} is a Circular Prime") else: print(f"{num} is NOT a Circular Prime")

return money - min_sum # Return the leftover money else: return money # If not possible, return the original money prices = list(map(int, input("Enter chocolate prices separated by spaces: ").split())) money = int(input("Enter your initial amount of money: "))

Calling the function and printing the result

print(min_leftover_money(prices, money))

4. Python program to calculate combinations (nCrnCrnCr) by taking input from the user:Combinations: nCr = n! / (r! * (n – r)!) Output: Enter the value of n: 5 Enter the value of r: 2 nCr (5C2) = 10 Code: Way 1: import math

Function to calculate nCr

def combination(n, r): return math.comb(n, r) # math.comb is available in Python 3.8+

Taking input from the user

n = int(input("Enter the value of n: ")) r = int(input("Enter the value of r: "))

Checking valid input

if r > n or n < 0 or r < 0: print("Invalid input! r should be less than or equal to n, and both should be non- negative.") else: print(f"nCr ({n}C{r}) = {combination(n, r)}") Way 2:

Function to calculate factorial

def factorial(num): if num == 0 or num == 1: return 1 result = 1 for i in range(2, num + 1):

result *= i return result

Function to calculate nCr

def combination(n, r): return factorial(n) // (factorial(r) * factorial(n - r)) n = int(input("Enter the value of n: ")) r = int(input("Enter the value of r: "))

Checking valid input

if r > n or n < 0 or r < 0: print("Invalid input! r should be less than or equal to n, and both should be non- negative.") else: print(f"nCr ({n}C{r}) = {combination(n, r)}")

5. Maximum digit sum of two combinations. Output: Input: 3 (no.of.inputs) 8 6 7 Output : 12 (8,6) (8,7) (6,7) => 86=48, 87= 56, 6*7 = 42 Digit sum the answers : 4+8 =12, 5+6 = 11, 4+2=6; max = 12 Code:

Function to calculate the sum of digits of a number

def digit_sum(n): return sum(int(digit) for digit in str(n)) n = int(input()) # Number of inputs arr = list(map(int, input().split())) # List of numbers

Generate all 2-combinations manually and compute the maximum digit sum

max_digit_sum = 0 for i in range(n): for j in range(i + 1, n): product = arr[i] * arr[j] max_digit_sum = max(max_digit_sum, digit_sum(product)) print(max_digit_sum) 6. Python program that generates a Fibonacci series iteratively based on user input.

Code: def print_integers_to_minus_one(N): for i in range(N + 1, 0): print(i, end=" ") N = int(input("Enter a number: ")) print_integers_to_minus_one(N)

9. Python to count the number of uppercase and lowercase letters in a string. Output: "Hello World!" Uppercase letters: 2, Lowercase letters: 8 Code: def count_case(s): upper_count = sum(1 for char in s if char.isupper()) lower_count = sum(1 for char in s if char.islower()) return upper_count, lower_count text = "Hello World!" upper, lower = count_case(text) print(f"Uppercase letters: {upper}, Lowercase letters: {lower}") 10. Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below. Note that the strings are case-insensitive, both lowercased and uppercased of the same letter are treated as if they are at the same row. In the American keyboard: the first row consists of the characters "qwertyuiop", the second row consists of the characters "asdfghjkl", and the third row consists of the characters "zxcvbnm". Output: ["Hello", "Alaska", "Dad", "Peace"] ['Alaska', 'Dad'] Code: from typing import List def findWords(words: List[str]) : row1 = set("qwertyuiop") row2 = set("asdfghjkl") row3 = set("zxcvbnm")

result = [] for word in words: lower_word = set(word.lower()) # Convert word to lowercase and get unique letters if lower_word <= row1 or lower_word <= row2 or lower_word <= row3: result.append(word) return result words = ["Hello", "Alaska", "Dad", "Peace"] print(words) print(findWords(words))

11. Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0. Output: Enter words separated by spaces: abcw baz foo bar xtfn apt Maximum product of lengths of two words without common letters: 16 Code: def max_product(words): word_sets = [{char for char in word} for word in words] max_product = 0 for i in range(len(words)): for j in range(i + 1, len(words)): if word_sets[i].isdisjoint(word_sets[j]): # No common letters max_product = max(max_product, len(words[i]) * len(words[j])) return max_product words = input("Enter words separated by spaces: ").split() result = max_product(words) print("Maximum product of lengths of two words without common letters:", result) 12. Convert a non-negative integer num to its English words representation. Output: Enter a non-negative integer: 1234567 One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven Code:

binary_result = decimal_to_binary_7bit(decimal_number) print(f"Binary (7-bit precision): {binary_result}")

14. Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order. Output: Enter elements of first list separated by space: 1 2 3 Enter elements of second list separated by space: 4 2 5 Enter elements of third list separated by space: 3 6 7 Numbers appearing in at least two lists: [2, 3] Code: def two_out_of_three(nums1, nums2, nums3): from collections import Counter # Convert lists to sets to remove duplicates within each list set1, set2, set3 = set(nums1), set(nums2), set(nums3) # Count occurrences in how many sets each number appears freq = Counter(set1) + Counter(set2) + Counter(set3) # Select numbers that appear in at least two sets result = [num for num, count in freq.items() if count >= 2] return result nums1 = list(map(int, input("Enter elements of first list separated by space: ").split())) nums2 = list(map(int, input("Enter elements of second list separated by space: ").split())) nums3 = list(map(int, input("Enter elements of third list separated by space: ").split()))

Calling the function and printing the result

print("Numbers appearing in at least two lists:", two_out_of_three(nums1, nums2, nums3)) 15. print the longest word Output: 'programming python' programming Code: title ='programming python' longest_word = max(title.split(), key=len) print(f"'{title}'") print(longest_word)

16. consecutive consonace like Consecutive Characters Output: Enter a string: beautifulstrongsky Longest consecutive consonants: 'ngsk' with length 4 Code: def longest_consecutive_consonants(s): vowels = {'a', 'e', 'i', 'o', 'u'} max_len = 0 current_len = 0 max_substr = "" current_substr = "" for char in s.lower(): # Convert to lowercase for uniformity if char.isalpha() and char not in vowels: # Check if consonant current_len += 1 current_substr += char if current_len > max_len: max_len = current_len max_substr = current_substr else: current_len = 0 current_substr = "" return max_substr, max_len input_string = input("Enter a string: ") result, length = longest_consecutive_consonants(input_string) print(f"Longest consecutive consonants: '{result}' with length {length}") 17. Count of palindromic sub-strings from a given string Output: Enter a string: ababa Count of palindromic substrings: 9 Code: def is_palindrome(s): return s == s[::-1] def count_palindromic_substrings(s): count = 0 n = len(s) for i in range(n): for j in range(i, n): if is_palindrome(s[i:j+1]):

for i in range(len(stones) - 1): total_duration += min(stones[i + 1] - stones[i], duration)

Add the last stone's duration

total_duration += duration return total_duration stones = list(map(int, input("Enter stone times (space-separated): ").split())) duration = int(input("Enter duration: "))

Calculating poisoned duration

result = poisoned_duration(stones, duration) print("Total poisoned duration:", result)

20. Python program to process the input list and classify the numbers into prime, composite, and negative numbers sorted in order. Output: 2 3 4 5 -3 -2 - [2,3,5] [4] [-2,-3,-7] Code: def is_prime(n): if n<2: return False for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def classify(num): neg= [] pri= [] com= [] for n in num: if n<0: neg.append(n) elif is_prime(n): pri.append(n) elif n>1: com.append(n) print(pri) print(com) print(sorted(neg))

num=list(map(int,input().split())) classify(num)

21. calculate and print the area of a circle, triangle, and rectangle Output: Enter the radius of the circle: 4 Area of Circle: 50. Enter the base of the triangle: 5 Enter the height of the triangle: 10 Area of Triangle: 25. Enter the length of the rectangle: 7 Enter the width of the rectangle: 3 Area of Rectangle: 21. Code: import math def area_of_circle(radius): return math.pi * radius ** 2 def area_of_triangle(base, height): return 0.5 * base * height def area_of_rectangle(length, width): return length * width radius = float(input("Enter the radius of the circle: ")) print(f"Area of Circle: {area_of_circle(radius):.2f}") base = float(input("Enter the base of the triangle: ")) height = float(input("Enter the height of the triangle: ")) print(f"Area of Triangle: {area_of_triangle(base, height):.2f}") length = float(input("Enter the length of the rectangle: ")) width = float(input("Enter the width of the rectangle: ")) print(f"Area of Rectangle: {area_of_rectangle(length, width):.2f}") 22. Given an integer array nums where nums[i] is either a positive integer or -1. We need to find for each -1 the respective positive integer, which we call the last visited integer. To achieve this goal, let's define two empty arrays: seen and ans. Start iterating from the beginning of the array nums. ļ‚· If a positive integer is encountered, prepend it to the front of seen.

if char not in vowels: # It's a consonant count += 1 if count > 3: return "no" else: count = 0 # Reset count if a vowel is found return "yes" word = input("Enter a word: ") print(three_consecutive_consonants(word))

24. MATRIX MULTIPLICATION Output: Enter the number of rows for Matrix A: 2 Enter the number of columns for Matrix A: 3 Enter the number of rows for Matrix B: 3 Enter the number of columns for Matrix B: 2 Enter the elements of A matrix row-wise: 1 2 3 4 5 6 Enter the elements of B matrix row-wise: 7 8 9 10 11 12 Resultant Matrix: 58 64 139 154 Code: def get_matrix(rows, cols, name): print(f"Enter the elements of {name} matrix row-wise:") matrix = [] for i in range(rows): row = list(map(int, input().split())) if len(row) != cols: print(f"Error: Please enter exactly {cols} values per row.") return get_matrix(rows, cols, name) matrix.append(row) return matrix def multiply_matrices(A, B, r1, c1, c2): result = [[0] * c2 for _ in range(r1)] for i in range(r1): for j in range(c2): for k in range(c1): result[i][j] += A[i][k] * B[k][j]

return result r1 = int(input("Enter the number of rows for Matrix A: ")) c1 = int(input("Enter the number of columns for Matrix A: ")) r2 = int(input("Enter the number of rows for Matrix B: ")) c2 = int(input("Enter the number of columns for Matrix B: ")) if c1 != r2: print("Matrix multiplication is not possible (columns of A must match rows of B).") else:

Input matrices

A = get_matrix(r1, c1, "A") B = get_matrix(r2, c2, "B")

Multiply matrices

result = multiply_matrices(A, B, r1, c1, c2)

Display result

print("Resultant Matrix:") for row in result: print(" ".join(map(str, row)))

25. MINIMUM ELEMENT SHARED BY BOTH ARRAYS Output: Enter elements of first array separated by space: 1 2 3 4 5 Enter elements of second array separated by space: 6 2 3 7 8 Minimum common element: 2 Code: def min_common_element(arr1, arr2): # Convert both lists to sets for quick lookup common_elements = set(arr1) & set(arr2) # If there are common elements, return the minimum, else return - return min(common_elements) if common_elements else - arr1 = list(map(int, input("Enter elements of first array separated by space: ").split())) arr2 = list(map(int, input("Enter elements of second array separated by space: ").split()))

Finding the minimum common element

result = min_common_element(arr1, arr2) print("Minimum common element:", result)

27. Quadratic Equation Solver Output: Enter coefficient a: 2 Enter coefficient b: 3 Enter coefficient c: 4 Two complex roots: -0.75 + 1.1989578808281798i, -0.75 - 1.1989578808281798i Code: import math

Function to solve the quadratic equation

def solve_quadratic(a, b, c): # Calculate the discriminant d = b2 - 4ac if d > 0: root1 = (-b + math.sqrt(d)) / (2a) root2 = (-b - math.sqrt(d)) / (2a) return f"Two real and distinct roots: {root1}, {root2}" elif d == 0: root = -b / (2a) return f"One real and repeated root: {root}" else: real_part = -b / (2a) imag_part = math.sqrt(abs(d)) / (2*a) return f"Two complex roots: {real_part} + {imag_part}i, {real_part} - {imag_part}i"

Taking inputs

a = float(input("Enter coefficient a: ")) b = float(input("Enter coefficient b: ")) c = float(input("Enter coefficient c: "))

Handling the case when a is zero

if a == 0: print("Not a quadratic equation.") else: print(solve_quadratic(a, b, c)) 28. prime number in range Output: Enter the start of the range: 5 Enter the end of the range: 20 Prime numbers between 5 and 20: [5, 7, 11, 13, 17, 19]

Code: def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def prime_numbers_in_range(start, end): primes = [num for num in range(start, end + 1) if is_prime(num)] return primes start = int(input("Enter the start of the range: ")) end = int(input("Enter the end of the range: "))

Finding and displaying prime numbers in range

print(f"Prime numbers between {start} and {end}: {prime_numbers_in_range(start, end)}")

29. permutation in string Output: Enter a string: abc abc acb bac bca cab cba Code: Way 1 from itertools import permutations

Function to get all permutations of a string

def get_permutations(s): return [''.join(p) for p in permutations(s)] input_str = input("Enter a string: ")

Generating and printing permutations

permuted_strings = get_permutations(input_str) for perm in permuted_strings: print(perm)