牛客刷题-数据结构篇(python)

前言

解题必备

【博客园】python基本数据结构函数速查 - 作者:给我取个名
【资料下载】python正则表达式的七种兵器


题解 - (简单-中等难度)

数字颠倒/字符串反转

a = str(input())
b = list(a.split(' '))
len1 = len(b)

for i in range(len1):
    print(b[len1-i-1],end=" ") 

外逆序+内逆序

a = str(input())
b = list(a.split(' '))
len1 = len(b)

for i in range(len1):
    len2 = len(b[len1-i-1])
    c = b[len1-i-1]
    if len2>1:
        for j in range(len2):
            print(c[len2-j-1],end="") 
        print(end=" ") 
    else:
        print(b[len1-i-1],end=" ") 

列表倒序输出

a = str(input())
lst1 = list(a)
len1 = len(lst)

lst2 = []

for i in range(len1):
        print(lst1[len1-i-1],end=" ")

汽水瓶

import math
    
def test2(n):
        if n<=1:
            return 0
        if n==2:
            return 2
        if n==3:
            return 1
        if n%3==0:
            n = n/3
            return n+test2(n)
        elif n%3>0:
            m = math.floor(n/3)
            n = math.floor(n/3) + n%3
            if(n<3):
                m = 0
            return m+test2(n)
        
a=[]        
while True:
    n = int(input())
    if(n!=0):
        a.append(int(test2(n)))
    else:
        break

for i in a:
    print(i)

兔子,斐波那契数列

n = int(input())
def test3(n):
    if n == 1:
        return 1
    if n == 2:
        return 1
    else:
        return test3(n-1)+test3(n-2)
    
print(test3(9))

小球弹5次

import math
a = float(input())
sum = 0.0
def test3(n):
    return math.pow(0.5,n)*a

sum = a
for i in range(1,5):
    sum=sum+test3(i)*2.0
    
print(sum)    
print(test3(5))

求A和B的最小公倍数

a = str(input())
numbers = list(a.split(' '))
numbers = [int(x) for x in numbers]

for i in range(1,max(numbers)+1):
    if((i*min(numbers))%max(numbers)==0):
        print(i*min(numbers))
        break
    

单词倒排,去除多余分隔符

a = str(input())
lst1 = list(a)
len1 = len(lst1)

lst2 = []

def judgezimu(a):
    if((ord(a)>=65 and ord(a)<=90) or (ord(a)>=97 and ord(a)<=122)):
        return True
    else:
        return False
b=""       
for i in range(0,len1):
    if judgezimu(lst1[i]) is True:
        b+=lst1[i]
        if i==(len1-1):
            lst2.append(b)
    else:
        if b != "":
            lst2.append(b)
            b=""
            continue
    
        
for i in range(len(lst2)):
        print(lst2[len(lst2)-i-1],end=" ")

单词倒排网友版-摘自解题评论

import re
while True:
    try:
        data = input()
        sp_data = re.split('[^a-zA-Z]+',data)
        #刚开始提交后会报90%格式错误
        #因为可能存在开头结尾是非字母的情况,所以需要去掉开头结尾的空字符
        print(' '.join(sp_data[::-1]).strip())
    except:
        break

统计字符,数字的个数、空格的个数、中英文的个数

while True:
    try:
        in_str = input()
        c_num,space_num,digit_num,other_num = 0,0,0,0
        for x in in_str:
            if x.isalpha():
                c_num = c_num + 1
            elif x == " ":
                space_num = space_num + 1
            elif x.isdigit():
                digit_num = digit_num+1
            else:
                other_num = other_num+1
        print(c_num)
        print(space_num)
        print(digit_num)
        print(other_num)
    except:
        break

等差数列

while True:
    try:
        n = int(input())
        d = 3
        a1 = 2
        an = a1+(n-1)*d
        sums = (a1+an)/2*n
        print(int(sums))
    except:
        break
        
#等差数列
n = 1

def getAn(n):
    if n == 1:
        return 2
    else:
        return getAn(n-1)+3

while True:
    sum=0
    try:
        n = int(input())
        for i in range(n):
            sum=sum+getAn(i+1)
        print(sum)
    except:
        break  

字符统计,按权重排名,按value顺排,按key逆排

while True:
    try:
        str1 = str(input())
        zifu = {}
        for i in str1:
            if i not in zifu.keys():
                zifu[i] = 0
            else:
                zifu[i] = zifu[i]+1

        zifu2 = dict(sorted(zifu.items(),key =lambda item:(-item[1],item[0])))
        print("".join(list(zifu2.keys())))
    except:
        break    

Redraiment的走法,即最长顺序数

while True:
    try:
        n = int(input())
        lst1 = list(str(input()).strip().split(" "))
        lst1 = [int(i) for i in lst1]

        maxnum = 0
        j = 0 #第几个开始
        k=1 #从第j格开始的顺序数长度

        for i in range(n):
            j=i+1
            a = lst1[i]
            for j in range(n):
                if j==(n-1):
                    break       
                b = lst1[j] #当前比较数
                if lst1[j+1]>a:
                    k=k+1
                    a = lst1[j+1]
            if k>maxnum:
                maxnum = k
                k=1
        print(maxnum)
    except:
        break


#动态规划求最大递增子序列-摘自网络
n, nums = int(input()), list(map(int, input().split()))
def length_of_LIS(nums):
    L = [1] * n
    
    for i in reversed(range(n)):
        for j in range(i+1,n):
            if nums[j]>nums[i]:
                L[i] = max(L[i], L[j] + 1)
    return max(L)

print(length_of_LIS(nums))


#动态规划求最大递增子序列
def getMaxSubSeqSum(arr):
    max_sum = arr[0]
    cur_sum = arr[0]
    for i in range(1, len(arr)):
        if cur_sum < 0:
            cur_sum = arr[i]
        else:
            cur_sum += arr[i]
        if cur_sum > max_sum:
            max_sum = cur_sum
    return max_sum


if __name__ == '__main__':
    arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
    res = getMaxSubSeqSum(arr)
    print(res)

记负均正1

n,nums = int(input()),list(str(input()).strip().split(" "))
nums = [int(i) for i in nums]
sum1 = 0
sum2 = 0
k = 0
for i in nums:
    if i<0:
        sum1=sum1+1
    elif i>0 and isinstance (i,int):
        sum2=sum2+i
        k=k+1
print("%d %.1f" % (sum1,sum2/k))

计负均正2

sum1 = 0
sum2 = 0
k = 0.0
while(True):
    try:
        i = int(input())
        if i<0:
            sum1=sum1+1
        else:
            sum2=sum2+i
            k=k+1
        try:
            a = sum2/k
        except:
            a = 0.0
    except:
        break

print("%d" % (sum1))
print("%.1f" % (a))

二分法求解立方根

num = float(input())
#记录符号
if num >0:
    sig = 1
else:
    sig = -1
start=end=0    
num = abs(num)    
if num>1:
    start=1
    end =num
elif 1>num>0:
    start=0
    end =num
elif num==1:
    print(round(sig*num,1))
elif num==0:
    print("0.0")
mid = (end+start)/2

#近似
while abs(mid**3-num)>0.001:
    if(mid**3>num):
        end = mid
    else:
        start = mid
    mid = (end+start)/2
print(round(sig*mid,1))


#二分法求解立方根2大神版
x = float(input())
lower, upper = 0, 0
if x>0:
    if x > 1:
        lower = 1
        upper = x
    elif 1 > abs(x) > 0:
        upper = 1
        lower = x
if x<0:
    if x < -1:
        lower = x
        upper = -1
    elif 1 > abs(x) > 0:
        upper = x
        lower = -1
med = (upper + lower) / 2

sum=0

# 找出x
while abs(abs(med ** 3) - abs(x)) > 0.01:
    sum=sum+1
    print(sum)
    if med**3-x>0:
        upper=med
    else:
        lower=med
    med = (upper + lower) / 2

# 保留一位有效数字
med = '{:.1f}'.format(med)
print(med)
#梯度下降求立方根
n=float(input())
op=-1 if n<0 else 1
n=op*n
lr=0.0001
x=0.1
for i in range(1000000):
    delta=6*(x**2)*(x**3-n)
    x=x-lr*delta
print(op*round(x,1))

杨辉三角的偶数位置问题

#标记为简单题,一定有直接的关联,要找全!!!
以下摘自题解评论:

  • 当n<3时,没有偶数,输出-1;
  • 当n为奇数时,第一个偶数位置在第二,输出2;
  • 当n为偶数且能被4整除时,第一个偶数位置在第三,输出3;
  • 当n为偶数但不能被4整除时,偶数位置在第四,输出4
while True:
    try:
        a = int(input())
        if(a==1 or a==2):
            print(-1)
            continue
        elif a%2==0:
            if a%4==0:
                print(3)
            else:
                print(4)
            continue
        else:
            print(2)
            continue
    except:
        break

完全数计算:大于这个数1/2的公因子是不存在的

while True:
    try:
        n = int(input())       
        sum1 = 0

        for i in range(1,n+1):
            a = []
            for j in range(1,int(i/2)+1):
                if i%j==0:
                    a.append(j)
            if sum(a)==i:
                sum1=sum1+1
        print(sum1)
    except:
        break

递归求解放苹果-摘自解题评论

'''
放苹果分为两种情况,一种是有盘子为空,一种是每个盘子上都有苹果。
令(m,n)表示将m个苹果放入n个盘子中的摆放方法总数。
1.假设有一个盘子为空,则(m,n)问题转化为将m个苹果放在n-1个盘子上,即求得(m,n-1)即可
2.假设所有盘子都装有苹果,则每个盘子上至少有一个苹果,即最多剩下m-n个苹果,问题转化为将m-n个苹果放到n个盘子上
即求(m-n,n)
'''
def f(m,n):
    if m<0 or n<0:
        return 0
    elif m==1 or n==1:
        return 1
    else:
        return f(m,n-1)+f(m-n,n)
while True:
    try:
        m,n=map(int,input().split())
        print(f(m,n))
    except:
        break

十进制转二进制,查找输入整数二进制的1的个数

n = int(input())
i=0
sum=0
while True:
    a = n%2
    n=int(n/2)
    sum=sum+a
    if n==0:       
        break   
print(sum)

计算某字母出现次数

while True:
    try:
        a = input().upper()
        b = input().upper()
        k=0
        for i in a:
            if i == b:
                k=k+1
        print(k)
    except:
        break

不足8位,补全输出,超过8位,截取8位换行输出

# 注意:不足8个和14个剩余6个,是相同子问题 - 摘自题解评论
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str;
    int less=0;
    while(cin>>str)
    {
        int left=str.size()%8;
        while(str.size()>=8)
        {
            cout<<str.substr(0,8)<<endl;
            str=str.substr(8);
        }
        if(left)
        {
            less=8-left;
            str.append(less,'0');
             cout<<str<<endl;
        }

  }

    return 0;
}
#解法2
while True:
    try:
        s = input()
        m = len(s) % 8
        if m:
            s = s.ljust(len(s) + 8 - m, '0')
        for i in range(len(s) // 8):
            print(s[i*8 : (i+1)*8])
    except:
        break
#解法3:每隔8个插入一个换行符
import re
while True:
    try:
        a = input()
        len1 = len(a)
        if len1<8:
            a=a+('0'*(8-len1))            
        elif len1>8:            
            a=re.sub(r"(.{8})","\\1\n",a)
            a=a+'0'*(8-(len1%8))
            a=a.replace("00000000","")
        print(a)    
    except:
        break    

质数因子

import math
n = int(input())
for i in range(2, int(math.sqrt(n))+1):
    while n % i == 0:
        print(i, end=' ')
        n = n // i
if n > 2:
    print(n)

四舍五入

while True:
    try:        
        n = float(input())
        print(int(n)+1 if n>=int(n)+0.5 else int(n))
    except:
        break

合并表记录

n = int(input())
b={}
for _ in range(n):
    a=input().split(" ")
    a[1]=int(a[1])
    a[0]=int(a[0])
    if a[0] not in b.keys():        
        b[a[0]]=a[1]
    else:
        b[a[0]]+=a[1]  
        
for x in sorted(b.keys()):
    print(x,b[x])

提取不重复的整数

a = input()
len1=len(a)
b = [0]*len1
        
i = len1-1
while True:
    if b[i]!=1:
        print(a[i],end="")
    if i==0:
        break
    k=0
    for j in range(i):
        if a[j]==a[i]:
            b[j]=1           
    i=i-1

字符个数统计,找不同的字符的个数

while(True):
    try:
        a = input()
        len1=len(a)
        b = [1]*len1

        i = len1-1
        while True:
            if i==0:
                break
            for j in range(i):
                if a[j]==a[i]:
                    b[j]=0           
            i=i-1
        print(sum(b))
    except:
        break

汽水瓶,数学题,多找找数与数的规律

sum=0
n=int(input())
if n==0:
	break
while n//3:
    a=n//3
    b=n%3
    sum=sum+a
    n=a+b
if n%3==2:
    sum=sum+1
print(sum)

计算日期到天数转换

from datetime import datetime
while True:
    try:
        a = input().split()
        a_year=int(a[0])
        a_month=int(a[1])
        a_day=int(a[2])

        d1=datetime(a_year,a_month,a_day)
        print(d1.strftime("%j").lstrip("0"))
    except:
        break

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值