python3的各种经典案例,总共299个案例,直接可以运行(前:100个案例)

Posted cui_yonghua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3的各种经典案例,总共299个案例,直接可以运行(前:100个案例)相关的知识,希望对你有一定的参考价值。

一. python3的各种经典案例,总共299个案例,直接可以运行(前:100个案例)

二. python3的各种经典案例,总共299个案例,直接可以运行(中:100个案例)

三. python3的各种经典案例,总共299个案例,直接可以运行(后:99个案例)

第一章 难度等级★

【例1】反转一个3位整数 难度等级★

3.代码实现

class Solution:
#参数number: 一个三位整数
    #返回值: 反转后的数字
    def reverseInteger(self, number):
        h = int(number/100)
        t = int(number%100/10)
        z = int(number%10)
        return (100*z+10*t+h)
#主函数
if __name__ == '__main__':
    solution = Solution()
    num = 123
    ans = solution.reverseInteger(num)
    print("输入:", num)
    print("输出:", ans)

【例2】合并排序数组 难度等级★

3.代码实现

class Solution:
    #参数A: 有序整数数组A
    #参数B: 有序整数数组B
    #返回:一个新的有序整数数组
    def mergeSortedArray(self, A, B):
        i, j = 0, 0
        C = []
        while i < len(A) and j < len(B):
            if A[i] < B[j]:
                C.append(A[i])
                i += 1
            else:
                C.append(B[j])
                j += 1
        while i < len(A):
            C.append(A[i])
            i += 1
        while j < len(B):
            C.append(B[j])
            j += 1
        return C
#主函数
#主函数
if __name__ == '__main__':
    A = [1,4]
    B = [1,2,3]
    D = [1,2,3,4]
    E = [2,4,5,6]
    solution = Solution()
    print("输入:", A, " ", B)
    print("输出:", solution.mergeSortedArray(A,B))
    print("输入:", D, " ", E)
    print("输出:", solution.mergeSortedArray(D,E))

【例3】旋转字符串 难度等级★

3.代码实现

class Solution:
    #参数s:字符列表
    #参数offset:整数
    #返回值:无
    def rotateString(self, s, offset):
        if len(s) > 0:
            offset = offset % len(s)
        temp = (s + s)[len(s) - offset : 2 * len(s) - offset]
        for i in range(len(temp)):
            s[i] = temp[i]
#主函数
if __name__ == '__main__':
    s = ["a","b","c","d","e","f","g"]
    offset = 3
    solution = Solution()
    solution.rotateString(s, offset)
    print("输入:s =", ["a","b","c","d","e","f","g"], " ", "offset =",offset)
    print("输出:s =", s)

【例4】相对排名 难度等级★

3.代码实现

class Solution:
    #参数nums为整数列表
    #返回列表
    def findRelativeRanks(self, nums):
        score = {}
        for i in range(len(nums)):
            score[nums[i]] = i
        sortedScore = sorted(nums, reverse=True)
        answer = [0] * len(nums)
        for i in range(len(sortedScore)):
            res = str(i + 1)
            if i == 0:
                res = 'Gold Medal'
            if i == 1:
                res = 'Silver Medal'
            if i == 2:
                res = 'Bronze Medal'
            answer[score[sortedScore[i]]] = res
        return answer
#主函数
if __name__ == '__main__':
    num = [5,4,3,2,1]
    s = Solution()
    print("输入为:",num)
    print("输出为:",s.findRelativeRanks(num))

【例5】二分查找 难度等级★

3.代码实现

class Solution:
    #参数nums: 整数数组
    #参数target: 要查找的目标数字
    #返回值:目标数字的第一个位置,从0开始 
	def binarySearch(self, nums, target):
		return self.search(nums, 0, len(nums) - 1, target)
	def search(self, nums, start, end, target):
		if start > end:
			return -1
		mid = (start + end)//2
		if nums[mid] > target:
			return self.search(nums, start, mid, target)
		if nums[mid] == target:
			return mid
		if nums[mid] < target:
			return self.search(nums, mid, end, target)
#主函数
if __name__ == '__main__':
my_solution = Solution()
    nums = [1,2,3,4,5,6]
    target = 3
    targetIndex = my_solution.binarySearch(nums, target)
    print("输入:nums =", nums, " ", "target =",target)
    print("输出:",targetIndex)

【例6】下一个更大的数 难度等级★

3.代码实现

class Solution:
    #参数nums1为整数数组
    #参数nums2为整数数组
    #返回整数数组
    def nextGreaterElement(self, nums1, nums2):
        answer = {}
        stack = []
        for x in nums2:
            while stack and stack[-1] < x:
                answer[stack[-1]] = x
                del stack[-1]
            stack.append(x)
        for x in stack:
            answer[x] = -1
        return [answer[x] for x in nums1]
#主函数
if __name__ == '__main__':
    s = Solution()
    nums1 = [4,1,2]
    nums2 = [1,3,4,2]
    print("输入1为:",nums1)
    print("输入2为:",nums2)
    print("输出为 :",s.nextGreaterElement(nums1,nums2))

【例7】字符串中的单词数 难度等级★

3.代码实现

class Solution:
    #参数s为字符串
    #返回整数
    def countSegments(self, s):
        res = 0
        for i in range(len(s)):
            if s[i] != ' ' and (i == 0 or s[i - 1] == ' '):
                res += 1 
        return res
