【项目02】 基于Python的算法函数创建
作业要求:
根据不同题目,完成代码书写并成功运行
# 题目1:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的两位数?都是多少?
# 该题目不用创建函数
import numpy as np
import pandas as pd
# 方法1
from itertools import product
num = [1, 2, 3, 4]
num_list = list(product(num, repeat=2))
n = 0
for (i,j) in num_list:
if i!=j:
n += 1
print('\n 第', n, '个组合:',i*10+j)
print ('\n 一共有 ', n, " 个组合")
# 方法2
n = 0
for i in num:
s = list(num)
s.remove(i)
for j in s:
nums = i*10+j
n += 1
print('\n 第', n, '个组合:',nums)
print ('\n 一共有 ', n, " 个组合")
# 题目2:输入三个整数x,y,z,请把这三个数由小到大输出,可调用input()。(需要加判断:判断输入数据是否为数字)
# 提示:判断是否为数字:.isdigit()
# 该题目需要创建函数
def input_num_cnt(n):
lst = []
for i in np.arange(1,n+1):
x = input("请输入第 %i 个数字 x: " %i)
while x.isdigit()==False:
x = input("输入非数字,请输入第 %i 个数字:" %i)
lst.append(float(x))
return sorted(lst)
# 题目3:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
# 提示:利用while语句,条件为输入的字符不为'\n'.
# 该题目不需要创建函数
# 方法1
strs = input("please input strs : ")
word_count = 0
space_count = 0
digit_count = 0
others_count = 0
for s in strs:
if s.isalpha():
word_count += 1
elif s.isspace():
space_count += 1
elif s.isdigit():
digit_count += 1
else :
others_count += 1
print("\n word_count=%d, space_countt=%d, digit_count=%d, others_count=%d" %(word_count, space_count, digit_count, others_count) )
# 方法2
import re
strs = input("please input strs : ")
word_count = len(re.findall('[a-zA-Z]', strs))
space_count = len(re.findall('\s', strs))
digit_count = len(re.findall('[0-9]', strs))
others_count = len(re.findall('\W', strs.replace(' ','')))
# 题目4:猴子吃桃问题
# 猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个,
# 第二天早上又将剩下的桃子吃掉一半,又多吃了一个。
# 以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少?
# 提示:采取逆向思维的方法,从后往前推断。
# 该题目不需要创建函数
n = 1
for day in np.arange(10, 0, -1):
m = 2*(n+1)
n = m
print(m)
# 题目5:猜数字问题,要求如下:
# ① 随机生成一个整数
# ② 猜一个数字并输入
# ③ 判断是大是小,直到猜正确
# 提示:random模块
# 该题目不需要创建函数
num = np.random.randint(100)
guess_num = input("**请输入一个<=100的整数: ")
while int(guess_num)!=num:
if int(guess_num)<num:
print("\n本次输入数字比正确数字小\n")
guess_num = input("**请重新输入一个<=100的整数: ")
elif int(guess_num)>num:
print("\n本次输入数字比正确数字大\n")
guess_num = input("**请重新输入一个<=100的整数: ")
print("\n正确数字为 %d, 猜对了!\n" %num)