-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday26_speakPython15.py
More file actions
111 lines (78 loc) · 1.92 KB
/
Copy pathday26_speakPython15.py
File metadata and controls
111 lines (78 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
"""🧠 **Day 26 – Speak Python 15**
### **Phase 4: Problem Solving with Recursion & Thinking Smart**
**Focus Areas:**
* Classic Recursion Problems
* Backtracking Basics
* Recursion vs Iteration
"""
"""✅ Problem 1: Power Function with Recursion
📌 **Task:**
Write a recursive function to calculate `a^b`.
📎 **Example:**
```python
power(2, 3) ➞ 8
power(5, 0) ➞ 1
```
💡 **Hint:**
`a^b = a \* a^(b-1)` with base case `power(a,0)=1`."""
def power(a, b):
if b == 0:
return 1
return a * power(a, b-1)
print(power(2, 3))
print(power(4, 3))
print(power(5, 0))
"""✅ Problem 2: Count Digits using Recursion
📌 **Task:**
Write a recursive function that counts digits in a number.
📎 **Example:**
```python
count\_digits(12345) ➞ 5
count\_digits(7) ➞ 1
```
💡 **Hint:**
`count\_digits(n) = 1 + count\_digits(n//10)` until `n==0`."""
def count_digits(n):
if n == 0:
return 0
return 1 + count_digits(n//10)
print(count_digits(1345))
print(count_digits(12345))
print(count_digits(7))
"""✅ Problem 3: Greatest Common Divisor (GCD)
📌 **Task:**
Find GCD of two numbers using recursion.
📎 **Example:**
```python
gcd(48, 18) ➞ 6
```
💡 **Hint:**
Use Euclidean Algorithm:
`gcd(a,b) = gcd(b, a%b)` with base `gcd(a,0)=a`.
"""
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
print(gcd(48, 18))
print(gcd(12, 18))
"""✅ Problem 4: Palindrome Check with Recursion
📌 **Task:**
Check if a string is palindrome using recursion.
📎 **Example:**
```python
is\_palindrome("madam") ➞ True
is\_palindrome("hello") ➞ False
```
💡 **Hint:**
Check first and last character, then recurse on the substring.
"""
def is_palindrome(s):
if len(s) == 0 or len(s) == 1:
return True
elif s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
print(is_palindrome("madam"))
print(is_palindrome("hello"))
print(is_palindrome("racecar"))