飞道的博客

怒刷python作业

474人阅读  评论(0)

以下作业题仅为参考答案,为了锻炼思维的目的,所有的底层操作都是独立实现,尽量少的引包,大家对题有更好的思路和更方便的包欢迎大家多多留言,祝愿大家共同进步

1 hello word

略…

2A+B

A = int(input())
B = int(input())
print(A+B)

#### 3N位小数 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20201010222245445.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzODA4NzAw,size_16,color_FFFFFF,t_70#pic_center)

f = float(input())
n = int(input())
print(round(f,n))

4二进制(题目错误,只要第二个输出的也是a的二进制题目就能通过)

调用函数

a = int(input())
b = int(input())
print(bin(a),bin(b),a & b)

全部自己实现

a = int(input())
b = int(input())
def toBin(num):
    s = ""
    while num > 0:
        s += str(num&1)
        num >>= 1
        l = list(s)
        l.reverse()
    return "".join(l)
print("0b"+toBin(a))
print("0b"+toBin(b))

5ASCII

n = int(input())
a = input()
print(chr(n),ord(a))

6进制转换

n = int(input())
print(oct(n), hex(n),bin(n), sep = ",")

7整数格式输出

a = int(input())
print("{:<10d}".format(a))
print("{:>10d}".format(a))
print("{:<+10d}".format(abs(a)))
print("{:>+10d}".format(abs(a)))

8浮点数输出

a = float(input())
print("{:<.6f}".format(a),"{:<.2f}".format(a),"{:<.8f}".format(a), "{:.6e}".format(a), "{:,}".format(a), sep = "/")

9各种表示

a = int(input())
print('{:b}'.format(a), '{:o}'.format(a), oct(a), '{:x}'.format(a), hex(a), '{:#X}'.format(a), sep = ",")

10动态宽度


toBin函数:按位得到n位长度的逆序二进制并借助list反转,然后使用join方法将list还原为字符串

m = int(input())
n = int(input())
def toBin(num, n):
    s = ""
    for i in range(0, n):
        s += str(num&1)
        num >>= 1
        l = list(s)
        l.reverse()
    return "".join(l)
print(toBin(m, n))

使用格式化函数format和rjust方法改进 1

a = int(input())
n = int(input())
print("{:b}".format(a).rjust(n, '0'))

11两个分数加减乘除

a = int(input())
b = int(input())
c = int(input())
d = int(input())
def simple(d):
    a = d['molecule']
    b = d['denominator']
    while a%b != 0:
        tmp=a%b
        a = b
        b = tmp
    d['molecule'] /= b
    d['denominator'] /= b
dict = {'molecule':a*d+b*c, 'denominator':b*d}
simple(dict)
print("("+str(a)+"/"+str(b)+")"+"+("+str(c)+"/"+str(d)+")"+"="+str(int(dict['molecule']))+"/" + str(int(dict['denominator'])))
dict['molecule'] = a*d-b*c
simple(dict)
print("("+str(a)+"/"+str(b)+")"+"-("+str(c)+"/"+str(d)+")"+"="+str(int(dict['molecule']))+"/" + str(int(dict['denominator'])))
dict['molecule'] = a*c
simple(dict)
print("("+str(a)+"/"+str(b)+")"+"*("+str(c)+"/"+str(d)+")"+"="+str(int(dict['molecule']))+"/" + str(int(dict['denominator'])))
dict['molecule'] = a*d
dict['denominator'] = b*c
simple(dict)
print("("+str(a)+"/"+str(b)+")"+"/("+str(c)+"/"+str(d)+")"+"="+str(int(dict['molecule']))+"/" + str(int(dict['denominator'])))

12计算狗的年龄

a = int(input())

if a<=2:
    print(a*10.5)
else:
    print(int(2*10.5+(a-2)*4))

13风寒指数

import math
v = float(input())
t = float(input())
chill = 13.12+0.6215*t-11.37*math.pow(v, 0.16)+0.3965*t*math.pow(v, 0.16)
print(round(chill))

14圆柱

import math
h = float(input())
r = float(input())
pai = 3.14159265
print("{:.4f}".format(pai*pow(r, 2)*h))
print("{:.4f}".format(pai*pow(r, 2)*2+2*pai*r*h))

