rmotr-curriculum / base-python-curriculum-questions

3 stars 1 forks source link

I'm not understanding this test, why I do not pass. It's not possible for my solution to have duplicates. #487

Closed lefthandkick closed 5 years ago

lefthandkick commented 5 years ago

def random_matrix(m, n): BOX_SIZE = m * n + 1

rad_list = []
ret_list = []

rad_set = set()

# create a rand set - no dups - (could have done seq too)
while len(rad_set) < BOX_SIZE:
    for x in range(m * n):
        rad_set.add(random.randint(2, BOX_SIZE + 92))

# mix up the rad_set into a rad_list
rad_list = [random.choice(list(rad_set)) for x in range(BOX_SIZE)]

# extract the need list
for x in range(m):
    ret_list.append([(rad_list.pop(0)) for y in range(n)])

return ret_list

Assignment: http://learn.rmotr.com/python/base-python-track/collections-part-3/random-numbers-matrix

User code:

import random

def random_matrix(m, n):
    BOX_SIZE = m * n + 1

    rad_list = []
    ret_list = []

    rad_set = set()

    # create a rand set - no dups - (could have done seq too)
    while len(rad_set) < BOX_SIZE:
        for x in range(m * n):
            rad_set.add(random.randint(2, BOX_SIZE + 92))

    # mix up the rad_set into a rad_list
    rad_list = [random.choice(list(rad_set)) for x in range(BOX_SIZE)]

    # extract the need list
    for x in range(m):
        ret_list.append([(rad_list.pop(0)) for y in range(n)])

    return ret_list
jwinf843 commented 5 years ago

I tried running your code on the platform and it passed the test. I'm not sure why it isn't working for you.

jsymons commented 5 years ago

Here's what's causing your issue:

rad_list = [random.choice(list(rad_set)) for x in range(BOX_SIZE)]

You are building your ret_list from the elements of rad_list. However you have no assurances that the items in rad_list are unique. Yes they're coming from a set but for example on a really unlucky seed you could actually get the same element from the set for every value in your list comprehension. I think you might be overcomplicating things a bit here. Let's take what you have here and simplify it a bit into a working solution:

def random_matrix(m, n):
    BOX_SIZE = m * n
    random_numbers = set()

    # create a rand set - no dups - (could have done seq too)
    while len(random_numbers) < BOX_SIZE:
        random_numbers.add(random.randint(2, BOX_SIZE + 92))

    return [[random_numbers.pop() for y in range(n)] for x in range(m)]

If you want the ordering more randomized than what a set being unordered provides you could add:

numbers = list(random_numbers)
random.shuffle(number)

and then pop from numbers instead in the list comprehension.