前言
最近需要開始使用python,但是對python了解的并不多,于是先從很早之前剛學C++時寫過的一些練手題開始,使用python來實現相同的功能,在溫習python基礎語法的同時,也一起來感受感受python的魅力
99乘法表
c++:
#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:
for lie in range(1, 10):for hang in range(1, lie + 1):print(f"{hang}*{lie}={hang * lie}", end=" ")print() # 打印空行
素數
c++
#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:
import mathn = int(input('請輸入數字n,判斷其是否為素數\nn='))
Is_SuShu = True
for i in range(2, int(math.sqrt(n))):if n % i == 0:Is_SuShu = Falsebreak
if Is_SuShu:print(f'{n}是素數')
else:print(f'{n}不是素數')
水仙花數
c++:
#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:
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)
括號匹配
#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;elsereturn false;
}
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 = Falsebreakelif i == ']':if st[-1] == '[':st.pop()else:Is_ok = Falsebreakelif i == '}':if st[-1] == '{':st.pop()else:Is_ok = Falsebreakif st is None and Is_ok:print('括號匹配', end="")
else:print('括號不匹配', end="")
python整體比C++要簡介的多,當然使用python完成C++的練習題肯定也不能完全體現python的優勢。