【算法刷题】1 Python基础篇

1.1 输入圆的半径r,输出其周长和面积

import math
from math import pi
class circle(object):
    def __init__(self, r):
        self.r = r
        self.__d = 2 * r # 私有对象,外部无法访问
        self.__s = pi * r ** 2
        self.__c = 2 * pi * r
        
    def get_square(self): # area
        return self.__s
    
    def get_perimeter(self):
        return self.__c
while(1):
    x = eval(input("请输入圆的半径:"))
    if not x: break
    c = circle(x)
    print(f"圆的面积为:{c.get_square()}")
    print(f"圆的周长为:{c.get_perimeter()}")
请输入圆的半径:5
圆的面积为:78.53981633974483
圆的周长为:31.41592653589793
请输入圆的半径:5
圆的面积为:78.53981633974483
圆的周长为:31.41592653589793
请输入圆的半径:2
圆的面积为:12.566370614359172
圆的周长为:12.566370614359172
请输入圆的半径:3
圆的面积为:28.274333882308138
圆的周长为:18.84955592153876
请输入圆的半径:4
圆的面积为:50.26548245743669
圆的周长为:25.132741228718345
请输入圆的半径:1
圆的面积为:3.141592653589793
圆的周长为:6.283185307179586
请输入圆的半径:12.564
圆的面积为:495.91326833265794
圆的周长为:78.94194019940433
请输入圆的半径:


Traceback (most recent call last):

  File "D:\ana3\lib\site-packages\IPython\core\interactiveshell.py", line 3444, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_20476/1614528114.py", line 2, in <module>
    x = eval(input("请输入圆的半径:"))

  File "<string>", line unknown
    
    ^
SyntaxError: unexpected EOF while parsing

1.2 将2.0开平方后设置不同的精度和宽度输出

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DnqyjMLT-1668439891380)(attachment:image.png)]

while(1):
    x = eval(input("请输入您需要开平方的数:"))
    if not x: break
    print("{}".format(x ** 0.5))
请输入您需要开平方的数:25
5.0
请输入您需要开平方的数:2
1.4142135623730951
请输入您需要开平方的数:456
21.354156504062622
请输入您需要开平方的数: 


Traceback (most recent call last):

  File "D:\ana3\lib\site-packages\IPython\core\interactiveshell.py", line 3444, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_20476/2710242934.py", line 2, in <module>
    x = eval(input("请输入您需要开平方的数:"))

  File "<string>", line unknown
    
    ^
SyntaxError: unexpected EOF while parsing
#正号表示正数
print("{:+2f}".format(3.14))
#+3.140000
print("{:-2f}".format(-1))
#-1.000000
#不带小数的
print("{:.0f}".format(3.23123131))
#3
#以逗号为分隔符的
print("{:,}".format(100000))
#100,000
#表示一个百份比
print("{:.2%}".format(0.25))
#25%
+3.140000
-1.000000
3
100,000
25.00%
while(1):
    x = eval(input("请输入您需要开平方的数:"))
    if not x: break
    print("{:.5f}".format(x ** 0.5))
    print("{:0>15d}".format(x ** 5))
请输入您需要开平方的数:54544
233.54657
482764047121379281076224
请输入您需要开平方的数:2
1.41421
000000000000032
请输入您需要开平方的数:


Traceback (most recent call last):

  File "D:\ana3\lib\site-packages\IPython\core\interactiveshell.py", line 3444, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_20476/1287905401.py", line 2, in <module>
    x = eval(input("请输入您需要开平方的数:"))

  File "<string>", line unknown
    
    ^
SyntaxError: unexpected EOF while parsing
bin(5)
'0b101'
hex(16)
'0x10'

1.3 求三位数字的个位、十位、百位上的数字

