Python教程

PTA | 浙大版《Python程序设计》题目集 | 题解汇总

本文主要是介绍PTA | 浙大版《Python程序设计》题目集 | 题解汇总,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

完结撒花!历时两天!

函数题

6-1

def fn(a, n):
    number = 0
    sum = 0
    for i in range(1, n + 1):
        number = number * 10 + a
        sum += number
    return sum

6-2

def prime(k):
    if k == 1:
        return 0
    x = 2
    while x * x <= k:
        if k % x == 0:
            return 0
        x += 1
    return 1

def PrimeSum(m,n):
    sum = 0
    for k in range(m, n + 1):
        if prime(k):
            sum += k
    return sum

6-3

def CountDigit(number, digit):
    if number == 0:
        return digit == 0
    if number < 0:
        number *= -1
    ans = 0
    while number > 0:
        ans += number % 10 == digit
        number //= 10
    return ans

6-4

def fib(n):
    x, y = 1, 1
    for i in range(2, n + 1):
        x, y = y, x + y
    return y

def PrintFN(m, n):
    x, y = 1, 1
    ans = []
    while x <= n:
        if x >= m:
            ans.append(x)
        x, y = y, x + y
    return ans

6-5

def fac(k):
    return 1 if k == 0 else k * fac(k - 1)

def funcos(eps, x):
    k = 0
    sum = 0
    fl = +1
    while 1:
        tmp = fl * x ** k / fac(k)
        if abs(tmp) < eps:
            break
        sum += tmp
        fl *= -1
        k += 2
    return sum

6-6

def acronym(phrase):
    phrase = phrase.split()
    ans = ""
    for s in phrase:
        ans += s[0].upper()
    return ans

编程题

1-1

a = int(input())
b = int(input())
print(a + b)

1-2

a, b, c = map(int, input().split())
print(b * b - 4 * a * c)

1-3

print("人生苦短,我学Python")

2-1

m = int(input())
sum = 0
for i in range(11, m + 1):
    sum += i
print("sum = {}".format(sum))

2-2

x = float(input())
result = 0 if x == 0 else 1 / x
print("f({:.1f}) = {:.1f}".format(x, result))

2-3

x = int(input())
if x < 0:
    print("Invalid Value!")
else:
    y = max(0, x - 50)
    cost = x * 0.53 + y * 0.05
    print("cost = %.2lf" % cost)

2-4

a, n = map(int, input().split())
number = 0
sum = 0
for i in range(1, n + 1):
    number = number * 10 + a
    sum += number
print("s = %d" % sum)

2-5

n = int(input())
sum = 0
cur = 1
for i in range(n):
    sum += 1 / cur
    cur += 2
print("sum = %.6lf" % sum)

2-6

n = int(input())
up = 1
dw = 1
ty = +1
sum = 0
for i in range(n):
    sum += ty * up / dw
    up += 1
    dw += 2
    ty = -ty
print("%.3lf" % sum)

2-7

a, b = map(int, input().split(','))
s = ""
while b > 0:
    s = s + str(a)
    b -= 1
print(s)

2-8

a, b = input().split(',')
b = int(b)
x = 0
for i in range(len(a)):
    x = x * b + int(a[i]) - int('0')
print(x)

2-9

a, b, c = map(int, input().split())
for i in range(10):
    if a > b:
        a, b = b, a
    if a > c:
        a, c = c, a
    if b > c:
        b, c = c, b
print("%d->%d->%d" % (a, b, c))

2-10

dw, up = map(int, input().split())
if dw > up or up > 100:
    print("Invalid.")
    exit(0)
print("fahr celsius")
for i in range(dw, up + 1, 2):
    print("%d%6.1lf" % (i, 5 * (i - 32) / 9))

2-11

m, n = map(int, input().split())
sum = 0
for i in range(m, n + 1):
    sum += i * i + 1 / i
print("sum = %.6lf" % sum)

2-12

