0% found this document useful (0 votes)
5 views12 pages

1 Loop, Function Task

Uploaded by

8530206489s
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)
5 views12 pages

1 Loop, Function Task

Uploaded by

8530206489s
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
You are on page 1/ 12

TASK

1. Factorial Calculation

Write a function calculate_factorial(n) that calculates the factorial of n


using both recursion and loops.
The factorial of a number nnn (denoted as n!n!n!) is the product of all positive integers from 1 to
nnn.
Mathematically, it is defined as:

n!=n×(n−1)×(n−2)×...×2×1n! = n \times (n - 1) \times (n - 2) \times ... \times 2 \times


1n!=n×(n−1)×(n−2)×...×2×1

 Example:

5!=5×4×3×2×1=1205! = 5 \times 4 \times 3 \times 2 \times 1 = 1205!=5×4×3×2×1=120

 Special Case: 0!=10! = 10!=1 (by definition).

2. Fibonacci Sequence

Write a function fibonacci(n) that returns the nth Fibonacci number.


Implement both iterative and recursive solutions.
💡 Example: fibonacci(6) → 8 (0, 1, 1, 2, 3, 5, 8...)
The Fibonacci sequence follows this pattern:

F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)F(n)=F(n−1)+F(n−2)

 Base cases:
F(0)=0F(0) = 0F(0)=0, F(1)=1F(1) = 1F(1)=1
 Example:
F(6)=8F(6) = 8F(6)=8 → (0,1,1,2,3,5,8)(0, 1, 1, 2, 3, 5, 8)(0,1,1,2,3,5,8)
3. Check Prime Number
A prime number is only divisible by 1 and itself (e.g., 2, 3, 5, 7, 11).

Write a function is_prime(n) that returns True if n is a prime number and


False otherwise.
💡 Example: is_prime(7) → True, is_prime(10) → False

4. Reverse a String
Uses Python slicing ([::-1]) to reverse the string.

Write a function reverse_string(s) that takes a string and returns it


reversed.
💡 Example: reverse_string("hello") → "olleh"

5. Find the Maximum Number in a List

Write a function find_max(lst) that returns the maximum number in a


given list without using max().
💡 Example: find_max([3, 7, 1, 8, 2]) → 8

6. Sum of Digits

Write a function sum_of_digits(n) that takes an integer and returns the


sum of its digits.
💡 Example: sum_of_digits(123) → 6 (1 + 2 + 3)
7. Count Vowels in a String

Write a function count_vowels(s) that returns the number of vowels (a,


e, i, o, u) in a string.
💡 Example: count_vowels("hello world") → 3 (e, o, o)

8. Palindrome Check
Compares original and reversed string.

Write a function is_palindrome(s) that checks if a given string is a


palindrome (same forward and backward).
💡 Example: is_palindrome("racecar") → True

9. Find the GCD (Greatest Common Divisor)

Write a function gcd(a, b) that returns the greatest common divisor of


two numbers using Euclidean Algorithm.
💡 Example: gcd(48, 18) → 6

10. Unique Elements in a List


Sets automatically remove duplicates.

Write a function unique_elements(lst) that returns a list containing only


unique elements from the input list.
💡 Example: unique_elements([1, 2, 2, 3, 4, 4, 5]) → [1, 2, 3, 4, 5]

SOLUTION
1. Factorial Calculation
 Base Case: If n=0n = 0n=0 or n=1n = 1n=1, return 1.
 Recursive Case: Multiply nnn by calculate_factorial(n - 1), reducing nnn until
it reaches 1.

Recursive and Iterative Approach

def calculate_factorial(n):
if n < 0:
return None # Factorial is not defined for negative numbers
if n == 0 or n == 1:
return 1
return n * calculate_factorial(n - 1)

# Iterative approach
def calculate_factorial_iterative(n):
if n < 0:
return None
result = 1
for i in range(2, n + 1):
result *= i
return result

# Example
print(calculate_factorial(5)) # Output: 120
print(calculate_factorial_iterative(5)) # Output: 120

2. Fibonacci Sequence
 Base Case: If n=0n = 0n=0, return 0; if n=1n = 1n=1, return 1.
 Recursive Case: Sum of the previous two Fibonacci numbers
Recursive and Iterative Approach

# Recursive approach
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)

# Iterative approach
def fibonacci_iterative(n):
if n <= 0:
return 0
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a

# Example
print(fibonacci(6)) # Output: 8
print(fibonacci_iterative(6)) # Output: 8

3. Check Prime Number

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
# Example
print(is_prime(7)) # Output: True
print(is_prime(10)) # Output: False

4. Reverse a String

def reverse_string(s):
return s[::-1]

# Example
print(reverse_string("hello")) # Output: "olleh"

5. Find the Maximum Number in a List (without max())

def find_max(lst):
if not lst:
return None # Return None for empty list
max_num = lst[0]
for num in lst:
if num > max_num:
max_num = num
return max_num

# Example
print(find_max([3, 7, 1, 8, 2])) # Output: 8

6. Sum of Digits

def sum_of_digits(n):
return sum(int(digit) for digit in str(abs(n))) # Convert to string and
sum digits

# Example
print(sum_of_digits(123)) # Output: 6

7. Count Vowels in a String

def count_vowels(s):
vowels = "aeiouAEIOU"
return sum(1 for char in s if char in vowels)

# Example
print(count_vowels("hello world")) # Output: 3

8. Palindrome Check

def is_palindrome(s):
return s == s[::-1]

# Example
print(is_palindrome("racecar")) # Output: True
print(is_palindrome("hello")) # Output: False

9. Find the GCD (Greatest Common Divisor)

def gcd(a, b):


while b:
a, b = b, a % b
return a

# Example
print(gcd(48, 18)) # Output: 6

10. Unique Elements in a List

def unique_elements(lst):
return list(set(lst)) # Convert list to set to remove duplicates

# Example
print(unique_elements([1, 2, 2, 3, 4, 4, 5])) # Output: [1, 2, 3, 4, 5]

LOOPS (For, While)

TASK

1. Print Numbers from 1 to N

Write a function print_numbers(n) that prints numbers from 1 to n using


both for and while loops.
💡 Example: print_numbers(5) should print:

1
2
3
4
5

2. Sum of First N Natural Numbers

Write a function sum_natural(n) that returns the sum of the first n


natural numbers using both for and while loops.
💡 Example: sum_natural(5) → 15 (1 + 2 + 3 + 4 + 5)
3. Reverse a Number

Write a function reverse_number(n) that takes an integer n and returns


its reverse using a while loop.
💡 Example: reverse_number(1234) → 4321

4. Multiplication Table of a Number

Write a function multiplication_table(n, limit) that prints the


multiplication table of n up to limit using a for loop.
💡 Example: multiplication_table(3, 5) should print:

3x1=3
3x2=6
3x3=9
3 x 4 = 12
3 x 5 = 15

5. Count Digits in a Number

Write a function count_digits(n) that returns the number of digits in an


integer using a while loop.
💡 Example: count_digits(12345) → 5

SOLUTION

1. Print Numbers from 1 to N

Using a for loop and a while loop


def print_numbers_for(n):
for i in range(1, n + 1):
print(i)

# Using a while loop


def print_numbers_while(n):
i=1
while i <= n:
print(i)
i += 1

# Example
print("Using for loop:")
print_numbers_for(5)
print("Using while loop:")
print_numbers_while(5)

Output:

Using for loop:


1
2
3
4
5
Using while loop:
1
2
3
4
5
2. Sum of First N Natural Numbers

Using a for loop and a while loop

# Using a for loop


def sum_natural_for(n):
total = 0
for i in range(1, n + 1):
total += i
return total

# Using a while loop


def sum_natural_while(n):
total = 0
i=1
while i <= n:
total += i
i += 1
return total

# Example
print(sum_natural_for(5)) # Output: 15
print(sum_natural_while(5)) # Output: 15

3. Reverse a Number (Using a While Loop)

def reverse_number(n):
reversed_num = 0
while n > 0:
digit = n % 10
reversed_num = reversed_num * 10 + digit
n //= 10
return reversed_num
# Example
print(reverse_number(1234)) # Output: 4321

4. Multiplication Table of a Number (Using a For Loop)

def multiplication_table(n, limit):


for i in range(1, limit + 1):
print(f"{n} x {i} = {n * i}")

# Example
multiplication_table(3, 5)

Output:

3x1=3
3x2=6
3x3=9
3 x 4 = 12
3 x 5 = 15

5. Count Digits in a Number (Using a While Loop)

def count_digits(n):
count = 0
while n > 0:
n //= 10
count += 1
return count

# Example
print(count_digits(12345)) # Output: 5

You might also like