0

I try do to the switch using generator in Python but i failed!Lol

I see a code in internet but i don't undestand the for loop

def get_tipo_dia(dia):
    dias = {
        (1, 7): 'final de semana',
        tuple(range(2, 7)): 'dia de semana'
    }
    generator = (tipo for numero ,tipo in dias.items() if dia in numero)  #This part i cant uderstand!!
    return next(generator, '**dia invalido**')


if __name__ == '__main__':
    for dia in range(0, 9):
        print(f'{dia}: {get_tipo_dia(dia)}')
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • Is this the part you don't understand? [if expression](https://stackoverflow.com/questions/11880430/how-to-write-inline-if-statement-for-print) - or something else? – Ahmet May 26 '20 at 17:02

3 Answers3

0
generator = (tipo for numero ,tipo in dias.items() if dia in numero)

The generator enumerates the key/value pairs in dias,filters out the pairs where the key does not contain the value in dia and emits the corresponding value. The generator only performs this action when its __next__ method is called, either implicitly through a loop (e.g., for, as part of a list comprension, as a parameter to a function that consumes iterables) or by using next().

next(generator, '**dia invalido**')

Consumes 1 item from the generator or raises StopIteration.

This is the same thing as

def get_tipo_dia(dia):
    dias = {
        (1, 7): 'final de semana',
        tuple(range(2, 7)): 'dia de semana'
    }
    for numero, tipo in dias.items():
        if dia in numero:
            return tipo
    else:
        raise StopIteration()
tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

not sure if this helps, but here's the same logic re-written with explicitly constructed list first, and then that list is converted to an iterator.

def get_tipo_dia(dia):
    dias = {
        (1, 7): 'final de semana',
        tuple(range(2, 7)): 'dia de semana'
    }

    generator = list()
    for numero , tipo in dias.items():
        if dia in numero:
            generator.append(tipo)

    generator = iter(generator)

    return next(generator, '**dia invalido**')


if __name__ == '__main__':
    for dia in range(0, 9):
        print(f'{dia}: {get_tipo_dia(dia)}')
avloss
  • 2,389
  • 2
  • 22
  • 26
0

Looks like tipo in

generator = (tipo for numero ,tipo in dias.items() if dia in numero)

checks the type of variable used for numero, which would be an int as well as the type for the items in dias which gets the values of 1 and 7 that returns the str 'final de semana' which would be the weekend days; and the range of the integers 2 through 7 which are the days of the week. If either of those are not returned, then the string '**dia invalido**' would return. The console then prints the returned string. I'm guessing you are confused mainly by the if expression. Please read about those here.

Yuuty
  • 123
  • 10