deftwoSum(nums: list, target_num: int): my_dict = {} for i inrange(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
给定一个由许多词根组成的字典和一个句子。你需要将句子中的所有继承词用词根替换掉。如果继承词中有很多形成它的词根,则用最短的替换。 例如,字典为[“cat”,”bat”,”rat”],句子为”the cattle was rattled by the battery”,经过替换,输出句子为”the cat was tar by the bat”。
defwordPattern(word_pattern, input_words): word = input_words.split(' ') iflen(word_pattern) != len(word): returnFalse used = {} hashed = {} for i inrange(len(word_pattern)): if word_pattern[i] in hashed: if hashed[word_pattern[i]] != word[i]: returnFalse else: if word[i] in used: returnFalse hashed[word_pattern[i]] = word[i] used[word[i]] = True returnTrue
defgetHint(secret, guess): secret_dict = {} guess_dict = {} A = 0 B = 0 for i inrange(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])
给定一个由很多词根组成的列表和一个句子。你需要将句子中的所有继承词用词跟替换掉。如果继承词中有很多许多形成它的词根,则用最短的词根替换它。 例如,列表为[“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
defreplaceWords(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 inenumerate(sentence): for j inrange(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))