Python嵩天第二版版基础习题代码

2021/10/13 11:14:16

本文主要是介绍Python嵩天第二版版基础习题代码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.1

str1 = input("请输入一个人的名字:")p
str2 = input("请输入一个国家的名字:")
print("世界这么大,{}想去{}康康。".format(str1,str2))

1.2

n = input("请输入正整数N:")
sum = 0
for i in range(int(n)+1):
    sum += i
print("1从N求和结果:", sum)

1.3

for i in range(1,10):
    for j in range(1,i+1):
        print("{}*{}={:2} ".format(j,i,i*j), end='')
    print('')

1.4

sum, tmp = 0, 1
for i in range(1,11):
    tmp *= i;
    sum += tmp
print("运算结果是:{}".format(sum))

1.5

n = 1
for i in range(5,0,-1):
    n = (n+1)*2
print(n)

1.6

diet = ['西红柿', '花椰菜', '黄瓜', '牛排', '虾仁']
for x in range(0, 5):
    for y in range(0, 5):
        if not(x == y):
            print("{}{}".format(diet[x], diet[y]))

1.7

from turtle import *
fillcolor("green")
begin_fill()
while True:
    forward(200)
    right(100)
    if abs(pos()) < 1:
        break
end_fill()
done()

1.8

from turtle import *
color('red', 'yellow')
begin_fill()
while True:
    forward(200)
    left(170)
    if abs(pos()) < 1:
        break
end_fill()
done()

2.2

money = input('请输入您要兑换的货币数额和符号:')
if money[-1] in ['$']:
    Y = 6 * eval(money[0:-1])
    print("你能兑换的人民币为:{}¥".format(Y))
elif money[-1] in ['¥']:
    M = eval(money[0:-1]) / 6
    print("你能兑换的美元为:{}$".format(M))
else:
    print('输入错误')

2.3

from turtle import *
setup(650,350,200,200)
penup()
fd(-250)
pendown()
pensize(25)
seth(-40)
Screen().colormode(255)
for i in range(4):
    pencolor(255-i*50,0+i*50,100+i*50)
    circle(40,80)
    pencolor(100+i*50,0+i*50,255-i*50)
    circle(-40,80)
circle(40,40)
fd(40)
circle(16,180)
fd(40*2/3)
done()

2.4

from turtle import *
for i in range(3):
    fd(200)
    seth(120+i*120)
done()

2.5

from turtle import *
for i in range(3):
    fd(30)
    seth(-120*(i+1))
seth(-120)
fd(30)
seth(0)
for i in range(3):
    fd(60)
    seth(120*(i+1))
done()

2.6

from turtle import *
for i in range(4):
    penup()
    fd(15)
    pendown()
    fd(60)
    penup()
    fd(15)
    left(90)
done()

2.7

from turtle import *
import math
seth(30)
for i in range(3):
    fd(300)
    right(120)

penup()
goto(50*math.sqrt(3),-150)
pendown()
'''
这里也可以用以下方法:
seth(-30)
fd(100)
seth(-90)
fd(100)
seth(30)
'''
for i in range(3):
    fd(300)
    left(120)
done()

2.8

from turtle import *
for i in range(100):
    fd(i*2)
    left(90)
done()

2.9

from turtle import *
penup()
fd(-250)
pendown()
pencolor("red")
pensize(18)
seth(-40)
for i in range(4):
    circle(40,80)
    circle(-40,80)
circle(40,40)
fd(40)
circle(16,180)
fd(40*2/3)
penup()
goto(-250,0)
seth(0)
pendown()
pencolor("green")
seth(40)
for i in range(4):
    circle(-40,80)
    circle(40,80)
circle(-40,40)
fd(40)
circle(-16,180)
fd(40*2/3)
done()

3.1

G_d = int(input("请输入你在地球上的体重(kg):"))
for i in range(10):
    print("第{}在地球上的体重为{}kg,在月球上的体重为{}kg".format(i+1, G_d, G_d*0.165))
    G_d += 0.5

3.2

n = int(input("请输入你将连续学习多少天:"))
value = 1
count = 0
for i in range(n):
    count += 1
    if 3 < count <= 7:
        value += 0.01 * value
    elif count > 7:
        count = 0;
print("按照该模型连续学习{}天后,你的能力值为{}".format(n, value))

3.3

n = int(input("请输入你将学习多少天:"))
m = int(input("请输入休息间隔:"))
value = 1
count = 0
for i in range(n):
    count += 1
    if 3 < count <= 7:
        value += 0.01 * value
    elif count > 7 or (i+1) % m == 0:
        count = 0;
print("按照该模型学习{}天后,你的能力值为{}".format(n, value))

3.4

h = input("请输入一串数字:")
j = True
for i in range(int(len(h)/2)):
    if h[i] != h[-i-1]:
        j = False
if j:
    print("该数为回文串")
else:
    print("该数非回文串")

3.5

a = "—— "
b = "+ "
c = "|"
d = " "
for i in range(11):
    if i % 5 == 0:
        print("{0}{1}{0}{1}{0}".format(b,a*4))
    else:
        print("{0}{1}{0}{1}{0}".format(c,d*13))

3.6

import time
for i in range(11):
    print("\rStarting {} Done!".format(i*'·'), end = '')
    time.sleep(0.5/(i+1))

3.7

while True:
    for i in ["/", "-", "|", "\\", "|"]:
        print("%s\r" % i, end = '')

3.8

from tqdm import tqdm
from time import sleep
for i in tqdm(range(1,100)):
    sleep(0.01)

4.1

from random import *
count = 0
n = randint(0, 9)
while True:
    count += 1
    m = eval(input("请输入一个整数:"))
    if m == n:
        print("预测{}次,你猜中了!".format(count))
        break
    elif m > n:
        print("遗憾,太大了")
    elif m < n:
        print("遗憾,太小了")

4.2

str = input("请输入一行字符串:")
kong, ying, shu, other = 0, 0, 0 ,0
for i in str:
    if i == ' ':
        kong += 1
    elif '0' <= i <= '9':
        shu += 1
    elif 'a' <= i <= 'z' or 'A' <= i <= 'Z':
        ying += 1
    else:
        other += 1
print("该字符串中英文字母个数为{},数字个数为{},空格数为{},其它字符数为{}".format(ying, shu, kong, other))

4.3

def gcd(x, y):
    if y == 0:
        return x
    else:
        return gcd(y, x % y)
n, m = map(int, input("请输入两个整数:").split())
print("这两数的最大公约数为{},最大公倍数为{}".format(gcd(n, m), int(n * m / gcd(n, m))))

4.4

from random import *
count = 0
n = randint(0, 100)
while True:
    count += 1
    m = eval(input("请输入一个整数:"))
    if m == n:
         print("预测{}次,你猜中了!".format(count))
         break
    elif m > n:
         print("遗憾,太大了")
    elif m < n:
          print("遗憾,太小了")

4.5

from random import *
count = 0
n = randint(0, 100)
while True:
    count += 1
    try:
        m = eval(input("请输入一个整数:"))
        if m == n:
            print("预测{}次,你猜中了!".format(count))
            break
        elif m > n:
            print("遗憾,太大了")
        elif m < n:
            print("遗憾,太小了")
    except NameError:
        print("请输入整数")

4.6

from random import *
count_y = 0
count_n = 0
for i in range(100):
    m_1 = randint(0, 1)             #三个门随机生成初始值,0为羊,1为车
    if m_1 == 1:
        m_2, m_3 = 0, 0
    else:
        m_2 = randint(0, 1)
        if m_2 == 1:
            m_3 = 0
        else:
            m_3 = 1
    n = randint(1, 3)
    if n == 1:
        if m_1 == 1:
            count_n += 1
        else:
            count_y += 1
    elif n == 2:
        if m_2 == 1:
            count_n += 1
        else:
            count_y += 1
    else:
        if m_3 == 1:
            count_n += 1
        else:
            count_y += 1
print("不更换自己选择有{}%机会猜对,更换自己的选择有{}%机会猜对".format(count_n, count_y), end='')
print(",参赛者更换选择后{}增加猜对汽车的机会".format("能" if count_n < count_y else "不能"))

4.7

from random import *
try:
    count = 0
    n = randint(0, 9)
    while True:
        count += 1
        m = eval(input("请输入一个整数:"))
        if m == n:
            print("预测{}次,你猜中了!".format(count))
            break
        elif m > n:
            print("遗憾,太大了")
        elif m < n:
            print("遗憾,太小了")
except NameError as err:
    print(err)
except ValueError as err:
    print(err)
else:
    print("成功")
finally:
    print("结束")

5.1

def hui(x):
    a = "—— "
    b = "+ "
    c = "|"
    d = " "
    for i in range(11*x):
        if i % 5 == 0:
            for j in range(x):
                print("{0}{1}{0}{1}".format(b, a*4), end='')
            print("{}".format(b))
        else:
            if (i < 11*x-x+1):
                for j in range(x):
                    print("{0}{1}{0}{1}".format(c, d*13), end='')
                print("{}".format(c))


n: int = eval(input("输入N,代表将会输出NxN个田字格:"))
hui(n)

5.2

def isOdd(x):
    return x % 2 != 0


n: int = eval(input("请输入一个整数:"))
print(isOdd(n))

5.3

def isNum(str):
    try:
        n = eval(str)
        return True
    except NameError as err:
        return False
    except SyntaxError as err:
        return isinstance(str, complex)


s = input("请输入一串字符串:")
print(isNum(s))

5.4

def multi(a, *b):
    num = 1
    for i in b:
        num *= i
    return a * num


print(multi(1, 2, 3))

5.5

def isPrime(x):
    try:
        y = eval(x)
        if y == 2:
            return True
        elif y < 2:
            return False
        for i in range(2, y):
            if y % i == 0:
                return False
        return True
    except NameError as err:
        return "输入错误{},请输入整数:".format(err)


n = input("请输入整数:")
print(isPrime(n))

5.6

from datetime import datetime
someday = datetime(2000, 10, 4)
print(someday.strftime("我的生日是%Y-%m-%d"))
print(someday.strftime("我的生日是%a %b %d %Y"))
print(someday.strftime("我的生日是%A %b %d %Y"))
print(someday.strftime("我的生日是%a %B %d %Y"))
print(someday.strftime("我的生日是%A %B %d %Y"))
print(someday.strftime("我的生日是{0:%Y}年,{0:%m}月,{0:%d}日".format(someday)))
print(someday.strftime("我的生日是%Y-%B-%d"))
print(someday.strftime("我的生日是%Y-%b-%d"))
print(someday.strftime("我的生日是%Y-%B-%A-%d"))
print(someday.strftime("我的生日是%Y-%b-%a-%d"))

5.7

def han_nuo(n, A, B, C):
    if n == 1:
        print("{}->{}".format(A, C))
    else:
        han_nuo(n-1, A, C, B)
        print("{}->{}".format(A, C))
        han_nuo(n-1, B, A, C)


n: int = eval(input("请输入汉诺塔的层数:"))
han_nuo(n, 'A', 'B', 'C')

6.1

import random
ls = []
for i in range(65, 91):
    ls.append(chr(i))
for i in range(97, 123):
    ls.append(chr(i))
for i in range(1,10):
    ls.append(i)
for i in range(10):
    ls2 = random.sample(ls, 8)
    s = ''
    for j in ls2:
        s += str(j)
    print("第{}个生成的密码为{}".format(i+1, s))

6.2

def check(ls):
    for i in range(len(ls)):
        for j in range(i+1, len(ls)):
            if ls[i] == ls[j]:
                return True
    return False


ls = input().split()
if check(ls):
    print("有重复元素")
else:
    print("无重复元素")

6.3

def check(ls):
    s = set()
    for i in ls:
        n = len(s)
        s.add(i)
        if len(s) == n:
            return True
    return False

ls = input().split()
if check(ls):
    print("有重复元素")
else:
    print("无重复元素")

6.4

import jieba
s = input("请输入字符串:")
s2 = jieba.lcut(s)
count = {}
for i in s2:
    count[i] = count.get(i, 0) + 1
items = list(count.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(len(items)):
    word, count = items[i]
    if word != ' ':
        print("{:<10}{:>5}".format(word, count))

6.5

from random import *

months = []
for i in range(1, 13):
    months.append(i)
days = []
for i in range(1, 32):
    days.append(i)
x = {1, 3, 5, 7, 8, 10, 12}
n = eval(input("请输入样本数量:"))
count = 0
for j in range(n):
    end_m = []
    end_d = []
    for i in range(23):
        month = choice(months)
        months2 = set(months)
        day = choice(days)
        while month not in months2:
            if month == 2 and day > 28:
                day = choice(days)
                continue
            elif day == 31:
                day = choice(days)
                continue
            else:
                break
        end_m.append(month)
        end_d.append(day)
    counts = {}
    for i in range(23):
        s = ''
        s += str(end_m[i])
        s += str(end_d[i])
        counts[s] = counts.get(s, 0) + 1
        if counts[s] >= 2:
            count += 1
            break
print("概率为{}%".format(count/n*100))

6.6

import jieba
text = open(r"C:绝对路径\\红楼梦.txt", "r", encoding="utf-8").read()
words = jieba.lcut(text)
counts = {}
excludes = {"什么","一个","我们","那里","你们","如今","说道","知道","起来","姑娘","这里","出来","他们","众人","自己",
            "一面","只见","怎么","奶奶","两个","没有","不是","不知","这个","听见","这样","进来","咱们","告诉","就是",
            "东西","袭人","回来","只是","大家","只得","老爷","丫头","这些","不敢","出去","所以","不过","的话","不好",
            "姐姐","探春","鸳鸯","一时","不能","过来","心里","如此","今日","银子","几个","答应","二人","还有","只管",
            "这么","说话","一回","那边","这话","外头","打发","自然","今儿","罢了","屋里","那些","听说","小丫头","不用",
            "如何","-----------------------","问道","人家","看见","妹妹","媳妇","到底","不得","原来","一声","这会子",}
for word in words:
    if len(word) == 1:
        continue
    else:
        counts[word] = counts.get(word, 0) + 1
for word in excludes:
    del(counts[word])
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(20):
    word, count = items[i]
    print("{:<10}{:>5}".format(word, count))



这篇关于Python嵩天第二版版基础习题代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程