Skip to content

Sde102 oop

OOP

 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
from enum import Enum
import heapq

class FreightType(Enum):
    EXPEDITED = 1
    EXPRESS = 2
    REGULAR = 3

class Priority(Enum):
    HIGH = 1
    MEDIUM = 2
    LOW = 3

class Freight:
    def __init__(self, freight_id, freight_type, priority):
        self.freight_id = freight_id
        self.freight_type = freight_type
        self.priority = priority

    def __lt__(self, other):
        # Compare by freight type first, then by priority
        if self.freight_type.value != other.freight_type.value:
            return self.freight_type.value < other.freight_type.value
        elif self.priority.value != other.priority.value:
            return self.priority.value < other.priority.value
        else:
            # For same type and priority, compare by freight ID
            return self.freight_id < other.freight_id

    def __str__(self):
        return f"Freight(freight_id={self.freight_id}, freight_type={self.freight_type}, priority={self.priority})"

class FreightQueue:
    def __init__(self):
        self.freights = []

    def add_freight(self, freight):
        heapq.heappush(self.freights, freight)

    def remove_freight(self):
        if self.freights:
            return heapq.heappop(self.freights)
        return None

    def __str__(self):
        return f"FreightQueue(freights={self.freights})"

class FreightYard:
    def __init__(self):
        self.freight_queue = FreightQueue()

    def add_freight_to_queue(self, freight):
        self.freight_queue.add_freight(freight)

    def exit_freights(self):
        while self.freight_queue.freights:
            freight = self.freight_queue.remove_freight()
            print(f"Freight {freight.freight_id} with type {freight.freight_type} and priority {freight.priority} is exiting the yard.")

def main():
    yard = FreightYard()

    # Create freights with different types and priorities
    f1 = Freight("F001", FreightType.REGULAR, Priority.LOW)  # Regular, Low priority
    f2 = Freight("F002", FreightType.EXPRESS, Priority.HIGH)  # Express, High priority
    f3 = Freight("F003", FreightType.REGULAR, Priority.MEDIUM)  # Regular, Medium priority
    f4 = Freight("F004", FreightType.EXPEDITED, Priority.LOW)  # Expedited, Low priority
    f5 = Freight("F005", FreightType.EXPRESS, Priority.MEDIUM)  # Express, Medium priority
    f6 = Freight("F006", FreightType.REGULAR, Priority.HIGH)  # Regular, High priority
    f7 = Freight("F007", FreightType.REGULAR, Priority.LOW)  # Regular, Low priority
    f8 = Freight("F008", FreightType.EXPRESS, Priority.MEDIUM)  # Express, Medium priority
    f9 = Freight("F009", FreightType.REGULAR, Priority.HIGH)  # Regular, High priority
    f10 = Freight("F010", FreightType.EXPRESS, Priority.LOW)  # Express, Low priority

    # Add freights to the queue
    yard.add_freight_to_queue(f1)
    yard.add_freight_to_queue(f2)
    yard.add_freight_to_queue(f3)
    yard.add_freight_to_queue(f4)
    yard.add_freight_to_queue(f5)
    yard.add_freight_to_queue(f6)
    yard.add_freight_to_queue(f7)
    yard.add_freight_to_queue(f8)
    yard.add_freight_to_queue(f9)
    yard.add_freight_to_queue(f10)

    # Exit freights
    yard.exit_freights()

if __name__ == "__main__":
    main()

Memcached

 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
import time

class Memcached:
    def __init__(self):
        self.store = {}
        self.expirations = {}

    def set(self, key, value, expiration=None):
        """Store a key-value pair, expiration time is optional (in seconds)"""
        self.store[key] = value
        if expiration:
            self.expirations[key] = time.time() + expiration
        else:
            self.expirations.pop(key, None)

    def get(self, key):
        """Get the value of the specified key, return None if expired or does not exist"""
        if key in self.store:
            if key in self.expirations:
                if time.time() > self.expirations[key]:
                    self.delete(key)
                    return None
            return self.store[key]
        return None

    def delete(self, key):
        """Delete the specified key and its value"""
        if key in self.store:
            del self.store[key]
        if key in self.expirations:
            del self.expirations[key]

    def __str__(self):
        """Print store and expiration information"""
        return f"Store: {self.store}\nExpirations: {self.expirations}"

# Example usage
if __name__ == "__main__":
    cache = Memcached()

    # Set cache
    cache.set("key1", "value1", expiration=1)  # Expiration time is 1 second
    cache.set("key2", "value2")

    print("Cache after setting values:")
    print(cache)

    # Get cache
    print("\nGetting 'key1':", cache.get("key1"))
    print("Getting 'key2':", cache.get("key2"))

    # Wait 1 second for 'key1' to expire
    time.sleep(1)

    print("\nCache after waiting 1 seconds:")
    print(cache)

    # Get cache again
    print("\nGetting 'key1' after expiration:", cache.get("key1"))
    print("Getting 'key2' after expiration:", cache.get("key2"))

    # Delete cache
    cache.delete("key2")
    print("\nCache after deleting 'key2':")
    print(cache)

LRUCache

 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
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.cache = OrderedDict()

    def get(self, key: int) -> int:
        """Get the value from the cache, return -1 if the key does not exist"""
        if key not in self.cache:
            return -1
        else:
            # Move to the end to indicate it was recently used
            self.cache.move_to_end(key)
            return self.cache[key]

    def put(self, key: int, value: int) -> None:
        """Put a key-value pair into the cache"""
        if key in self.cache:
            # Update the value and move to the end to indicate it was recently used
            self.cache.move_to_end(key)
            self.cache[key] = value
        else:
            # If the cache is full, remove the least recently used item
            if len(self.cache) >= self.capacity:
                self.cache.popitem(last=False)
            self.cache[key] = value

    def __str__(self):
        """Print the current cache state"""
        return str(self.cache)

# Example usage
if __name__ == "__main__":
    # Create an LRU cache with a capacity of 3
    lru_cache = LRUCache(3)

    # Insert cache items
    lru_cache.put(1, 1)
    lru_cache.put(2, 2)
    print("Cache after putting (1, 1) and (2, 2):")
    print(lru_cache)

    # Get cache items
    print("Get 1:", lru_cache.get(1))  # Returns 1, indicating (1, 1) is the most recently used
    print("Cache after getting 1:")
    print(lru_cache)

    # Insert cache items, causing (2, 2) to be evicted
    lru_cache.put(3, 3)
    print("Cache after putting (3, 3):")
    print(lru_cache)

    # Insert cache items, causing (1, 1) to be evicted
    lru_cache.put(4, 4)
    print("Cache after putting (4, 4):")
    print(lru_cache)

    # Get cache items
    print("Get 2:", lru_cache.get(2))  # Returns -1, because (2, 2) was evicted
    print("Get 3:", lru_cache.get(3))  # Returns 3
    print("Get 4:", lru_cache.get(4))  # Returns 4

CardGame

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import random

class Player:
    def __init__(self, id):
        self.id = id
        self.score = 0

class Game:
    def __init__(self, p1, p2):
        self.p1 = p1
        self.p2 = p2
        self.matches = []
        self.winner = None

    def run(self):
        print("run")
        if self.p1.score == 3:
            self.winner = self.p1
            return
        elif self.p2.score == 3:
            self.winner = self.p2
            return