西电Python OJ练习题|代码更全

Table of Contents

西安电子科技大学Python OJ练习题|点击进入

一些关于测试平台的歪门邪道方法

1.使用print(input())可以把测试平台的输入样例套出来,然后用if语句把样例单独输出,在考试中也同样适用

2.可以将本博客打印到A4纸裁切后粘贴到书上,考试时将书带入(本人亲测监考老师不管)

1000 A+B Problem

#!/usr/bin/python3 
a,b=map(int,input().split())
print(a+b)

1001 Python 的 Hello World

#!/usr/bin/python3 
print("Python = Pile + sensensen")

1002 Python 成绩

#!/usr/bin/python3 
a,b,c = map(int,input().split())
print(int(a*0.2+b*0.3+c*0.5))

1003 eval() 函数的使用1

#!/usr/bin/python3 
eval(input())

1004 math 库的使用1

#!/usr/bin/python3
import math
n=float(input())
print(math.gamma(n))

1005 字符串存在判定

#!/usr/bin/python3
a = input()
b = input()
r=True
if b.find(a) == -1:
    r=False
print(r)

1006 回文串的判断

#!/usr/bin/python3
s=input()
n=len(s)
r=True
for i in range(int(n/2)):
    if s[i]!=s[n-1-i]:
        r=False
        break
print(r)

1007 成绩分析

#!/usr/bin/python3
s=(int(input()))
r='Error!'
if s>=90 and s<=100:
    r='A'
elif s>=80 and s<=89:
    r='B'
elif s>=70 and s<=79:
    r='C'
elif s>=60 and s<=69:
    r='D'
elif s>=0 and s<=59:
    r='F'
print(r)

1008 最大公约数

#!/usr/bin/python3
import math
print(math.gcd(int(input()),int(input())))

1009 输出偶数

#!/usr/bin/python3
n=int(input())
for i in range(n):
    if((i+1)%2==0):
        print(i+1)

1010 计算均值

#!/usr/bin/python3
n=int(input())
s=0
for i in range(n):
    s+=int(input())
print('{} {:.5f}'.format(s,s/n))

1011 计算阶乘

#!/usr/bin/python3
def col(n):
    s=1
    for i in range(1,n+1):
        s*=i
    return s

n=int(input())
s=0
for i in range(1,n+1):
    s+=col(i)
print(s)

1012 汇率兑换

#!/usr/bin/python3
s=input()
r=s[-1]
s=int(s.strip(r))

