<jupyter_start><jupyter_text>Slicing with Itertools ![title](imgs/104.png)<jupyter_code>def slice_(iterable,start,stop):
    for _ in range(0,start):
        next(iterable)
    for _ in range(start,stop):
        yield next(iterable)
import math

def factorials(n):
    for i in range(n):
        yield math.factorial(i)
facts = factorials(100)
list(slice_(factorials(100),0,10))
list(slice_(factorials(100),3,10))
from itertools import islice
list(islice(factorials(100),3,10))
def factorials():
    index = 0
    while True:
        yield math.factorial(index)
        index += 1
facts = factorials()
for _ in range(0,5):
    print(next(facts))
list(islice(factorials(),3,10))<jupyter_output><empty_output><jupyter_text>Select and Filter ![title](imgs/105.png)![title](imgs/106.png)![title](imgs/107.png)![title](imgs/108.png)![title](imgs/109.png)![title](imgs/110.png)![title](imgs/111.png)<jupyter_code>def gen_cube(n):
    for i in range(n):
        print(f'yielding {i}')
        yield i**3
def is_odd(x):
    return x%2==1
list(filter(is_odd,gen_cube(10)))
def is_even(x):
    return x%2 == 0
filtered = list(filter(is_even,gen_cube(10)))
filtered
from itertools import filterfalse
list(filterfalse(is_odd,gen_cube(10)))
from itertools import dropwhile,takewhile
from math import sin, pi
def sin_wave(n):
    start = 0
    max_ = 2*pi
    step = (max_ - start) / (n-1)
    
    for _ in range(n):
        yield round(sin(start),2)
        start += step
list(sin_wave(15))
list(takewhile(lambda x: 0 <= x <= 0.9,sin_wave(15)))
l = [1,3,5,2,1]
list(dropwhile(lambda x: x < 5,l))
data = ['a','b','c','d','e']
selector = [True,False,True,0] # None
list(zip(data,selector))
[item for item, truth_value in zip(data,selector) if truth_value]
from itertools import compress
list(compress(data,selector))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16421167484997273, 'fraction_numerical': 0.0447354064375341, 'mean_word_length': 4.878205128205129, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 9, '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': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '225444', 'license': 'MIT', 'n_tokens_mistral': 746, 'n_tokens_neox': 698, 'n_words': 137, 'path': 'Slicing, Selecting and Filtering.ipynb', 'repo_name': 'nikgun1984/Python-Programming-Part-2', 'size': '1833'}