简体   繁体   中英

Why doesn't my code generate random numbers without str?

Can someone explain to me why when I remove 'str' from 7 line of code "myset.add(str(i))", do I get the same numbers every time I hit run and get random numbers with 'str' included?

def RandomFunction(x, y):
    myset = set()
    mylist = []
    listofnumbers = []

    for i in range(x, y):
        myset.add(str(i))
    for x in myset:
        mylist.append(int(x))

    if len(mylist) <= 5:
        print('In order to generate 5 numbers, the range of input needs to be higher')
    else:
        for y in mylist:
            listofnumbers.append(y)
            if len(listofnumbers) >= 5:
                print(listofnumbers)
                break


RandomFunction(10, 20)

Set keeps the elements in hash table, it uses default python's hash() function. Its implementation for numeric types looks like this:

def hash(number):
    return number % (2 ** 61 - 1)

So, if the numbers aren't huge, hash value of an integer will be equal to the same integer. Because of this integers in python's set will be kept in ascending order ( for also reads hash table in ascending order).

But string is a sequense of unicode characters with \0 at the end and python has another implementation of hash() for strings, so it won't work the same way for them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM