简体   繁体   English

Python查找没有特定数字的最长数字字符串

[英]Python Finding Longest String of Digits Without a Particular Number

Sorry if the title is confusing. 抱歉,标题令人困惑。 I am trying to write a python function that takes a string of numbers (digits) as input (ex: "123456789123"). 我正在尝试编写一个将一串数字(数字)作为输入的python函数(例如:“ 123456789123”)。 The function should also take in an int n, and then should return the largest segment of the string of digits that does NOT contain n. 该函数还应接受一个int n,然后应返回不包含n的数字字符串的最大部分。 For example, if my string of numbers was 1211211121 and my n is 2, then my function should return "111" since it is the longest segment of the string where 2 is not encountered. 例如,如果我的数字字符串是1211211121,而我的n是2,则我的函数应返回“ 111”,因为它是字符串中最长的段,其中未遇到2。

Python is my first "scripting" language and I am still learning to successfully incorporate the built-in functionality that the language has. Python是我的第一种“脚本”语言,但我仍在学习如何成功整合该语言具有的内置功能。 I have written a solution to the above problem that involves splitting the string of digits into an array of individual digits and then iterating through each and every one to find segments of digits without n. 我已经为上述问题写了一个解决方案,其中涉及将数字字符串分成单个数字数组,然后遍历每个数字以查找没有n的数字段。 I then compare the segments to find the longest. 然后,我比较分段以找到最长的分段。 However, the TA for this course told us there was a more "pythonic" way to approach this problem and that my current function, while working, could be significantly shorter. 但是,本课程的技术支持告诉我们,有一种更“ Python式”的方法来解决此问题,并且我当前的功能在工作时可能会大大缩短。

I'm stumped, does anyone have a more "pythonic" solution they can assist me with? 我很困惑,有人可以为我提供更多“ pythonic”解决方案吗? Thanks in advance! 提前致谢!

PS: Not sure if it is relevant to a python solution, but I should mention that the string of digits can be very long in some test cases (~1000+ at times IIRC). PS:不确定它是否与python解决方案有关,但我应该指出,在某些测试案例中,数字字符串可能会很长(有时IIRC约为1000+)。

In [15]: text = '1211211121'

In [16]: text.split('2')
Out[16]: ['1', '11', '111', '1']

In [18]: max(text.split('2'), key=len)
Out[18]: '111'

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM