Skip to content

Instantly share code, notes, and snippets.

@kyungkoo
Last active April 4, 2021 15:22
Show Gist options
  • Select an option

  • Save kyungkoo/e29e446a917c7273deadd8b8ab0450e5 to your computer and use it in GitHub Desktop.

Select an option

Save kyungkoo/e29e446a917c7273deadd8b8ab0450e5 to your computer and use it in GitHub Desktop.
import unittest
class Ch2Test(unittest.TestCase):
# range 정의는 https://docs.python.org/3/library/functions.html#func-range 참고
def test_ragne(self):
# 1 ~ 4
wrong = [n for n in range(1, 4)]
self.assertEqual(3, len(wrong))
expect = [1, 2, 3, 4]
start = 1
stop = 4 + 1 # stop 값은 원하는 값 + 1
actual = [n for n in range(start, stop)]
self.assertEqual(4, len(actual))
self.assertEqual(actual, expect)
def test_list_comprehension(self):
# 1~10 중 홀수 에 2 를 곱한다
expect = [2, 6, 10, 14, 18]
actual = [n * 2 for n in range(1, 10 + 1) if n % 2 == 1]
self.assertEqual(actual, expect)
# 딕셔너리 생성도 가능
def test_list_comprehension_make_dict(self):
dict1 = {"k1": "v1",
"k2": "v2",
"k3": "v3"
}
dict2 = {key: value for key, value in dict1.items() if value != "v3"}
self.assertEqual(len(dict2), 2)
self.assertEqual(dict2["k1"], "v1")
self.assertEqual(dict2["k2"], "v2")
def get_natural_number(self):
n = 0
while True:
# generator 생성 시점에 이미 n +=1 한번 수행된다는 점을 기억하자
n += 1
yield n
def test_generator(self):
g = self.get_natural_number()
for idx in range(0, 100):
value = next(g)
self.assertEqual(value, idx+1)
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment