Calculate the numbers taken to reach the distinct numbers. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Calculate the numbers taken to reach the distinct numbers.

Given 'n' distinct random numbers, how many random numbers are needed to generate distinct number? Unable to get the total elements took to find distinct numbers. For say, I need 100 distinct random numbers, it may take more than 100 numbers to get distinct random numbers. All I am getting is only count of distinct values (duplicates) and not the total numbers count to reach the count of distinct values. Below is my code: import random def numbers(n): l=list() # Empty list Distinct_nums = 0 # Initializing Distinct numbers #while Distinct_nums == n: for i in range(n*n): r = random.randint(1,1000) # Generating random numbers if r not in l: # Filtering distinct numbers l.append(r) Distinct_nums += 1 return Distinct_nums # printing distinct numbers n = int(input("Enter the number of elements: ")) print(numbers(n))

12th Feb 2020, 10:10 AM
Prithvi
8 Answers
+ 2
import random def numbers(n): unique = set() cnt = 0 while len(unique) < n: r = random.randint(1,n) unique.add(r) cnt += 1 return cnt
12th Feb 2020, 2:54 PM
Diego
Diego - avatar
+ 4
I believe Diego has provided the best solution
12th Feb 2020, 5:51 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
I am not sure I understand your question. Are you asking: 1. If you input a number within a given range, IE: 1 -100 2. Then generate random numbers within that range until the given number is returned 3. Return the number of iterations for that result.
12th Feb 2020, 10:28 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
Yes. Diego has helped me get through. Thank you for yor time
12th Feb 2020, 5:55 PM
Prithvi
+ 2
Jay Matthews, thank you. I really appreciate your time. Your code is generating numbers. I already got the answer from Diego. I am so dumb right now, I am still learning to code, mostly I get stuck with such questions after trying a few times.
12th Feb 2020, 6:33 PM
Prithvi
+ 2
With practice, you will improve Prithvi
12th Feb 2020, 6:44 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Rik Wittkopp I think you understood. I want the iterations of the result, All I am getting is, if I am giving 100 as input. It is generating less than 100 distinct numbers, but I want 100 distinct numbers and the total numbers of iterations required to get that 100 distinct values. And using 'set' wont help.
12th Feb 2020, 2:21 PM
Prithvi
0
Jay Matthews I don't want any duplicate values. I just want to find total random numbers needed to have all distinct numbers. Like for e.g. if I give input as 100. It has to generate 100 distinct random numbers, and the count of the total numbers taken to find the 100 distinct random numbers.
12th Feb 2020, 2:15 PM
Prithvi