Python学习之路_第七周

本文通过三道LeetCode题目详解算法实现:打乱数组利用深复制与随机洗牌;回文数采用字符串反转验证;全排列借助itertools库快速生成所有可能组合。适合初学者实践与理解。

这次是实操,上LeetCode找3道题来写


第一道题:打乱数组




思路:

1.将原始数组深复制进类中的

self.origin 
(避免干扰)

2.reset时返回原始数组

3.shuffle时先把self.origin深复制给一个临时变量tmp并对其调用random.shuffle(tmp)并返回


代码:

import random
import copy
class Solution:

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.origin = copy.copy(nums)


    def reset(self):
        """
        Resets the array to its original configuration and return it.
        :rtype: List[int]
        """
        return self.origin

    def shuffle(self):
        """
        Returns a random shuffling of the array.
        :rtype: List[int]
        """
        tmp = copy.copy(self.origin)
        random.shuffle(tmp)
        return tmp

# Your Solution object will be instantiated and called as such:

第二道题: 回文数



思路:

1.将int转换为str

2.将str反转

3.比较是否相同


代码:

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """"
        a = str(x)
        b = a[::-1]
        if a == b:
            return True
        return False



第三道题: 全排列



思路:

调用itertools库中的permutation函数完成(本来需要自己写递归,可能这就是高级语言吧)



代码:

import itertools
class Solution:
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        x=list(itertools.permutations(nums,len(nums)))
        return x



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值