Python将类的对象转换为int

Python将类的对象转换为int,python,object,hash,Python,Object,Hash,我是Python新手。我的任务是为arrray和双链表创建一个双哈希表。我有一个使用数组和双链表的代码。但我不知道如何将带有链接列表的对象转换为int。我知道如何使用Integer类在Java上转换它,但在Python中我不知道。我试图创建一个函数defint(self)并返回self.data,但它不起作用。我试图找到如何制作模板或类似的东西,但没有找到任何东西。请帮帮我 这是一个代码: from random import randint class doubleHashTable:

我是Python新手。我的任务是为arrray和双链表创建一个双哈希表。我有一个使用数组和双链表的代码。但我不知道如何将带有
链接列表的对象转换为
int
。我知道如何使用Integer类在Java上转换它,但在Python中我不知道。我试图创建一个函数
defint(self)
并返回
self.data
,但它不起作用。我试图找到如何制作模板或类似的东西,但没有找到任何东西。请帮帮我

这是一个代码:

from random import randint
class doubleHashTable:
    # initialize hash Table
    def __init__(self):
        self.size = int(input("Enter the Size of the hash table : "))
        self.num = 5
        # initialize table with all elements 0
        self.table = list(0 for i in range(self.size))
        self.elementCount = 0
        self.comparisons = 0

    # method that checks if the hash table is full or not
    def isFull(self):
        if self.elementCount == self.size:
            return True
        else:
            return False

    # method that returns position for a given element
    # replace with your own hash function
    def h1(self, element):
        return element % self.size

    # method that returns position for a given element
    def h2(self, element):
        return element % self.num

    # method to resolve collision by quadratic probing method
    def doubleHashing(self, element, position):
        posFound = False
        # limit variable is used to restrict the function from going into infinite loop
        # limit is useful when the table is 80% full
        limit = 50
        i = 2
        # start a loop to find the position
        while i <= limit:
            # calculate new position by quadratic probing
            newPosition = (i * self.h1(element) + self.h2(element)) % self.size
            # if newPosition is empty then break out of loop and return new Position
            if self.table[newPosition] == 0:
                posFound = True
                break
            else:
                # as the position is not empty increase i
                i += 1
        return posFound, newPosition

    # method that inserts element inside the hash table
    def insert(self, element):
        # checking if the table is full
        if self.isFull():
            print("Hash Table Full")
            return False

        posFound = False

        position = self.h1(element)

        # checking if the position is empty
        if self.table[position] == 0:
            # empty position found , store the element and print the message
            self.table[position] = element
            print("Element " + str(element) + " at position " + str(position))
            isStored = True
            self.elementCount += 1

        # collision occured hence we do linear probing
        else:
            while not posFound:
                print("Collision has occured for element " + str(element) + " at position " + str(
                    position) + " finding new Position.")
                posFound, position = self.doubleHashing(element, position)
                if posFound:
                    self.table[position] = element
                    self.elementCount += 1

        return posFound

    # method that searches for an element in the table
    # returns position of element if found
    # else returns False
    def search(self, element):
        found = False
        position = self.h1(element)
        self.comparisons += 1

        if (self.table[position] == element):
            return position

        # if element is not found at position returned hash function
        # then we search element using double hashing
        else:
            limit = 50
            i = 2
            newPosition = position
            # start a loop to find the position
            while i <= limit:
                # calculate new position by double Hashing
                position = (i * self.h1(element) + self.h2(element)) % self.size
                self.comparisons += 1
                # if element at newPosition is equal to the required element

                if self.table[position] == element:

                    found = True
                    break

                elif self.table[position] == 0:
                    found = False
                    break

                else:
                    # as the position is not empty increase i
                    i += 1
            if found:
                return position
            else:
                print("Element not Found")
                return found

                # method to remove an element from the table

    def remove(self, element):
        position = self.search(element)
        if position is not False:
            self.table[position] = 0
            print("Element " + str(element) + " is Deleted")
            self.elementCount -= 1
        else:
            print("Element is not present in the Hash Table")
        return

    # method to display the hash table
    def display(self):
        print("\n")
        for i in range(self.size):
            print(str(i) + " = " + str(self.table[i]))
        print("The number of element is the Table are : " + str(self.elementCount))

"""DOUBLY-LINKED LIST"""
class Node():
    def __init__(self, next_node=None, previous_node=None, data=None):
        self.next_node = next_node
        self.previous_node = previous_node
        self.data = data

