Home > database >  Trying to show all numbers lower than the average in another list
Trying to show all numbers lower than the average in another list

Time:11-13

For school we have to make a code which shows the average of a certain list into another list but for some reason my list which should show the smaller numbers is empty, I don't know if it is possible but I tried using an extra variable which counts 1 to itself

from random import randint

kleiner = []
list = []
teller = 0
aantal = int(input("Hoeveel random getallen wilt u? "))
veelvoud = int(input("Welke veelvoud? "))

while len(list) < aantal:
    getal = randint(1, 100)
    if getal % veelvoud == 0:
        list.append(getal)
gemiddelde = sum(list) / len(list)

while len(list) < aantal:
    if list[teller] < gemiddelde:
        kleiner.append(list[teller])
        teller  = 1

print(list)
print(list[::-1])
print(kleiner)

help is appreciated in advance.

CodePudding user response:

2 things:

  • don't name a variable list as list is also a builtin python function
  • the second while loop causes the issue, as the length of the list is by default equal to aantal as the list has already been created. So whatever is in the while loop is never executed. Rather you could just iterate over the list in a simple for loop

That makes:

from random import randint

kleiner = []
list_ = []
teller = 0
aantal = int(input("Hoeveel random getallen wilt u? "))
veelvoud = int(input("Welke veelvoud? "))

while len(list_) < aantal:
    getal = randint(1, 100)
    if getal % veelvoud == 0:
        list_.append(getal)
gemiddelde = sum(list_) / len(list_)

for i in list_:
    if i < gemiddelde:
        kleiner.append(i)

print(list_)
print(list_[::-1])
print(kleiner)

CodePudding user response:

Once you have the average (gemiddelde), you can build the resulting list using a list comprehension:

kleiner = [n for n in list_ if n < gemiddelde ]

If you want a list of random numbers that are a multiple of veelvoud <= 100, you can get that using the choices() function:

list_ = random.choices(range(velvoud,100,velvoud), k=aantal)
  • Related