学习Python是困难的Ex39,很难理解它的代码 [英] Learn Python the hard way Ex39, having a hard time understanding its code

查看:374
本文介绍了学习Python是困难的Ex39,很难理解它的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解学习Python The Extender Ex39 < a>。

我的第一个混淆是关于为什么作者在这里使用模块化部门 hash(key)%len(aMap)。它返回什么价值?为什么作者需要提醒?

  def hash_key(aMap,key):
给定一个键将创建一个数字,然后将其转换为aMap的桶的索引。
返回哈希(键)%len(aMap)

第二个令我困惑的是下一个代码

  def get_bucket(aMap ,'key'):
给定一个键,找到它要去的桶。
bucket_id = hash_key(aMap,键)
返回aMap [bucket_id]

在我的理解中, bucket_id 应该等于值 hash(key)%len(aMap)为什么我们不返回 aMap [hash(key)]

Modulo用于将数字约束到一个范围。这是一个众所周知的技巧。这样,如果你溢出你发送数字回到范围。

假设我想在[0,9)中的一个数字,我有一个哈希生成器比生成数字范围[0,100)。如果我使用 hash%10 ,它肯定会在我预期的范围内。在第一段代码中,这个技巧用于匹配一个项目和一个存储桶,因为散列不一定是有限的,但是存储桶是存在的。

第二段代码只是提取带有受限哈希的桶(在桶范围内)。为了理解它,你必须明白,大部分时间哈希映射都适用于桶。一个好的哈希映射在整个桶中平均分配项(或接近它)。

所以如果我们重新迭代 - 如果你有散列在范围[0,100)和10个桶[0,10]中,每个项目的桶索引可以用 hash%10 来计算。这会将每个项目的散列值与想要的范围[0,10)中的一个桶匹配。


I'm having a hard time understanding a lot of the code in Learn Python The Hard Way Ex39.

My first confusion is regarding why the author used modular division here hash(key) % len(aMap). What value does it return? Why does author need the reminders?

def hash_key(aMap, key):
    """Given a key this will create a number and then convert it to an index for the aMap's buckets."""
    return hash(key) % len(aMap)

The second confusing thing to me is the next code

def get_bucket(aMap, key):
    """Given a key, find the bucket where it would go."""
    bucket_id = hash_key(aMap, key)
    return aMap[bucket_id]

In my understanding, bucket_id should be equal to the value of hash(key) % len(aMap) so why don't we just return aMap[hash(key)]?

解决方案

Modulo is used to constrain a number to a range. This is a well known trick. That way if you overflow you "send" the number back to the range.

Suppose I want a number in [0, 9) and I have a hash generator than generates numbers in the range [0, 100). If I use hash % 10 it is guaranteed to be in my expected range. In the first piece of code the trick is used to match an item with a bucket, since hashes not necessarily limited but buckets are.

The second piece of code just fetches the bucket with the constrained hash (in bucket range). To understand it you must understand that a hash map most of the times works with buckets. A good hash map distributes items across the buckets equally (or close to it).

So if we re-iterate - if you have hashes in the range [0, 100) and 10 buckets [0, 10), the bucket index for each item could be calculated with hash % 10. This would match each item's hash to a bucket in the wanted range [0, 10).

这篇关于学习Python是困难的Ex39,很难理解它的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