-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday31_speakPython20.py
More file actions
146 lines (96 loc) Β· 3.19 KB
/
Copy pathday31_speakPython20.py
File metadata and controls
146 lines (96 loc) Β· 3.19 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
"""π§ Day 31 β Speak Python 20
Phase 6: Balanced Learning (Recursion + Core Topics + Debugging + Mini Project)"""
"""β
Problem Set
π Recursion (2 problems)
1. Sum of Digits
Write a recursive function that takes an integer and returns the sum of its digits.
Input: 1234 β Output: 10 (1+2+3+4)"""
def sum_digits(d):
if d // 10 == 0:
return d
return (d % 10) + sum_digits(d // 10)
print(sum_digits(565))
print(sum_digits(1234))
"""2. Palindrome Check (Recursive)
Write a recursive function to check if a string is a palindrome.
# Input: "madam" β True
# Input: "python" β False"""
def is_palindrom(s):
if len(s) <= 1:
return True
elif s[0] != s[-1]:
return False
return is_palindrom(s[1:-1])
print(is_palindrom("madam"))
print(is_palindrom("python"))
"""β‘ Other Concepts (2 problems)
3. Lambda + Filter
Use lambda and filter() to filter only the even numbers from a list."""
nums = [5, 12, 17, 18, 24, 32]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)
"""4. JSON File Handling
Save a Python dictionary into a file in JSON format, then load it back and print it."""
import json
student = {"name": "Jisan", "age": 20, "skills": ["Python", "Git", "OOP"]}
def write_json(filename, obj, indent=2):
with open(filename, "w") as f:
json.dump(obj, f, indent=indent)
write_json("student.json", student)
# this for testing
write_json("test.json", student, indent=4)
def read_json(filename):
with open(filename, "r") as f:
return json.load(f)
data = read_json("student.json")
print(data)
print(data.get("name"))
print(data.get("age"))
print(data.get("skills")[2])
"""π οΈ Debugging Task
5. Recursive Factorial Bug Fix
Debug the following code (the base case is wrong):
def fact(n):
if n == 0:
return 0
return n * fact(n-1)
print(fact(5)) # Expected: 120"""
# fixed code:
def fact(n):
if n == 0:
return 1
return n * fact(n-1)
print(fact(5))
"""π Mini Project
6. Expense Tracker (File Handling + OOP)
Create a class ExpenseTracker.
Features:
add_expense(name, amount) β add an expense (save it to file)
view_expenses() β show all expenses
total_expense() β calculate the total amount
Save each entry in JSON format in a file."""
class ExpenseTracker:
def __init__(self):
self.exp_amount = []
self.expenses = {}
def add_expense(self, name, amount):
self.expenses.update({name: amount})
# i alrady writed this function 'write_json()' in problam 4
write_json("expenses.json", self.expenses)
self.exp_amount.append(amount)
def view_expenses(self):
# i alrady writed this function 'read_json()' in problam 4.
data = read_json("expenses.json")
print("Your Expenses:")
for exp, amount in data.items():
print(f"{exp}: {amount}")
def total_expenses(self):
return sum(self.exp_amount)
ts = ExpenseTracker()
ts.add_expense("cake", 50)
ts.add_expense("cokies", 45)
ts.add_expense("biskit", 34)
ts.add_expense("speed", 25)
ts.add_expense("coffi", 275)
ts.view_expenses()
print(ts.total_expenses())