避免循环后重复代码? [英] Avoiding repeat of code after loop?

查看:123
本文介绍了避免循环后重复代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用循环时,我经常最终要写两次代码.例如,在学习Udacity计算机科学课程时,我编写了代码(用于查找顺序最重复的元素的函数):

I often end up writing a bit of code twice when using a loops. For example, while going over the Udacity computer science course, I wrote the code (for a function to find the most sequentially repeated element):

def longest_repetition(l):
    if not l:
        return None
    most_reps = count = 0 
    longest = prv = None
    for i in l:
        if i == prv:
            count += 1
        else:
            if count > most_reps:
                longest = prv
                most_reps = count
            count = 1
        prv = i
    if count > most_reps:
        longest = prv
    return longest

在这种情况下,我要检查两次计数是否大于先前最重复的元素.当当前元素与最后一个元素不同以及我到达列表的末尾时,都会发生这种情况.

In this case, I'm checking twice if the count is greater than the previously most repeated element. This happens both when the current element is different from the last and when I've reached the end of the list.

在逐字符解析字符串时,我也遇到过几次.有时也有多达5行代码.这是普遍现象,还是我的思维/编码方式的结果.我该怎么办?

I've also run into this a few times when parsing a string character by character. There have also been a few times where it's been up to about 5 lines of code. Is this common, or a result of the way I think/code. What should I do?

edit:同样,在人为的字符串拆分示例中:

edit: Similarly, in a contrived string splitting example:

def split_by(string, delimeter):
    rtn = []
    tmp = ''
    for i in string:
        if i == delimeter:
            if tmp != '':
                rtn.append(tmp)
                tmp = ''
        else:
            tmp += i
    if tmp != '':
        rtn.append(tmp)
    return rtn

edit:此项考试是为该课程的学生准备的,他们不应该对Python有所了解.只有以前单元讲授的内容.尽管我确实有使用Python的经验,但是我尝试遵守这些限制以充分利用本课程.教了诸如str.split,列表和Python的许多基础知识之类的知识,但在导入方面却一无所获-尤其是诸如groupby之类的东西.就是说,如何在没有编程入门课程中不会讲授的任何语言功能的情况下编写它.

edit: The exam this was from was written for students of the course who are not expected to have any outside knowledge of Python; only what was taught in the previous units. Although I do have prior experience in Python, I'm trying to adhere to these restrictions to get the most of the course. Things like str.split, lists, and a lot of the fundamentals of Python were taught, but nothing yet on imports - especially not things like groupby. That being said, how should it be written without any of the language features that probably wouldn't be taught in a programming introduction course.

推荐答案

自从您标记了language-agnostic以来,我发现您对可用于使代码高效,紧凑和易读的特定于python的东西没有太大的兴趣.出于同样的原因,我不会显示可以用python编写的代码多么漂亮.

Since you tagged language-agnostic, I see that you wont be much interested in python-specific stuff you could use to make your code efficient, compact and readable. For the same reason, I am not going to show how beautiful a code can be written in python.

在某些情况下,根据您的算法,可以避免最后使用if,但是大多数情况下,这就像如果存在,它应该是重要的和/或有效的".我不知道python解释器的工作原理,但使用的是C/C ++/etc等编译语言.编译器执行各种循环优化,包括如果执行相同的操作,则将if块移出循环.

In some of the cases that extra if at the end can be avoided depending on your algorithm, but most cases it's like "If it exists, it should be significant and/or efficient." I dont know about the how the python interpreter works, but in compiled languages like C/C++/etc. the compiler performs various kinds of loop optimisations, including moving the if-blocks out of a loop if it does the same thing.

我跑步并比较了各种摘要的运行时间:

I ran and compared the running time of various snippets:

  • @JFSebastian-8.9939801693
  • @srgerg-3.13302302361
  • 您的用户-2.8182990551.
  • @JFSebastian - 8.9939801693
  • @srgerg - 3.13302302361
  • yours - 2.8182990551.

尾随的if给您最好的时间并不是一种概括.我的观点是:只需遵循您的算法,然后尝试对其进行优化.最后的if没错.可能的替代解决方案很昂贵.

It's not a generalisation that a trailing if gives you the best time. My point is: just follow your algorithm, and try to optimise it. There's nothing wrong with an if at the end. Probably alternative solutions are expensive.

关于您放入的第二个示例:完成检查tmp == ''以确保仅返回非空字符串.实际上,这是拆分算法之外的一种附加条件.无论如何,循环后都需要一个附加的rtn.append,因为最后一个定界符之外还有其他内容.您总是可以将一个if条件放入类似if curCharIndex == lastIndex: push items to list的循环中,该条件将在每次迭代中执行,并且其条件再次相同.

About the second example you have put in: The check tmp == '' is done to ensure only non-empty strings are returned. That actually is a sort of additional condition over your splitting algorithm. In any case, you need an additional rtn.append after the loop because there's still something beyond the last delimiter. You could always push an if condition inside the loop like if curCharIndex == lastIndex: push items to list which will execute in every iteration, and its sort of the same case again.

简而言之,我的答案:

  • 您的代码与您想到的算法一样高效.
  • 在很多情况下都会遇到if的情况-无需担心它们,它们可能使代码比没有if的替代方法更有效率(示例就在这里).
  • 此外,编译器还可以发现和修改/移动代码周围的块.
  • 如果有一种语言功能/库可以使您的代码快速且可读,请使用它. (这里的其他答案指出了python提供的内容:))
  • Your code is as efficient as your algorithm that you have in mind.
  • The ifs in the end are encountered in many cases -- no need to worry about them, they may be making the code more efficient than alternative approaches without such an if (examples are right here).
  • Additionally compilers can also spot and modify/move the blocks around your code.
  • If there's a language feature/library that makes your code fast and at the same time readable, use it. (Other answers here point out what python offers :))

这篇关于避免循环后重复代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