两个数之和

要求在给定的一些数字中找出两个数,是的它们的和为N,前提是这些数据中保证有正确答案且只有一个答案。
例如,给定5个数: 3、4、5、7、10,从中选择两个数使得他们的和为11,可以选择4和7。

1
2
3
4
5
6
7
8
9
10
11
12
def twoSum(nums: list, target_num: int):
my_dict = {}
for i in range(len(nums)):
m = nums[i]
if target_num - m in my_dict:
return my_dict[target_num - m] + 1, i + 1
my_dict[m] = i

if __name__ == '__main__':
target = 11
arrays = [3, 4, 5, 7, 10]
print(twoSum(arrays, target))

单词模式匹配

给定一个由许多词根组成的字典和一个句子。你需要将句子中的所有继承词用词根替换掉。如果继承词中有很多形成它的词根,则用最短的替换。
例如,字典为[“cat”,”bat”,”rat”],句子为”the cattle was rattled by the battery”,经过替换,输出句子为”the cat was tar by the bat”。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def wordPattern(word_pattern, input_words):
word = input_words.split(' ')
if len(word_pattern) != len(word):
return False
used = {}
hashed = {}
for i in range(len(word_pattern)):
if word_pattern[i] in hashed:
if hashed[word_pattern[i]] != word[i]:
return False
else:
if word[i] in used:
return False
hashed[word_pattern[i]] = word[i]
used[word[i]] = True
return True

if __name__ == '__main__':
print(wordPattern(['一', '二', '一', '二'], "香蕉 苹果 香蕉 苹果"))
print(wordPattern(['一', '一', '一', '二'], "苹果 苹果 苹果 香蕉"))

猜词游戏

一个人写下几个数字让另一个人猜,当每次答题方猜完后,出题方会给出答题方一个提示,告诉他刚才的猜测中有多少位数字猜对了(称为”Bulls”,公牛),还有多少数字猜对了但是位置不对(称为”Cows”,奶牛)。
例如,秘密数字为2018,猜测数字为8021,由0这个数不仅猜对了,位置也和秘密数字一致,所以它算一个公牛(A),而其他数字猜对了到但是位置不对,所以只能算奶牛(B),程序应该返回1A3B;再比如秘密数字为1123,猜测数字为9111,程序应该返回1A1B(因为一旦某个数字和猜测的某一位数字匹配,该数字就不能和其他数字匹配了)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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]] += 1
else:
secret_dict[secret[i]] = 1
if guess[i] in guess_dict:
guess_dict[guess[i]] += 1
else:
guess_dict[guess[i]] = 1
for i in guess_dict:
if i in secret_dict:
B += min(secret_dict[i], guess_dict[i])

return f'{A}A{B}B'


if __name__ == '__main__':
# secret = '2018'
secret = '1123'
# guess = '8021'
guess = '9111'
print(getHint(secret, guess))

神奇的词根

给定一个由很多词根组成的列表和一个句子。你需要将句子中的所有继承词用词跟替换掉。如果继承词中有很多许多形成它的词根,则用最短的词根替换它。
例如,列表为[“cat”,”bat”,”rat”],句子为”the battle was rattled by the battery”,经过替换,输出句子为”the cat was rat by the bat”。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def replaceWords(mylist, sentence):
d = collections.defaultdict(set)
s = collections.defaultdict(int)
sentence = sentence.split()
for w in mylist:
print(w[0])
d[w[0]].add(w)
s[w[0]] = max(s[w[0]], len(w))
for i,w in enumerate(sentence):
for j in range(s[w[0]]):
if w[:j+1] in d[w[0]]:
sentence[i] = w[:j+1]
break
return ' '.join(sentence)

if __name__ == '__main__':
mylist = ["cat","bat","rat"]
sentence = "the battle was rattled by the battery"
print(replaceWords(mylist, sentence))