Perl与Python编程实例解析

Perl与Python编程实践案例解析 本文汇总了多个编程实践案例,涵盖Perl和Python语言,内容包括文本右对齐输出、列宽控制、哈希表应用、环境变量处理、正则表达式匹配、文件操作、版权添加、猜数字游戏以及目录操作等,适合编程初学者和进阶者参考学习。 阅读详情

48、编写一个子例程 total,用于计算传入参数的总和

以下是实现该功能的 Perl 代码:

sub total {
    my $sum = 0;
    foreach my $num (@_) {
        $sum += $num;
    }
    return $sum;
}

上述代码定义了一个名为 total 的子例程,它接受一个数字列表作为参数,通过遍历列表将每个数字累加到 $sum 变量中,最后返回总和。

49、编写程序,让用户输入一个字符串和一个数字,将字符串重复指定的次数并输出,要求字符串出现在不同的行

以下是一个使用 Perl 语言实现的程序示例:

print "请输入一个字符串: ";
chomp(my $str = <STDIN>);
print "请输入一个数字: ";
chomp(my $num = <STDIN>);
for (my $i = 0; $i < $num; $i++) { 
    print $str . "\n";
}

这个程序首先提示用户输入一个字符串和一个数字,然后使用 for 循环将字符串重复指定的次数,并将每次重复的字符串输出到不同的行。

50、编写一个子程序计算 1 到 1000 的数字总和并输出结果

以下是一个通用的 Perl 代码示例来计算 1 到 1000 的数字总和并输出结果:

#!/usr/bin/perl
use strict;
use warnings;

sub sum_numbers {
    my ($start, $end) = @_;
    my $sum = 0;
    for (my $i = $start; $i <= $end; $i++) {
        $sum += $i;
    }
    return $sum;
}

my $result = sum_numbers(1, 1000);
print "1 到 1000 的数字总和是: $result\n";

此代码定义了一个名为 sum_numbers 的子程序,用于计算从 $start 到 $end 的数字总和,然后调用该子程序计算 1 到 1000 的总和并输出结果。

51、编写程序读取用户输入的一些行,打印一个标尺行,然后将每一行右对齐到第 20 列输出

以下是一个实现该功能的 Perl 示例代码:

# 打印标尺行
print '1 2 3';
print '01234567890123456789';
# 读取用户输入的行
while (my $line = <STDIN>) {
    chomp $line; # 去除行末换行符
    printf "%20s\n", $line; # 右对齐到第 20 列输出
}

上述代码先打印了一个标尺行,然后通过 while 循环读取用户输入的每一行,使用 chomp 去除行末换行符,最后使用 printf 函数将每一行右对齐到第 20 列输出。

52、编写代码实现读取用户输入的多行文本,将每行文本右对齐到20个字符宽度并输出,同时打印一个到第75列的标尺行

以下是使用Python实现该功能的代码:

# 打印标尺行
ruler = ''.join([str(i % 10) for i in range(1, 76)])
print(ruler)

# 读取用户输入的多行文本
lines = []
while True:
    line = input()
    if not line:
        break
    lines.append(line)

# 右对齐并输出每行文本
for line in lines:
    print(line.rjust(20))

代码解释:

  1. 打印标尺行 :使用 ''.join() 方法和列表推导式生成一个到第75列的标尺行,然后打印出来。
  2. 读取用户输入的多行文本 :使用 while 循环不断读取用户输入的行,直到用户输入空行为止。将每行文本添加到 lines 列表中。
  3. 右对齐并输出每行文本 :使用 rjust() 方法将每行文本右对齐到20个字符宽度,并打印出来。

53、编写代码实现先询问用户需要的列宽,然后读取用户输入的多行文本,将每行文本右对齐到指定列宽并输出,同时打印合适长度的标尺行

以下是使用 Python 实现该功能的代码:

# 询问用户需要的列宽
width =
Perl与Python文件操作编程实例解析 本文详细介绍了多个使用Perl和Python编写的文件操作程序,包括符号链接检测、文件数量统计、目录信息列出、文件排序、时间设置、字符串查找等功能。涵盖了Perl的readlink、glob、opendir、stat、utime等函数,以及Python的os、math模块使用,适用于系统管理和自动化脚本开发。 阅读详情

相关推荐

Perl与Python实用编程案例解析

本博客包含多个编程实例,涵盖Perl与Python语言的应用。内容包括文件操作、目录处理、硬链接与软链接创建、信号处理、正则匹配、日期判断等。每段代码均提供详细实现和说明,适用于系统管理、脚本开发等场景,有助于提升编程实践能力。

u9v0w的博客 302

医疗保健编程:Perl、Python与Ruby的实用方法

