From 0cf4afc46e4792ba1995bb0880bebc8371c475d5 Mon Sep 17 00:00:00 2001 From: mervereis Date: Mon, 27 Jul 2026 22:55:37 +0100 Subject: [PATCH 1/5] Implement cat, ls, and wc commands with line, word, and byte counting features --- implement-shell-tools/cat/cat.js | 50 +++++++++++++++++++ implement-shell-tools/ls/ls.js | 52 ++++++++++++++++++++ implement-shell-tools/wc/wc.js | 82 ++++++++++++++++++++++++++++++++ 3 files changed, 184 insertions(+) create mode 100644 implement-shell-tools/cat/cat.js create mode 100644 implement-shell-tools/ls/ls.js create mode 100644 implement-shell-tools/wc/wc.js diff --git a/implement-shell-tools/cat/cat.js b/implement-shell-tools/cat/cat.js new file mode 100644 index 000000000..cabd33ee2 --- /dev/null +++ b/implement-shell-tools/cat/cat.js @@ -0,0 +1,50 @@ +const fs = require("fs"); + +const args = process.argv.slice(2); + +let numberLines = false; +let numberNonBlank = false; +const files = []; + +for (const arg of args) { + if (arg === "-n") { + numberLines = true; + } else if (arg === "-b") { + numberNonBlank = true; + } else { + files.push(arg); + } +} + +if (numberNonBlank) { + numberLines = false; +} + +let lineNumber = 1; + +for (const file of files) { + try { + const contents = fs.readFileSync(file, "utf8"); + const lines = contents.split("\n"); + + lines.forEach((line, index) => { + const output = index < lines.length - 1 ? line + "\n" : line; + + if (numberNonBlank) { + if (line.trim() === "") { + process.stdout.write(output); + } else { + process.stdout.write(`${String(lineNumber).padStart(6)}\t${output}`); + lineNumber++; + } + } else if (numberLines) { + process.stdout.write(`${String(lineNumber).padStart(6)}\t${output}`); + lineNumber++; + } else { + process.stdout.write(output); + } + }); + } catch (err) { + console.error(`cat: ${file}: ${err.message}`); + } +} diff --git a/implement-shell-tools/ls/ls.js b/implement-shell-tools/ls/ls.js new file mode 100644 index 000000000..01c4ded03 --- /dev/null +++ b/implement-shell-tools/ls/ls.js @@ -0,0 +1,52 @@ +const fs = require("fs"); + +const args = process.argv.slice(2); + +let onePerLine = false; +let showHidden = false; +let paths = []; + +for (let i = 0; i < args.length; i++) { + if (args[i] === "-1") { + onePerLine = true; + } else if (args[i] === "-a") { + showHidden = true; + } else { + paths.push(args[i]); + } +} +if (paths.length === 0) { + paths.push("."); +} + +for (let i = 0; i < paths.length; i++) { + let path = paths[i]; + + try { + if (fs.statSync(path).isFile()) { + console.log(path); + } else { + let files = fs.readdirSync(path); + + files.sort(); + + for (let j = 0; j < files.length; j++) { + let file = files[j]; + if (!showHidden && file.startsWith(".")) { + continue; + } + if (onePerLine) { + console.log(file); + } else { + process.stdout.write(file + " "); + } + } + + if (!onePerLine) { + console.log(); + } + } + } catch (error) { + console.log("Cannot access: " + path); + } +} diff --git a/implement-shell-tools/wc/wc.js b/implement-shell-tools/wc/wc.js new file mode 100644 index 000000000..d54e0c02e --- /dev/null +++ b/implement-shell-tools/wc/wc.js @@ -0,0 +1,82 @@ +const fs = require("fs"); + +const args = process.argv.slice(2); + +let countLines = false; +let countWords = false; +let countBytes = false; + +let files = []; + +for (let arg of args) { + if (arg === "-l") { + countLines = true; + } else if (arg === "-w") { + countWords = true; + } else if (arg === "-c") { + countBytes = true; + } else { + files.push(arg); + } +} + +if (!countLines && !countWords && !countBytes) { + countLines = true; + countWords = true; + countBytes = true; +} + +let totalLines = 0; +let totalWords = 0; +let totalBytes = 0; +let filesCounted = 0; + +function countFile(fileName) { + try { + const content = fs.readFileSync(fileName, "utf8"); + let lines = content.split("\n").length - 1; + let words = content + .trim() + .split(/\s+/) + .filter((word) => word.length > 0).length; + let bytes = Buffer.byteLength(content); + totalLines += lines; + totalWords += words; + totalBytes += bytes; + filesCounted++; + let result = ""; + if (countLines) { + result += lines + " "; + } + if (countWords) { + result += words + " "; + } + if (countBytes) { + result += bytes + " "; + } + result += fileName; + console.log(result); + } catch (error) { + console.log("Cannot read file: " + fileName); + } +} + +for (let file of files) { + countFile(file); +} + +if (filesCounted > 1) { + let result = ""; + if (countLines) { + result += totalLines + " "; + } + if (countWords) { + result += totalWords + " "; + } + if (countBytes) { + result += totalBytes + " "; + } + result += "total"; + + console.log(result); +} From 4aaf1c1c2eaad1707d32f8db01299743dd83d0ad Mon Sep 17 00:00:00 2001 From: mervereis Date: Thu, 27 Aug 2026 21:43:53 +0100 Subject: [PATCH 2/5] Refactor output handling in cat, ls, and wc commands for improved formatting --- implement-shell-tools/cat/cat.js | 8 +++++-- implement-shell-tools/ls/ls.js | 2 +- implement-shell-tools/wc/wc.js | 41 +++++++++++++------------------- 3 files changed, 23 insertions(+), 28 deletions(-) diff --git a/implement-shell-tools/cat/cat.js b/implement-shell-tools/cat/cat.js index cabd33ee2..f4a9c66b3 100644 --- a/implement-shell-tools/cat/cat.js +++ b/implement-shell-tools/cat/cat.js @@ -25,10 +25,14 @@ let lineNumber = 1; for (const file of files) { try { const contents = fs.readFileSync(file, "utf8"); - const lines = contents.split("\n"); + const hasTrailingNewline = contents.endsWith("\n"); + const lines = hasTrailingNewline + ? contents.slice(0, -1).split("\n") + : contents.split("\n"); lines.forEach((line, index) => { - const output = index < lines.length - 1 ? line + "\n" : line; + const output = + index < lines.length - 1 || hasTrailingNewline ? line + "\n" : line; if (numberNonBlank) { if (line.trim() === "") { diff --git a/implement-shell-tools/ls/ls.js b/implement-shell-tools/ls/ls.js index 01c4ded03..4874656c3 100644 --- a/implement-shell-tools/ls/ls.js +++ b/implement-shell-tools/ls/ls.js @@ -43,7 +43,7 @@ for (let i = 0; i < paths.length; i++) { } if (!onePerLine) { - console.log(); + process.stdout.write("\n"); } } } catch (error) { diff --git a/implement-shell-tools/wc/wc.js b/implement-shell-tools/wc/wc.js index d54e0c02e..11529ec11 100644 --- a/implement-shell-tools/wc/wc.js +++ b/implement-shell-tools/wc/wc.js @@ -31,6 +31,20 @@ let totalWords = 0; let totalBytes = 0; let filesCounted = 0; +function formatResult(lines, words, bytes, fileName) { + let result = ""; + if (countLines) { + result += String(lines).padStart(8); + } + if (countWords) { + result += String(words).padStart(8); + } + if (countBytes) { + result += String(bytes).padStart(8); + } + return result + " " + fileName; +} + function countFile(fileName) { try { const content = fs.readFileSync(fileName, "utf8"); @@ -44,18 +58,7 @@ function countFile(fileName) { totalWords += words; totalBytes += bytes; filesCounted++; - let result = ""; - if (countLines) { - result += lines + " "; - } - if (countWords) { - result += words + " "; - } - if (countBytes) { - result += bytes + " "; - } - result += fileName; - console.log(result); + console.log(formatResult(lines, words, bytes, fileName)); } catch (error) { console.log("Cannot read file: " + fileName); } @@ -66,17 +69,5 @@ for (let file of files) { } if (filesCounted > 1) { - let result = ""; - if (countLines) { - result += totalLines + " "; - } - if (countWords) { - result += totalWords + " "; - } - if (countBytes) { - result += totalBytes + " "; - } - result += "total"; - - console.log(result); + console.log(formatResult(totalLines, totalWords, totalBytes, "total")); } From b6d8da7046c39aaeca2a7f9848801c34f061e748 Mon Sep 17 00:00:00 2001 From: mervereis Date: Tue, 1 Sep 2026 22:51:10 +0100 Subject: [PATCH 3/5] Add exercises for Person class, laptop management, and user input handling --- Sprint5/exercise1.py | 3 + Sprint5/exercise10.py | 89 ++++++++++++++++++++++++++ Sprint5/exercise11.py | 143 ++++++++++++++++++++++++++++++++++++++++++ Sprint5/exercise12.py | 57 +++++++++++++++++ Sprint5/exercise2.py | 12 ++++ Sprint5/exercise3.py | 36 +++++++++++ Sprint5/exercise4.py | 17 +++++ Sprint5/exercise5.py | 23 +++++++ Sprint5/exercise6.py | 10 +++ Sprint5/exercise7.py | 21 +++++++ Sprint5/exercise8.py | 25 ++++++++ Sprint5/exercise9.py | 26 ++++++++ 12 files changed, 462 insertions(+) create mode 100644 Sprint5/exercise1.py create mode 100644 Sprint5/exercise10.py create mode 100644 Sprint5/exercise11.py create mode 100644 Sprint5/exercise12.py create mode 100644 Sprint5/exercise2.py create mode 100644 Sprint5/exercise3.py create mode 100644 Sprint5/exercise4.py create mode 100644 Sprint5/exercise5.py create mode 100644 Sprint5/exercise6.py create mode 100644 Sprint5/exercise7.py create mode 100644 Sprint5/exercise8.py create mode 100644 Sprint5/exercise9.py diff --git a/Sprint5/exercise1.py b/Sprint5/exercise1.py new file mode 100644 index 000000000..c362071a5 --- /dev/null +++ b/Sprint5/exercise1.py @@ -0,0 +1,3 @@ +# Predict what double("22") will do. Then run the code and check. Did it do what you expected? Why did it return the value it did? +# double("22") returns "2222". +# "22" is a string, so * 2 repeats the string twice. \ No newline at end of file diff --git a/Sprint5/exercise10.py b/Sprint5/exercise10.py new file mode 100644 index 000000000..41308a5ed --- /dev/null +++ b/Sprint5/exercise10.py @@ -0,0 +1,89 @@ +#Try changing the type annotation of Person.preferred_operating_system from str to List[str]. +#Run mypy on the code. +#It tells us different places that our code is now wrong, because we’re passing values of the wrong type. +#We probably also want to rename our field - lists are plural. Rename the field to preferred_operating_systems. +#Run mypy again. +#Fix all of the places that mypy tells you need changing. Make sure the program works as you’d expect. + +from dataclasses import dataclass +from typing import List + + +@dataclass(frozen=True) +class Person: + name: str + age: int + preferred_operating_systems: List[str] + + +@dataclass(frozen=True) +class Laptop: + id: int + manufacturer: str + model: str + screen_size_in_inches: float + operating_system: str + + +def find_possible_laptops( + laptops: List[Laptop], + person: Person +) -> List[Laptop]: + possible_laptops = [] + + for laptop in laptops: + if laptop.operating_system in person.preferred_operating_systems: + possible_laptops.append(laptop) + + return possible_laptops + + +people = [ + Person( + name="Imran", + age=22, + preferred_operating_systems=["Ubuntu", "Arch Linux"] + ), + Person( + name="Eliza", + age=34, + preferred_operating_systems=["Arch Linux", "macOS"] + ), +] + + +laptops = [ + Laptop( + id=1, + manufacturer="Dell", + model="XPS", + screen_size_in_inches=13, + operating_system="Arch Linux" + ), + Laptop( + id=2, + manufacturer="Dell", + model="XPS", + screen_size_in_inches=15, + operating_system="Ubuntu" + ), + Laptop( + id=3, + manufacturer="Dell", + model="XPS", + screen_size_in_inches=15, + operating_system="ubuntu" + ), + Laptop( + id=4, + manufacturer="Apple", + model="MacBook", + screen_size_in_inches=13, + operating_system="macOS" + ), +] + + +for person in people: + possible_laptops = find_possible_laptops(laptops, person) + print(f"Possible laptops for {person.name}: {possible_laptops}") diff --git a/Sprint5/exercise11.py b/Sprint5/exercise11.py new file mode 100644 index 000000000..8ee8ea1b1 --- /dev/null +++ b/Sprint5/exercise11.py @@ -0,0 +1,143 @@ +#Write a program which: + +#Already has a list of Laptops that a library has to lend out. +#Accepts user input to create a new Person - it should use the input function to read a person’s name, age, and preferred operating system. +#Tells the user how many laptops the library has that have that operating system. +#If there is an operating system that has more laptops available, tells the user that if they’re willing to accept that operating system they’re more likely to get a laptop. +#You should convert the age and preferred operating system input from the user into more constrained types as quickly as possible, and should output errors to stderr and terminate the program with a non-zero exit code if the user input bad values. + +from dataclasses import dataclass +from enum import Enum +from typing import List +import sys + + +class OperatingSystem(Enum): + MACOS = "macOS" + ARCH = "Arch Linux" + UBUNTU = "Ubuntu" + + +@dataclass(frozen=True) +class Person: + name: str + age: int + preferred_operating_system: OperatingSystem + + +@dataclass(frozen=True) +class Laptop: + id: int + manufacturer: str + model: str + screen_size_in_inches: float + operating_system: OperatingSystem + + +def find_possible_laptops( + laptops: List[Laptop], + person: Person +) -> List[Laptop]: + possible_laptops = [] + + for laptop in laptops: + if laptop.operating_system == person.preferred_operating_system: + possible_laptops.append(laptop) + + return possible_laptops + + +laptops = [ + Laptop( + id=1, + manufacturer="Dell", + model="XPS", + screen_size_in_inches=13, + operating_system=OperatingSystem.ARCH, + ), + Laptop( + id=2, + manufacturer="Dell", + model="XPS", + screen_size_in_inches=15, + operating_system=OperatingSystem.UBUNTU, + ), + Laptop( + id=3, + manufacturer="Dell", + model="XPS", + screen_size_in_inches=15, + operating_system=OperatingSystem.UBUNTU, + ), + Laptop( + id=4, + manufacturer="Apple", + model="MacBook", + screen_size_in_inches=13, + operating_system=OperatingSystem.MACOS, + ), +] + + +name = input("What is your name? ") + +try: + age = int(input("What is your age? ")) +except ValueError: + print("Error: age must be a number.", file=sys.stderr) + sys.exit(1) + + +print("Available operating systems:") +for operating_system in OperatingSystem: + print(f"- {operating_system.value}") + +preferred_os_input = input("What is your preferred operating system? ") + +try: + preferred_operating_system = OperatingSystem(preferred_os_input) +except ValueError: + print( + f"Error: '{preferred_os_input}' is not a valid operating system.", + file=sys.stderr, + ) + sys.exit(1) + + +person = Person( + name=name, + age=age, + preferred_operating_system=preferred_operating_system, +) + + +possible_laptops = find_possible_laptops(laptops, person) + +print( + f"The library has {len(possible_laptops)} " + f"laptop(s) with {person.preferred_operating_system.value}." +) + + +laptop_counts = {} + +for laptop in laptops: + laptop_counts[laptop.operating_system] = ( + laptop_counts.get(laptop.operating_system, 0) + 1 + ) + +most_available_os = max( + laptop_counts, + key=laptop_counts.get +) + + +if ( + most_available_os != person.preferred_operating_system + and laptop_counts[most_available_os] > len(possible_laptops) +): + print( + f"There are more {most_available_os.value} laptops available. " + f"If you're willing to accept {most_available_os.value}, " + f"you're more likely to get a laptop." + ) \ No newline at end of file diff --git a/Sprint5/exercise12.py b/Sprint5/exercise12.py new file mode 100644 index 000000000..89a269db9 --- /dev/null +++ b/Sprint5/exercise12.py @@ -0,0 +1,57 @@ +person1 = Child("Elizaveta", "Alekseeva") +# Prediction: Creates instance of Child class with first name "Elizaveta" and last name "Alekseeva". +print(person1) +print(person1.first_name) +print(person1.last_name) +# Outcome: As expected. + + +print(person1.get_name()) +# Prediction: Child inherits Parent methods, therefore calls get_name method: "Elizaveta Alekseeva" +# Outcome: As expected. + +print(person1.get_full_name()) +# Prediction: Calls get_full_name on child, no previous names: "Elizaveta Alekseeva" +# Outcome: As expected. + +person1.change_last_name("Tyurina") +# Prediction: Changes last_name to "Tyurina", and previous_last_names to ["Alekseeva"], returns nothing +print(person1.last_name) +print(person1.previous_last_names) +# Outcome: As expected. + +print(person1.get_name()) +# Prediction: Child inherits Parent methods, therefore calls get_name method: "Elizaveta Alekseeva" +# Outcome: As expected. + +print(person1.get_full_name()) +# Prediction: Returns first_name last_name (née previous_last_names[0]) (original last name) +# ""Elizaveta Tyurina (née Alekseeva)" +# Outcome: As expected. + +person2 = Parent("Elizaveta", "Alekseeva") +# Prediction: Creates instance of Parent class with first name "Elizaveta" and last name "Alekseeva". +print(person2) +print(person2.first_name) +print(person2.last_name) +# Outcome: As expected. + +print(person2.get_name()) +# Prediction: Calls get_name method: "Elizaveta Alekseeva" +# Outcome: As expected. + +# print(person2.get_full_name()) +# Prediction: Parent instance has not access to Child methods, will error that there is no method of get_full_name. +# Outcome: AttributeError: 'Parent' object has no attribute 'get_full_name' + +# person2.change_last_name("Tyurina") +# Prediction: Parent instance has not access to Child methods, will error that there is no method of change_last_name. +# Outcome: AttributeError: 'Parent' object has no attribute 'change_last_name' + +print(person2.get_name()) +# Prediction: Calls get_name method: "Elizaveta Alekseeva" as name has not changed due to inability to call change_last_name +# Outcome: As expected. + +# print(person2.get_full_name()) +# Prediction: Parent instance has not access to Child methods, will error that there is no method of get_full_name. +# Outcome: AttributeError: 'Parent' object has no attribute 'get_full_name' \ No newline at end of file diff --git a/Sprint5/exercise2.py b/Sprint5/exercise2.py new file mode 100644 index 000000000..7f94657d4 --- /dev/null +++ b/Sprint5/exercise2.py @@ -0,0 +1,12 @@ +def double(number): + return number * 3 + +print(double(10)) + +# Read the above code and write down what the bug is. How would you fix it? +# Since the function is called double, it should multiply the number by 2. + +def double(number): +return number * 2 + +print(double(10)) diff --git a/Sprint5/exercise3.py b/Sprint5/exercise3.py new file mode 100644 index 000000000..516210d75 --- /dev/null +++ b/Sprint5/exercise3.py @@ -0,0 +1,36 @@ +def open_account(balances: dict[str, int], name: str, amount: int) -> None: + balances[name] = amount + + +def sum_balances(accounts: dict[str, int]) -> int: + total = 0 + for name, pence in accounts.items(): + print(f"{name} had balance {pence}") + total += pence + return total + + +def format_pence_as_string(total_pence: int) -> str: + if total_pence < 100: + return f"{total_pence}p" + + pounds = int(total_pence / 100) + pence = total_pence % 100 + + return f"£{pounds}.{pence:02d}" + + +balances = { + "Sima": 700, + "Linn": 545, + "Georg": 831, +} + +open_account(balances, "Tobi", 913) +open_account(balances, "Olya", 713) + +total_pence = sum_balances(balances) +total_string = format_pence_as_string(total_pence) + +print(f"The bank accounts total {total_string}") + diff --git a/Sprint5/exercise4.py b/Sprint5/exercise4.py new file mode 100644 index 000000000..e32fffa33 --- /dev/null +++ b/Sprint5/exercise4.py @@ -0,0 +1,17 @@ +class Person: + def __init__( + self, + name: str, + age: int, + preferred_operating_system: str, + address: str + ): + self.name = name + self.age = age + self.preferred_operating_system = preferred_operating_system + self.address = address + + imran = Person("Imran", 22, "Ubuntu", "Sheffield") +print(imran.address) + +#mypy knows what attributes a Person object is supposed to have. If you try to access an attribute that isn't defined in the class, mypy can warn you before you run the program.Adress needed to define in person object for print. \ No newline at end of file diff --git a/Sprint5/exercise5.py b/Sprint5/exercise5.py new file mode 100644 index 000000000..00675130d --- /dev/null +++ b/Sprint5/exercise5.py @@ -0,0 +1,23 @@ +class Person: + def __init__(self, name: str, age: int, preferred_operating_system: str): + self.name = name + self.age = age + self.preferred_operating_system = preferred_operating_system + + +imran = Person("Imran", 22, "Ubuntu") +print(imran.name) + +eliza = Person("Eliza", 34, "Arch Linux") +print(eliza.name) + + +def is_adult(person: Person) -> bool: + return person.age >= 18 + + +print(is_adult(imran)) + + +def get_address(person: Person) -> str: + return person.address \ No newline at end of file diff --git a/Sprint5/exercise6.py b/Sprint5/exercise6.py new file mode 100644 index 000000000..3a05a288d --- /dev/null +++ b/Sprint5/exercise6.py @@ -0,0 +1,10 @@ +#Think of the advantages of using methods instead of free functions. Write them down in your notebook. + + +#Advantages of methods over free functions: + +#Methods keep related data and behaviour together. +#They make code easier to read and understand. +#They can directly access an object's attributes using self. +#They make it clear which object is performing an action. +#They help organise and maintain larger programs. diff --git a/Sprint5/exercise7.py b/Sprint5/exercise7.py new file mode 100644 index 000000000..dd7bbddde --- /dev/null +++ b/Sprint5/exercise7.py @@ -0,0 +1,21 @@ +#Change the Person class to take a date of birth (using the standard library’s datetime.date class) and store it in a field instead of age. +#Update the is_adult method to act the same as before. + +from datetime import date + + +class Person: + def __init__(self, date_of_birth: date): + self.date_of_birth = date_of_birth + + def is_adult(self) -> bool: + today = date.today() + age = today.year - self.date_of_birth.year + + if (today.month, today.day) < ( + self.date_of_birth.month, + self.date_of_birth.day, + ): + age -= 1 + + return age >= 18 \ No newline at end of file diff --git a/Sprint5/exercise8.py b/Sprint5/exercise8.py new file mode 100644 index 000000000..04b084db5 --- /dev/null +++ b/Sprint5/exercise8.py @@ -0,0 +1,25 @@ +#Write a Person class using @datatype which uses a datetime.date for date of birth, rather than an int for age. + +#Re-add the is_adult method to it. + +from dataclasses import dataclass +from datetime import date + + +@dataclass +class Person: + name: str + date_of_birth: date + preferred_operating_system: str + + def is_adult(self) -> bool: + today = date.today() + age = today.year - self.date_of_birth.year + + if (today.month, today.day) < ( + self.date_of_birth.month, + self.date_of_birth.day, + ): + age -= 1 + + return age >= 18 \ No newline at end of file diff --git a/Sprint5/exercise9.py b/Sprint5/exercise9.py new file mode 100644 index 000000000..8510a5917 --- /dev/null +++ b/Sprint5/exercise9.py @@ -0,0 +1,26 @@ +#Fix the above code so that it works. You must not change the print on line 17 - we do want to print the children’s ages. (Feel free to invent the ages of Imran’s children.) + +from dataclasses import dataclass +from typing import List + + +@dataclass(frozen=True) +class Person: + name: str + age: int + children: List["Person"] + + +fatma = Person(name="Fatma", age=5, children=[]) +aisha = Person(name="Aisha", age=3, children=[]) + +imran = Person(name="Imran", age=30, children=[fatma, aisha]) + + +def print_family_tree(person: Person) -> None: + print(person.name) + for child in person.children: + print(f"- {child.name} ({child.age})") + + +print_family_tree(imran) \ No newline at end of file From 21a8176b03389295f70c5b04743420c04c323d24 Mon Sep 17 00:00:00 2001 From: mervereis Date: Tue, 1 Sep 2026 23:02:49 +0100 Subject: [PATCH 4/5] removed unrelated changes --- implement-shell-tools/cat/cat.js | 54 ----------------------- implement-shell-tools/ls/ls.js | 52 ----------------------- implement-shell-tools/wc/wc.js | 73 -------------------------------- 3 files changed, 179 deletions(-) delete mode 100644 implement-shell-tools/cat/cat.js delete mode 100644 implement-shell-tools/ls/ls.js delete mode 100644 implement-shell-tools/wc/wc.js diff --git a/implement-shell-tools/cat/cat.js b/implement-shell-tools/cat/cat.js deleted file mode 100644 index f4a9c66b3..000000000 --- a/implement-shell-tools/cat/cat.js +++ /dev/null @@ -1,54 +0,0 @@ -const fs = require("fs"); - -const args = process.argv.slice(2); - -let numberLines = false; -let numberNonBlank = false; -const files = []; - -for (const arg of args) { - if (arg === "-n") { - numberLines = true; - } else if (arg === "-b") { - numberNonBlank = true; - } else { - files.push(arg); - } -} - -if (numberNonBlank) { - numberLines = false; -} - -let lineNumber = 1; - -for (const file of files) { - try { - const contents = fs.readFileSync(file, "utf8"); - const hasTrailingNewline = contents.endsWith("\n"); - const lines = hasTrailingNewline - ? contents.slice(0, -1).split("\n") - : contents.split("\n"); - - lines.forEach((line, index) => { - const output = - index < lines.length - 1 || hasTrailingNewline ? line + "\n" : line; - - if (numberNonBlank) { - if (line.trim() === "") { - process.stdout.write(output); - } else { - process.stdout.write(`${String(lineNumber).padStart(6)}\t${output}`); - lineNumber++; - } - } else if (numberLines) { - process.stdout.write(`${String(lineNumber).padStart(6)}\t${output}`); - lineNumber++; - } else { - process.stdout.write(output); - } - }); - } catch (err) { - console.error(`cat: ${file}: ${err.message}`); - } -} diff --git a/implement-shell-tools/ls/ls.js b/implement-shell-tools/ls/ls.js deleted file mode 100644 index 4874656c3..000000000 --- a/implement-shell-tools/ls/ls.js +++ /dev/null @@ -1,52 +0,0 @@ -const fs = require("fs"); - -const args = process.argv.slice(2); - -let onePerLine = false; -let showHidden = false; -let paths = []; - -for (let i = 0; i < args.length; i++) { - if (args[i] === "-1") { - onePerLine = true; - } else if (args[i] === "-a") { - showHidden = true; - } else { - paths.push(args[i]); - } -} -if (paths.length === 0) { - paths.push("."); -} - -for (let i = 0; i < paths.length; i++) { - let path = paths[i]; - - try { - if (fs.statSync(path).isFile()) { - console.log(path); - } else { - let files = fs.readdirSync(path); - - files.sort(); - - for (let j = 0; j < files.length; j++) { - let file = files[j]; - if (!showHidden && file.startsWith(".")) { - continue; - } - if (onePerLine) { - console.log(file); - } else { - process.stdout.write(file + " "); - } - } - - if (!onePerLine) { - process.stdout.write("\n"); - } - } - } catch (error) { - console.log("Cannot access: " + path); - } -} diff --git a/implement-shell-tools/wc/wc.js b/implement-shell-tools/wc/wc.js deleted file mode 100644 index 11529ec11..000000000 --- a/implement-shell-tools/wc/wc.js +++ /dev/null @@ -1,73 +0,0 @@ -const fs = require("fs"); - -const args = process.argv.slice(2); - -let countLines = false; -let countWords = false; -let countBytes = false; - -let files = []; - -for (let arg of args) { - if (arg === "-l") { - countLines = true; - } else if (arg === "-w") { - countWords = true; - } else if (arg === "-c") { - countBytes = true; - } else { - files.push(arg); - } -} - -if (!countLines && !countWords && !countBytes) { - countLines = true; - countWords = true; - countBytes = true; -} - -let totalLines = 0; -let totalWords = 0; -let totalBytes = 0; -let filesCounted = 0; - -function formatResult(lines, words, bytes, fileName) { - let result = ""; - if (countLines) { - result += String(lines).padStart(8); - } - if (countWords) { - result += String(words).padStart(8); - } - if (countBytes) { - result += String(bytes).padStart(8); - } - return result + " " + fileName; -} - -function countFile(fileName) { - try { - const content = fs.readFileSync(fileName, "utf8"); - let lines = content.split("\n").length - 1; - let words = content - .trim() - .split(/\s+/) - .filter((word) => word.length > 0).length; - let bytes = Buffer.byteLength(content); - totalLines += lines; - totalWords += words; - totalBytes += bytes; - filesCounted++; - console.log(formatResult(lines, words, bytes, fileName)); - } catch (error) { - console.log("Cannot read file: " + fileName); - } -} - -for (let file of files) { - countFile(file); -} - -if (filesCounted > 1) { - console.log(formatResult(totalLines, totalWords, totalBytes, "total")); -} From 2ef68a3e294467a085ddff529b23c15e4a6476e4 Mon Sep 17 00:00:00 2001 From: mervereis Date: Mon, 7 Sep 2026 21:42:08 +0100 Subject: [PATCH 5/5] Fix multiplication error in double function and update formatting in format_pence_as_string function --- Sprint5/exercise2.py | 2 +- Sprint5/exercise3.py | 2 +- Sprint5/exercise4.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Sprint5/exercise2.py b/Sprint5/exercise2.py index 7f94657d4..74218ec9a 100644 --- a/Sprint5/exercise2.py +++ b/Sprint5/exercise2.py @@ -7,6 +7,6 @@ def double(number): # Since the function is called double, it should multiply the number by 2. def double(number): -return number * 2 + return number * 2 print(double(10)) diff --git a/Sprint5/exercise3.py b/Sprint5/exercise3.py index 516210d75..a5b09f1fd 100644 --- a/Sprint5/exercise3.py +++ b/Sprint5/exercise3.py @@ -14,7 +14,7 @@ def format_pence_as_string(total_pence: int) -> str: if total_pence < 100: return f"{total_pence}p" - pounds = int(total_pence / 100) + pounds = (total_pence // 100) pence = total_pence % 100 return f"£{pounds}.{pence:02d}" diff --git a/Sprint5/exercise4.py b/Sprint5/exercise4.py index e32fffa33..97e2a8a9d 100644 --- a/Sprint5/exercise4.py +++ b/Sprint5/exercise4.py @@ -10,8 +10,8 @@ def __init__( self.age = age self.preferred_operating_system = preferred_operating_system self.address = address - - imran = Person("Imran", 22, "Ubuntu", "Sheffield") + +imran = Person("Imran",22,"Ubuntu","Sheffield") print(imran.address) #mypy knows what attributes a Person object is supposed to have. If you try to access an attribute that isn't defined in the class, mypy can warn you before you run the program.Adress needed to define in person object for print. \ No newline at end of file