Python--单元四练习

一、算24

描述:

给出4个小于10的正整数,可以使用加、减、乘、除4种运算以及括号把4个数连接起来得到一个表达式。现在问题是,是否存在一种方式使得所得表达式的结果等于24。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬

这里加、减、乘、除以及括号的运算结果和运算优先级跟平常定义一致。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬

         例如,对于5,5,5,1,可知5×(5-1/5)=24。又如,对于1,1,4,2无论如何都不能得到24

代码:

from itertools import permutations
n1 = input("请输入第一个数:
")
n2 = input("请输入第二个数:
")
n3 = input("请输入第三个数:
")
n4 = input("请输入第四个数:
")
n = n1+n2+n3+n4
sum = 1
for i in n:
    sum *= eval(i)
if sum < 24:
    print("NO")
    exit()
notation = ['+', '-', '*', "/"]
st = set()
num = 0
number = set(permutations(n))#将n进行相应的排列组合
for i in notation:
    s = i
    t1 = notation.copy()
    t1.remove(i)#进行一次就去掉一个运算符
    for j in t1:
        s += j
        t2 = t1.copy()
        t2.remove(j)
        for p in t2:
            s += p
            st.add(s)
            s = i+j
        s = i
newst = set()
for i in number:
    for j in st:
        newst.add(i[0]+j[0]+i[1]+j[1]+i[2]+j[2]+i[3])
# print(newst)
all = set()
for i in newst:
    i1 = '('+i[0:3]+')'+i[3:]
    i2 = i[0:2]+'('+i[2:5]+')'+i[5:]
    i3 = i[0:4] + '(' + i[4:] + ')'
    i4 = '(('+i[0:3]+')'+i[3:5]+")"+i[5:]
    i5 = i[0:2]+'(('+i[2:5]+')'+i[5:]+")"
    i6 = '(' + i[0:2] + '(' + i[2:5] + '))' + i[5:]
    i7 = i[0:2]+'('+i[2:4]+'('+i[4:]+"))"
    all.add(i1)
    all.add(i2)
    all.add(i3)
    all.add(i4)
    all.add(i5)
    all.add(i6)
    all.add(i7)
result = []
for i in all:
    try:
        if eval(i) == 24:
          result.append(i)
    except:
        pass
print("YES")
print("("+sorted(result)[0]+")")

运行结果:

 二、Collatz猜想

描述:

Collatz猜想也叫3n+1猜想,给一个正整数,如果是偶数,则减半;如果是奇数,则变为它的三倍加一。直到变为1停止。猜想对于所有正整数经过足够多次变换最终达到1。

代码:

m=int(input("输入一个整数:"))
while m!=1:
    if m%2==0:
        m=m/2;
        print('%.1f' %m)
    else:
        m=(3*m+1);
        print('%.1f' %m)

运行结果:

 三、二分法求平方根

描述:

设计一个用二分法计算一个大于或等于 1 的实数 n 的平方根的函数sqrt_binary(n),计算精度控制在计算结果的平方与输入的误差不大于1e-6。

代码:

import math
def sqrt_biary(n):
    low=0 #设置下限为0
    high=max(n,1) #设置上限为n和1之中的最大数,即:如果n>=1,那么上限为n;如果n<1,那么上限为1
    guess=(low+high)/2 #先从中间值开始猜
    count=1   #设置猜测次数起始值为1
    while abs(guess**2-n)>(1e-6) and count<100: #当猜测值的平方和n本身的差值无限接近误差值时,循环才会停止;同时设置猜测次数不超过100次
        if guess**2<n:  #如果猜测值的平方小于n,那么将此设为下限
            low=guess
        else:           #如果猜测值的平方大于n,那么将此设为上限
            high=guess
        guess=(low+high)/2  #根据新的上下限,重新进行猜测
        count+=1            #猜测次数每次增加1
    print(guess) 

m=float(input("请输入需要计算的数:"))
print("二分法运算结果:")
sqrt_biary(m)
print("库函数运算结果:
",math.sqrt(m))

运行结果:

 

原文地址:https://www.cnblogs.com/Wang1107/p/11777857.html