a = list(map(int, input().split()))
a.sort()
if a[0] + a[1] <= a[2]:
    print("These sides do not correspond to a valid triangle")
    exit(0)
s = sum(a) / 2
area = (s * (s - a[0]) * (s - a[1]) * (s - a[2])) ** 0.5
print("area = %.2lf; perimeter = %.2lf" % (area, sum(a)))

2-13

x = int(input())
y = 4 * x / 3 if x <= 15 else 2.5 * x - 17.5
print("%.2lf" % y)

2-14

A, B = map(int, input().split())
cnt = 4
sum = 0
for x in range(A, B + 1):
    sum += x
    cnt = (cnt + 1) % 5
    if x != A and cnt == 0:
        print()
    print("{:5}".format(x), end = "")
print()
print("Sum = {}".format(sum))

3-1

h1 = list(map(int, input().split()))
avg = sum(h1) / len(h1)
h2 = []
for h in h1:
    if h > avg:
        h2.append(h)
for h in h2:
    print("{} ".format(h), end = "")
print()

3-2

w = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
v = "10X98765432"
l = []

n = int(input())
for case in range(n):
    id = input()
    sum = 0
    for i in range(17):
        sum += w[i] * (ord(id[i]) - 48)
    sum %= 11
    if v[sum] != id[17]:
        l.append(id)
if len(l) == 0:
    print("All passed")
else:
    for id in l:
        print(id)

3-3

s = input()
a, b = input().split()
for i in range(len(s) - 1, -1, -1):
    if s[i] == a:
        print("{} {}".format(i, a))
    elif s[i] == b:
        print("{} {}".format(i, b))

3-4

a, b = input(), input()
print("index = {}".format(b.rfind(a)) if b.rfind(a) != -1 else "Not Found")

3-5

s = input()
sum = 0
for c in s:
    if ord(c) >= 48 and ord(c) <= 48 + 9:
        sum = sum * 10 + ord(c) - 48
print(sum)

3-6

count = {}
for i in map(int, input().split()[1:]):
    if i not in count:
        count[i] = 0
    count[i] += 1
l = list(count.items())
l.sort(key = lambda x:x[1], reverse = True)
print("{} {}".format(l[0][0], l[0][1]))

3-7

n = int(input())
a = list(map(int, input().split()))
value = max(a)
pos = 0
while a[pos] != value:
    pos += 1
print("{} {}".format(value, pos))

3-8

s = input()
print(s[::-1])

3-9

s = input()
neg = +1
tag = 0
value = 0
for c in s:
    if c == '-' and tag == 0:
        neg = -1
    number = None
    if      ord('0') <= ord(c) and ord(c) <= ord('9'):
        number = ord(c) - ord('0')
    elif    ord('a') <= ord(c) and ord(c) <= ord('f'):
        number = ord(c) - ord('a') + 10
    elif    ord('A') <= ord(c) and ord(c) <= ord('F'):
        number = ord(c) - ord('A') + 10
    if number != None:
        tag = 1
        value = value * 16 + number
value *= neg
print(value)

3-10

T = "AEIOU"
s = input()
sum = 0
for c in s:
    sum += c.isupper() and c not in T
print(sum)

3-11

s = input().split()
s.sort()
print("After sorted:")
for t in s:
    print(t)

3-12

s = input()
m = len(s)
x = 0
for c in s:
    x += ord(c) - ord('0')
print("{} {}".format(m, x))

3-13

s = input()
t = ""
for c in s:
    if not c.isupper():
        t = t + c
    else:
        t = t + chr(ord('A') + ord('Z') - ord(c))
print(t)

3-14

s = list(input())[:-1]
for i in range(len(s)):
    if s[i].isupper():
        s[i] = chr(ord(s[i]) - ord('A') + ord('a'))
    elif s[i].islower():
        s[i] = chr(ord(s[i]) - ord('a') + ord('A'))
ans = ""
for c in s:
    ans = ans + c
print(ans)

3-15

print(len(input().split()))

3-16

s = input()
count = {}
for c in s:
    count[c] = 0
l = list(count.items())
l.sort()
t  = ""
for x, y in l:
    t += x
print(t)

3-17

s = input().strip()
c = input().strip().lower()
s2 = ""
for i in s:
    if i.lower() != c:
        s2 += i
print("result: {}".format(s2))

3-18

own = set()
s = input()
ans = ""
for c in s:
    if c.isalpha() and c.lower() not in own:
        ans += c
        own.add(c.lower())
    if len(own) == 10:
        break
print("not found" if len(own) < 10 else ans)

3-19

n = int(input())
s = []
for numstr in range(n):
    t = input()
    s.append(t)
s.sort(key = lambda t:len(t), reverse = True)
print("The longest is: {}".format(s[0]))

3-20

s = list(map(int, input()))
x = s[0] + s[1] * 10 + s[2] * 100
print(x)

3-21

s = input()
print(s)
print("Yes" if s == s[::-1] else "No")

3-22

s = input()
own = set()
ans = ""
for c in s:
    if c.isupper() and c not in own:
        own.add(c)
        ans += c
print("Not Found" if len(own) == 0 else ans)

4-1

n = int(input())
for k in range(n + 1):
    print("pow(3,{}) = {}".format(k, 3 ** k))

4-2

def prime(k):
    if k == 1:
        return 0
    x = 2
    while x * x <= k:
        if k % x == 0:
            return 0
        x += 1
    return 1

m, n = map(int, input().split())
cnt, sum = 0, 0
for k in range(m, n + 1):
    if prime(k):
        cnt += 1
        sum += k
print("{} {}".format(cnt, sum))

4-3

n = int(input()) - 1
x = 1
for day in range(n):
    x = (x + 1) * 2
print(x)

4-4

def prime(x):
    k = 2
    while k * k <= x:
        if x % k == 0:
            return 0
        k += 1
    return 1
    
n = int(input())
if n == 4:
    print("4 = 2 + 2")
    exit(0)
for p in range(3, n - 3 + 1):
    q = n - p
    if prime(p) and prime(q):
        print("{} = {} + {}".format(n, p, q))
        exit(0)

4-5

n = int(input())
value = 1
sum = 1
for i in range(1, n + 1):
    value /= i
    sum += value
print("{:.8f}".format(sum))

4-6

n = int(input())
if n < 1:
    print("Invalid.")
    exit(0)
f = [0 for i in range(n + 1)]
f[1] = 1
if n >= 2:
    f[2] = 1
for i in range(3, n + 1):
    f[i] = f[i - 2]+ f[i - 1]
for i in range(1, n + 1):
    print("{:11}".format(f[i]), end = "\n" if i % 5 == 0 else "")
if n % 5 != 0:
    print()

4-7

n = int(input())
if n == 0:
    print("average = 0.0")
    print("count = 0")
    exit(0)
score = list(map(int, input().split()))
print("average = {:.1f}".format(sum(score) / len(score)))
count = 0
for x in score:
    count += x >= 60
print("count = {}".format(count))

4-8

n = int(input())
x, y = 2, 1
sum = 0
for i in range(1, n + 1):
    sum += x / y
    x, y = x + y, x
print("{:.2f}".format(sum))

4-9

print("[1] apple")
print("[2] pear")
print("[3] orange")
print("[4] grape")
print("[0] exit")
a = list(map(int, input().split()))[:5]
price = [3.00, 2.50, 4.10, 10.20]
for x in a:
    if x == 0:
        exit(0)
    p = price[x - 1] if 1 <= x and x <= 4 else 0
    print("price = {:.2f}".format(p))

4-10

def gcd(x, y):
    if y == 0:
        return x
    return gcd(y, x % y)


x, y = map(int, input().split())
g = gcd(x, y)

lcm = int(x * y / g)

