Python算法实现:寻找ugly numbers丑数

Python算法实现:寻找ugly numbers丑数

Ugly numbers是指只包含质因子2、3和5的正整数,比如1、2、3、4、5、6、8、9、10、12等。本篇文章将介绍一种用Python实现寻找ugly numbers的算法,并提供完整源代码。

算法分析:

我们可以通过动态规划(DP)的方式来解决这个问题。首先,我们定义三个指针p2、p3和p5,它们分别表示当前ugly number乘以2、3、5的位置,同时我们也定义一个ugly数组用来存储已经找到的ugly numbers。

  • 将ugly数组初始化为1,p2、p3和p5都初始化为0。
  • 每次从ugly[p2]*2、ugly[p3]*3和ugly[p5]*5中选取最小值,此值即为下一个ugly number。
  • 如果最小值为ugly[p2]*2,则p2加1;如果最小值为ugly[p3]*3,则p3加1;如果最小值为ugly[p5]*5,则p5加1。
  • 重复执行步骤2和步骤3,直到找到第n个ugly number。

完整源代码如下所示:

def getUglyNumber(n):
# 初始化ugly数组
ugly = [1] * n
# 初始化三个指针
p2, p3, p5 = 0, 0, 0
# 每次求解下一个ugly number,直到找到第n个
for i in range(1, n):
# 求解下一个ugly number
ugly[i] = min(ugly[p2]*2, ugly[p3]*3, ugly[p5]*5)
# 移动指针
if ugl

Python ugly numbers丑数算法详解及源码 丑数是指只能被2、3和5整除的正整数。ugly numbers算法用于找出按照从小到大的顺序的第n个丑数。 阅读详情

相关推荐

Python:实现ugly numbers丑数算法(附完整源码)

Python:实现ugly numbers丑数算法(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 714

避坑指南:HslCommunication连接西门子PLC时常见的5个错误及解决方法(S7-1200/S1500适用)

本文详细解析了使用HslCommunication连接西门子S7-1200/S1500 PLC时常见的5个错误及解决方法,包括基础连接配置、数据块读写异常、连接闪断、防火墙与权限问题以及高级调试技巧。通过实战案例和代码示例,帮助开发者快速定位和解决连接问题,提升工业自动化项目的开发效率。

weixin_30752699的博客 400

MagicDraw-需求图

MagicDraw学习笔记

木头征的博客 4144

SKF SimPro Quick 4.8.1发布

发布说明可以在SimPro手册的SKF SimPro Quick应用程序的一般部分下找到(帮助→SKF SimPro快速手册→一般→发布说明)。请删除旧版本,请备份您存储在C:\SKF SimPro xxx\files文件夹中的文件以及所有自定义报告模板和表格。我们很高兴地通知您,我们的轴承应用工程软件SKF SimPro Quick 4.8.1可供下载。将新的安装文件下载到本地计算机后,双击它安装向导将打开(按照说明操作)3.安装后,在本地机器上启动SKF SimPro Expert软件。

小韩的博客 1823

TNS-12516及ORA-12516错误解决

在客户端进行sqlplus连接报错如下: ORA-12516: TNS: 监听程序找不到符合协议堆栈要求的可用处理程序 在/home/oracle/product/10.2.0/db_1/network/log/listener.log中查看到错误如下: TNS-12516: TNS:listener could not find available handler with matchin

KEL 2万+

七自由度机械臂逆运动学实战:从几何简化到KDL库高效求解

本文深入探讨了七自由度机械臂逆运动学求解的实战方法。针对冗余自由度带来的挑战,文章对比了两种核心方案:一是利用任务约束进行几何简化,快速求解特定任务;二是基于DH参数法配置KDL库,实现通用高效的数值迭代求解。文中结合宇树H1机器人实例,详细阐述了从模型解析、参数提取到代码实现与验证的全流程,并提供了几何法与KDL库的适用场景对比与避坑指南。

weixin_29044713的博客 644

Full Range && Limit Range

Full Range && Limit Range1 Full range和Limit Range定义2 为什么会需要Limit Range3 用Full range去显示limit Range图片4 YUV转RGB5 额外 1 Full range和Limit Range定义 我们知道,对于RGB和YUV的色彩空间来说,有个位深(bit-depth)的概念;位深是指记录图像每个像素的色彩通道时所使用的bit数,常见的RGB888,YUV420-8bit。以RGB888为例,其代表R G B

zjhcj1的博客 1万+

SPD5 集线器协议内容解析

​ 若不同SPD5 Hub后面的本地侧设备同时发送请求,则是22和23、24的混合过程,先通过LID裁决,再通过HID裁决,这里的LID是本地设备的,若LID一致,则看HID,由于SPD5 Hub的本地侧设备HID均为111,因此实际上是比较SPD5 Hub的HID,这个过程在前文提到,SPD5 Hub会转换HID。​ 若MR27[4]=1且MR27[3:0]=1,如果MR51[3:0]=1时,发送IBI,并且MR48[7]置1,将GETSTATUS CCC的待处理中断位[3:0]更新为0001。

weixin_50591344的博客 3864

【VibeCoding系列】小白入门指南:模型选择、编辑器选择、项目预定全分析

开箱即用:下载安装就能用,不用配 API Key(也可以自己配)Cmd+K 快速修改:选中代码,按 Cmd+K,直接让 AI 修改Cmd+L 对话:侧边栏聊天,支持引用文件和代码@文件引用:输入 @ 就能引用项目中的文件,AI 自动读取上下文Agent 模式:告诉 AI 一个需求,它自动跨文件修改下载地址cursor.com(免费版有额度限制,足够入门)✅下载 Cursorcursor.com),安装打开✅选一个小项目(个人名片页 or Todo List)✅按照七步工作流开干。

十年老程序猿,AI 疯狂研究专家,前沿硬核知识分享 224

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

上一篇: Python 实现插入已排好序的链表(含完整源码)
下一篇: Python:实现求任意级数的总和(包含完整源代码)
普通网友
博客等级 码龄4年 1011粉丝 1742原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编码实践

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址