-2

I'm taking on a project for university! Programming in python, I need to make a function called generate_key that receives an argument called letters, which is a tuple of 25 characters. The function should return a tuple of 5 tuples of characters, each one with 5 elements, that are the letters disposed by lines. For example:

>>> letters = (‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, \
... ‘H’, ‘I’, ‘J’, ‘ ’, ‘L’, ‘M’, ‘N’, \
... ‘O’, ‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, \
... ‘V’, ‘X’, ‘Z’, ‘.’)

>>> generate_key(letters)
... ((‘A’, ‘B’, ‘C’, ‘D’, ‘E’),
... (‘F’, ‘G’, ‘H’, ‘I’, ‘J’),
... (‘ ’, ‘L’, ‘M’, ‘N’, ‘O’),
... (‘P’, ‘Q’, ‘R’, ‘S’, ‘T’),
... (‘U’, ‘V’, ‘X’, ‘Z’, ‘.’))
Francisco
  • 10,918
  • 6
  • 34
  • 45

1 Answers1

0

You may use itertools.islice() to create your custom iterator function as:

from itertools import islice

def chunk(my_iter, size):
    my_iter = iter(it)
    return iter(lambda: tuple(islice(my_iter, size)), ())

Now use this function to divide the list in your custom size as:

>>> import string  # for getting all the alphabets
>>> my_list = list(string.ascii_uppercase) + ['.']
# my_list holds the value:
# ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '.']
>>> my_size = 5
>>> list(chunk(my_list, my_size))
[('A', 'B', 'C', 'D', 'E'), ('F', 'G', 'H', 'I', 'J'), ('K', 'L', 'M', 'N', 'O'), ('P', 'Q', 'R', 'S', 'T'), ('U', 'V', 'W', 'X', 'Y'), ('Z', '.')]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126