15直角坐标转换为极坐标

import math
x = float(input())
y = float(input())
print("{:.4f}".format(math.sqrt(pow(x, 2)+pow(y, 2))), "{:.4f}".format(math.atan2(y, x)), sep = ",")

16给定经纬度计算地球上两点之间的距离

import math
latitude1 = math.radians(float(input()))
longitude1 = math.radians(float(input()))
latitude2 = math.radians(float(input())) #纬度
longitude2 = math.radians(float(input())) #经度

#经纬度转换弧度

def har(th):
    return math.pow(math.sin(th/2), 2)

#求差值
vlon = abs(longitude1 - longitude2)
vlat = abs(latitude1 - latitude2)

h = har(vlat)+math.cos(latitude1)*math.cos(latitude2)*har(vlon)
print("{:.4f}".format(2*6371*math.asin(math.sqrt(h))), "km", sep = "")

17勾股定理

import math
a = int(input())
b = int(input())
max = a if a>b else b
min = a if a<b else b
def isTriangle(a, b, c):
    if a+b > c and a+c > b and b+c > a and abs(a-b) < c and abs(a-c) < b and abs(c-b) < a:
        return True
    else:
        return False
condition1 = int(math.sqrt(math.pow(max, 2) - math.pow(min,2)))
condition2 = int(math.sqrt(math.pow(max, 2) + math.pow(min,2)))
if(isTriangle(min, max, condition2) and math.pow(min, 2)+math.pow(max, 2) == math.pow(condition2, 2) and condition2 > max):
        print("c")
elif(isTriangle(min, max, condition1) and  math.pow(min, 2)+math.pow(condition1, 2) == math.pow(max, 2) ):
    if condition1<min:
        print("a")
    if condition1<max and condition1>min:
        print("b")
else:
    print("non")

18RGB转换HSV

R = int(input())/255
G = int(input())/255
B = int(input())/255
def max(a, b, c):
    m = a if a > b else b
    m = m if m > c else c
    return m
def min(a, b, c):
    m = a if a < b else b
    m = m if m < c else c
    return m
V = maximum = max(R, G, B)
minimum = min(R, G, B)
S = (maximum - minimum)/maximum
if maximum == R:
    H = (G-B)/(V-minimum)
if maximum == G:
    H = 2+(B-R)/(maximum-minimum)
if maximum == B:
    H = 4+(R-G)/(maximum-minimum)
H *= 60
if H<0:
    H += 360
print("{:.4f}".format(H), "{:.4%}".format(S), "{:.4%}".format(V), sep = ",")

19比率

f = float(input())
# 分数通分
def simple(d):
    a = d['molecule']
    b = d['denominator']
    while a%b != 0:
        tmp=a%b
        a = b
        b = tmp
    d['molecule'] /= b
    d['denominator'] /= b
# 判断小数位有几位
len = len(str(f))-len(str(int(f)))-1
dict = {'molecule':f*pow(10, len), 'denominator':pow(10, len)}
simple(dict)
print(str(int(dict['molecule']))+"/" + str(int(dict['denominator'])))

20.指定精度输入


第一步得到保留n+1位浮点数的字符串s,判断要保留的最后一位小数的下一位要不要进位并完成舍和入得到最后一位小数,然后将保留n-1位小数的字符串和最后一位小数合并字符串得到最终结果:从精度上考虑,缺点也很明显,只判断了要保留的最后一位小数位的下一位,而不是整个小数部分进位,会出现应该进位却没进位的情况

f = float(input())
n = int(input())
s = str(f)[0:len(str(int(f)))+n+2]
if(int(s[len(s)-1])>4):
    s2 = str(int(s[len(s)-2])+1) 
else:
    s2 = str(int(s[len(s)-2]))
s = s[0:len(str(int(f)))+n]+s2
print(s)

可以参考前面 N位小数的那一道题 使用round函数,但是注意round函数并不总是四舍五入,会受计算机表示精度的影响,同时也受python版本影响 2
根据题目给的测试用例,很明显千分位的5是进位的情况,说明距离两端一样远的情况下,则保留到离0远的一边,那么很明显刷题平台是python2.x的环境,直接使用round函数就能通过

