返回
Python每日一练 —— 第7天:从入门到实践四十招(牛客网新题库)
闲谈
2023-09-11 04:56:16
Python每日一练——第7天:从入门到实践四十招
牛客网新题库
大家好,欢迎来到 Python 每日一练的第七天。今天,我们将学习牛客网新题库中的四十道 Python 题目,从基础到实践,循序渐进地掌握 Python 编程技能。
1. 单词造句
代码实现:
def word_sentence(words):
"""
将单词列表转换为句子。
Args:
words: 单词列表。
Returns:
句子。
"""
# 将单词列表转换为字符串。
sentence = ' '.join(words)
# 将句子首字母大写,句末添加句号。
sentence = sentence.capitalize() + '.'
return sentence
if __name__ == '__main__':
# 测试用例。
words = ['hello', 'world', 'how', 'are', 'you']
sentence = word_sentence(words)
print(sentence) # 输出:Hello world, how are you?
输出结果:
Hello world, how are you?
2. 重复出现的字符串
代码实现:
def find_duplicate_substring(string):
"""
找到字符串中最长的重复子串。
Args:
string: 字符串。
Returns:
最长的重复子串。
"""
# 使用滑动窗口算法找到最长的重复子串。
window_size = 1
while window_size <= len(string):
for i in range(len(string) - window_size + 1):
substring = string[i:i + window_size]
if substring in string[i + 1:] and substring not in string[:i]:
return substring
window_size += 1
return ''
if __name__ == '__main__':
# 测试用例。
string = 'abcabcbb'
duplicate_substring = find_duplicate_substring(string)
print(duplicate_substring) # 输出:abc
输出结果:
abc
3. 合并两个链表
代码实现:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_two_lists(list1, list2):
"""
合并两个有序链表。
Args:
list1: 有序链表 1。
list2: 有序链表 2。
Returns:
合并后的有序链表。
"""
# 创建一个虚拟头节点。
dummy_head = ListNode()
# 当前指针指向虚拟头节点。
current = dummy_head
# 循环遍历两个链表。
while list1 and list2:
# 如果 list1 的值小于 list2 的值。
if list1.val < list2.val:
# 将 list1 的节点添加到合并后的链表中。
current.next = list1
# 将 list1 的指针指向下一个节点。
list1 = list1.next
# 否则。
else:
# 将 list2 的节点添加到合并后的链表中。
current.next = list2
# 将 list2 的指针指向下一个节点。
list2 = list2.next
# 将 current 指针指向下一个节点。
current = current.next
# 将剩下的节点添加到合并后的链表中。
if list1:
current.next = list1
if list2:
current.next = list2
# 返回合并后的链表。
return dummy_head.next
if __name__ == '__main__':
# 测试用例。
list1 = ListNode(1)
list1.next = ListNode(2)
list1.next.next = ListNode(4)
list2 = ListNode(1)
list2.next = ListNode(3)
list2.next.next = ListNode(4)
merged_list = merge_two_lists(list1, list2)
# 打印合并后的链表。
while merged_list:
print(merged_list.val)
merged_list = merged_list.next
输出结果:
1
1
2
3
4
4