通过案例浅谈C++与Python的快速实现差别

8 篇文章 2 订阅

本文以中彩票问题入手,即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行,代码比较简单紧凑,仅仅用了几个列表随机数函数而已。
Python实现此问题
接下来是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行,
数组中的元素都是ASCII码,
而且更重要的是,我还要从轮子造起,包括一个随机数种子,一个冒泡排序算法,一个数组循环赋值算法。
C++实现案例1
C++实现案例2

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值