Python 刷题集(1)

训练题集

 

Q1: 空瓶换水

某商店规定:三个空汽水瓶可以换一瓶汽水,允许向老板借空汽水瓶(但是必须要归还)。

小张手上有n个空汽水瓶,她想知道自己最多可以喝到多少瓶汽水。

数据范围:输入的正整数满足 1 <= n <= 100

注意:本题存在多组输入。输入的 0 表示输入结束,并不用输出结果。

Code:

while True:
    n = int(input())
    if n == 0:
        break
    print(n//2)

Q2: 随机式生成及排序

明明生成了个1到500之间的随机整数。请你删去其中重复的数字,即相同的数字只保留一个,把其余相同的数去掉,然后再把这些数从小到大排序,按照排好的顺序输出。

数据范围: 1<=n<=1000 

Code 1(慢):

import random
import math
n = int(input())
def random_list(n):
    a = []
    i = 0
    while i < n:
        b = random.randint(1,500)
        if b not in a:
            a.append(b)
        else:
            pass
    return a
 
new_a = random_list(n)
sort(new_a)
for m in new_a:
    print(m)

Code 2 (大神代码):

while True:
    try:
        n = input()      #指定为N个数,输入
        lst = []         #指定一个空列表
        for i in range(int(n)):        #循环N次
            lst.append(int(input()))      #空集合中追加一个N个数中的某一个随机数
        uniq=set(lst)        #列表去重,但是会变成无序
        lst=list(uniq)       #集合转列表
        lst.sort()           #列表排序
        for i in lst:
            print(i)         #打印列表
    except:
        break

Q3: 16进制转10进制

写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。

数据范围:保证结果在 1 <= n <= 2^{31} - 1

Code:

while True:
    try:
        print(int(input(),16))
    except:
        break

Q4: 反转链表

给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。数据范围: 0≤n≤1000

如当输入链表{1,2,3}时,经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}

Code:

    def ReverseList(self , head: ListNode) -> ListNode:
        if not head:	# 如果非空
            return head
        a, a.next, b =head, None, head.next		# 初始化
        while b:
            b, a, a.next = b.next, b, a			# 遍历
        return a

Q5:设计LRU缓存结构

#构建双向链表
class Node:
    def __init__(self, key, val):
        self.key = key
        self.val = val
        self.pre = None
        self.next = None
        
class Solution:
    def __init__(self):
        #双向链表头尾
        self.size = 0
        self.head = None
        self.tail = None
        #哈希表记录key值
        self.mp = dict()
    
    #将节点插入表头函数
    def insertFirst(self, node: Node):
        node.pre = self.head
        node.next = self.head.next
        self.head.next.pre = node
        self.head.next = node
    
    #移到表头函数
    def moveToHead(self, node: Node):
        #已经到了表头
        if node.pre == self.head:  
            return
        #将节点断开,取出来
        node.pre.next = node.next
        node.next.pre = node.pre
        #插入第一个前面
        self.insertFirst(node)
    
    #删去表尾函数,最近最少使用
    def removeLast(self):
        #哈希表去掉key
        self.mp.pop(self.tail.pre.key)
        #断连该节点
        self.tail.pre.pre.next = self.tail; 
        self.tail.pre = self.tail.pre.pre
    
    #插入函数
    def set(self, key: int, val: int):
        #没有见过这个key,新值加入
        if key not in self.mp:
            node = Node(key, val)
            self.mp[key] = node
            #超出大小,移除最后一个
            if self.size <= 0:
                self.removeLast()
            #大小还有剩余
            else:
                #大小减1
                self.size -= 1 
            #加到链表头
            self.insertFirst(node); 
        #哈希表中已经有了,即链表里也已经有了
        else:
            self.mp[key].val = val
            #访问过后,移到表头
            self.moveToHead(self.mp[key])
    
    #获取数据函数
    def get(self, key: int) -> int:
        #找不到返回-1
        res = -1
        #哈希表中找到
        if key in self.mp:
            #获取
            res = self.mp[key].val
            #访问过后移到表头
            self.moveToHead(self.mp[key])
        return res

    def LRU(self , operators: List[List[int]], k: int) -> List[int]:
        res = []
        #构建初始化连接
        #链表剩余大小
        self.size = k 
        self.head = Node(0, 0)
        self.tail = Node(0, 0)
        self.head.next = self.tail
        self.tail.pre = self.head
        #遍历所有操作
        for i in range(len(operators)):
            op = operators[i]
            if op[0] == 1: 
                #set操作
                self.set(op[1], op[2])
            else:
                #get操作
                res.append(self.get(op[1]))
        return res

 Q6: 排序

class Solution:
    def MySort(self , arr ):
        # write code here
        return sorted(arr)

Q7: 选取最小的四个数

给定一个长度为 n 的可能有重复值的数组,找出其中不去重的最小的 k 个数。例如数组元素是4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4(任意顺序皆可)。

数据范围:0≤k,n≤10000,数组中每个数的大小0 ≤val≤1000

Code:

class Solution:
    def GetLeastNumbers_Solution(self, a, k):
         a.sort()
         return a[:k]

Q8:  寻找第K大

Code

class Solution:
    def findKth(self , a: List[int], n: int, K: int) -> int:
            a = sorted(a, reverse=True)
            return a[K-1]

Q9: 两数之和

Code:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hash_map = {}
        for i, x in enumerate(nums):
            if target - x in hash_map:
                return [hash_map[target-x]+1, i+1]
            hash_map[x] = i

Q10:合并两个排序的链表

Code:

    def Merge(self, pHead1, pHead2):
        # write code here
        if not pHead1 or not pHead2:
            return pHead1 or pHead2
        if pHead1.val < pHead2.val:
            pHead1.next = self.Merge(pHead1.next, pHead2)
            return pHead1
        else:
            pHead2.next = self.Merge(pHead1, pHead2.next)
            return pHead2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

[Karel]

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

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

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

打赏作者

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

抵扣说明:

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

余额充值