问题一:老师给出一道题目,要求在给定的一些数字中找出俩个数,使得他们的和为N。前提是这些数据中保证有答案,并且只有一个答案。例如3,4,5,7,10中选择两个数使他们的和为11,可以选择4和7.
# 解法一(双指针解法)
def twosum(nums, targe):
res = [] # 储存结果编号数据
newnums = nums[:]
newnums.sort()
left = 0
right = len(newnums) - 1
while left < right:
if newnums[left] + newnums[right] == targe:
for i in range(0, len(nums)):
if nums[i] == newnums[left]:
res.append(i)
break
for i in range(len(nums) - 1, -1, -1):
if nums[i] == newnums[right]:
res.append(i)
break
res.sort()
break
elif newnums[left] + newnums[right] < targe:
left = left + 1
elif newnums[left] + newnums[right] > targe:
right = right - 1
return (res[0] + 1, res[1] + 1) 存在返回下标,这个下标是原始列表中的位置所以+1
解法一的时间浪费在排序和寻找两个数据的位置上了,哈希算法不需要排序和寻找原始位置。
解法二(哈希算法):
# 解法二(哈希函数法)
def twosum(nums, target):
dict = {}
for i in range(len(nums)):
m = nums[i]
if target - m in dict:
return (dict[target - m] + 1, i + 1)
dict[m] = i #没有找到就把该数放到字典中,以备之后查询使用
问题二:猜词游戏,给定一个几位秘密数字然后提醒有几位让另外一个人去猜,若猜到的数中有一个数的位置和数组都对记为一个A,若数对位置不对记为一个B。例如:秘密数字是2018猜的是8021则为1A3B。
例如:秘密数字是1123猜的是9111则为1A1B
def gethint(secret, guess):
secret_dict = {}
guess_dict = {}
A = 0
B = 0
for i in range(len(secret)):
if secret[i] == guess[i]:
A += 1
else:
if secret[i] in secret_dict:
secret_dict[secret[i]] = secret_dict[secret[i]] + 1
else:
secret_dict[secret[i]] = 1
if guess[i] in guess_dict:
guess_dict[guess[i]] = guess_dict[guess[i]] + 1
else:
guess_dict[guess[i]] = 1
for digit in secret_dict:
if digit in guess_dict:
B += min(secret_dict[digit], guess_dict[digit])
return str(A) + 'A' + str(B) + 'B'
问题三:讲一句话用他们词根代替后输出
例如:the cattle was rattled by the battery
字典为【‘cat’,‘bat’,‘rat’】
经过替换后:
the cat was rat by bat
from collections import defaultdict
def replaceword(dict, sentence):
d = defaultdict(set)
s = defaultdict(int)
sentence = sentence.split() # 将句子分成单词
for w in dict:
print(w[0]) # 提取每个单词第一个字母
d[w[0]].add(w) # 以单词第一个字母为键,单词为值存储到字典中
s[w[0]] = max(s[w[0]], len(w)) # 记录下首字母所对应词根的最大长度
for i, w in enumerate(sentence): # 使用enumerate()函数来遍历句子,它把索引放在第一个变量中,把元素放在第二个变量中
for j in range(s[w[0]]):
if w[:j + 1] in d[w[0]]:
sentence[i] = w[:j + 1]
break
return ' '.join(sentence) # 将单词连接起来