Skip to content
Closed
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
91 changes: 91 additions & 0 deletions allocate_laptop.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
from dataclasses import dataclass
from enum import Enum
from typing import List, Dict, Tuple, Optional

class OperatingSystem(Enum):
MACOS = "macOS"
ARCH = "Arch Linux"
UBUNTU = "Ubuntu"

@dataclass(frozen=True)
class Person:
name: str
age: int
# Sorted in order of preference, most preferred is first.
preferred_operating_systems: List[OperatingSystem]


@dataclass(frozen=True)
class Laptop:
id: int
manufacturer: str
model: str
screen_size_in_inches: float
operating_system: OperatingSystem

def norm_os_values(value: str) -> OperatingSystem:
value = value.strip().lower()
if value == "ubuntu":
return OperatingSystem.UBUNTU
if value == "arch linux":
return OperatingSystem.ARCH
if value == "macos":
return OperatingSystem.MACOS
raise ValueError(f"Unknown OS: {value}")


people = [
Person(name="Imran", age=22, preferred_operating_systems=[norm_os_values("Ubuntu"), norm_os_values("Arch Linux")]),
Person(name="Eliza", age=34, preferred_operating_systems=[norm_os_values("Arch Linux"), norm_os_values("macOS"), norm_os_values("Ubuntu")]),
Person(name="Ira", age=21, preferred_operating_systems=[norm_os_values("Ubuntu"), norm_os_values("Arch Linux")]),
Person(name="Anna", age=34, preferred_operating_systems=[norm_os_values("Ubuntu"), norm_os_values("macOS")]),
Person(name="Nahimn", age=42, preferred_operating_systems=[norm_os_values("Ubuntu"), norm_os_values("Arch Linux")])
]

laptops = [
Laptop(id=1, manufacturer="Dell", model="XPS", screen_size_in_inches=13, operating_system=norm_os_values("Arch Linux")),
Laptop(id=2, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system=norm_os_values("Ubuntu")),
Laptop(id=3, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system=norm_os_values("ubuntu")),
Laptop(id=4, manufacturer="Apple", model="macBook", screen_size_in_inches=13, operating_system=norm_os_values("macOS")),
]


def allocate_laptops(people: List[Person], laptops: List[Laptop]) -> Dict[Tuple[str, int], int]:
sadness_table: Dict[Tuple[str, int], int] = {}
for person in people:
for laptop in laptops:
if laptop.operating_system in person.preferred_operating_systems:
index = person.preferred_operating_systems.index(laptop.operating_system)
sadness = index
else:
sadness = 100
sadness_table[(person.name, laptop.id)] = sadness
return sadness_table


sadness_table = allocate_laptops(people, laptops)

allocation_list: List[Tuple[str, Optional[int], int]] = []
allocated_laptops: set[int] = set()
allocated_persons: set[str] = set()
total_happiness: int = 0

for (person_name, laptop_id), sadness in sorted(sadness_table.items(), key=lambda value: value[1]):
if laptop_id in allocated_laptops:
continue
if person_name in allocated_persons:
continue
allocation_list.append((person_name, laptop_id, sadness))
allocated_laptops.add(laptop_id)
allocated_persons.add(person_name)
total_happiness += sadness
print(f"{person_name} got laptop {laptop_id}")


for person in people:
if person.name not in allocated_persons:
print(f"{person.name} did not get laptop")
print(f"Total happiness: {total_happiness}")

print(allocation_list)

24 changes: 24 additions & 0 deletions dataclasses_ex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from datetime import date
from dataclasses import dataclass

@dataclass(frozen=True)
class Person:
name: str
preferred_operating_system: str
birth_date: date

def is_adult(self) -> bool:
today = date.today()
age = today.year - self.birth_date.year

if (today.month, today.day) < (self.birth_date.month, self.birth_date.day):
age -=1

return age >= 18

imran = Person("Imran", "Ubuntu", date(2000, 9, 12))

print(imran.is_adult())



105 changes: 105 additions & 0 deletions enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
from dataclasses import dataclass
from enum import Enum
from typing import List, Dict
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 count_laptops(laptops: List[Laptop]) -> Dict[OperatingSystem, int]:
number_eachOS_laptops: Dict[OperatingSystem, int] = {
OperatingSystem.MACOS: 0,
OperatingSystem.ARCH: 0,
OperatingSystem.UBUNTU: 0}
for laptop in laptops:
number_eachOS_laptops[laptop.operating_system] +=1
return number_eachOS_laptops


def count_possible_laptops(laptops: List[Laptop], person: Person) -> int:
possible_laptops: List[Laptop] =[]
for laptop in laptops:
if laptop.operating_system == person.preferred_operating_system:
possible_laptops.append(laptop)
number_possible_laptops = len(possible_laptops)
return number_possible_laptops

def chose_alternative_laptops(laptops: List[Laptop], person: Person) -> Dict[OperatingSystem, int]:
number_possible_laptops = count_possible_laptops(laptops, person)
number_eachOS_laptops = count_laptops(laptops)
preferred_os = person.preferred_operating_system
alternative_laptops: Dict[OperatingSystem, int] = {}
for eachOS, count in number_eachOS_laptops.items():
if eachOS == preferred_os:
continue
if count > number_possible_laptops:
alternative_laptops[eachOS] = count
if len(alternative_laptops) != 0:
print(f"There is an operating system that has more laptops available.If you’re willing to accept them, there is a list: {alternative_laptops}.")
return alternative_laptops
else:
print("There is not an operating system that has more laptops available.")
return alternative_laptops

