#!/usr/bin/env python # coding: utf-8 # # Python itertools # > Swarm Intelligence from social interaction # # - toc: false # - badges: true # - hide: true # - comments: true # - image: images/copied_from_nb/my_icons/static_pso.png # - categories: [jupyter, optimisation, visualisation] # ## Pre-requisits # You can pass functions as variables # In[27]: def add_two(x): return x+2 def do_something_then_add_three(something_to_do_first, x): # first call something_to_do_first with the input, then add 3 return something_to_do_first(x) + 3 # We pass add_two (note the lack of brackets beside it) do_something_then_add_three(add_two, 0) # An iterator is an object representing a stream of data. You can call `next` on an iterator to get the next value. # In[4]: from string import ascii_lowercase ascii_lowercase # In[5]: iter(ascii_lowercase) # In[6]: alphabet_iterator = iter(ascii_lowercase) next(alphabet_iterator) # In[7]: next(alphabet_iterator) # In[8]: def add_underscore(x,y): return f'{x}_{y}' # In[9]: import itertools alphabet_iterator = iter(ascii_lowercase) # In[13]: my_list = [1,3,5,6] list(itertools.islice(my_list, 3)) # Say we want to create a list of tuples with ( position_in_alphabet, letter ) starting at (1, 'a') like # In[55]: [(1, 'a'), (2, 'b'), (3, 'c')] # In[56]: alphabet_tuples = [] for i in range(len(ascii_lowercase)): alphabet_tuples.append((i+1, ascii_lowercase[i])) alphabet_tuples # In[58]: list(zip(count(start=1), ascii_lowercase)) # In[3]: import IPython.display as ipd import numpy as np import itertools # In[14]: import itertools def ascii_wav(times=3): wave = "°º¤ø,¸¸,ø¤º°`" return ''.join(itertools.repeat(wave, times)) ascii_wav() # In[75]: