<jupyter_start><jupyter_text>Inflearn 파이썬 중급 - 파이썬 병행성 - 기본 (1-1, 1-2)- toc: false- badges: false- comments: true- author: <NAME>- categories: [ ___  A. ENGINEERING __________ > PYTHON 인프런 강의] - - - 병행성 (Concurrency)- 이터레이터 (Iterator)- 제네레이터 (Generator)  파이썬 반복 가능한 타입 (iterable)- collections- text file- Dict- Set- Tuple- unpacking- *args- etc.<jupyter_code># 반복 가능한 이유? => 내부적으로 iter(x) 함수 호출하고 있기 떄문!!
t = 'ABCDEFGHIJKLMNOPURSTQVWXYZ'

for c in t:
	print(c, end=' ')

# while
w = iter(t)

print('\n- - - - - - - -')
print(next(w))
print(next(w))
print(next(w))

# 내부적인 반복의 원리
w = iter(t)

while True:
	try:
		print(next(w), end=' ')
	except StopIteration:
		break

# 반복가능한 객체인지 확인하는 방법

## 1.
print('__iter__' in dir(t))    # in 함수 이용

## 2.
print(hasattr(t, '__iter__'))  # hasattr 함수 이용

## 3.
from collections import abc
print(isinstance(t, abc.Iterable))



# iterator 패턴 구현
class WordSplitter:
	def __init__(self, text):
		self._idx = 0
		self._text = text.split(' ')

	def __next__(self):
		print('Called __next__')
		try:
			word = self._text[self._idx]
		except IndexError:
			raise StopIteration('Stopped Iteration. ^-^')
		self._idx += 1
		return word

	def __repr__(self):
		return 'WordSplit(%s)' % (self._text)

wi = WordSplitter('Do today what you could do tommorrow')

print(wi)
print(next(wi))
print(next(wi))
print(next(wi))
print(next(wi))
print(next(wi))
print(next(wi))
print(next(wi))
print(next(wi))

# Generator 패턴

# 1. List/dictionary/set comprehension -> 데이터 양 증가 -> 메모리 사용량 증가 // 제네레이터 사용권장
# 2. 단위 실행 가능한 코루틴(Coroutine) 구현과 연동
# 3. 작은 메모리 조각 사용

class WorldSplitGenerator:
	def __init__(self, text):
		self._text = text.split(' ')

	def __iter__(self):
		for word in self._text:
			yield word # 제네레이터
		return

	def __repr__(self):
		return 'WordSplitGenerator(%s)' % (self._text)

wg = WorldSplitGenerator('Do today what you could do tommorrow')

wt = iter(wg)

print(wt, wg, sep='\n')

print(wt)
print(next(wt))
print(next(wt))
print(next(wt))
print(next(wt))
print(next(wt))
print(next(wt))
print(next(wt))
print(next(wt))<jupyter_output><generator object WorldSplitGenerator.__iter__ at 0x10c995b10>
WordSplitGenerator(['Do', 'today', 'what', 'you', 'could', 'do', 'tommorrow'])
<generator object WorldSplitGenerator.__iter__ at 0x10c995b10>
Do
today
what
you
could
do
tommorrow
{'fraction_non_alphanumeric': 0.15780371811500216, 'fraction_numerical': 0.012105490704712495, 'mean_word_length': 4.307339449541284, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '53111', 'license': 'Apache-2.0', 'n_tokens_mistral': 1095, 'n_tokens_neox': 1161, 'n_words': 245, 'path': '_notebooks/2021-11-13-ENG-python_inflearn10.ipynb', 'repo_name': 'Jaysung00/jays_blog', 'size': '2315'}