Last active
December 24, 2015 21:59
-
-
Save iskigow/6869071 to your computer and use it in GitHub Desktop.
Seletiva Facebook Hackaton 2013: Dados dois inteiros positivos n e k, gerar todos os binários entre os inteiros 0 e (2^n)-1, inclusive. Estes binários serão ordenados em ordem descrescente segundo a quantidade de 1s existentes no numero binário. Caso haja empate deve escolher o menor valor númerico. Retorne o k-ésimo elemento da lista ordenada.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Ex.: n = 3 e k = 5 | |
['0b111', '0b11', '0b101', '0b110', '0b1', '0b10', '0b100', '0b0'] | |
quinto elemento '0b1' | |
n = 4 | |
['0b1111', '0b111', '0b1011', '0b1101', '0b1110', '0b11', '0b101', '0b110', '0b1001', '0b1010', '0b1100', '0b1', '0b10', '0b100', '0b1000', '0b0'] | |
n = 5 | |
['0b11111', '0b1111', '0b10111', '0b11011', '0b11101', '0b11110', '0b111', '0b1011', '0b1101', '0b1110', '0b10011', '0b10101', '0b10110', '0b11001', '0b11010', '0b11100', '0b11', '0b101', '0b110', '0b1001', '0b1010', '0b1100', '0b10001', '0b10010', '0b10100', '0b11000', '0b1', '0b10', '0b100', '0b1000', '0b10000', '0b0'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def qtd1(arg): | |
return arg.count('1') | |
def hack(n,k): | |
lista = [bin(num) for num in range(2**n)] # Gera lista de binários | |
lista.sort(key=qtd1, reverse=True) # Ordena pela qtd de 1 | |
return lista[k-1] # retorna o k-ésimo número | |
n, k = int(input('n: ')), int(input('k: ')) | |
print(hack(n,k)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Solução usando uma única linha | |
print(bin(sorted(range(2**int(input('n: '))),key=lambda num: bin(num).count('1'), reverse=True)[int(input('k: '))-1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment