RUNOOB python练习题24 斐波那契数列的衍生问题

Python之求斐波那契数列前n项 源码如下: # fibo.py def fibo(n): a, b = 0, 1 for i in range(n): print(a,end='\t') a,b = b, a + b n = eval(input("请输入一个整数:")) print('斐波那契前n项'.center(20,'-')) fibo(n) 运行结果: 关键代码也就两三行 ... 阅读详情

用来练手的python练习题,原题链接 : python练习实例24

题干: 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13…求出这个数列的前20项之和。

拿到题目观察数列,我们不难发现,分子和分母都是斐波那契数列,因此我们只需要用递归或是循环分别计算出每一项的分子和分母对应的值,源代码如下:

def sum_fibonacci_frac(length_sequence):
  result = 0
  for i in range(1,length_sequence+1):
    if i == 1:
      numerator_2 = 2
      denominator_2 = 1
      result += numerator_2/denominator_2
    elif i == 2:
      numerator_1 = 3
      denominator_1 = 2
      result += numerator_1/denominator_1
    else:
      numerator = numerator_2 + numerator_1
      denominator = denominator_2 + denominator_1
      result += numerator/denominator
      numerator_2 = numerator_1
      denominator_2 = denominator_1
      numerator_1 = numerator
      denominator_1 = denominator
  return result    

输出结果如下:
在这里插入图片描述
代码中定义了函数可以用于计算题干中数列的前n项和,n由参数length_sequence决定。我们知道对于斐波那契数列而言,总满足 F [ n ] = F [ n − 1 ] + F [ n − 2 ] F[n] = F[n-1] + F[n-2] F[n]=F[n−1]+F[n−2]。因此我们定义numrator_1,numrator_2,denominator_1,denominator_2用于分别计算分子分母上的斐波那契数列的值。

Python练习案例(二)——斐波那契数列 前言 大家好,今天我们主要练习的就是斐波那契数列,相信很多同学都对这个数列有一定的了解,今天就来试一试用python来写出斐波那契数列,并且画出他的图像。 正文 大家知道斐波那契数列其实是有规律的,如果想写出斐波那契数列中的任意一个数,我们可以通过函数来实现,python定义函数的结构如下: def f(x) expression 1 ....... expression n return() 如果不加return,程序可能会报错,然后按照斐波那契数列的递推公式我们可以得到: def F(n): 阅读详情

相关推荐

SOC设计必看!Tessent DRC检查中最容易踩的5个坑(附解决方案)

本文针对SOC设计中Tessent DRC检查的常见问题,详细分析了5个最易忽视的陷阱,包括时钟域交叉、扫描链虚连、多电压域规则等,并提供专业解决方案。特别针对芯片设计中的DFT验证难点,分享了经过验证的调试方法和Tessent工具使用技巧,帮助工程师提升DRC检查效率。

weixin_29280657的博客 496

Python每日一练-----斐波那契数列

☀(day39) 目录 📝题目: 🚩题目分析: 💡解题思路: 🌟解法一:常规解法 🌈代码实现 🌟解法一:动态规划 🌈代码实现 📝题目: 斐波那契数 (通常用 F(n) 表示)形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: F(0) = 0,F(1)= 1 F(n) = F(n - 1) + F(n - 2),其中 n > 1 ⭐示例 1: 输入:n = 2 输出:1 解释:F(2) = F(1).

m0_61791601的博客 2054

Amesim与Simulink联合仿真:S-Function接口配置与实战避坑指南

本文详细介绍了Amesim与Simulink联合仿真中S-Function接口的配置方法与实战避坑指南。从环境搭建、编译器配置到S-Function接口实战,逐步解析关键步骤与常见问题解决方案,帮助工程师高效实现多领域系统仿真,特别适合汽车、航空航天等复杂系统建模场景。

weixin_29173777的博客 344

Python-数据思维-6.2Numpy科学计算应用1

第1关:创建numpy数组 本关任务:按要求生成numpy数组: 1 使用numpy的linspace函数,创建初值为1,终止为5,元素个数为20的等差数组 2 将数组B变换成2行5列的二维数组 3 随机数种子为7,生成4行3列的随机数数组,值在[0,1)之间 4 随机数种子为11,生成3行4列的正态分布随机数数组,期望值为5,标准差为2 5 将数组D的内容写入文本文件,使用英文分号为分隔符,浮点数精确到小数点后5位,文件名为1.txt 6 使用斐波那契数列(1,1,2,3,5,...)生成一个5行4列的

Meropidae的博客 4823

U8+ 新建账套

一、登录 账套主管:demo 对账套有修改权限,有账套库权限 系统管理员:admin 其他所有权限 二、新建账套 admin登录–>点击系统管理–>账套–>建立 选择了参照已有账套结转期初:就是上一个的期末数据作为这一次新表的期初数据 启用会计期一旦选择更改不了。 ...

茶茶很困i 3695

项目介绍 MATLAB实现基于LSTM-XGBoost长短期记忆网络(LSTM)结合极端梯度提升(XGBoost)进行多变量时序预测的详细项目实例(含模型描述及部分示例代码)

本项目基于MATLAB平台,实现LSTM-XGBoost混合模型进行多变量时序预测。通过LSTM网络自动提取时序特征,结合XGBoost强大的回归能力,有效解决多变量时序数据的高维复杂性、长短期依赖捕捉等难题。项目包含完整的数据预处理流程、模型构建与训练方法,以及性能评估指标。提供的GUI界面支持参数调整、训练监控和结果可视化,适用于能源、金融、气象等多领域预测任务。配套代码详细注释,便于理解模型实现细节,为时序预测研究提供实用参考框架。

优质创作者: 人工智能技术领域 对于有一定基础的 MATLAB和Python带具体需求都可以详谈 MATLAB和Python可以提供代码调试服务加油 谢谢 你的鼓励是我前行的动力 谢谢支持 加油 谢谢 103

python9-14

python 9-14

Lumos427的博客 7032

Qt C++ HTTP 调用通义千问大模型 X 学术论文润色工具(SCI 格式适配)

请求地址:`https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation`;| Windows | 打包时携带 `Qt6Network.dll`/`libcrypto-1_1-x64.dll` 等依赖;| Linux | 安装 `libssl-dev` 和 `libcurl4-openssl-dev`;| API 调用失败 | 检查 API-KEY 是否有效;

寒寒豆豆软件公司的博客 104

Python婓波那契数列(Fibonacci sequence)

在数学上,斐波那契数列定义为:第一项F(1)=0,第二项F(2)=1,而后续每一项都是前两项的和,即F(n)=F(n-1)+F(n-2)(n≥3),因此,斐波那契数列的前几个数字是:0、1、1、2、3、5、8、13、21、34、……对于第n项,通项公式可以写作:。这种方法利用了矩阵的幂运算的性质,避免了传统的递归或迭代方法中的重复计算,从而大大提高了计算效率。使用函数递归或非递归的方式都可以方便地计算斐波那契函数:F(1)=0,F(2)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 3)。

moment159的博客 2万+

【ROS2实体机械臂驱动】rokae xCoreSDK Python测试使用

本文记录了使用xCoreSDK-Python驱动Rokae实体机械臂的测试流程。

机器人梦想家 Bing Lee 1502

手把手教你学SOME/IP「3.2.1.发布/订阅行为」

本文详细介绍了SOME/IP协议中的服务发现机制,重点解析了发布/订阅行为的流程。主要内容包括:1)服务发布与Method通信流程,涵盖find/offer报文交互、TTL保活机制及异常处理;2)服务订阅与Event通信流程,包括subscribe/ack报文交互和组播延迟机制;3)特殊场景如快速发送、半周期回复、重置订阅等机制。通过邮局订阅报纸的类比,帮助理解服务发现的核心原理,并强调流程图对于问题定位的重要性。文章为SOME/IP协议的工程实现提供了实用指导。

nihaoljq2010的博客 1222

python程序题斐波那契数列_Python_经典题_斐波那契数列

古典问题:3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月兔子总数是多少?(使用循环实现)分析:第一个月是1对第二个月还是1对第三个月是2对(因为第三个月之前的一对兔子可以生一对兔子)第四个月是3对(因为三个月以后的兔子每个月都可以生一对兔子)第五个月是5对(因为老兔子又生了一对,前两个月生的一对幼兔3个月了,以后的每个月都可以生一对兔子了).........

weixin_39572764的博客 838

Sigrity OptimizePI IC Device Power Pin Inductance Analysis模式如何计算IC电源管脚电感操作指导

Sigrity OptimizePI IC Device Power Pin Inductance Analysis模式可以计算电容到IC电源管脚的电感,用于评估电容位置对于IC电源管脚的效果,如何分析,以下图为例进行说明。Capacitors:选择层面,这里选择top layer(IC在top层),下方可以选择电容的size,这里选择All Size。IC devices,输入U*, A*, B*, Q*, P*,将所有这些字母开头的器件都识别为IC。模式如何计算IC电源管脚电感操作指导。

weixin_54787054的博客 410

debug记录3:求数列和,数列的分子分母都是Fibonacci数列

/*求数列和,数列的分子分母都是Fibonacci数列 从键盘输入正整数N,求以下数列的前N项的和SN: SN=1/1+2/1+3/2+5/3+8/5+13/8+…… 即分子分母都是Fibonacci数列。输入形式为"%d", 输出形式为"%f"。例如,输入:5,则输出7.766667*/ #include<stdio.h> int main() { int N,i; double sum=0.0,t=1;//double初值自动变成有小数点的 scanf("%d",&...

