C++/Python简单练手题

前言

最近需要开始使用python,但是对python了解的并不多,于是先从很早之前刚学C++时写过的一些练手题开始,使用python来实现相同的功能,在温习python基础语法的同时,也一起来感受感受python的魅力

99乘法表

c++:

cpp 复制代码
#include<iostream>
int main()
{
	int i,j;
	for (i = 1; i <= 9; i++)
	{
		for (j = 1; j <= i; j++)
			std::cout <<j<<"*"<<i <<"=" << i * j << "  ";
		std::cout << '\n';
	}
}

python:

python 复制代码
for lie in range(1, 10):
    for hang in range(1, lie + 1):
        print(f"{hang}*{lie}={hang * lie}", end="  ")
    print()  # 打印空行

素数

c++

cpp 复制代码
#include<iostream>
int judge(int ,bool);
int main()
{
	int n;
	std::cout << "请输入数字n,判断其是否为素数" << '\n' << "n=";
	std::cin >> n;
	bool flage = true;
	if (judge(n,flage) == false) std::cout << n<<"不是素数";
	else if (judge(n,flage) == true) std::cout << n<<"是素数";
}
int judge(int n, bool flage)
{
	for (int i = 2; i <= sqrt(n); i++)
	{
		if ((n % i) == 0)
		{
			flage = false;
			break;
		}
	}
	return flage;
}

python:

python 复制代码
import math

n = int(input('请输入数字n,判断其是否为素数\nn='))
Is_SuShu = True
for i in range(2, int(math.sqrt(n))):
    if n % i == 0:
        Is_SuShu = False
        break
if Is_SuShu:
    print(f'{n}是素数')
else:
    print(f'{n}不是素数')

水仙花数

c++:

cpp 复制代码
#include<iostream>

//水仙花数:各位数字的立方相加等于其本身
//如果三位数的话,就是个位数的立方加上十位数的立方加上百位数的立方等于其本身的数,就叫水仙花数
int main()//求100到999内的所有水仙花数
{
	int i = 100;
	int ge, shi, bai;
	do 
	{
		ge = i % 10;
		shi = (i % 100) / 10;
		bai = (i % 1000) / 100;
		if (ge * ge * ge + shi * shi * shi + bai * bai * bai == i)
			std::cout << i << '\n';
		i++;
	} while (i <= 999);
return 0;
}

python:

python 复制代码
for i in range(100, 999):
    bai_wei = int(i / 100 % 10)
    shi_wei = int(i / 10 % 10)
    ge_wei = int(i / 1 % 10)
    if bai_wei ** 3 + shi_wei ** 3 + ge_wei ** 3 == i:
        print(i)

括号匹配

cpp 复制代码
#include<iostream>
#include<string>
#include<stack>
static bool Is_righ(std::string In_str);

int main()
{
	std::string In_str;
	std::cout << "请输入一个表达式 :";//如:{{([])}}
	std::cin >> In_str;
	if (Is_righ(In_str)) {
		std::cout << "括号匹配";
	}
	else {
		std::cout << "括号不匹配";
	}
}
static bool Is_righ(std::string In_str) {
	std::stack<char> st;
	bool check = true;
	for (int i = 0; i < In_str.length(); i++) {
		switch (In_str[i]) {
		case '(': {
			st.push('('); break;
		}
		case '[': {
			st.push('['); break;
		}
		case '{': {
			st.push('{'); break;
		}

		case ')': {
			if (st.top() == '(')
				st.pop();
			else {
				check = false;
				break;
			}
			break;
		}
		case ']': {

			if (st.top() == '[')
				st.pop();
			else {
				check = false;
				break;
			}
			break;
		}
		case '}': {
			if (st.top() == '{')
				st.pop();
			else {
				check = false;
				break;
			}
			break;
		}
		default:break;
		}
	}
	if (st.empty() && check)
		return true;
	else
		return false;
}

python:

python 复制代码
st = []
In_str = input("请输入一个表达式:")  # 如{()[]}

Is_ok = True
for i in In_str:
    if i == '(':
        st.append('(')
    elif i == '[':
        st.append('[')
    elif i == '{':
        st.append('{')
    elif i == ')':
        if st[-1] == '(':
            st.pop()
        else:
            Is_ok = False
            break
    elif i == ']':
        if st[-1] == '[':
            st.pop()
        else:
            Is_ok = False
            break
    elif i == '}':
        if st[-1] == '{':
            st.pop()
        else:
            Is_ok = False
            break

if st is None and Is_ok:
    print('括号匹配', end="")
else:
    print('括号不匹配', end="")

python整体比C++要简介的多,当然使用python完成C++的练习题肯定也不能完全体现python的优势。

相关推荐
X56611 小时前
如何在 Laravel 中正确保存嵌套动态表单数据(主服务与子服务)
jvm·数据库·python
ZhengEnCi1 小时前
03ab-PyTorch安装教程 📚
python
狐狐生风2 小时前
LangChain 向量存储:Chroma、FAISS
人工智能·python·学习·langchain·faiss·agentai
狐狐生风2 小时前
LangChain RAG 基础
人工智能·python·学习·langchain·rag·agentai
汉克老师2 小时前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
老前端的功夫3 小时前
【Java从入门到入土】28:Stream API:告别for循环的新时代
java·开发语言·python
yaoxin5211233 小时前
397. Java 文件操作基础 - 创建常规文件与临时文件
java·开发语言·python
dFObBIMmai3 小时前
MySQL主从同步中大事务导致的延迟_如何拆分大事务优化同步
jvm·数据库·python
szccyw03 小时前
mysql如何限制特定存储过程执行权限_MySQL存储过程安全访问
jvm·数据库·python
小白学大数据3 小时前
Python 自动化爬取网易云音乐歌手歌词实战教程
爬虫·python·okhttp·自动化