f = float(input())
n = int(input())
print(round(f, n))

21.整数组合

import math
n = int(input())
m = int(input())
sum = 0
for i in range(m):
    sum += n*int(math.pow(10, i))*(m-i)
print(sum)

# 解法为按位计算,第一次循环统计各位,第二次十位以此类推...每一位的个数随循环减少
# 555
#  55
#   5

# pow(10, i)效率还可以提升,利用迭代
sum = 0
tmp = 1
for i in range(m):
    sum += n*tmp*(m-i)
    tmp *= 10
print(sum)

22.组合数

n = int(input())
count = 0
for a in range(10):
    for b in range(10):
        for c in range(10):
                d = n-a-b-c
                if 0 <= d <= 9:
                    count += 1
print(count)

23对称数

integer = int(input())
def isSymmetry(a, b):
    if (a=='9'and b=='6') or (a=='6'and b=='9') or a == b:
        return True
    else:
        return False
flag = True
for i in range(len(str(integer))>>1):
    if False == isSymmetry(str(integer)[i], str(integer)[len(str(integer))-i-1]):
        flag = False
if flag:
    print("Yes")
else:
    print("No")

24.平行线

x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
x3 = float(input())
y3 = float(input())
x4 = float(input())
y4 = float(input())
if(y2-y1)/(x2-x1) == (y4-y3)/(x4-x3):
    print("Yes")
else:
    print("No")

25.阶乘末尾

n = int(input())
product = 1
for i in range(1, n+1):
    product *= i
num = 0
for i in range(len(str(product))):
    if('0' == str(product)[len(str(product))-i-1]):
        num+=1
    else:
        break
print(num)

26.操作数

n = int(input())
def count(n):
    sum = 0
    while(n > 0):
        sum += int(n%10)
        n /= 10
    return sum
nums = 0
while n>0:
    n -= count(n)
    nums += 1
print(nums)

27.斐波那契数列

n = int(input())
def fib(n):
    if 1 == n or 2 == n:
        return 1
    a = 0
    b = 1
    c = 1
    for i in range(n-2): 
        a = b
        b = c
        c = a+b
    return c
print(fib(n))

28.圆

import math
x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
x3 = int(input())
y3 = int(input())
a=2*(x2-x1)
b=2*(y2-y1)
c=2*(x3-x2)
d=2*(y3-y2)
e=x2*x2+y2*y2-x1*x1-y1*y1
f=x3*x3+y3*y3-x2*x2-y2*y2
x=(b*f-d*e)/(b*c-d*a)
y=(c*e-a*f)/(b*c-d*a)
r=math.sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1))
print("{:.3f}".format(r), "{:.3f}".format(x), "{:.3f}".format(y), sep = ",")

29.回文数

integer = int(input())
def isSymmetry(a, b):
    if a == b:
        return True
    else:
        return False
flag = True
for i in range(len(str(integer))>>1):
    if False == isSymmetry(int(str(integer)[i]), int(str(integer)[len(str(integer))-i-1])):
        flag = False
if flag:
    print("Yes")
else:
    print("Not")

代码改进

n = int(input())
s = str(n)
res = ""
for i in range(len(str(n))):
    res += str(s[i])
if int(res) == n:
    print("Yes")
else:
    print("Not") 

30.方程组

a = float(input())
b = float(input())
c = float(input())
d = float(input())
e = float(input())
f = float(input())
if a/d == b/e and a/d != c/f:
    print("error")
else:
    x=(c*e-f*b)/(a*e-d*b)
    y=(c*d-a*f)/(b*d-e*a)
    print("{:.3f}".format(x), "{:.3f}".format(y), sep = " ")

31.长安


以下代码每输入一行就会输出结果到缓冲区

# a!/(a-n)!
def factorial(n, a):
        pro = 1
        tmp = n
        for i in range(a):
            pro *= tmp
            tmp -= 1
        return pro
# b!/a!*(b-a)!
def c(a, b):
    return factorial(a+b, a)/factorial(a, a)
