Sort() - Python

Asked

Viewed 216 times

-1

Good evening guys, I’m starting in python and I’m having a doubt that I can not think of a solution... I made a code to generate 6 numbers in a list and print without repeating any items but increasingly ordered. I used the Sort() method without success I tried to reorder the objects in another list also with the Sorted(list) and they both went wrong[Didn’t sort in print], one thing I found interesting is that when I run the tests in python prompt without Sort() it seems that only set() already sorts the numbers... [! [code

from random import randint
import msvcrt
def gerar (quantidade):
    for i in range(0,quantidade):
        jogada = {}
        numeros = []
        while len(jogada) < 6:
            numeros.append(randint(1, 60))
            numeros.sort() # Pq não funciona??
            jogada = set(numeros)
        print('Jogo numero {n}: {j}'.format(n = i+1, j = jogada) )
    while True:
        if msvcrt.kbhit() and msvcrt.getch().decode() == chr(27):
            break
#->
gerar(int(input('Numero de jogos: ')))

]1]1 [executando teste da 'anomalia' hahaha ou nao...]2

1 answer

0

The problem was set, python sets are disordered structures, "indexing has no meaning to the point that one cannot access an element of a set set set by index", so even Sort is sorting its list when the "move = set(numbers) is executed." the set becomes cluttered, the solution I found was to convert the move to a list and then do the Sort on it.

from random import randint
import msvcrt
def gerar (quantidade):
    for i in range(0,quantidade):
        jogada = {}
        numeros = []
        while len(jogada) < 6:
            numeros.append(randint(1, 60))
            jogada = set(numeros)
        jogada = list(jogada)
        jogada.sort()
        print('Jogo numero {n}: {j}'.format(n = i+1, j = jogada) )
    while True:
        if msvcrt.kbhit() and msvcrt.getch().decode() == chr(27):
            break
#->
gerar(int(input('Numero de jogos: ')))

I’m also new to python but I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.