本书《医疗保健编程:Perl、Python与Ruby的实用方法》旨在介绍如何将编程技术应用于医疗保健领域。作者Jules J. Berman通过具体的示例和应用,深入讲解了在医疗信息学中运用这些编程语言进行文本文件解析、转换和数据处理的基础方法。书籍不仅提供了丰富的编程脚本算法和分析,还鼓励读者将数学、统计学和计算方法整合进生物学研究,以促进学科间的交叉融合。

weixin_36364707的博客 427

【LVGL】学习笔记--(3)界面切换以及显示优化

界面切换和帧率优化

sinat_33408502的博客 1万+

Java utgard连接OPC问题记录

怎么开启是个问题, 是在引入openscada的jar包里的Sever类中修改,这就犯难了, 其实没必要, 只要在自己项目下创建与openscada中Server类相同的路径,并复制Server过去改就行了, 项目会优先使用本地类,像下面这样。奇迹发生了,0x00000005解决. 注: 我的安全补丁编码跟网上查到的并不一样, 所以最初没有删,后来全都删了就好了,这个编码规则咱也不知道.安全日志中记录用户登录行为, OPC通信需要使用Windows系统用户进行登录, 如果用户名密码错误这里会有相关记录.

wangxin1949的博客 2840

qcc514x-qcc304x调试笔记

qcc514x-qcc304x调试笔记-1-QCC514x系列 qcc514x-qcc304x调试笔记-2-开发环境搭建 qcc514x-qcc304x调试笔记-3-如何修改蓝牙名称 qcc514x-qcc304x调试笔记-4-如何修改蓝牙地址 qcc514x-qcc304x调试笔记-5-如何区分左右耳 qcc514x-qcc304x调试笔记-6-PIO相关操作 ...

leezs的博客 1244

上位机图像处理和嵌入式模块部署(开篇)

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】 图像处理是现实生活当中很实用的一门技术。工业上一般采用的是机器视觉,以传统算法和光源控制为主,部分采用了深度学习技术。而生活当中,则主要以二维码识别、人脸识别、车牌识别和ocr识别为主,这中间深度学习与AI扮演了很重要的角色。过去,市场上的商业收费软件,主要还是以传统设备厂商提供的上位机软件为主,那这一部分是不是结合最新的npu技术,应该做出一些新的东西出来呢?

嵌入式-老费,一个分享专业嵌入式知识的blog 1337

CloudCompare 二次开发:插件中的 PCL 环境配置与编程

在进行 CloudCompare 的二次开发过程中,我们常常需要使用点云库(Point Cloud Library,简称 PCL)来处理和分析点云数据。在 CloudCompare 的界面中,选中一个点云对象,然后点击菜单栏中的 “插件” -> “MyPluginAction”。插件将对选中的点云对象进行体素滤波处理,并更新显示结果。下面我们将展示一个简单的插件编程示例,该示例使用 PCL 对输入的点云数据进行体素滤波处理。方法进行体素滤波处理,并将结果点云赋值给选中的点云对象。文件并点击 “打开”。

2301_79331387的博客 283

UG\NX二次开发 找不到指定的dlx文件(Specified Dlx file not found)

有群友问:用Ctrl+U运行的时候就报错,找不到指定的dlx文件Specified Dlx file not found。怎么处理。

王牌飞行员_里海的博客 1130

ScanNetV2 数据集讲解和选择性下载

写在前面的话: 不可转载!!!!!!!!!!!! ScanNetV2一共1.2T,数据太大本文会简单讲解如何下载自己想要的文件,并附上修改后的下载程序 ScanNetV2:http://www.scan-net.org/ 简介 ScanNetV2的作者是斯坦福大学的博士,其团队通过收集RGB-D的视频序列,通过ipad应用加深传感器而收集的,然后视频会被上传到服务器,并被自动重建。然后,视频会被给到亚马逊 Mechanical Turk,将标注工作众包出去。ScanNetV2是RGB-D数据集,.

qq_35781447的博客 2万+

搭建ROS小车真的难吗?

搭建ROS小车真的难吗?不难 1.引言 本着为大家谋福利的心态,根据自己以往的开发经验,打算写一个从零开始制作一个可以实现地图构建和导航的ROS小车。目前某宝上面有很多现成产品,但是我个人认为,一个好的移动机器人开发工程师,应该对机器人的整个流程都能具备维护的能力,然后再深入研究其中一个方向即可。看到网上很少有整个系列的开发教程,看到同学们大多东拼西凑,浪费了不少时间。我就想着利用空余时间,将我本人的开发过程输出给大家。有基础理论、有实际工程代码、有丰富的学习资料,尽最大努力帮大家进入移动机器人的大门。 国

「小白学移动机器人」一个专注分享移动机器人相关知识的公众号! 1万+

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

深度学习工具包 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")

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

上一篇: 17、以太坊创新与自主区块链开发指南
下一篇: Perl文件与目录操作及信号处理编程
java5
博客等级 码龄22年 85粉丝 2103原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值