Rules in python list creation

Asked

Viewed 101 times

-4

Good afternoon,

I need to follow some rules when generating my list.

Are these:

1.Have at least one repeated value

2.Have at least 6 unique values

3.All the numbers cannot be repeated

How can I do this??

Follows the code

import numpy as np
import statistics as st
import random

def lista_random():
    lista = random.sample(range(0, 50), 12)
    lista.sort()
    return lista

lista = lista_random()
print('A sua lista é: ', lista)
print('A média dos índices é: {:.4f} '.format(np.mean(lista)))
print('A moda é: {:.4f} '.format(st.mode(lista)))
print('A Mediana é: {:.4f} '.format(st.median(lista)))
print('A variância amostral é: {:.4f}'.format(st.pvariance(lista)))
print('O desvio padrão amostral é: {:.4f}'.format(st.stdev(lista)))
print('O coeficiente de variação é: {:.4f}'.format(st.variance(lista)))

  • Put an example of a real attempt to address the problem.

3 answers

0

The rendom.simple function will not generate a repeated number... then you would break your first condition.

import random

def lista_random():
    lista = []
    for i in range(0,12):
        lista.append(random.randint(0,50))
    lista.sort()
    return lista

def gerar_lista():
    lista = lista_random()
    print(lista)
    pelo_menos_um_igual = False
    quant_unicos = 0
    for aux in lista:
        repetidos = lista.count(aux)
        print(repetidos)
        if repetidos == len(lista):
            return False
        elif repetidos > 1:
            pelo_menos_um_igual = True
        elif repetidos == 1:
            quant_unicos = quant_unicos + 1
    print(f"Unicos {quant_unicos}")
    if pelo_menos_um_igual and quant_unicos >= 6:
        return True
    return False

while not gerar_lista():
    pass

Try this codic above, it’s pretty disorganized, so if it works you can organize it.

  • remembering that this code will only print the list with the conditions, you can modify it to save in a variable.

0

import random


def containDuplicate(listOfElements: list) -> bool:
    if len(listOfElements) == len(set(listOfElements)):
        return False
    else:
        return True

def lista_random():
    while not containDuplicate(lista) or len(set(lista)) < 6 and len(set(lista)) == 1:
        lista[random.randrange(1, 50) for i in range(12)]
    return sorted(lista)

The setis used to bring unique values from the list. The len(set()) counts the number of unique values in your list. I used these 2 methods to create a function that checks for unique values in the list.

Just add it all into one conditional while for him to repeat as long as the conditions are not met.

0


I just didn’t understand this question: "3.You can’t repeat all the numbers". But test the code to see if it is the result you want.

from random import randint
import numpy as np
import statistics as st
lista = []
while len(lista) < 7:
    num = randint(1, 10)
    if num not in lista:
        lista.append(num)
while len(lista) < 8:
    num = randint(1, 10)
    if num == lista[-1]:
        lista.append(num)

print(f'A sua lista é: {lista}')
print(f'A média dos índices é: {np.mean(lista):.4f} ')
print(f'A moda é: {st.mode(lista):.4f} ')
print(f'A Mediana é: {st.median(lista):.4f} ')
print(f'A variância amostral é: {st.pvariance(lista):.4f}')
print(f'O desvio padrão amostral é: {st.stdev(lista):.4f}')
print(f'O coeficiente de variação é: {st.variance(lista):.4f}')
  • I think he meant that no number repeats.

  • 1

    Oh yes. True, now I understand. So that code solves his problem.

  • So the code fit perfectly but I made some adjustments, because I need 12 numbers in the list and 2 or more have to repeat, I changed the value of the first while to 11 and the random number range from 1 to 50

Browser other questions tagged

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