while True:
user_name = input("Type your name: ").strip()
if len(user_name) < 3:
print(f"Error, {user_name} is not valid. Try again, length should be more than 3 characters.")
continue
break

while True:
user_age = input("Type your age: ").strip()
try:
user_age_int = int(user_age)
if user_age_int < 18:
raise ValueError
break
except ValueError:
print("Invalid age, try again! Borrowing allowed from 18 years old.")

available_os = [os.value for os in OperatingSystem]
print("Available OSs are: ", ",".join(available_os))
user_operating_system = input("Type operating system: ").strip()
if user_operating_system not in available_os:
print(f"Error, {user_operating_system} is not in available list\n"
f"Available OSs are: {','.join(available_os)}", file=sys.stderr)
sys.exit(1)

preferred_operating_system = OperatingSystem(user_operating_system)

user = Person(name=user_name, age=user_age_int, preferred_operating_system=preferred_operating_system)


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),
]


possible_laptops = count_possible_laptops(laptops, user)
print(f"Possible laptops for {user_name}: {possible_laptops}")
alternative_laptops = chose_alternative_laptops(laptops, user)
20 changes: 20 additions & 0 deletions familytree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from dataclasses import dataclass
from typing import List

@dataclass(frozen=True)
class Person:
name: str
children: List["Person"]
age: int

fatma = Person(name="Fatma", children=[], age=17)
aisha = Person(name="Aisha", children=[], age=25)

imran = Person(name="Imran", children=[fatma, aisha], age=51)

def print_family_tree(person: Person) -> None:
print(person.name, f"({person.age})")
for child in person.children:
print(f"- {child.name} ({child.age})")

print_family_tree(imran)
33 changes: 33 additions & 0 deletions implement-shell-tools/cat/cat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import process from "node:process";
import { promises as fs } from "node:fs";

const arrArgv = process.argv.slice(2);

const numberLines = arrArgv.includes("-n");
const numberNonemptyLines = arrArgv.includes("-b");

const nonFlagArrArgv = arrArgv.filter((arr) => !arr.startsWith("-"));

let number = 1;

for (let file of nonFlagArrArgv) {
const content = await fs.readFile(file, "utf-8");

const linedText = content.split("\n");

const numbered = linedText.map((line) => {
if (numberNonemptyLines) {
if (line.trim() === "") {
return line;
} else {
return `${String(number++).padStart(3)} ${line}`;
}
}
if (numberLines) {
return `${String(number++).padStart(3)} ${line}`;
}

return line;
});
console.log(numbered.join("\n"));
}
56 changes: 56 additions & 0 deletions implement-shell-tools/ls/ls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import process from "node:process";
import { promises as fs } from "node:fs";
import path from "node:path";

const arrArgv = process.argv.slice(2);

const longFormat = arrArgv.includes("-l");
const showHidden = arrArgv.includes("-a");

const paths = arrArgv.filter((argv) => !argv.startsWith("-"));
if (paths.length === 0) path = "[.]";

for (let listFile of paths) {
const status = await fs.stat(listFile);

if (status.isFile()) {
const permissions = (status.mode & 0o777).toString(8);
const sizeFile = status.size;
const owner = status.uid;
const group = status.gid;
const timeMod = status.mtime.toLocaleString();

if (longFormat) {
console.log(
`${permissions}, ${owner}, ${group}, ${sizeFile}, ${timeMod}, ${listFile}`
);
} else {
console.log(listFile);
}
} else {
let files = await fs.readdir(listFile, { withFileTypes: true });

if (!showHidden) {
files = files.filter((file) => !file.name.startsWith("."));
}

for (let file of files) {
const wholePath = path.join(listFile, file.name);
const statusFile = await fs.stat(wholePath);

const permissions = (statusFile.mode & 0o777).toString(8);
const sizeFile = statusFile.size;
const owner = statusFile.uid;
const group = statusFile.gid;
const timeMod = statusFile.mtime.toLocaleString();

if (longFormat) {
console.log(
`${permissions}, ${owner}, ${group}, ${sizeFile}, ${timeMod}, ${file.name}`
);
} else {
console.log(file.name);
}
}
}
}
38 changes: 38 additions & 0 deletions implement-shell-tools/wc/wc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import process from "node:process";
import { promises as fs } from "node:fs";

const arrArgv = process.argv.slice(2);

const lines = arrArgv.includes("-l");
const words = arrArgv.includes("-w");
const bytes = arrArgv.includes("-c");

const noFlags = !lines && !words && !bytes;

const paths = arrArgv.filter((argv) => !argv.startsWith("-"));

for (let path of paths) {
const context = await fs.readFile(path, "utf-8");

const countLines = context.split(/\r?\n/).length;
const countWords = context.split(/\s+/).length;
const countBytes = Buffer.byteLength(context, "utf-8");

let startInput = "";

if (noFlags || lines) {
startInput += `${countLines} `;
}

if (noFlags || words) {
startInput += `${countWords} `;
}

if (noFlags || bytes) {
startInput += `${countBytes} `;
}

startInput += path;

console.log(startInput);
}
Loading
Loading