dimanche 15 novembre 2020

Variable not appending to the list

I wanted to do the following task:
Given a number N, let's say it's 5. I want to generate a list with all numbers in the range from 1 to N (5) with no duplicates in a random order.
So I wrote this code. Using these debug outputtes, I realized that the first time I generate a variable, it doesn't append to the list.

import random
def generate(n):
    amount = n
    print('Line 1 success') #TODO:DEBUG
    randnum = 0
    print('Line 2 success') #TODO:DEBUG
    finished = False
    print('Line 3 success') #TODO:DEBUG
    nums = []
    print('Line 4 success') #TODO:DEBUG
    while amount != 0:
        while finished != True:
            print('Line 5 success', amount) #TODO:DEBUG
            randnum = random.randint(1,n)
            print('Line 6 success') #TODO:DEBUG
            if not randnum in nums:
                finished = True
                print('Generation', amount, 'success') #TODO:DEBUG
                print(nums) #TODO:DEBUG
                nums.append(randnum)
                print('Line 7 success') #TODO:DEBUG
            amount = amount - 1
            print('Line 8 success') #TODO:DEBUG
            finished = False
            print('Line 9 success') #TODO:DEBUG
    print(nums)


generate(5)

And in conclusion, this whole code is kinda messy and I have no idea what could be wrong, because it actually works, but not as intended to.
Well the question is:

Why doesn't my variable being appended to the list? What else might be wrong with the code?




Aucun commentaire:

Enregistrer un commentaire