def cout(bx, by, px, py):
    if px <= bx and py <= by:
        return c(bx, by) - c(px, py)*c(bx-px, by-py)
    else:
        return c(bx, by)
bx = by = px = py = 1
while True:
    bx,by,px,py = map(int,input().split(","))
    if bx>=0 and by>=0 and px>=0 and py>=0:
        print(int(cout(bx, by, px, py)))
    else:
        break

以下代码每输入一条用例就会将结果存储到列表中,直到输入的测试用例不符合条件,再一次性输出所有结果

# a!/(a-n)!
def factorial(n, a):
        pro = 1
        tmp = n
        for i in range(a):
            pro *= tmp
            tmp -= 1
        return pro
# b!/a!*(b-a)!
def c(a, b):
    return factorial(a+b, a)/factorial(a, a)
def cout(bx, by, px, py):
    if px <= bx and py <= by:
        return c(bx, by) - c(px, py)*c(bx-px, by-py)
    else:
        return c(bx, by)
bx = by = px = py = 1
L = []
while True:
    bx,by,px,py = map(int,input().split(","))
    if bx>=0 and by>=0 and px>=0 and py>=0:
        L.append(int(cout(bx, by, px, py)))
    else:
        break
for i in range(0, len(L)):
    print(L[i])

以上代码对于这题都是正确的,但是有时候是要区分的,刷题平台的后台如果是一条一条测试用例输入,要求一条一条结果输出那么以上第一种代码正确 3,第二种就会错误 4。如果刷题平台的后台测试用例是一次性输入多条测试用例最后一条是不符合条件终止循环的,要求最终一次性输出所有结果,那么以上两种代码都是正确的

32.最接近的分数 5

以下简单的枚举就可以通过题目

n, a, b = map(int,input().split(" "))
p = 1
q = n
for x in range(1, n+1):
    for y in range(n, 0, -1):
        if(b * x < a * y and x * q > p * y):
           p = x
           q = y
print(str(p)+"/"+str(q))

碰到题目测试用例刁钻的请增加通分函数通分,如下

n, a, b = map(int,input().split(" "))
p = 1
q = n
def simple(d):
    a = d['molecule']
    b = d['denominator']
    while a%b != 0:
        tmp=a%b
        a = b
        b = tmp
    d['molecule'] /= b
    d['denominator'] /= b
for x in range(1, 101):
    for y in range(100, 0, -1):
        if(b * x < a * y and x * q > p * y):
           p = x
           q = y
max = {
   'molecule':p, 'denominator':q}
simple(max)
print(str(int(max['molecule']))+"/"+str(int(max['denominator'])))

来自方一舟的损失精度评测是否有分子分母有公因子

def most_common_divisor(num1, num2):
    # 求num1和num2的最大公因子
    if num2 > num1:
        num1, num2 = num2, num1
    divisor = 1 # 返回值最大公因子
    i = 1 # 循环出口标志
    while i <= num2:
        if num1%i==0 and num2%i==0:
            if i >= divisor:
                divisor = i
        i += 1
    if divisor == 1:
        return False
    else:
        return True

n, a, b = map(int, input().split())
value = a/b
gap_min = 1001
result_deno = 1
result_nume = 0
for denominator in range(1, n+1):
    numerator = int(denominator * value)
    gap = abs(numerator/denominator - value)
    if gap < gap_min and gap != 0 and ~most_common_divisor(denominator, numerator):
        gap_min = gap
        result_deno = denominator
        result_nume = numerator
print(result_nume, '/', result_deno, sep='')

利用辗转相除法求最大公因子改造以上一舟代码使得判断是否存在公因子的函数时间复杂度降到O(1),判断某些情况是否发生只需要判断充分条件是否满足就行,不一定求得公因子只需要判断公因子存在得条件是否成立

n, a, b = map(int,input().split(" "))
p = 1
q = n
def most_common_divisor(d):
    a = d['numerator']
    b = d['denominator']
    if a%b != 0:
        tmp=a%b
        a = b
        b = tmp
    if b == d['denominator']:
        return False
    else:
        return True