print("{} {}".format(g, lcm))

4-11

def prime(x):
    if x == 1:
        return 0
    k = 2
    while k * k <= x:
        if x % k == 0:
            return 0
        k += 1
    return 1
    
n = int(input())
for case in range(n):
    x = int(input())
    print("Yes" if prime(x) else "No")

4-12

x, y = 1, 1
value = int(input())
while y < value:
    x, y = y, x + y
print(y)

4-13

error = float(input())
value = 1
sum = 1
for i in range(1, 10 ** 9):
    value /= i
    sum += value
    if value < error:
        break
print("{:.6f}".format(sum))

4-14

letter, blank, digit, other = 0, 0, 0, 0
cnt = 0
done = 0
while 1:
    t = input()
    for c in t:
        cnt += 1
        if c.isalpha():
            letter += 1
        elif c.isspace():
            blank += 1
        elif c.isdigit():
            digit += 1
        else:
            other += 1
        if cnt == 10:
            done = 1
            break
    if done:
        break
    cnt += 1
    blank += 1
    if cnt == 10:
        break
    print("letter = {}, blank = {}, digit = {}, other = {}" \
      .format(letter, blank, digit, other))

4-15

x = int(input())
count = 0
for x5 in range(x, 0, -1):
    for x2 in range(x, 0, -1):
        if 5 * x5 + 2 * x2 < x:
            x1 = x - 5 * x5 - 2 * x2
            print("fen5:{}, fen2:{}, fen1:{}, total:{}".format(\
                x5, x2, x1, x5 + x2 + x1))
            count += 1
print("count = {}".format(count))

4-16

a, b, c = map(int, input().split())
for cc in range(4):
    if a > b:
        a, b = b, a
    if b > c:
        b, c = c, b
print("yes" if a + b > c else "no")

4-17

n = int(input())
L = 10 ** (n - 1)
R = 10 ** n

def judge(x):
    y = 0
    for c in str(x):
        y += (ord(c) - ord('0')) ** n
    # print(x, y)
    return x == y

for x in range(L, R):
    if judge(x):
        print(x)

4-18

n = int(input())
vis = [i > 0 for i in range(n + 1)]
cur = 0

def nxt(cur, vis):
    while vis[cur] == 0:
        cur = cur % n + 1
    return cur

for turns in range(n - 1):
    cur = nxt(cur % n + 1, vis)
    cur = nxt(cur % n + 1, vis)
    cur = nxt(cur % n + 1, vis)
    vis[cur] = 0
print(nxt(cur % n + 1, vis))

4-19

n = int(input())
a = []
for i in range(n):
    a.append(list(map(int, input().split())))
sum = 0
for i in range(n):
    for j in range(n):
        if i + j == 0 + n - 1 or i == n - 1 or j == n - 1:
            1
        else:
            sum += a[i][j]
print(sum)

4-20

m = int(input().split()[0])
for cc in range(m):
    print(sum(map(int, input().split())))

4-21

T = int(input())
while T > 0:
    n = int(input())
    flag = 1
    for i in range(n):
        a = list(map(int, input().split()))
        for j in range(i):
            flag &= a[j] == 0
    print("YES" if flag else "NO")
    T -= 1

4-22

n = int(input())
a = []
for i in range(n):
    a.append(list(map(int, input().split())))
row = []
for i in range(n):
    row.append(max(a[i]))
col = [10 ** 9 for i in range(n)]
for j in range(n):
    for i in range(n):
        col[j] = min(col[j], a[i][j])
for i in range(n):
    for j in range(n):
        if a[i][j] == row[i] and a[i][j] == col[j]:
            print(i, j)
            exit(0)
print("NONE")

4-23

n, m = map(int, input().split())
a = []
for i in range(n):
    a.append(list(map(int, input().split())))

x4 = [0, 0, -1, +1]
y4 = [-1, +1, 0, 0]