if r=='R' or r=='r':
    print('%dD' % (s//6))
elif r=='D' or r=='d':
    print('%dR' % (s*6))
else:
    print('Error!')

1013 进度条的显示

#!/usr/bin/python3
scale=int(input())
print("------start------")
for i in range(scale+1):
    print('{:3} %['.format(i*100//scale),end='')
    for j in range(i):
        print('**',end='')
    print('->',end='')
    for j in range(scale-i):
        print('..',end='')
    print(']')
print("------end-----")

1014 因子数

#!/usr/bin/python3
n=int(input())

n1=n
n2=n
s1=0
s2=0

while n1%4==0:
    n1//=4
    s1+=1
while n2%7==0:
    n2//=7
    s2+=1

print(s1,s2)

1015 文章检测

#!/usr/bin/python3 

stopword = ''
stri = ''
try:
    for line in iter(input, stopword):
        stri += line + '\n'
except EOFError:
   pass
stri = stri[0:-1]

spaces=0
letters=0
numbers=0
other=0

for i in stri:
    if i.isupper() or i.islower():
        letters+=1
    elif i.isnumeric():
        numbers+=1
    elif i==' ':
        spaces+=1
    else:
        other+=1

print('{} spaces, {} numbers, {} letters, {} other characters.' .format(spaces,numbers,letters,other))

1016 eval() 函数的使用2

#!/usr/bin/python3
import math
x=12
y=14
print(eval(input()))

1017 质数的和与积

#!/usr/bin/python3 
from math import sqrt

def isprime(x):
    for i in range(2,int(sqrt(x))+1):
        if x%i==0:
            return False
    return True

s=int(input())
result=[]

for i in range(2,s//2):
    if isprime(i) and isprime(s-i):
        result.append(i*(s-i))

print(max(result))

1018 寻找多数元素

#!/usr/bin/python3 
array={}
while True:
    try:
        i=input()
        try:
            array[i]+=1
        except KeyError:
            array[i]=1
    except EOFError:
        break
    
print(max(array.values()))

1019 判断素数

#!/usr/bin/python3
import math

def is_prime(x):
    if x<2:
        return False
    for i in range(2,int(math.sqrt(x))):
        if x%i==0:
            return False
    return True

try:
    num=int(input())
except ValueError:
    print('invalid')
else:
    print(is_prime(num))

1020 所有参数的乘积

#!/usr/bin/python3 
def multi(*x):
    u=1
    count=1
    for i in x:
        try:
            i+=0
            u*=i
            count+=1
        except TypeError:
            return 'Invalid arg %d'%count
    return u

print(eval(input()))  

1021 到底怎么样才能写好 Python?

#!/usr/bin/python3
import this

1022 CSV 文件解析

#!/usr/bin/python3
import csv

#输入csv文件
fo = open("shishi.csv","w")
list=[]

stopword = ''
stri = ''
try:
    for line in iter(input, stopword):
        stri += line + '\n'
except EOFError:
   pass
stri = stri[0:-1]
list = stri.split(",")

fo.write(",".join(list)+"\n")
fo.close()

#输出csv文件
fo = open("shishi.csv","r")
ls = []
for line in fo:
    line = line.replace("\n","")
    ls = line.split(",")
    lns = ""
    for s in ls:
       lns += "{}\t".format(s)
    print(lns)
fo.close()

1023 重复元素的判定

#!/usr/bin/python3 
n=int(input())
num=[]
re=0
count=1
for i in range(n):
    k=input()
    if re==0 and num.count(k)==1:
        re=count
    count+=1
    num.append(k)
if re==0:
    print('False')
else:
    print('True\n%d'%re)

1024 计算集合的并

#!/usr/bin/python3
a=set(map(int,input().split()))
b=set(map(int,input().split()))
print(a|b)

1025 计算标准差

#!/usr/bin/python3
from math import sqrt
def dev(m):
    s=0
    x=sum(m)/len(m)
    for i in m:
        s+=(i-x)**2
    return sqrt(s/(len(m)-1))
    
m = []
try:
    for line in iter(input,''):
        m.append(int(line))
except:
   pass

print("dev = {:.2}.".format(dev(m)))

第25题提到的标准差是样本标准差:
样本标准差

1026 键值查询

#!/usr/bin/python3
d=eval(input())
print(d[input()])

1027 月份输出

#!/usr/bin/python3
print('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ')[int(input())-1])

1028 字符串进制转换

#!/usr/bin/python3
print(hex(int(input())))

1030 集合的交

#!/usr/bin/python3
print(set(map(int,input().split()))&set(map(int,input().split())))

1031 小型登陆系统

#!/usr/bin/python3
usr='Pile'
passwd='MAKIKAWAYI'
for i in range(3):
    login_usr=input()
    login_passwd=input()
    if login_usr==usr and login_passwd==passwd:
        print('SUCCESS')
        break
    if i==2:
        print('FAILED')

1032 密码

# !/usr/bin/python3
def col(passwd):
    if not 8<=len(passwd)<=16:
        return False

    state=[0,0,0,0]
    for n in passwd:
        if n.isdigit():
            state[0]=1
        elif n.isupper():
            state[1]=1
        elif n.islower():
            state[2]=1
        else:
            state[3]=1

    if sum(i for i in state)>=3:
        return True
    else:
        return False

M=int(input())
for i in range(M):
    passwd=input()
    if col(passwd):
        print('YES')
    else:
        print('NO')

1033 斐波那契数列Fibonacci问题

#!/usr/bin/python3
index=[1,1]
def f(x):
    try:
        return index[x]
    except:
        index.append(f(x-1)+f(x-2))
        return index[x]

T=int(input())
for i in range(T):
    print(f(int(input())))

1034 列表实现筛选法求素数

# !/usr/bin/python3
from math import * 
def is_prime(x):
    for i in range(2,int(sqrt(x)+1)):
        if x%i==0:
            return False
    return True

x=int(input())
n=2
s=[0,0]
while n>0:
    if is_prime(x):
        s[n-1]=x
        n-=1
    x-=1
print(s)

1035 圆周率的计算

#!/usr/bin/python3

from random import random,seed

num = int(input())
zhongzi = int(input())
seed(zhongzi)

hits = 0
for i in range(0, num):
    x, y = random(), random()
    square = pow(x ** 2 + y ** 2, 0.5)
    if square <= 1.0:
        hits += 1

print("{:.6f}".format(4*hits/num))

1036 凯撒密码

#!/usr/bin/python3

sym1 = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
sym2 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
st = input()
num = int(input())
lst = ""
for s in st:
    if s in sym1:
        s = sym1[(sym1.index(s)+num+1) % 26 - 1]
    if s in sym2:
        s = sym2[(sym2.index(s)+num+1) % 26 - 1]
    lst += s

print(lst)

1037 字符串重复判断

#!/usr/bin/env python3
import ast

def main():
    a = ast.literal_eval(input())
    dataset2 = []
    out = ''
    stra = ''
    for i in a[0]:
        dataset2.append(i)
        for i1 in range(1,len(a)):
            if i not in a[i1]:
                del(dataset2[-1])
                break
            stra = a[i1].replace(i,'',1)
            a[i1] = stra
    dataset2 = sorted(dataset2)
    for i in range(len(dataset2)):
        out += str(dataset2[i])
    print('"{}"'.format(out))
if __name__ == '__main__':
    main()

1038 卡片选择

#!/usr/bin/python3

def maxlist(lst):
    if 0 not in lst:
        print(-1)
    elif 5 not in lst:
        print(0)
    else:
        for i in range(lst.count(5), 8, -1):
            if 5 * i % 9 == 0:
                print('5'*i+'0'*lst.count(0))
                exit(0)
        print(0)
n = int(input())
lst = []
fil = list(map(int, input().split()))
maxlist(fil)

1039 Life, the Universe, and Everything

#!/usr/bin/python3
lst = []
while True:
    n = int(input())
    if n == 42:
        break
    lst.append(n)

for n in lst:
    print(n)

1040 23333

#!/usr/bin/python3

n,k = input().split()
n = int(n)
k = int(k)
lst = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
ls = ''
while n >= 1:
    ls += lst[int(n % k)]
    n = n // k

print(ls[::-1])

1041 整数数列求和

#!/usr/bin/python3
n,a=input().split()
a=int(a)
b=a
s=0
for i in range(int(n)):
    s+=b
    b=10*b+a
print(s)

1042 星号三角形

#!/usr/bin/python3

n = int(input())
k = n // 2
ls = "*"
for i in range(0, (n + 1) // 2 - 1):
    for j in range(0, k):
        print(" ", end="")
    k -= 1
    print(ls, end='')
    for j in range(0, k + 1):
        print(" ", end="")
    print()
    ls += "**"

print(ls)

1043 手机短号

#!/usr/bin/python3
N=int(input())
s=[]
for i in range(N):
    t=input()
    if len(t)==11:
        s.append('6'+t[-5:])
    else:
        s.append("Halation - I can't join it!")
for i in s:
    print(i)

1044

#!/usr/bin/python3

n = int(input())#字符串数量
ls = []
for i in range(n):
    s =input (). split()#读取字符串并分割为两个字符
    a = int.from_bytes(s[0].encode(),'big')#将第一个字符编码成整数
    b = int.from_bytes(s[1].encode(),'big')#将第二个字符编码成整数
    c = a + b#整数加法
    ls.append(c)

for i in ls:
    print(i)

1045 6翻了

#!/usr/bin/python3
s=input()
i=0
while i<len(s):
    # print('s:'+str(len(s))+' i:'+str(i))
    t='6'   
    if s[i]=='6':   
        j=i+1
        try:
            while s[j]=='6':
                t+='6'
                j+=1
        except:
            pass
    if len(t)>3 and len(t)<=9:
        s=s.replace(t,'9',1) 
    elif len(t)>9:
        s=s.replace(t,'27',1)
    else:
        pass
    i+=1
print(s)

1046 有理数四则运算1

#!/usr/bin/python3

import fractions as f

s = input()
s = f.Fraction(s)
t = input()
t = f.Fraction(t)
sum = s+t
print("{}/{}".format(sum.numerator,sum.denominator))


1049 admin 的密码问题

#!/usr/bin/python3

n = int(input())

namelst = []
passlst = []
count = 0
for i in range(0, n):
    name, password = input().split()
    flag = 0
    if password.find('1') != -1:
        password = password.replace('1', '@', 100)
        flag = 1
    if password.find('0') != -1:
        password = password.replace('0', '%', 100)
        flag = 1
    if password.find('O') != -1:
        password = password.replace('O', 'o', 100)
        flag = 1
    if password.find('l') != -1:
        password = password.replace('l', 'L', 100)
        flag = 1
    if flag:
        namelst.append(name)
        passlst.append(password)
        count += 1

if count == 0:
    if n > 1:
        print("There are {} accounts and no account is modified".format(n))
    else:
        print("There is {} account and no account is modified".format(n))
else:
    print(count)
    for i in range(0, count):
        print(namelst[i], end=" ")
        print(passlst[i])

1050 分级

#!/usr/bin/python3

n = int(input())

lst = list(input().split())

L, R = input().split()
L = int(L)
R = int(R)
sum = 0

for i in lst:
    sum += int(i)

def calculate(lst, num):
    global n
    global sum
    L = 0
    R = 0
    count = 0
    for k in lst:
        if count < num:
            L += int(k)
        else:
            R = sum - L
            break
        count += 1

    return L, R


for i in range(0, n):
    less, greater = calculate(lst, i)
    if n == 2:
        print(0)
        break
    if less >= L and less <= R and greater >= L and greater <= R:
        print(i+1)
        break

1051 统计工龄

#!/usr/bin/python3

import fractions as f

s = input()
s = f.Fraction(s)
t = input()
t = f.Fraction(t)
sum = s+t
print("{}/{}".format(sum.numerator,sum.denominator))


1053 跟奥巴马一起画方块(研究生期末考试题目)

#!/usr/bin/python3
n,s=input().split(' ')
n=int(n)
m=max(int(n/2),int(n/2+0.5))
for i in range(m):
    for j in range(n):
        print(s,end='')
    print('')

1054 IP的计算

#!/usr/bin/python3
def calcu(stri):
    amount = int(stri,2)
    return amount

stopword=' '
lt=[]
try:
    for line in iter(input,stopword):
        lt.append(int(line))
except EOFError:
    pass
for n in lt:
    x = 31
    while 2 ** (32-x) <= n + 2:
        x -= 1
    stri = '1' * x + '0' * (32-x)
    print('{}.{}.{}.{}'.format(calcu(stri[0:8]),calcu(stri[8:16]),calcu(stri[16:24]), calcu(stri[24:])))

1058 Cut Integer

#!/usr/bin/python3
N=int(input())
for i in range(N):
    x=input()
    n=int(len(x)/2)
    a=int(x[:n])
    b=int(x[n:])
    x=int(x)
    try:
        if  x%(a*b)==0:
            print('Yes')
        else:
            print('No')
    except:
        print('No')


1066 列表排序

#!/usr/bin/python3

n = int(input())

lst1 = []
for i in range(0, n):
    k = int(input())
    lst1.append(k)

lst1.sort()

n = int(input())
lst2 = []
for i in range(0, n):
    k = int(input())
    lst2.append(k)

for i in lst2:
    print(lst1[i])

1073 寻找目标

#!/usr/bin/python3

stopword = ''
ls = []
try:
    for line in iter(input, stopword):
        ls.append(line)
except EOFError:
    pass

result = 1
for i in ls:
    t = i.split(',')
    if 'target' in t:
        num = t.index('target')
        result = 0
    if result == 0:
        if t[num] == '1':
            print(i)

if result:
    print("File is not OK!")

1075 寻找目标2

#!/usr/bin/python3
import json

stopword = ''
ls = []
count = 0
result = 1
try:
    for line in iter(input, stopword):
        line = line.replace('\n', '')
        line = line.split(',')
        if count == 0:
            if line.count('target') != 0:
                ls.append(line)
                num = line.index('target')
                result = 0
            else:
                break
            count = 1
        if line[num] == '1':
            ls.append(line)

except EOFError:
    pass

if result:
    print("File is not OK!" )
    quit(0)

for i in range(1,len(ls)):
    ls[i] = dict(zip(ls[0], ls[i]))

s = json.dumps(ls[1:], indent=4)
print(s)

1076 扫雷问题

#!/usr/bin/python3

def calculate(lst, i, j):
    global n
    global m
    count = 0
    for k in range(0, 3):
        for s in range(0, 3):
            if i - 1 + k >= 0 and j - 1 + s >= 0 and i - 1 + k < n and j - 1 + s < m:
                if lst[i-1+k][j-1+s] == '*':
                    count += 1

    return count

n, m = input().split()
n = int(n)
m = int(m)
ls = []
for i in range(0, n):
    line = input()
    ls.append(line)

lst = []
for i in range(0, n):
    st = ''
    for j in range(0, m):
        if ls[i][j] == '*':
            st += '*'
        else:
            st += str(calculate(ls, i, j))
    lst.append(st)

for i in lst:
    print(i)

1077 说反话(研究生期末考试题目)

#!/usr/bin/python3

lst = input().split()

for i in range(len(lst)-1, 0, -1):
    print(lst[i], end=' ')

print(lst[0])

1079 JSON 文件转换成 CSV 文件

#!/usr/bin/python3

lst = input().split()

for i in range(len(lst)-1, 0, -1):
    print(lst[i], end=' ')

print(lst[0])

1080 JSON 文件转换成 CSV 文件2(建议作为期末考试题目)

#!/usr/bin/python3

import json

stopword = ''
ls = ''
try:
    for line in iter(input, stopword):
        ls += line
except EOFError:
    pass

ls = json.loads(ls)

data = [list(ls[0].keys())]
for item in ls:
    data.append(list(item.values()))

for item in data:
    print(','.join(item))

1085 RGB 和十六进制颜色字符串转换

#!/usr/bin/python3

stopword = ''
ls = []
try:
    for line in iter(input, stopword):
        if line[0] == '#':
            num1 = line[1:3]
            num2 = line[3:5]
            num3 = line[5:]
            s = 'rgb('+ str(int(num1, 16)) + ', ' + str(int(num2, 16)) + ', ' + str(int(num3, 16)) + ')'
            ls.append(s)
        else:
            line = line[4:-1]
            line = line.replace(',', '')
            num1, num2, num3 = line.split()
            num1 = hex(int(num1))[2:].upper()
            num2 = hex(int(num2))[2:].upper()
            num3 = hex(int(num3))[2:].upper()
            if len(num1) < 2:
                num1 = '0' + num1
            if len(num2) < 2:
                num2 = '0' + num2
            if len(num3) < 2:
                num3 = '0' + num3
            s = '#' + num1 + num2 + num3
            ls.append(s)

except EOFError:
    pass

for i in ls:
    print(i)

1088 列表递归降维

#!/usr/bin/python3

import json
stopword = ''
ls = []
try:
    for line in iter(input, stopword):
        # print(type(line))
        line = line.replace('[', '', 100)
        line = line.replace(']', '', 100)
        line = line.replace('(', '', 100)
        line = line.replace(')', '', 100)
        line = '[' + line + ']'
        ls.append(line)
except EOFError:
    pass

for i in ls:
    print(i)


1089 派送蛋糕(模拟考试题目)

#!/usr/bin/python3

import math
num = int(input())
sum = 0

ls = input().split()
for i in ls:
    sum += math.ceil(int(i) / 10)

print(sum)

1090 装饰水果

#!/usr/bin/python3

num = int(input())
ls = input().split()

if ls.count('0') > 0:
    print('Error!')
else:
    a = num // int(ls[0])
    b = num // int(ls[1])
    c = num // int(ls[2])

    if min(a, b, c) == 0:
        print('Error!')
    else:
        print(min(a, b, c))

1100 求素数

#!/usr/bin/python3

import math
def isPrime(x):
    if x == 2 or x == 3:
        return 1
    for i in range(2, int(math.sqrt(x)+1)):
        if x % i == 0:
            return 0
    return 1

num = int(input())
for i in range(num, 0, -1):
    if isPrime(i):
        print(i)
        break

1104 (3n + 1) 猜想

#!/usr/bin/python3

num = int(input())

if num == 1:
    print("OK")
else:
    while True:
        if num == 1:
            break
        if num % 2 == 0:
            num = num // 2
        else:
            num = num * 3 + 1
        print(num)

1108 质因数分解

'''
    █████▒█    ██  ▄████▄   ██ ▄█▀       ██████╗ ██╗   ██╗ ██████╗
  ▓██   ▒ ██  ▓██▒▒██▀ ▀█   ██▄█▒        ██╔══██╗██║   ██║██╔════╝
  ▒████ ░▓██  ▒██░▒▓█    ▄ ▓███▄░        ██████╔╝██║   ██║██║  ███╗
  ░▓█▒  ░▓▓█  ░██░▒▓▓▄ ▄██▒▓██ █▄        ██╔══██╗██║   ██║██║   ██║
  ░▒█░   ▒▒█████▓ ▒ ▓███▀ ░▒██▒ █▄       ██████╔╝╚██████╔╝╚██████╔╝
   ▒ ░   ░▒▓▒ ▒ ▒ ░ ░▒ ▒  ░▒ ▒▒ ▓▒       ╚═════╝  ╚═════╝  ╚═════╝
   ░     ░░▒░ ░ ░   ░  ▒   ░ ░▒ ▒░
   ░ ░    ░░░ ░ ░ ░        ░ ░░ ░
            ░     ░ ░      ░  ░
'''
#!/usr/bin/python3
import math
def isPrime(x):
    if x == 2 or x == 3:
        return 1
    for i in range(2, int(math.sqrt(x)+1)):
        if x % i == 0:
            return 0
    return 1

num = int(input())
for i in range(2,num):
    if isPrime(num - i):
        print(i)
        break

1110 查验身份证(模拟考试题目)

#!/usr/bin/python3

def check(line):
    ls = ['1','0','X','9','8','7','6','5','4','3','2']
    lst = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    sum = 0
    for i in range(0, 17):
        sum += lst[i] * int(line[i])
    sum = sum % 11
    if line[-1] == ls[sum]:
        return 1
    else:
        return 0

n = int(input())
ls = []
for i in range(0, n):
    line = input()
    if line[:-1].isnumeric() and check(line):
        pass
    else:
        ls.append(line)

if len(ls) == 0:
    print("All passed")
else:
    for i in ls:
        print(i)

1111 孪生素数

#!/usr/bin/python3

import math
def isPrime(x):
    if x == 2 or x == 3:
        return 1
    for i in range(2, int(math.sqrt(x)+1)):
        if x % i == 0:
            return 0
    return 1

a = int(input())
b = int(input())

result = 1
for i in range(2, a + 1):
    if isPrime(i) and isPrime(i+b):
        print(i,end=' ')
        print(i+b)
        result = 0

if result:
    print('Empty')

1112 两个向量的余弦相似度(研究生期末考试题目)

#!/usr/bin/python3

import json
import math

A = input()
B = input()

A = json.loads(A)
B = json.loads(B)
modulu_A = 0
modulu_B = 0
cos = 0

if len(A) != len(B):
    print("The length is not same")
else:
    for i in range(0, len(A)):
        cos += A[i] * B[i]
        modulu_A += A[i] * A[i]
        modulu_B += B[i] * B[i]
    if cos:
        modulu_A = modulu_A ** 0.5
        modulu_B = modulu_B ** 0.5
        cos = cos / (modulu_A * modulu_B)
    else:
        if modulu_A == 0 and modulu_B == 0:
            cos = 1
        else:
            cos = 0
    print("%.6f" % cos)

1113 跳舞机

#!/usr/bin/python3

ls1 = input()
ls2 = input()

score = 0
for i in range(0, len(ls1)):
    if ls2[i] == ls1[i]:
        score += 20
    if ls2[i] != ls1[i]:
        if score != 0:
            score -= 10
        else:
            pass

print(score)

1118 求指定层的元素个数

#!/usr/bin/python3
def function(lst,k,rank):
    cnt = 0
    for i in lst: 
        if rank != k and isinstance(i,list):    #如果当前层数不是指定层数,并且该元素为列表,那么我们就进入该列表,然后增加一个层数
            cnt += function(i,k,rank+1)
        elif rank == k and isinstance(i,int) or isinstance(i,float):   #如果是当前层数,并且是数字,就加起来
            cnt += 1
    return cnt

ls = eval(input())
k = int(input())
print(function(ls,k,1))               #函数(列表,指定层数,从第一层开始)

1119 列表元素个数的加权和(模拟考试题目)

#!/usr/bin/python3

# 后进先出
class myStack():
    def __init__(self,size):
        self.size=size  #栈的大小
        self.stack=[]	#定义一个空栈
        self.top=-1		#指示栈的存储情况,初始为-1,表示空栈,每入栈一个元素,top增加1,每出栈一个元素,top减少1

    def push(self, x): # 入栈之前检查栈是否已满
        if self.isfull():
            print("stack is full")
            return False
        else:
            self.stack.append(x)
            self.top = self.top + 1
            return True

    def pop(self):# 出栈之前检查栈是否为空
        if self.isempty():
            print("stack is empty")
            return False
        else:
            self.top = self.top - 1
            self.stack.pop()
            return True
    def gettop(self):
        if self.top!=-1:
            return self.stack[self.top]
    def isfull(self):
        return self.top+1 == self.size
    def isempty(self):
        return self.top == '-1'
    def showStack(self):
        print(self.stack)


st = input()
s=myStack(st.count('['))
num = 0
n = ''
sum = 0
for i in st:
    if i == '[':
        s.push(i)
        num += 1
        n = ''
    elif i == ']':
        s.pop()
        if len(n) != 0:
            sum += num
        num -= 1
        n = ''
    elif i == ',' and len(n) != 0:
        sum += num
        n = ''
    elif i.isdigit():
        n += i

print(sum)


文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年3月5日 下午8:30
下一篇 2023年3月5日 下午8:31

相关推荐

此站出售,如需请站内私信或者邮箱!