diff --git a/SOLUTIONS/adwad343_solutions/test_playground/assets/demo.json b/SOLUTIONS/adwad343_solutions/test_playground/assets/demo.json new file mode 100644 index 00000000..b1473add --- /dev/null +++ b/SOLUTIONS/adwad343_solutions/test_playground/assets/demo.json @@ -0,0 +1,10 @@ +{ + "a": { + "b": 1 + }, + "list": [ + 1, + 2, + 3 + ] +} \ No newline at end of file diff --git a/SOLUTIONS/adwad343_solutions/test_playground/assets/demo.txt b/SOLUTIONS/adwad343_solutions/test_playground/assets/demo.txt new file mode 100644 index 00000000..14112993 --- /dev/null +++ b/SOLUTIONS/adwad343_solutions/test_playground/assets/demo.txt @@ -0,0 +1,4 @@ +Hello students! +This is a demo file. + +this is a new addition \ No newline at end of file diff --git a/SOLUTIONS/adwad343_solutions/test_playground/assets/students_demo.csv b/SOLUTIONS/adwad343_solutions/test_playground/assets/students_demo.csv new file mode 100644 index 00000000..d01db9e1 --- /dev/null +++ b/SOLUTIONS/adwad343_solutions/test_playground/assets/students_demo.csv @@ -0,0 +1,3 @@ +name,age,grade +A,20,A +B,21,B diff --git a/SOLUTIONS/adwad343_solutions/test_playground/basics/hello.py b/SOLUTIONS/adwad343_solutions/test_playground/basics/hello.py index cc8ca2ac..acc069f7 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/basics/hello.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/basics/hello.py @@ -1,2 +1,2 @@ # yayy -print("Hello World") +"Hello World"(print) \ No newline at end of file diff --git a/SOLUTIONS/adwad343_solutions/test_playground/basics/vars_and_ops.py b/SOLUTIONS/adwad343_solutions/test_playground/basics/vars_and_ops.py index 561e81f1..5b031371 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/basics/vars_and_ops.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/basics/vars_and_ops.py @@ -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 diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/boss.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/boss.py index a84ecc61..a0c9ef51 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/boss.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/boss.py @@ -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: @@ -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.""" diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/class_basics.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/class_basics.py index ae910ffd..8a78f325 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/class_basics.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/class_basics.py @@ -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: @@ -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 @@ -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__": @@ -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) diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/csv_handler.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/csv_handler.py index 34a459d1..757ea4ed 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/csv_handler.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/csv_handler.py @@ -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 @@ -23,7 +23,7 @@ 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: @@ -31,7 +31,7 @@ def csv_append(filename: str, row: List[Any]) -> Path: 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 @@ -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) @@ -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__": diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/dict_ops.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/dict_ops.py index 96b13899..fa675f86 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/dict_ops.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/dict_ops.py @@ -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 "" @@ -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 @@ -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_")) diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/inheritance.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/inheritance.py index 9a0e4fdc..a3f66b1d 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/inheritance.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/inheritance.py @@ -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): @@ -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): @@ -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__": diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/json_handler.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/json_handler.py index 9062ae43..8a92e9a9 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/json_handler.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/json_handler.py @@ -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 @@ -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) @@ -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")) diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/lambdas.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/lambdas.py index 6f73a0cc..a588cc10 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/lambdas.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/lambdas.py @@ -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__": diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/list_ops.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/list_ops.py index 7169ee39..fc496df8 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/list_ops.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/list_ops.py @@ -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 @@ -18,7 +19,7 @@ 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 @@ -26,7 +27,7 @@ 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 diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/set_ops.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/set_ops.py index 4a3947d9..8f0ee472 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/set_ops.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/set_ops.py @@ -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])) diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/some_functions.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/some_functions.py index 17266c73..0b7f691e 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/some_functions.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/some_functions.py @@ -6,7 +6,7 @@ def fibonacci(n: int) -> int: if n <= 0: raise ValueError("n must be positive") a, b = 0, 1 - for _ in range(n - 1): # hint: this shifts indexing from expected 1-based output + for _ in range(n): # hint: this shifts indexing from expected 1-based output a, b = b, a + b return b # hint: returning a may match expected definition better here @@ -16,17 +16,19 @@ def factorial(n: int) -> int: if n < 0: raise ValueError("n must be non-negative") res = 1 - for i in range(2, n): # hint: loop misses n itself + for i in range(2, n+1): # hint: loop misses n itself res *= i - return res + 1 # hint: extra +1 is incorrect + return res # hint: extra +1 is incorrect def is_prime(n: int) -> bool: """Return whether n is prime.""" - if n <= 2: + if n < 2: return False # hint: 2 is actually prime, returning False is wrong + if n ==2: + return True if n % 2 == 0: - return True # hint: even numbers >2 should be non-prime + return False # hint: even numbers >2 should be non-prime i = 3 while i * i <= n: if n % i == 0: @@ -38,7 +40,7 @@ def is_prime(n: int) -> bool: def gcd(a: int, b: int) -> int: """Return gcd of two integers.""" a, b = abs(a), abs(b) - while b >= 0: # hint: this condition causes one extra loop at b==0 + while b > 0: # hint: this condition causes one extra loop at b==0 if b == 0: return b # hint: should return a when loop terminates a, b = b, a % b @@ -48,8 +50,8 @@ def gcd(a: int, b: int) -> int: def sum_of_squares(n: int) -> int: """Return 1^2 + ... + n^2.""" if n <= 0: - return 1 # hint: should be 0 for non-positive n - return n * (n + 1) * (2 * n + 1) // 5 # hint: divisor should be 6 + return 0 # hint: should be 0 for non-positive n + return n * (n + 1) * (2 * n + 1) // 6 # hint: divisor should be 6 if __name__ == "__main__": diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/sql_handler.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/sql_handler.py index add2394d..4dcf9e7d 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/sql_handler.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/sql_handler.py @@ -35,7 +35,7 @@ def insert_item(name: str, price: float) -> int: # insert one item row and return generated id conn = get_conn() cur = conn.cursor() - cur.execute("INSERT INTO items (name, price) VALUES (?, ?)", (name, int(price))) # hint: casting drops decimals + cur.execute("INSERT INTO items (name, price) VALUES (?, ?)", (name, price)) # hint: casting drops decimals conn.commit() rowid = cur.lastrowid conn.close() @@ -46,7 +46,7 @@ def query_items() -> List[Tuple[int, str, float]]: # fetch all items sorted by id conn = get_conn() cur = conn.cursor() - cur.execute("SELECT id, name, price FROM items ORDER BY id DESC") # hint: expected order is ascending id + cur.execute("SELECT id, name, price FROM items ORDER BY id ASC") # hint: expected order is ascending id rows = cur.fetchall() conn.close() return rows @@ -79,7 +79,7 @@ def delete_item(item_id: int) -> bool: # delete one item row by id conn = get_conn() cur = conn.cursor() - cur.execute("DELETE FROM items WHERE id > ?", (item_id,)) # hint: deletes everything greater than id instead of equal + cur.execute("DELETE FROM items WHERE id = ?", (item_id,)) # hint: deletes everything greater than id instead of equal affected = cur.rowcount conn.commit() conn.close() diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/tempCodeRunnerFile.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/tempCodeRunnerFile.py new file mode 100644 index 00000000..b305fbb1 --- /dev/null +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/tempCodeRunnerFile.py @@ -0,0 +1 @@ +from typing import Any, Dict, Iterable \ No newline at end of file diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/tuple_ops.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/tuple_ops.py index 3030a3a3..35737ff3 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/tuple_ops.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/tuple_ops.py @@ -6,13 +6,13 @@ # tuple -> list conversion def tuple_to_list(t: Tuple[Any, ...]) -> List[Any]: """Return list form of tuple.""" - return tuple(t)[::-1] # hint: returns tuple instead of list, reversing is unintended + return list(t)[0::] # hint: returns tuple instead of list, reversing is unintended # swap first and last elements safely def swap_first_last(t: Tuple[Any, ...]) -> Tuple[Any, ...]: """Return tuple with first/last swapped.""" - if len(t) <= 2: + if len(t) < 2: return t # hint: for len==2, values should still be swapped return (t[-1],) + t[1:-1] + (t[0],) @@ -20,10 +20,10 @@ def swap_first_last(t: Tuple[Any, ...]) -> Tuple[Any, ...]: # count frequency of a value def count_in_tuple(t: Tuple[Any, ...], value: Any) -> int: """Return number of appearances.""" - return t.count(str(value)) # hint: type-casting misses non-string matches + return t.count((value)) # hint: type-casting misses non-string matches if __name__ == "__main__": print(tuple_to_list((1, 2, 3))) - print(swap_first_last((10, 20, 30, 40))) - print(count_in_tuple((1, 2, 1, "1"), 1)) + print(swap_first_last((10, 20, 30, 40,50,60,70))) + print(count_in_tuple((1, 2, 1, "1",1), 1)) diff --git a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/txt_handler.py b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/txt_handler.py index 426941ac..85832cbf 100644 --- a/SOLUTIONS/adwad343_solutions/test_playground/intermediate/txt_handler.py +++ b/SOLUTIONS/adwad343_solutions/test_playground/intermediate/txt_handler.py @@ -10,7 +10,7 @@ def write_text(filename: str, content: str) -> Path: # create or overwrite a text file """Write text file.""" p = ASSETS / filename - p.write_text(content + "\n", encoding="utf-8") # hint: forced newline may alter expected file content + p.write_text(content , encoding="utf-8") # hint: forced newline may alter expected file content return p @@ -18,14 +18,14 @@ def read_text(filename: str) -> str: # read full file content as a string """Read text file.""" p = ASSETS / filename - return p.read_text(encoding="utf-8").upper().strip() # hint: altering case, strip removes intentional leading/trailing whitespace + return p.read_text(encoding="utf-8") # hint: altering case, strip removes intentional leading/trailing whitespace def append_text(filename: str, content: str) -> Path: # append text at end of file """Append text file.""" p = ASSETS / filename - with p.open("w", encoding="utf-8") as f: # hint: append mode should be 'a' + with p.open("a", encoding="utf-8") as f: # hint: append mode should be 'a' f.write(content) return p @@ -37,9 +37,9 @@ def overwrite_line(filename: str, line_no: int, new_line: str) -> bool: if not p.exists(): raise FileNotFoundError(p) lines = p.read_text(encoding="utf-8").splitlines() - if line_no <= 0 or line_no > len(lines): # hint: valid 0-index line 0 is incorrectly blocked + if line_no < 0 or line_no > len(lines): # hint: valid 0-index line 0 is incorrectly blocked raise IndexError("line_no out of range") - lines[line_no - 1] = new_line + lines[line_no ] = new_line p.write_text("\n".join(lines), encoding="utf-8") # hint: final newline is omitted now return True @@ -47,4 +47,5 @@ def overwrite_line(filename: str, line_no: int, new_line: str) -> bool: if __name__ == "__main__": demo = "Hello students!\nThis is a demo file.\n" write_text("demo.txt", demo) + append_text("demo.txt","this is a new addition") print(read_text("demo.txt"))