[Python] I did some inline code for an assignment and I was wondering if using it would be...

Discussão em 'Python' iniciado por Stack, Abril 27, 2025.

  1. Stack

    Stack Membro Participativo

    The goal of the assignment was to initialize an empty list called rand_array then fill it with 10 unique random numbers

    I figured out the assignment normally as per the teacher's directions:

    import random

    rand_array = []
    while len(rand_array) != 10:
    lmnt = random.randint(1, 15)
    if lmnt not in rand_array:
    rand_array.append(lmnt)

    print(rand_array)


    I modified it later to have inline to make it more efficient since my teacher didn't like me using inline:

    import random

    rand_array[]
    while len(rand_array < 10:
    lmnt = random.randint(1, 15)
    rand_array.append(lmnt) if lmnt not in rand_array else None


    I started questioning if this was actually more efficient and if I could still make it better if I take off the requirement of initializing an empty list. So, the main question is: "Is the second version more efficient than the first?" and also "Can I make the second version even more efficient?"

    Also, before anyone says, "This is such a small assignment, it doesn't matter", if I use lots of inline code in the future, I need to know if the way I'm using it is more efficient than non-inline code.

    Also I apologize in advance if anything I have typed is inaccurate.

    Continue reading...

Compartilhe esta Página