def judge(x, y, n, m):
    for k in range(4):
        nx = x + x4[k]
        ny = y + y4[k]
        if a[x][y] <= a[nx][ny]:
            return 0
    return 1

cnt = 0
for i in range(1, n - 1):
    for j in range(1, m - 1):
        if judge(i, j, n, m):
            print(a[i][j], i + 1, j + 1)
            cnt += 1
if cnt == 0:
    print("None {} {}".format(n, m))

4-24

n = int(input())
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print("{}*{}={:<4}".format(i, j, i * j), end = "")
    print()

4-25

n = int(input())
cur = ord('A')
for i in range(n, 0, -1):
    for j in range(i):
        print(chr(cur), end = " ")
        cur += 1
    print()

4-26

n = int(input())

def fac(n):
    ans = 1
    for i in range(1, n + 1):
        ans *= i
    return ans

sum = 0
for i in range(1, n + 1, 2):
    sum += fac(i)
print("n={},s={}".format(n, sum))

4-27

a = list(map(int, input().split()))
b = [a[0:3], a[3:6], a[6:9]]
for i in range(3):
    print("{:4}{:4}{:4}{:4}{:4}".format(b[i][0], b[i][1], b[i][2], max(b[i]), sum(b[i])))

4-28

a = list(map(int, input().split()))
b = [a[0:3], a[3:6], a[6:9]]
for i in range(3):
    for j in range(3):
        print("{:4}".format(b[j][i]), end = "")
    print()

4-29

a = list(map(int, input().split()[1:]))
b = list(map(int, input().split()[1:]))

s = a.copy()
s.extend(b)
# print(s)

value = set()

tag = 0
for i in s:
    if i not in value and (i not in a or i not in b):
       print("{}{:d}".format("" if tag == 0 else " ", i), end = "")
       tag = 1
       value.add(i)
print()

4-30

