【python练习】--《learn python the hard way》ex39

————————

正在学《learn python the hard way》(笨方法学Python),

发一篇在ex39练习hashmap时,自己敲的一些注释,希望对学着学着就卡在这的朋友们有点作用大笑

最后附上文件。


# -*- coding: utf-8 -*-
#Copyright XD

#hashmap是以两级列表实现字典功能的轮子,能帮助理解字典。
#aMap是数据,key是小列表(里层列表)的第一个元素,value是小列表的第二个元素
#使用哈希函数,获得每一个小列表的id(哈希值模除列表长度),方便查找
#i 是通过enumberate函数,获得的index(位置、索引),
#i 用来确定小列表是不是空的,方便下面的list()遍历非空小列表


def new(num_bucket=256):
	"""Initializes a Map with the given number of buckets."""
	#创建256个篮子
	aMap = []
	for i in range(0,num_bucket):
		aMap.append([])
	return aMap

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)
	#获得一个放置key值的位置
	#%代表求模运算,取余数,这里用%是为了最小化最大数,不然单纯的hash(key)得出的是一个很大的数字

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] 

def get_slot(aMap,key,default=None):
	"""
	Return the index,key,and the value of a slot found in a bucket.
	Return -1,key,and default(None if not set)when not found.
	"""
	bucket = get_bucket(aMap,key)

	for i , kv in enumerate(bucket):  #enumerate函数用于遍历列表内容及其索引(位置),先显示下标,再显示内容。
		k,v = kv
		if key == k:
			return i,k,v

	return -1,key,default

def get(aMap, key,default=None):
	"""Gets the value in a bucket for the given key, or the default."""
	i,k,v = get_slot(aMap,key,default=default)
	return v

def set(aMap,key,value):
	"""Sets the key to the value, replacing any existing value."""
	bucket = get_bucket(aMap,key)
	i,k,v = get_slot(aMap,key)

	if i >=0:
		# the key exits,replace it
		bucket[i] = (key, value)
	else:
		#the key does not , append to create it
		bucket.append((key, value))

def delete(aMap, key):
	"""Deletes the given ket from the map."""
	bucket = get_bucket(aMap, key)
#使用xrange做循环要比用range的性能更好,尤其是在返回值很大的时候。
#使用range会直接生成一个列表,而xrange不会,xrange返回一个生成器。
	for i in xrange(len(bucket)):
		k, v = bucket[i]
		if key == k:
			del bucket[i]
			break

def list(aMap):
	"""Print out what's in the map."""
	for bucket in aMap:
		if bucket: #当bucket不为空时,打印出来(遍历)
			for k, v in bucket:
				print k, v
下面是测试,书里也有,还是贴上来吧

import hashmap

#create a mapping of state to abbreviation
states = hashmap.new()
hashmap.set(states,"Oregon","OR")
hashmap.set(states, 'Florida', 'FL')
hashmap.set(states, 'California', 'CA')
hashmap.set(states, 'New York', 'NY')
hashmap.set(states, 'Michigan', 'MI')

# create a basic set of states and some cities in them
cities = hashmap.new()
hashmap.set(cities, 'CA', 'San Francisco')
hashmap.set(cities, 'MI', 'Detroit')
hashmap.set(cities, 'FL', 'Jacksonville')

# add some more cities
hashmap.set(cities, 'NY', 'New York')
hashmap.set(cities, 'OR', 'Portland')

# print out some cities
print '-' * 10
print "NY State has: %s" % hashmap.get(cities, 'NY')
print "OR State has: %s" % hashmap.get(cities, 'OR')

# print some states
print '-' * 10
print "Michigan's abbreviation is: %s" % hashmap.get(states, 'Michigan')
print "Florida's abbreviation is: %s" % hashmap.get(states, 'Florida')

# do it by using the state then cities dict
print '-' * 10
print "Michigan has: %s" % hashmap.get(cities, hashmap.get(states, 'Michigan'))
print "Florida has: %s" % hashmap.get(cities, hashmap.get(states, 'Florida'))

# print every state abbreviation
print '-' * 10
hashmap.list(states)

# print every city in state
print '-' * 10
hashmap.list(cities)

print '-' * 10
state = hashmap.get(states, 'Texas')

if not state:
  print "Sorry, no Texas."

# default values using ||= with the nil result
# can you do this on one line?
city = hashmap.get(cities, 'TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city


新年第一发,

新年快乐~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值