#主函数
if __name__ == '__main__':
    s = Solution()
    n =  "Hello, my name is John"
    print("输入为:",n)
    print("输出为:",s.countSegments(n))

【例8】勒索信 难度等级★

3.代码实现

class Solution:
    """
    参数ransomNote为字符串
    参数magazine为字符串
    返回布尔类型
    """
    def canConstruct(self, ransomNote, magazine):
        arr = [0] * 26
        for c in magazine:
            arr[ord(c) - ord('a')] += 1 
        for c in ransomNote:
            arr[ord(c) - ord('a')] -= 1
            if arr[ord(c) - ord('a')] < 0:
                return False
        return True
#主函数
if __name__ == '__main__':
    s = Solution()
    ransomNote = "aa"
    magazine = "aab"
    print("输入勒索信为:",ransomNote)
    print("输入杂志内容:",magazine)
    print("输出为:",s.canConstruct(ransomNote,magazine))

【例9】不重复的两个数 难度等级★

3.代码实现
#参数arr是输入的待查数组
#返回值是两个值的列表,内容没有重复的

class Solution:
    def theTwoNumbers(self, a):
        ans = [0, 0]
        for i in a:
            ans[0] = ans[0] ^ i
        c = 1
        while c & ans[0] != c:
            c = c << 1
        for i in a:
            if i & c == c:
                ans[1] = ans[1] ^ i
        ans[0] = ans[0] ^ ans[1]
        return ans
if __name__ == '__main__':
    arr = [1, 2, 5, 1]
    solution = Solution()
    print(" 数组为:", arr)
    print(" 两个没有重复的数字是:", solution.theTwoNumbers(arr))

【例10】双胞胎字符串 难度等级★

3.代码实现

#参数s和t是一对字符串
#返回值是个字符串,能否根据规则转换
class Solution:
    def isTwin(self, s, t):
        if len(s) != len(t):
            return "No"
        oddS = []
        evenS = []
        oddT = []
        evenT = []
        for i in range(len(s)):
            if i & 1:
                oddS.append(s[i])
                oddT.append(t[i])
            else :
                evenS.append(s[i])
                evenT.append(t[i])
        oddS.sort()
        oddT.sort()
        evenS.sort()
        evenT.sort()
        for i in range (len(oddS)) :
            if oddS[i] != oddT[i]:
                return "No"
        for i in range (len(evenS)) :
            if evenS[i] != evenT[i]:
                return "No"
        return "Yes"
if __name__ == '__main__':
    s="abcd"
    t="cdab"
    solution = Solution()
    print(" s与t分别为:", s, t)
    print(" 是否:", solution.isTwin(s, t))

【例11】最接近target的值 难度等级★

3.代码实现

#参数array是输入列表
#参数target是目标值
#返回值是整数
class Solution:
    def closestTargetValue(self, target, array):
        n = len(array)
        if n < 2:
            return -1
        array.sort()
        diff = 0x7fffffff
        left = 0
        right = n - 1
        while left < right:
            if array[left] + array[right] > target:
                right -= 1
            else:
                diff = min(diff, target - array[left] - array[right])
                left += 1
        if diff == 0x7fffffff:
            return -1
        else:
            return target - diff
if __name__ == '__main__':
    array = [1,3,5,11,7]
    target = 15
    solution = Solution()
    print(" 输入数组为:", array,"目标值为:", target)
    print(" 最近可以得到值为:", solution.closestTargetValue(target, array))

【例12】点积 难度等级★

3.代码实现

#参数A和B是输入列表
#返回值是个整数,是点积
class Solution:
    def dotProduct(self, A, B):
        if len(A) == 0 or len(B) == 0 or len(A) != len(B):
            return -1
        ans = 0
        for i in range(len(A)):
            ans += A[i] * B[i]
        return ans
if __name__ == '__main__':
    A = [1,1,1]
    B = [2,2,2]
    solution = Solution()
    print(" A与B分别为:", A, B)
    print(" 点积为:", solution.dotProduct(A, B))

【例13】函数运行时间 难度等级★

3.代码实现

#参数s为输入原始字符串
#返回值是个字符串,意为每个名字的函数运行了多久
class Solution:
    def getRuntime(self, a):
        map={}
        for i in a:
            count = 0
            while not i[count] == ' ':
                count = count + 1
            fun = i[0 : count]
            if i[count+2] == 'n':
                count = count + 7
                v = int(i[count:len(i)])
                if fun in map.keys():
                    map[fun] = v - map[fun]
                else:
                    map[fun] = v
            else:
                count = count + 6
                v = int(i[count:len(i)])
                map[fun] = v - map[fun]
        res=[]
        for i in map:
            res.append(i)
        res.sort()
        for i in range(0,len(res以上是关于python3的各种经典案例,总共299个案例,直接可以运行(前:100个案例)的主要内容,如果未能解决你的问题,请参考以下文章

python3的各种经典案例,总共299个案例,直接可以运行(中:100个案例)

python3的各种经典案例,总共299个案例,直接可以运行(前:100个案例)

python3的各种经典案例,总共299个案例,直接可以运行(后:99个案例)

python3的各种经典案例,总共299个案例,直接可以运行(中:100个案例)

python3操作MongoDB的crud以及聚合案例,代码可直接运行(python经典编程案例)

python3操作MongoDB的crud以及聚合案例,代码可直接运行(python经典编程案例)