class number(object):
    def __init__(self, x):
        self.__x  = x
        
    def get_ten(self):
        return self.__x % 10
    
    def get_hundred(self):
        return int(self.__x//10) % 10
n = number(2282545)
n.get_ten(), n.get_hundred()
(5, 4)

1.4 整数增加1,扩大十倍,缩小十倍的效果

x = 425
print(x+=1)
x *= 10
print(x)
x /= 10
print(x)
  File "C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_20476/4213375544.py", line 2
    print(x+=1)
           ^
SyntaxError: invalid syntax
a = 1
switch(a):
    case 1:
        print('jellop')
  File "C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_20476/2610721851.py", line 2
    switch(a):
              ^
SyntaxError: invalid syntax

1.5 大小写转换

print(int('a') - int('A') + int('z'))
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_20476/1581520911.py in <module>
----> 1 print(int('a') - int('A') + int('z'))

ValueError: invalid literal for int() with base 10: 'a'
'A'.lower()
'a'

1.6 求两个整数的 gcd 和 lcm

def gcd(x, y):
    t = x % y
    while(t):
        x, y = y, t # 如果x < y,那么这一步x和y将互换!
        t = x % y
    return y

def lcm(x, y): # 最小公倍数=两整数的乘积÷最大公约数。
    g = gcd(x, y)
    return ((x * y) / g)
lcm(12, 32), lcm(32, 12), gcd(32, 12)
(96.0, 96.0, 4)

1.7 用递归倒序输出

a = [12,21,23,23,23,123,223]
def prints(n):
    print(a[n])
    if n-1 >= 0: prints(n-1)
prints(len(a) - 1)
223
123
23
23
23
21
12

1.8 递归

def frac(n):
    return 1 if n <= 1 else n * frac(n-1)

frac(121)
809429852527344373968162284544935082997082306309701607045776233628497660426640521713391773997910182738287074185078904956856663439318382745047716214841147650721760223072092160000000000000000000000000000

1.9 斐波那契数列

def fibo(n):
    if 1 <= n <= 2:
        return 1
    return fibo(n-1) + fibo(n-2)
fibo(7) # 1 1 2 3 5 8 13
13

1.10 递归求解1~n的累加

def summary(n):
    if n == 1:
        return 1
    return n + summary(n-1)
summary(115)
6670

1.11 定义一个结构体

  • python中没有结构体,使用类进行代替
class student:
    def __init__(self, name, number, sex, age, score):
        self.name = name
        self.number = number
        self.sex = sex
        self.age = age
        self.score = score
s1 = student("小红", "D123456", '男', 35, 96.5)
s1.name
'小红'
s1.score
96.5

1.12 给定n个灯,知道k个人关灯后,多少个灯是开着的

def close(n, k):
    deng = [0] * (n+1)
    for i in range(1, k+1):
        for j in range(1, n+1):
            if j % i == 0:
                if deng[j] == 0:
                    deng[j] = 1  
                elif deng[j] == 1:
                    deng[j] = 0
    return [i for i, item in enumerate(deng) if i != 0 and item == 1]
close(100, 100)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
def close(n):
    k = n
    deng = [0] * (n+1)
    for i in range(1, k+1):
        for j in range(1, n+1):
            if j % i == 0:
                if deng[j] == 0:
                    deng[j] = 1  
                elif deng[j] == 1:
                    deng[j] = 0
    return sum(deng)
800000 - 894
799106
close(100000)
---------------------------------------------------------------------------

KeyboardInterrupt                         Traceback (most recent call last)

C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_14556/941356374.py in <module>
----> 1 close(100000)

C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_14556/146113109.py in close(n)
      4     for i in range(1, k+1):
      5         for j in range(1, n+1):
----> 6             if j % i == 0:
      7                 if deng[j] == 0:
      8                     deng[j] = 1

KeyboardInterrupt: 

1.13 蛇形填数字

def snack_num(n):
    nums = [[0 for i in range(n)] for j in range(n)]
    i, j = 0, 0
    total = 1
    while(total <= n*n):
        # 向右边
        while(1):
            nums[i][j] = total
            if j+1 == n or nums[i][j+1]: break
            j += 1
            total += 1

        # 向下边
        while(1):
            nums[i][j] = total
            if i+1 == n or nums[i+1][j]: break
            i += 1
            total += 1

        # 向左边
        while(1):
            nums[i][j] = total
            if j-1 < 0 or nums[i][j-1]: break
            j -= 1
            total += 1

        # 向上边
        while(1):
            nums[i][j] = total
            if i-1 < 0 or nums[i-1][j]: break
            i -= 1
            total += 1
        
        # 需要回到小一圈的左上角
        if j+1<n: 
            total += 1
            j += 1
        else:
            break
    return nums
snack_num(8)
[[1, 2, 3, 4, 5, 6, 7, 8],
 [28, 29, 30, 31, 32, 33, 34, 9],
 [27, 48, 49, 50, 51, 52, 35, 10],
 [26, 47, 60, 61, 62, 53, 36, 11],
 [25, 46, 59, 64, 63, 54, 37, 12],
 [24, 45, 58, 57, 56, 55, 38, 13],
 [23, 44, 43, 42, 41, 40, 39, 14],
 [22, 21, 20, 19, 18, 17, 16, 15]]




  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值