class LinkedList():
    def __init__(self, node):
        assert isinstance(node, Node)
        self.first_node = node
        self.last_node = node

    def push(self, node):
        '''Pushes the node <node> at the "front" of the ll
        '''
        node.next_node = self.first_node
        node.previous_node = None
        self.first_node.previous_node = node
        self.first_node = node

    def pop(self):
        '''Pops the last node out of the list'''
        old_last_node = self.last_node
        to_be_last = self.last_node.previous_node
        to_be_last.next_node = None
        old_last_node.previous_node = None

        # Set the last node to the "to_be_last"
        self.previous_node = to_be_last

        return old_last_node

    def removing(self, node):
        '''Removes and returns node, and connects the previous and next
        '''
        next_node = node.next_node
        previous_node = node.previous_node

        previous_node.next_node = next_node
        next_node.previous_node = previous_node

        # Make it "free"
        node.next_node = node.previous_node = None

        return node

    # def int(self):
    #     return self.data

    def __str__(self):
        next_node = self.first_node
        s = ""
        while next_node:
            s += "--({:2d})--\n".format(next_node.data)
            next_node = next_node.next_node
        return s
        return


# main function

"""LISTS1"""
print("\nLISTS\n")
node1 = Node(data=1)
linked_list = LinkedList(node1)
for i in range(100):
    if i == 5:
        node1 = Node(data=5)
        linked_list.push(node1)
    else:
        linked_list.push(Node(data=i))
print (linked_list)

print ("popping")
liast = linked_list.pop().data
#print(type(liast))
print(liast)
print (linked_list)
lalalal = linked_list
print(type(lalalal))
#print (linked_list.pop().data)

table_list1 = doubleHashTable()
for i in range (100):
    table_list1.insert(lalalal)

# displaying the Table
table_list1.display()
print()

# printing position of elements
print("The position of element 31 is : " + str(table_list1.search(31)))
print("The position of element 28 is : " + str(table_list1.search(28)))
print("The position of element 90 is : " + str(table_list1.search(90)))
print("The position of element 77 is : " + str(table_list1.search(77)))
print("The position of element 1 is : " + str(table_list1.search(1)))
print("\nTotal number of comaprisons done for searching = " + str(table_list1.comparisons))
print()

table_list1.remove(90)
table_list1.remove(12)

table_list1.display()


# storing elements in table
# table1.insert(12)
# table1.insert(26)
# table1.insert(31)
# table1.insert(17)
# table1.insert(90)
# table1.insert(28)
# table1.insert(88)
# table1.insert(40)
# table1.insert(77)  # element that causes collision at position 0
来自随机导入randint
类双哈希表:
#初始化哈希表
定义初始化(自):
self.size=int(输入(“输入哈希表的大小:”)
self.num=5
#使用所有元素0初始化表
self.table=列表(0表示范围内的i(self.size))
self.elementCount=0
self.compariations=0
#方法,该方法检查哈希表是否已满
def已满(自身):
如果self.elementCount==self.size:
返回真值
其他:
返回错误
#方法返回给定元素的位置
#替换为您自己的哈希函数
def h1(自身,元件):
返回元素%self.size
#方法返回给定元素的位置
def h2(自身,元件):
返回元素%self.num
#用二次探测法解决碰撞问题的方法
def双重散列(自身、元素、位置):
posFound=False
#限制变量用于限制函数进入无限循环
#当表格已满80%时,“限制”非常有用
限额=50
i=2
#开始一个循环以找到位置

而我短版本则在
h1()
和代码中的其他位置(
h2()
)上使用
hash(element)
,这些位置使用对象的hash来确定is在哈希表中的位置

您正在插入一个链接列表
lalal

lalalal = linked_list
table_list1.insert(lalalal)
要计算它的位置,请使用此方法

def h1(self, element):
        return element % self.size
您正试图从链表对象和int中获取mod,作为错误状态

您需要使用某种逻辑将链表转换为数字的某种表示形式(最好使用统一哈希函数)

尝试在将返回
int
so的链接列表上使用类似于
的smth to\u hash()

def h1(self, element):
        return element.to_hash() % self.size
您还可以覆盖
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

这几项更改将使您的代码运行

def h1(self, element):
    return hash(element) % self.size

def h2(self, element):
    return hash(element) % self.num
并在
链接列表中添加

def __hash__(self):
    return randint(1, 1000)

注意:此哈希函数仅用于草稿,如果您的has映射大于1000或您选择的任何固定值,元素将不会均匀分布在映射上,这可能会影响映射性能…

。只是向下滚动。通过关注a的“最小”部分,您可能会吸引更多的帮助。您能解释一下为什么要将链接列表转换为整数吗?你不能只获取整数属性吗?这个
def\uuuu hash\uuuu(self):
必须在类
doubleHashTable
?@Lado,不,它需要在链表类中抱歉。我使用了这个
def\uu散列(self,element):
然后返回
returnhash(element)
。然后在类
doubleHashTable
中使用它,就像
hash(element)%self.size
defh1(self,element)
中一样,但我有一个错误
TypeError:\uuuuuuuuuuuuuuu hash\uuuuuu()缺少一个必需的位置参数:“element”
。我必须在LinkedList类中定义此元素?@Lado,不要这样,我编辑了答案并添加了需要进行的更改,以便您的代码运行。。。
def __hash__(self):
    return randint(1, 1000)