Python每日一练(20230302) 字符串统计、合并有序链表、下一个排列

文章提供了三个编程题目,包括统计字符串中特定次数的字符、合并两个有序链表以及找到数组的下一个排列。每个题目都给出了Python代码实现,并介绍了如何利用字典优化字符串统计。此外,还概述了Python字典的常用方法。

目录

1. 字符串统计

2. 合并两个有序链表

3. 下一个排列

附录

Python字典内置方法

其它


1. 字符串统计

从键盘输入一个包含有英文字母、数字、空格和其它字符的字符串,并分别实现下面的功能:统计字符串中出现2次的英文字母(区分大小写) 统计字符串中出现n次的数字,n从键盘输入。

代码: 

#第一题
s=input('input a string:')
dict1={}
for c in s:
    if c.isalpha():
        if c not in dict1.keys():
            dict1[c] = 1
        else:
            dict1[c] += 1
for key in dict1.keys():
    if dict1[key]==2:
        print(key)
        
#第二题
s=input('input a string:')
n=int(input('input a n:'))
dict2={}
for c in s:
    if c.isdigit(): #只判断数字
        if c not in dict2.keys():
            dict2[c] = 1
        else:
            dict2[c] += 1
for key in dict2.keys():
    if dict2[key]==n:
        print(key)

2. 合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例 1:

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [], l2 = []
输出:[]

示例 3:

输入:l1 = [], l2 = [0]
输出:[0]

提示:

  • 两个链表的节点数目范围是 [0, 50]
  • -100 <= Node.val <= 100
  • l1 和 l2 均按 非递减顺序 排列

代码:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class LinkList:
    def __init__(self):
        self.head=None
    def initList(self, data):
        self.head = ListNode(data[0])
        r=self.head
        p = self.head
        for i in data[1:]:
            node = ListNode(i)
            p.next = node
            p = p.next
        return r
    def    convert_list(self,head):
        ret = []
        if head == None:
            return
        node = head
        while node != None:
            ret.append(node.val)
            node = node.next
        return ret

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        h = ListNode(0, None)
        p = h
        while l1 and l2:
            if l1.val < l2.val:
                p.next = l1
                p = l1
                l1 = l1.next
            else:
                p.next = l2
                p = l2
                l2 = l2.next
        if l1:
            p.next = l1
        else:
            p.next = l2
        return h.next

# %%
l = LinkList()
list1 = [1,2,4]
list2 = [1,3,4]
l1 = l.initList(list1)
l2 = l.initList(list2)
s = Solution()
print(l.convert_list(s.mergeTwoLists(l1, l2)))

3. 下一个排列

实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。

必须 原地 修改,只允许使用额外常数空间。

示例 1:

输入:
nums = [1, 2, 3]
输出:
[1, 3, 2]

示例 2:

输入:
nums = [3, 2, 1]
输出:
[1, 2, 3]

示例 3:

输入:
nums = [1, 1, 5]
输出:
[1, 5, 1]

示例 4:

输入:
nums1 = [1]
输出:
[1]

代码: 

class Solution(object):
    def nextPermutation(self, nums):
        ls = len(nums)
        if ls <= 1:
            return
        pair = []
        for i in range(ls):
            for j in range(i + 1, ls):
                if nums[i] < nums[j]:
                    pair.append([i,j])
        pos = 0
        if len(pair) > 0:
            self.swap(nums, pair[-1][0], pair[-1][1])
            pos = pair[-1][0] + 1
        for i in range(pos, ls):
            for j in range(i + 1, ls):
                if nums[i] > nums[j]:
                    self.swap(nums, i, j)
        return nums
    def swap(self, nums, index1, index2):
        if index1 == index2:
            return
        nums[index1], nums[index2] = nums[index2], nums[index1]

# %%
s = Solution()
print(s.nextPermutation(nums = [1,2,3]))
print(s.nextPermutation(nums = [3,2,1]))
print(s.nextPermutation(nums = [1,1,5]))
print(s.nextPermutation(nums = [1]))

#注:长度为1的列表返回1,这个问题原题所附代码没有考虑

附录

Python字典内置方法

dict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default

dict.clear() 删除字典内所有元素

popitem() 返回并删除字典中的最后一对键和值。

pop(key[,default]) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。

del dic

dict.update(dict2) 把字典dict2的键/值对更新到dict里

dict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值

dict.keys() 以列表返回一个字典所有的键

dict.values() 以列表返回字典中的所有值

dict.items() 以列表返回可遍历的(键, 值) 元组数组

其它

dict.copy() 返回一个字典的浅复制

dict.fromkeys(seq[, val]) 创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值

dict.has_key(key) 如果键在字典dict里返回true,否则返回false


对于第一题可以用dict.get()优化: 

get(self, key, default=None, /) 
Return the value for key if key is in the dictionary, else default.

#第一题
s=input('input a string:')
dict1={}
for c in s:
    if c.isalpha():
        dict1[c] = dict1.get(c, 0) + 1

for key in dict1.keys():
    if dict1[key]==2:
        print(key)
        
#第二题
s=input('input a string:')
n=int(input('input a n:'))
dict2={}
for c in s:
    if c.isdigit(): #只判断数字
        dict2[c] = dict2.get(c, 0) + 1

for key in dict2.keys():
    if dict2[key]==n:
        print(key)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hann Yang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值