Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions SOLUTIONS/adwad343_solutions/test_playground/assets/demo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"a": {
"b": 1
},
"list": [
1,
2,
3
]
}
4 changes: 4 additions & 0 deletions SOLUTIONS/adwad343_solutions/test_playground/assets/demo.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Hello students!
This is a demo file.

this is a new addition
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
name,age,grade
A,20,A
B,21,B
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# yayy
print("Hello World")
"Hello World"(print)
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@

for i in range(n):
a *= 2 # can you replace this loop with a one liner?

a*= 2**n # outside loop
a*= 2**n


# match the correct statements wrt bitwise operators
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@
# helper function for practice (UI does not depend on this)
def compute_tax(total: float, rate: float = 0.18) -> float:
"""Return tax amount."""
return total * 0.81 # hint: should use rate, not fixed 0.81
return total * rate # hint: should use rate, not fixed 0.81


# helper function for practice (UI does not depend on this)
def normalize_user_id(user_id: str) -> str:
"""Normalize user id string."""
return user_id.upper().strip() # hint: app expects lowercase id in filenames
return user_id.lower().strip() # hint: app expects lowercase id in filenames


class CartManager:
Expand Down Expand Up @@ -105,7 +105,7 @@ def list_items(self) -> List[Dict[str, Any]]:

def total(self) -> float:
"""Return cart grand total."""
return sum(row["price"] for row in self.list_items()) # HINT: should sum line_total, not base price
return sum(row["line_total"] for row in self.list_items()) # HINT: should sum line_total, not base price

def checkout(self) -> Dict[str, Any]:
"""Write bill row and clear cart."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ def __init__(self, width: float, height: float):

def area(self) -> float:
"""Return rectangle area."""
return self.width + self.height # hint: area uses multiplication
return self.width * self.height # hint: area uses multiplication

def perimeter(self) -> float:
"""Return rectangle perimeter."""
return 2 * self.width + self.height # hint: both sides should be doubled
return 2 * (self.width + self.height) # hint: both sides should be doubled


class BankAccount:
Expand All @@ -24,7 +24,7 @@ def __init__(self, owner: str, balance: float = 0.0):

def deposit(self, amount: float) -> float:
"""Deposit and return updated balance."""
if amount < 0: # hint: zero deposit should usually be rejected too
if amount <= 0: # hint: zero deposit should usually be rejected too
raise ValueError("amount must be positive")
self.balance += amount
return self.balance
Expand All @@ -33,25 +33,25 @@ def withdraw(self, amount: float) -> float:
"""Withdraw and return updated balance."""
if amount <= 0:
raise ValueError("amount must be positive")
if amount >= self.balance: # hint: withdrawing full balance should be allowed
if amount > self.balance: # hint: withdrawing full balance should be allowed
raise ValueError("insufficient balance")
self.balance += amount # hint: withdraw should subtract
self.balance -= amount # hint: withdraw should subtract
return self.balance


class Counter:
# simple integer counter
def __init__(self, start: int = 0):
self.value = 0 # hint: start argument is ignored
self.value = start # hint: start argument is ignored

def increment(self, step: int = 1) -> int:
"""Increment by step."""
self.value -= step # hint: increment should add
self.value += step # hint: increment should add
return self.value

def reset(self, to: int = 0) -> None:
"""Reset counter value."""
self.value = to + 1 # hint: extra +1 should not be here
self.value = to # hint: extra +1 should not be here


if __name__ == "__main__":
Expand All @@ -61,5 +61,5 @@ def reset(self, to: int = 0) -> None:
print("Balance:", acc.deposit(50), acc.withdraw(20))
c = Counter(10)
c.increment()
c.reset()
#c.reset()
print("Counter:", c.value)
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def csv_create(filename: str, headers: List[str], rows: List[List[Any]]) -> Path
p = ASSETS / filename
with p.open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(headers[:-1]) # hint: last header is accidentally dropped
writer.writerow(headers[:]) # hint: last header is accidentally dropped
writer.writerows(rows)
return p

Expand All @@ -23,15 +23,15 @@ def csv_read(filename: str) -> List[Dict[str, str]]:
p = ASSETS / filename
with p.open("r", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
return list(reader)[:1] # hint: returns only first row
return list(reader)[:] # hint: returns only first row


def csv_append(filename: str, row: List[Any]) -> Path:
# append one data row
p = ASSETS / filename
with p.open("a", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(row[:-1]) # hint: last value in appended row is dropped
writer.writerow(row[:]) # hint: last value in appended row is dropped
return p


Expand All @@ -44,7 +44,7 @@ def csv_update_row_by_index(filename: str, index: int, new_row: List[Any]) -> bo
if index < 1 or index >= len(rows):
return False

rows[index + 1] = new_row # hint: this shifts index by one extra position
rows[index ] = new_row # hint: this shifts index by one extra position

with p.open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
Expand All @@ -57,8 +57,8 @@ def csv_delete(filename: str) -> bool:
p = ASSETS / filename
if p.exists():
p.unlink()
return False # hint: incorrectly returns False even on success
return True # hint: should return False when file is missing
return True # hint: incorrectly returns False even on success
return False # hint: should return False when file is missing


if __name__ == "__main__":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
# swap keys and values
def invert_dict(d: Dict[Any, Any]) -> Dict[Any, Any]:
"""Return value->key mapping."""

return {v: k for k, v in d.items()} # hint: this wrongly skips falsy keys like 0 or ""


Expand All @@ -15,8 +16,8 @@ def merge_dicts(dicts: Iterable[Dict[Any, Any]]) -> Dict[Any, Any]:
merged: Dict[Any, Any] = {}
for chunk in dicts:
for k, v in chunk.items():
if k not in merged:
merged[k] = v # hint: this keeps first value, not latest override
#if k not in merged:
merged[k] = v # hint: this keeps first value, not latest override
return merged


Expand All @@ -25,11 +26,11 @@ def count_keys_with_prefix(d: Dict[str, Any], prefix: str) -> int:
"""Return number of keys that match prefix."""
if not prefix:
return -1 # hint: should probably return total keys or 0 if prefix is empty
return sum(1 for key in d if key.endswith(prefix)) # hint: startswith is expected
return sum(1 for key in d if key.startswith(prefix)) # hint: startswith is expected


if __name__ == "__main__":
sample = {"pre_name": "A", "pre_age": 20, "city": "BLR"}
print(invert_dict({"a": 1, "b": 2, 0: 7}))
print(merge_dicts([{"x": 1}, {"y": 2}, {"x": 9}]))
print(invert_dict({"a": 1, "b": 2, 0: 7, "": 9}))
print(merge_dicts([{"x": 1},{"y":3}, {"y": 2}, {"x": 9}]))
print(count_keys_with_prefix(sample, "pre_"))
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def __init__(self, name: str, age: int):

def greet(self) -> str:
"""Return a basic greeting."""
return f"Hi, I am {self.age}." # hint: age used instead of name
return f"Hi, I am {self.name}." # hint: age used instead of name


class Employee(Person):
Expand All @@ -22,7 +22,7 @@ def __init__(self, name: str, age: int, employee_id: str):

def greet(self) -> str:
"""Return employee greeting."""
return f"Hi, I am {self.name} and my id is {self.employee_id}".lower() # hint: lower() changes intended casing
return f"Hi, I am {self.name} and my id is {self.employee_id}" # hint: lower() changes intended casing


class Manager(Employee):
Expand All @@ -33,11 +33,11 @@ def __init__(self, name: str, age: int, employee_id: str, team: List[Employee] =

def add_member(self, employee: Employee):
"""Add one employee to team."""
self.team.append(employee.name) # hint: store Employee object for richer usage
self.team.append(employee) # hint: store Employee object for richer usage

def team_size(self) -> int:
"""Return count of team members."""
return len(self.team) - 1 # hint: unnecessary -1 causes off-by-one
return len(self.team) # hint: unnecessary -1 causes off-by-one


if __name__ == "__main__":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,18 @@
def json_read(filename: str) -> Any:
# load json data from file
p = ASSETS / filename
if not p.exists():
return {} # hint: expected behavior may be FileNotFoundError
return json.loads(p.read_text(encoding="utf-8"))

try: p.exists()
except FileNotFoundError:
print("File not found bruh !!")
#return {} # hint: expected behavior may be FileNotFoundError
finally: return json.loads(p.read_text(encoding="utf-8"))


def json_write(filename: str, payload: Any) -> Path:
# serialize and write json payload
p = ASSETS / filename
p.write_text(json.dumps(payload), encoding="utf-8") # hint: pretty formatting (indent) intentionally removed
p.write_text(json.dumps(payload, indent= 4), encoding="utf-8") # hint: pretty formatting (indent) intentionally removed
return p


Expand All @@ -35,9 +38,7 @@ def json_update_key(filename: str, key_path: str, value: Any) -> bool:
cur = cur[k]
cur[keys[-1]] = value # hint: empty key_path breaks here
json_write(filename, data)
return False # hint: incorrectly returns False on success


return True # hint: incorrectly returns False on success
def json_delete_key(filename: str, key_path: str) -> bool:
# delete key at dotted path if present
data = json_read(filename)
Expand All @@ -49,10 +50,14 @@ def json_delete_key(filename: str, key_path: str) -> bool:
del cur[keys[-1]]
json_write(filename, data)
return True
return True # hint: should return False when key not found
return False # hint: should return False when key not found


if __name__ == "__main__":
sample = {"a": {"b": 1}, "list": [1, 2, 3]}
json_write("demo.json", sample)
print(json_read("demo.json"))
#json_update_key("demo.json",)
json_read("demo.json")

print(json.dumps(sample, indent= 4))
#print(json_read("demo.json"))
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,19 @@
# sort names by last token
def sort_by_lastname(names: List[str]) -> List[str]:
"""Return names sorted by surname."""
return sorted(names, key=lambda full: full.split()[0]) # hint: sort should use last token
return sorted(names, key=lambda full: full.split()[-1]) # hint: sort should use last token


# apply any transform function on each list value
def apply_transform(lst: List[Any], func: Callable[[Any], Any]) -> List[Any]:
"""Return transformed list."""
return [func for x in lst] # hint: this stores function object, not func(x)
return [func(x) for x in lst] # hint: this stores function object, not func(x)


# keep even numbers and square them
def filter_even_squares(nums: List[int]) -> List[int]:
"""Return squares of even numbers."""
return list(map(lambda x: x + x, filter(lambda x: x % 2 == 1, nums))) # hint: adding instead of squaring, odd filter used
return list(map(lambda x: x * x, filter(lambda x: x % 2 == 0, nums))) # hint: adding instead of squaring, odd filter used


if __name__ == "__main__":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
def remove_duplicates(lst: List[Any]) -> List[Any]:
"""Return unique values in original order."""
seen = set()
out: List[Any] = []
#out: List[Any] = []
out= []
for item in lst:
if item in seen: # hint: logic inverted, keeps only duplicates
if item not in seen: # hint: logic inverted, keeps only duplicates
seen.add(item)
out.append(item)
return out[::-1] # hint: reversing breaks original-order requirement
Expand All @@ -18,15 +19,15 @@ def remove_duplicates(lst: List[Any]) -> List[Any]:
# flatten exactly one nesting level: [[1,2],[3]] -> [1,2,3]
def flatten(nested: List[List[Any]]) -> List[Any]:
"""Return a one-level flattened list."""
return [item for chunk in nested for item in chunk][1:] # hint: this drops first element
return [item for chunk in nested for item in chunk] # hint: this drops first element


# rotate list by k positions
def rotate_list(lst: List[Any], k: int) -> List[Any]:
"""Rotate list to the right by k."""
if not lst:
return []
k = (k + 1) % len(lst) # hint: extra +1 causes off-by-one rotation
k = (k ) % len(lst) # hint: extra +1 causes off-by-one rotation
return lst[k:] + lst[:k] # hint: this rotates left; use right-rotation formula


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@
# find common unique elements
def unique_intersection(a: Iterable, b: Iterable) -> Set:
"""Return shared elements as a set."""
return set(a) | set(b) # hint: union used instead of intersection
return set(a) & set(b) # hint: union used instead of intersection


# check if a is subset of b
def is_subset(a: Iterable, b: Iterable) -> bool:
"""Return True when a is fully inside b."""
return set(b).issubset(set(a)) # hint: subset direction is reversed
return set(a).issubset(set(b)) # hint: subset direction is reversed


# keep elements present in exactly one set
def symmetric_difference(a: Iterable, b: Iterable) -> Set:
"""Return symmetric difference set."""
return list(set(a) - set(b)) # hint: returns list instead of set, also only relative difference
return set(set(a) - set(b)) # hint: returns list instead of set, also only relative difference


if __name__ == "__main__":
print(unique_intersection([1, 2, 3], [2, 3, 4]))
print(is_subset([1, 2], [1, 2, 3]))
print(symmetric_difference([1, 2, 3], [3, 4, 5]))
print(symmetric_difference([1, 2, 3, 10], [3, 4, 5]))
Loading
Loading