weixin_64132768的博客 790

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

48.求斐波那契分数数列之和

编程题目: 48.有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13… 求出这个数列的前20项之和。 示例代码: package program.calculation.exercise48; import java.util.Scanner; /** * 48.有一分数序列:1/2,2/3,3/5,5/8,8/13,13/21... 求出这个数列的前20项之和。 * 分析:注意分子与分母的变化规律:分子和分母分别是一组斐波那契数列,即每一项等于前两项的和。 */ public cla

SC的博客 3177

深度学习工具包 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'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('DeepLearnToolbox'));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('state',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'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',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 = 'sigm';%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, 'Too big error');```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('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';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)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';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, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% 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'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 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, 'Too big error');```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('state',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, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',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, 'Too big error');%% ex3 neural net with dropoutrand('state',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, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % 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, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % 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, 'Too big error');%% 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('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % 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, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Python - 求斐波那契数列前N项之和

n = int(input("Input N: ")) a = 0 b = 1 sum = 0 for i in range(n): sum += a a, b = b, a + b print("The sum of", n, "FIB is", sum,"!")

MagHSK.Blog 2万+

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

输出斐波拉契数列的前n项(python)

思路:使用列表 代码如下: n=int(input('输出斐波拉契数列的前n项:n=')) list=[] for m in range(0,n): if m==0: list.append(0) elif m==1: list.append(1) else: list.append(list[m-1]+list[m-2]) ...

qq_44787076的博客 2万+

生成斐波那契数列数组

const fibonacci  = ((init=[0,1],n)=>{ const fib = (n)=>{ let result = init[n]; if(typeof result !=='number'){ result=fib(n-1)+fib(n-2); init[n]=result; } return result; } fib(n); return init

zxw305的博客 709

斐波那契数列的衍生问题和辗转相除法

以上就是今天要讲的内容,本文仅仅简单介绍了辗转相除法和递归的使用。

weixin_69939913的博客 468

python编程练习-斐波那契数列

斐波那契数列 生成斐波那契数列的前20个数。 说明:斐波那契数列(Fibonacci sequence),又称黄金分割数列,是意大利数学家莱昂纳多·斐波那契(Leonardoda Fibonacci) 在《计算之书》中提出一个在理想假设条件下兔子成长率的问题而引入的数列,所以这个数列也被戏称为"兔子数列"。 斐波那契数列的特点是数列的前两个数都是1,从第三个数开始,每个数都是它前面两个数的和, 形如:1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...。斐波那契数列

一个小白 1万+

使用python实现斐波那契数列的四种方法

第一种方法实现(顺序输出) 第二种方法实现(利用python的组包拆包原理) 第三种方法实现(利用递归函数实现) 第四种方法实现(利用列表实现)

但行好事,莫问前程 3万+

程序 数列求和 c语言,[编程入门]有规律的数列求和-题解(C语言代码)

第一种:我们发现其实分子和分母都是斐波那契数列(从第三项开始,每一项等于前两项之和),所以我们可以定义两个数组,分别来存放分子和分母。然后两个数组里的数按位置相除累加。参考代码:#includeint main (){int N;double total = 0;scanf("%d",&N);int a[N],b[N];a[0] = 2,a[1] = 3; //这里需要手动输入0 1位置的...

weixin_32165903的博客 3164

python Fibonacci数列(蓝桥杯)

小提示: 今天使用蓝桥杯系统时发现一个问题,同样的代码,封装和不封装在蓝桥杯评测系统运行时是不一样的, 首先是不封装运行的数据如下: 然后是封装后运行的数据如下: 可以看到,虽然封装后的占用内存稍大于不封装的,但是封装后的运行速度明显比不封装的快 题目要求: 时间限制:1.0s 内存限制:256.0MB 问题描述 Fibonacci数列的递推公式为:Fn=Fn-1+Fn-2,其中F1=F2...

qq_45894553的博客 1341

每日一题--分数到小数

这道题目的关键是当余数出现重复时意味着商也开始重复了,抓住这一点我们就可以写出代码了,要注意的是一些边界情况的判断: class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: if numerator == 0: retur...

Angel__c的博客 369

python笔试题—斐波那契数列

已知一个数列:1,1,2,3,5,8,13…的规律为从3开始的每一项都等于其前两项的和,这是斐波那契数列.求满足规律的100以内的所有数据

nickyff的博客 583
上一篇: RUNOOB python练习题 23 使用*号输出菱形
下一篇: RUNOOB python练习题25 递归实现阶乘
Cy_coding
博客等级 码龄7年 49粉丝 88原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值