value = a/b
gap_min = 1001
result_deno = 1
result_nume = 0
for denominator  in range(1, n+1):
    numerator = int(denominator * value)
    gap = abs(numerator/denominator - value)
    max = {
   'numerator':numerator, 'denominator':denominator}
    if gap < gap_min and gap != 0 and ~most_common_divisor(max):
        gap_min = gap
        result_deno = max['denominator']
        result_nume = max['numerator']
print(result_nume, '/', result_deno, sep='')

33.小木棍等式 6

n = int(input())
def stick_number(num):
    # 函数返回两位数字num需要的火柴个数
    # 记录下数字0~9需要的火柴个数
    stick_num = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
    result = 0
    if num < 10:
        result = stick_num[num]
    elif 10 <= num < 100:
        # 返回个位和十位的火柴个数
        result = stick_num[num%10] + stick_num[num//10]
    elif 100 <= num < 1000:
        result = stick_num[num%10] + stick_num[(num//10)%10] + stick_num[num//100]
    else:
        result = stick_num[num%10] + stick_num[(num//10)%10] + stick_num[num//100%10] + stick_num[num//1000]
    return result

def stick_eqution(n):
    count = 0
    if n <= 4:
        return count
    else:
        n -= 4 # 减去+=用去的4根火柴
        for num1 in range(1000):
            for num2 in range(1000):
                if stick_number(num1) + stick_number(num2) + stick_number(num1 + num2) == n:
                    count += 1
    return count
print(stick_eqution(n))

经过贪心算法测试以下代码正确,但是不能满足本题通过的时间复杂度

n = int(input())
dict = {
   0:6, 1:2, 2:5, 3:5, 4:4, 5:5, 6:6, 7:3, 8:7, 9:6}  
def countStick(num):
    count = 0
    for i in range(0, len(num)):
        count += dict[int(num[i])]
    return count

def c(n):
    count = 0
    for i in range(0, 1000):
        for j in range(0, 1000):
            c = i+j
            if(countStick(str(i))+countStick(str(j))+countStick(str(c)) == n-4):
                list = [i, j, c]
                count+=1
    return count
print(c(n))

以上两种代方法的贪心测试代码


def stick_number(num):
    # 函数返回两位数字num需要的火柴个数
    # 记录下数字0~9需要的火柴个数
    stick_num = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
    result = 0
    if num < 10:
        result = stick_num[num]
    elif 10 <= num < 100:
        # 返回个位和十位的火柴个数
        result = stick_num[num%10] + stick_num[num//10]
    elif 100 <= num < 1000:
        result = stick_num[num%10] + stick_num[(num//10)%10] + stick_num[num//100]
    else:
        result = stick_num[num%10] + stick_num[(num//10)%10] + stick_num[num//100%10] + stick_num[num//1000]
    return result

def stick_eqution(n):
    count = 0
    if n <= 4:
        return count
    else:
        n -= 4 # 减去+=用去的4根火柴
        for num1 in range(1000):
            for num2 in range(1000):
                if stick_number(num1) + stick_number(num2) + stick_number(num1 + num2) == n:
                    count += 1
    return count





dict = {
   0:6, 1:2, 2:5, 3:5, 4:4, 5:5, 6:6, 7:3, 8:7, 9:6}  
def countStick(num):
    count = 0
    for i in range(0, len(num)):
        count += dict[int(num[i])]
    return count

def c(n):
    count = 0
    for i in range(0, 1000):
        for j in range(0, 1000):
            c = i+j
            if(countStick(str(i))+countStick(str(j))+countStick(str(c)) == n-4):
                list = [i, j, c]
                count+=1
    return count


for n in range(25):
    if(c(n) != stick_eqution(n)):
        print("n:", n, "远", c(n), "舟:", stick_eqution(n))
print("same")

34.铺地板 7

动态规划

MAX = 1001
s = [i for i in range(MAX)]
n = int(input())
s[0]=1
s[2]=3
for i in range(4, MAX, 2):
    s[i]=4*s[i-2]-s[i-4]
while n>0:
    if n&1:
        print(0)
    else:
        print(s[n]%100003)
    n = int(input())

来自一舟大佬的动态:

def floor(n):
    if n%2 == 1:
        return 0
    f = [0 for i in range(n+1)]
    f[0] = 1
    f[2] = 3
    for i in range(4, n+1, 2):
        f[i] = f[i-2]*4 - f[i-4]
    return f[n]%100003

n = int(input())
while n != 0:
    print(floor(n))
    n = int(input())

35.排队过河 8

def Jump(s, y):
    k = 0
    if s == 0:
        k = y + 1
    else:
        k = 2 * Jump(s - 1, y)
    return k
s,y = map(int,input().split(","))
while(-1 != s and -1 != y):
    sum = Jump(s, y)
    print(sum)
    s,y = map(int,input().split(","))

36.乘方

简单的找出规律,末尾数随次方模4的值存在规律

0: 1, 1, 1, 1…
1: 1, 1, 1, 1…
2: 2, 4, 8, 6…
3: 3, 9, 7, 1…
4: 4, 6, 4, 6…
5: 5, 5, 5, 5…
6: 6, 6, 6, 6…
7: 7, 9, 3, 1…
8: 8, 4, 2, 6…
9: 9, 1, 9, 1…

dic2 = [2, 4, 8, 6]
dic3 = [3, 9, 7, 1]
dic4 = [4, 6, 4, 6]
dic7 = [7, 9, 3, 1]
dic8 = [8, 4, 2, 6]
dic9 = [9, 1, 9, 1]
a,b = map(int,input().split(" "))
while(0 < a and 0 < b):
    if(a == 1 or a%10 == 5 or a%10 == 6):
        print(a%10)
    if(a%10 == 2):
        print(dic2[b%4 - 1])
    if(a%10 == 3):
        print(dic3[b%4 - 1])
    if(a%10 == 4):
        print(dic4[b%4 - 1])
    if(a%10 == 7):
        print(dic7[b%4 - 1])
    if(a%10 == 8):
        print(dic8[b%4 - 1])
    if(a%10 == 9):
        print(dic9[b%4 - 1])
    a,b = map(int,input().split(" "))

37.数字 9

def number(n):
    for a1 in range(n, 0, -1):
        for a2 in range(n, 0, -1):
            if (a1+a2)%2 != 0:
                continue
            for a3 in range(n, 0, -1):
                if  (a2+a3)%3 == 0 and (a1+a2+a3)%5 == 0:
                    max = a1+a2+a3
                    return max

n = int(input())
print(number(n))

38.吃糖果

就是简单的fibonacci数列

def F(N):
    if N == 1 or N == 2:
        return N
    else:
        return F(N - 1) + F(N - 2)
n = int(input())
while n > 0:
    print(F(n))
    n = int(input())

使用迭代改进

def F(N):
    a = 1
    b = 2
    if N == 1 or N == 2:
        return N
    else:
        for i in range(N-2):
            c = a+b
            a = b
            b = c
        return c
n = int(input())
while n > 0:       
    print(F(n))
    n = int(input())

39.上楼梯

def GoUpstairs(n):
    a = [i for i in range(n+3)]
    a[1] = 1
    a[2] = 2
    a[3] = 4
    for i in range(4, n+1, 1):
        a[i] = ((a[i-1]  + a[i-2])%1000000007  + a[i-3])%1000000007
    return a[n]
n = int(input())
while n > 0:
    print(GoUpstairs(n))
    n = int(input())

40.除法算式

题目错误:欢迎驳反


  1. rjust方法:返回一个原字符串并右对齐。第一个参数是填充字符的目标长度,第二个参数是空位要填充的字符 ↩︎

  2. Python2.7中,保留值将保留到离上一位更近的一端(四舍六入),如果距离两端一样远,则保留到离0远的一边;python3.5中,保留值将保留到离上一位更近的一端(四舍六入),如果距离两边一样远,会保留到偶数的一边 注意:python3.8.5并非保留偶端 ↩︎

  3. 终端看到的结果就应该是一行测试用例紧跟着一行结果 ↩︎

  4. 多测试用例,然后才是多行结果 ↩︎

  5. ↩︎

  6. ↩︎

  7. ↩︎

  8. ↩︎

  9. ↩︎


转载:https://blog.csdn.net/qq_43808700/article/details/109005206
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场