小编Rom*_*man的帖子

如何退出if子句

过早退出if条款有哪些方法?

有时我正在编写代码并希望breakif子句中放置一个语句,只记住那些只能用于循环.

让我们以下面的代码为例:

if some_condition:
   ...
   if condition_a:
       # do something
       # and then exit the outer if block
   ...
   if condition_b:
       # do something
       # and then exit the outer if block
   # more code here
Run Code Online (Sandbox Code Playgroud)

我可以想到一种方法:假设退出情况发生在嵌套的if语句中,将剩余的代码包装在一个大的else块中.例:

if some_condition:
   ...
   if condition_a:
       # do something
       # and then exit the outer if block
   else:
       ...
       if condition_b:
           # do something
           # and then exit the outer if block
       else:
           # more code here …
Run Code Online (Sandbox Code Playgroud)

python control-flow

87
推荐指数
8
解决办法
26万
查看次数

Perl在分隔符之前/之后用空文本分割

我注意到Perl的split命令有一些奇怪的行为,特别是在我希望结果数组包含空字符串的情况下,但实际上并没有.

例如,如果我在字符串的结尾(或开头)有一个分隔符,则结果数组没有空字符串''作为最后一个(或第一个)元素.

例:

@s = split(/x/, 'axb')
Run Code Online (Sandbox Code Playgroud)

产生2个元素数组['a','b']

@s = split(/x/, 'axbx')
Run Code Online (Sandbox Code Playgroud)

生成相同的数组

@s = split(/x/, 'axbxxxx')
Run Code Online (Sandbox Code Playgroud)

生成相同的数组

但是当我在最后放置一些东西时,所有这些空字符串都会显示为元素:

@s = split(/x/, 'axbxxxxc')
Run Code Online (Sandbox Code Playgroud)

产生一个6元素数组['a','b','','','','c']

如果分隔符在开头,则行为类似.

我希望在分隔符之间,之前或之后的空文本总是在分割中生成元素.任何人都可以向我解释为什么分裂在Perl中表现得像这样?我只是在Python中尝试了相同的东西,它按预期工作.

注意:Perl v5.8

perl

23
推荐指数
1
解决办法
1万
查看次数

在不使用数组/向量的情况下计算数字序列的模式

我是MATLAB课程入门级的TA,该课程尚未学习数组的使用(或在MATLAB,向量中).有一个考试即将开始,学习指南中的一个问题如下:

[难题]模式是序列中出现次数最多的数字.提示用户一个接一个地以非递减顺序输入一系列非负数.用户通过输入负数来指示序列的结束.编写脚本以获取此类用户输入并确定序列的模式.如果有多种模式,您可以将其中任何一种模式报告为模式.不要使用数组.下面是一个示例运行:

Determine mode of a set of nonnegative integers.
Use a negative number to quit.
Give me a number:  70
Another number not smaller than the previous: 71
Another number not smaller than the previous: 80
Another number not smaller than the previous: 80
Another number not smaller than the previous: 80
Another number not smaller than the previous: 91
Another number not smaller than the previous: 93
Another number not smaller than the previous: -1
  Mode is 80. …
Run Code Online (Sandbox Code Playgroud)

algorithm matlab

3
推荐指数
2
解决办法
2126
查看次数

标签 统计

algorithm ×1

control-flow ×1

matlab ×1

perl ×1

python ×1