최종: 원장 포팅하기
Coddy의 Python 개발자를 위한 Dart 코스 레슨. 48개 중 47번째.
챌린지
쉬움원본 참조 프로그램을 포팅하세요. Ledger()를 구현하고, bool change(String name,int delta), int? get(String name), List<String> report()를 제공하세요. 변경할 때 존재하지 않는 이름은 잔액이 0인 것으로 시작합니다. 변경 결과 잔액이 음수가 되면 상태를 바꾸지 않고 거부하세요. 값이 0인 변경도 성공하면 항목을 생성합니다. 양수 잔액만 이름순으로 정렬해 name=value 형식으로 보고하세요. 입력 줄은 add name delta, get name 또는 report 형식이며, 이름은 ASCII 문자로 구성되고 부호가 있는 정수의 합은 100만 이하여야 합니다. 각 add 명령은 소문자 불리언 텍스트를 출력하고, get 명령은 값 또는 missing을 출력하며, report 명령은 쉼표로 구분된 항목 또는 empty를 출력합니다. 명령이 없으면 empty를 출력합니다. 공개 API를 각각 독립적으로 사용할 수 있도록 하세요.
편집 가능한 파일에서 출력하지 마세요. 제공된 exercise.dart가 입력을 구문 분석하고 출력을 반환합니다. 잠긴 드라이버는 공개 API를 독립적으로 테스트하고 결과를 줄바꿈 문자 하나와 함께 출력합니다.
코드는 Ledger.dart, exercise.dart에 작성하세요. main.dart에는 제공된 입출력 코드가 있으며 수정할 수 없습니다.
완성된 Python 참조 프로그램:
import sys
class Ledger:
def __init__(self): self.balances={}
def change(self,name,delta):
value=self.balances.get(name,0)+delta
if value<0: return False
self.balances[name]=value
return True
def get(self,name): return self.balances.get(name)
def report(self):
return [f'{key}={self.balances[key]}' for key in sorted(self.balances) if self.balances[key]>0]
ledger=Ledger()
out=[]
for line in sys.stdin.read().splitlines():
a=line.split()
if not a: continue
if a[0]=='add': out.append(str(ledger.change(a[1],int(a[2]))).lower())
elif a[0]=='get':
value=ledger.get(a[1]);out.append('missing' if value is None else str(value))
else: out.append(','.join(ledger.report()) or 'empty')
print('\n'.join(out) if out else 'empty')
직접 해보기
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Ledger.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final l=Ledger();check(l.change('a',4)&&!l.change('a',-5)&&l.get('a')==4);check(l.change('z',0)&&l.get('z')==0&&l.get('missing')==null);check(l.report().join(',')=='a=4');
stdout.writeln(solve(input));
}
Python 개발자를 위한 Dart의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러