Dictionary 클래스 python 및 dart 구현

2023. 7. 15. 22:44개발

Problem) 아래 테스트 코드를 패스할 Dictionary 클래스를 만들기!

from class_dict import Dictionary

def test_dictionary():
    # Create a new instance of Dictionary
    dictionary = Dictionary()

    # Test add and get methods
    dictionary.add('apple', 'A fruit that grows on trees.')
    assert dictionary.get('apple') == 'A fruit that grows on trees.'

    # Test showAll and count methods
    dictionary.add('banana', 'A long curved fruit.')
    dictionary.add('orange', 'A citrus fruit.')
    dictionary.add('grape', 'A small, sweet fruit that grows in clusters.')
    dictionary.showAll()
    assert dictionary.count() == 4

    # Test update method
    dictionary.update('apple', 'A delicious fruit.')
    assert dictionary.get('apple') == 'A delicious fruit.'

    # Test upsert method
    dictionary.upsert('kiwi', 'A small, fuzzy fruit.')
    assert dictionary.get('kiwi') == 'A small, fuzzy fruit.'

    # Test delete method
    dictionary.delete('banana')
    assert dictionary.get('banana') is None

    # Test bulkAdd and bulkDelete methods
    entries = {'mango': 'A tropical fruit.', 'pear': 'A sweet, juicy fruit.'}
    dictionary.bulkAdd(entries)
    dictionary.showAll()
    assert dictionary.count() == 6

    terms_to_delete = ['apple', 'grape']
    dictionary.bulkDelete(terms_to_delete)
    assert dictionary.get('apple') is None
    assert dictionary.get('grape') is None
    assert dictionary.count() == 4

    print("All tests passed successfully.")


# Run the test code
test_dictionary()

Python

class Dictionary:
    def __init__(self):
        self.dictionary = dict()

    def _print_no__exists(self, term):
        print(f'{term} does not exist in the dictionary')

    def _exists(self, term):
        return self.dictionary.get(term)
    
    def add(self, term, definition):
        if self._exists(term):
            print(f'{term} exists in the dictionary already')
        else:
            self.dictionary[term] = definition
            print(f'added. {term}: {definition}')

    def get(self, term):
        if self._exists(term):
            definition = self.dictionary.pop(term)
            print(f'got. {term}: {definition}')
        else:
            self._print_no__exists(term)

    def delete(self, term):
        if self._exists(term):
            definition = self.dictionary.pop(term)
            print(f'deleted. {term}: {definition}')
        else:
            self._print_no__exists(term)

    def update(self, term, definition):
        if self._exists(term):
            self.dictionary[term] = definition
            print(f'updated. {term}: {definition}')
        else:
            self._print_no__exists(term)

    def showAll(self):
        for term, definition in self.dictionary.items():
            print(f'{term}: {definition}')
        print("That's All")

    def upsert(self, term, definition):
        if self._exists(term):
            self.update(term, definition)
        else:
            self.add(term, definition)

    def count(self):
        return len(self.dictionary)
    
    def bulkAdd(self, words):
        for term, definition in words.items():
            self.add(term, definition)

    def bulkDelete(self, terms):
        for term in terms:
            self.delete(term)

Dart

class Dictionary {
  Map<String, String> entries = {};

  void addEntry(String term, String definition) {
    entries[term] = definition;
  }

  String? getDefinition(String term) {
    return entries[term];
  }

  void showAll() {
    entries.forEach((term, definition) {
      print('$term: $definition');
    });
  }

  int count() {
    return entries.length;
  }

  void update(String term, String newDefinition) {
    if (entries.containsKey(term)) {
      entries[term] = newDefinition;
      print('Definition updated for $term');
    } else {
      print('$term does not exist in the dictionary');
    }
  }

  void upsert(String term, String definition) {
    entries[term] = definition;
    print('Upserted $term into the dictionary');
  }

  void deleteEntry(String term) {
    if (entries.containsKey(term)) {
      entries.remove(term);
      print('$term deleted from the dictionary');
    } else {
      print('$term does not exist in the dictionary');
    }
  }

  void bulkAdd(Map<String, String> newEntries) {
    entries.addAll(newEntries);
  }

  void bulkDelete(List<String> terms) {
    terms.forEach((term) {
      entries.remove(term);
    });
  }
}

void main() {
  testDictionary();
}

void testDictionary() {
  // Create a new instance of Dictionary
  Dictionary dictionary = Dictionary();

  // Test addEntry and getDefinition methods
  dictionary.addEntry('apple', 'A fruit that grows on trees.');
  assert(dictionary.getDefinition('apple') == 'A fruit that grows on trees.');

  // Test showAll and count methods
  dictionary.addEntry('banana', 'A long curved fruit.');
  dictionary.addEntry('orange', 'A citrus fruit.');
  dictionary.addEntry('grape', 'A small, sweet fruit that grows in clusters.');
  dictionary.showAll();
  assert(dictionary.count() == 4);

  // Test update method
  dictionary.update('apple', 'A delicious fruit.');
  assert(dictionary.getDefinition('apple') == 'A delicious fruit.');

  // Test upsert method
  dictionary.upsert('kiwi', 'A small, fuzzy fruit.');
  assert(dictionary.getDefinition('kiwi') == 'A small, fuzzy fruit.');

  // Test deleteEntry method
  dictionary.deleteEntry('banana');
  assert(dictionary.getDefinition('banana') == null);

  // Test bulkAdd and bulkDelete methods
  Map<String, String> entries = {
    'mango': 'A tropical fruit.',
    'pear': 'A sweet, juicy fruit.'
  };
  dictionary.bulkAdd(entries);
  dictionary.showAll();
  assert(dictionary.count() == 6);

  List<String> termsToDelete = ['apple', 'grape'];
  dictionary.bulkDelete(termsToDelete);
  assert(dictionary.getDefinition('apple') == null);
  assert(dictionary.getDefinition('grape') == null);
  assert(dictionary.count() == 4);

  print("All tests passed successfully.");
}
728x90
반응형