m, n = map(int, input().split())
cnt = 0
for x in range(m, n + 1):
    l = []
    y = 1
    while y * y <= x:
        if x % y == 0:
            l.append(y)
            if y * y < x:
                l.append(x // y)
        y += 1
    l.sort()
    l = l[:-1]
    if x == sum(l):
        cnt += 1
        print("{} = {}".format(x, l[0]), end = "")
        for y in l[1:]:
            print(" + {}".format(y), end = "")
        print()
if cnt == 0:
    print("None")

5-1

day = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print(day[int(input()) - 1])

5-2

n = int(input())
m, sum = 0, 0
for i in range(n):
    s = eval(input())
    for u, v in s.items():
        for p, q in v.items():
            m += 1
            sum += q
print("{} {} {}".format(n, m, sum))

5-3

a = float(input())
op = input()
b = float(input())

try:
    res = {'+': a + b, '-': a - b, '*': a * b, '/': a / b}
    print("{:.2f}".format(res[op]))
except:
    print("divided by zero")

5-4

a = set(map(int, input().split(',')))
tag = 0
for i in range(6, 10 + 1):
    if i not in a:
        print("{}{}".format("" if tag == 0 else " ", i), end = "")
        tag = 1
print()

5-5

s = input()
c = input()
cnt = 0
for a in s:
    cnt += a == c
print(cnt)

5-6

dict = {}
input()
for i in map(int, input().split()):
    if i not in dict:
        dict[i] = 0
    dict[i] += 1
for x, y in sorted(dict.items()):
    print("{}:{}".format(x, y))

5-7

a = eval(input())
s = set()
b = []
for u in a:
    if u not in s:
        b.append(u)
        s.add(u)
print(" ".join(list(map(str, b))))

5-8

a, b = map(int, input().split())
cnt = 0
for x in range(a, b + 1):
    cnt += x % (3 * 5 * 7) == 0
print(cnt)

5-9

n = int(input())
a = []
for i in range(n):
    a.append(list(map(int, input().split())))
row = []
for i in range(n):
    row.append(max(a[i]))
col = [10 ** 9 for i in range(n)]
for j in range(n):
    for i in range(n):
        col[j] = min(col[j], a[i][j])
cnt = 0
for i in range(n):
    for j in range(n):
        if a[i][j] == row[i] and a[i][j] == col[j]:
            cnt += 1
print(cnt)

5-10

a = list(map(int, input().split(',')))
s = int(input())
dict = {}
for i in range(len(a)):
    dict[a[i]] = i
for i in range(len(a)):
    if s - a[i] in dict:
        print(i, dict[s - a[i]])
        exit(0)
print("no answer")

5-11

a = eval(input())
b = eval(input())
for i in b:
    if i not in a:
        a[i] = 0
    a[i] += b[i]
l = []
for u, v in list(a.items()):
    l.append([ord('0') + u - 300 if type(u) == type(1) else ord(u), v])
l.sort()
o = ["{}:{}".format(x - ord('0') + 300      \
                    if x < 0                \
                    else                    \
                    "\"" + chr(x) + "\""    \
                    , y) for x, y in l]
print("{", end = "")
print(",".join(o), end = "")
print("}")

6-1

print(sum(eval(input())))

6-2

n = int(input())
a = []
for i in range(n):
    a.append(input().split())
    a[-1][0] = int(a[-1][0])
cursor = [n - 1, n - 1]
vis = [0 for i in range(n)]
for i in range(n):
    if not vis[i]:
        ano = a[i][0] ^ 1
        while a[cursor[ano]][0] != ano or vis[cursor[ano]]:
            cursor[ano] -= 1
        print(a[i][1], a[cursor[ano]][1])
        vis[i], vis[cursor[ano]] = 1, 1

6-3

a = eval(input())
sum = 0
def acc(a):
    global sum
    for u in a:
        if type(u) == int or type(u) == float:
            sum += u
        elif type(u) == list or type(u) == tuple:
            acc(u)
acc(a)
print(sum)

6-4

a = eval(input())
sum = 0
def acc(a, dep):
    global sum
    for u in a:
        if type(u) == int or type(u) == float:
            sum += u * dep
        elif type(u) == list or type(u) == tuple:
            acc(u, dep + 1)
acc(a, 1)
print(sum)

6-5

a = eval(input())
sum = 0
def acc(a, dep):
    global sum
    for u in a:
        if type(u) == int or type(u) == float:
            sum += dep
        elif type(u) == list or type(u) == tuple:
            acc(u, dep + 1)
acc(a, 1)
print(sum)

6-6

a = eval(input())
c = int(input())
sum = 0
def acc(a, dep):
    global sum
    if dep == c:
        sum += type(a) == int or type(a) == float
    if type(a) == list or type(a) == tuple:
        for u in a:
            acc(u, dep + 1)
acc(a, 0)
print(sum)

6-7

n = int(input())
a = []
for i in range(n):
    a.append(input().split())
a.sort(key = lambda x: int(x[2]) + int(x[3]) + int(x[4]), reverse = True)
print(a[0][1], a[0][0], int(a[0][2]) + int(a[0][3]) + int(a[0][4]))

6-8

n = int(input())
s = set(i for i in range(1, n + 1))
for x in range(10 ** (n - 1), 10 ** n):
    if set(map(int, list(str(x)))) == s:
        print(x)

7-1

import sys
text = sys.stdin.read()
text = text[:text.find('#')]

for c in text:
    if not c.isalnum() and c != '_':
        text = text.replace(c, ' ')
text = text.lower().split(' ')

dict = {}
for s in text:
    if s == '':
        continue
    else:
        s = s[:15]
        dict[s] = dict.get(s, 0) + 1

data = sorted(dict.items(), key = lambda x: (-x[1], x[0]))

print(len(data))
num = int(len(data) * 0.1)
for x in data[:num]:
    print("{}:{}".format(x[1], x[0]))
这篇关于PTA | 浙大版《Python程序设计》题目集 | 题解汇总的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!