Hi I would like to use randint from random to get random numbers, and after doing this I would like to add it to Dict or List and check if the number already added and which Postions this an have so it shoudl print out which possition this number have, but the code should add the number to the list even if it is already in a list/dict. So I don't know which i should choice the Dict or List or adding the numbers and which one for the result?

Recommended Answers

All 4 Replies

An ordered dictionary remembers its insertion order.

Use variable to remember how many different numbers have been selected and increase that every time new is selected. Store current count of unique numbers with the current counter to dictionary.

count_store[this_random_int] = current_count

What exactly you want as result, I do not know without example.

This simple example might give you enough hints to get going:

import random as rn
import collections as co

size = 100
low = 0
high = 100
mylist = []
for n in range(size):
    mylist.append(rn.randint(low, high))

# use collection module's Counter() to find the top most common duplicates
top = 10
most = co.Counter(mylist).most_common(top)
print("of {} random integers between {} and {}".format(size, low, high))
for rnum, count in most:
    print("{} appears {} times".format(rnum, count))

print('-'*30)

# find index in mylist of the highest count number
highest_count = most[0][0]
for ix, n in enumerate(mylist):
    if n == highest_count:
        print("{} at index {}".format(n, ix))

''' possible result ...
of 100 random integers between 0 and 100
10 appears 5 times
6 appears 4 times
99 appears 4 times
2 appears 3 times
25 appears 3 times
39 appears 3 times
71 appears 3 times
85 appears 3 times
98 appears 3 times
7 appears 2 times
------------------------------
10 at index 22
10 at index 24
10 at index 38
10 at index 61
10 at index 88
'''

A defaultdictionary is another possibility:

''' defaultdict-random_integers.py
shows index of random integers in the form
random_integer: list_of_indexes
'''

import random as rn
import collections as co

size = 100
low = 0
high = 100
ddict = co.defaultdict(list)
for n in range(size):
    v = rn.randint(low, high)
    ddict[v].append(n)

print(ddict)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.