实例比较C++与Python的快速实现差别

2022-07-29,,,

以中彩票问题入手,即15个元素(包含单个数字和字母)中依次取出4个元素,每次取出后不放回。彩票的奖金序列为随意取定的4个元素(包含单个数字和字母)。要求程序返回中奖前运行的次数。
依据数学中的组合原理可知,中奖的概率为1/1365

先用Python写出程序如下:

from random import choice
def doit():
loft=[0,2,3,5,‘k’,‘l’,‘u’,6,9,4,‘n’,1,7,‘q’,‘r’]
co=[]
for i in range(0,4):
temp = choice(loft)
loft.remove(temp)
co.append(temp)
return co
count=0
while True:
d=doit()
#print(d)
count=count+1
if (‘r’ in d) and (6 in d) and (0 in d) and (‘u’ in d):
print(f"The truth is {d}")
print(f"运行{count}次中奖 ")
break;
可以Python看到总共是18行,代码比较简单紧凑,仅仅用了几个列表随机数函数而已。

接下来是C++

#include
#include
#include
int n = 15;
using namespace std;
void thefour() {
int count = 0;
bool flag = false;
srand((unsigned int)time(NULL));
while (true) {
int arr[15] = { 48,50,51,53,107,97,117,54,57,52,110,56,55,113,114 };
int array[4] ;
int a[4] = {48,54,114,117};
n = 15;
for (int i = 0; i < 4; i++) {
int num = 0;
if (n != 0) {
num = rand() % n;
}
array[i] = arr[num];
int temp = num;
for (int i = 1; i <= n - 1 - temp; i++) {
arr[num] = arr[num+1];
num++;
}
n–;
}
for (int i = 1; i < 4;i++) {
for (int j = 3; j >= i; j–) {
if (array[j] < array[j - 1]) {
int it = array[j - 1];
array[j - 1] = array[j];
array[j] = it;
}
}
}
count++;
if (array[0]==a[0]&& array[1] == a[1]&& array[2] == a[2]&& array[3] == a[3]) {
flag = true;
}
if (flag == true) {
cout << "运行 " << count << “次中奖” << endl;
cout << "中奖的四个元素为: "<< " 0 6 r u " << endl;
break;
}
}
}
int main() {
thefour();
system(“pause”);
return 0;
}

可以看到C++大概是55行,
而且更重要的是,我还要从轮子造起,包括一个随机数种子,一个冒泡排序算法,一个数组循环赋值算法。

本文地址:https://blog.csdn.net/m0_47472749/article/details/109061482

《实例比较C++与Python的快速实现差别.doc》

下载本文的Word格式文档,以方便收藏与打印。