Python:如何检测长序列号中的特定数字

2024-03-28 19:56:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在做这个项目,一个小的Python和Tkinter项目,作为一个初学者,如果不是因为这个小问题,我几乎完成了它,我做了一些测试后发现。 程序应该说明我在输入中输入的序列号是否是“魔鬼号”,这取决于该序列号中是否有数字“666”。在正的情况下,应该有数字“666”,它应该远离其他6,这意味着不应该有这样的“666”。66“如果把66“这个数字重复了几次就可以认为是66”。在

我遇到的问题是,当我测试只有一个“666”并且同时以该数字(666)结尾的数字时,这些数字不应被视为魔鬼数字。我似乎解决不了这个问题。在

为了实现这个项目,我使用了Python和Tkinter。代码如下:

"""*************************************************************************"""
""" Author: CHIHAB        Version: 2.0        Email: chihab2007@gmail.com   """
""" Purpose: Practice     Level: Beginner     2016/2017                     """
"""*************************************************************************"""
############################ I M P O R T S#####################################
from tkinter import*
from types import *
############################ T K I N T E R ####################################
main = Tk()

e = Entry(main, bg="darkblue", fg="white")
e.pack(fill=X)

l = Label(main, bg="blue", fg="yellow")
l.pack(fill=X)
############################ F U N C T I O N S ################################
def devil(x): #TEST ENTERED VALUE FOR DEVIL NUMBER
    c = 0
    i = 0
    l = list(x)
    while i < len(l):                   #This block of code means that as long as the index i 
        if l[i] == "6":                 #   is below the length of the list to which we have 
            c = c+1                     #       converted the entry, the program is allowed to keep 
            print("this is c :", c)     #           reading through the list's characters.
        else:
            c = 0
        if i <= (len(l)-2) and c == 3 and l[i+1] != "6":
            return True
        i = i+1
    return False
def printo():   #GET VALUE ENTRY AND SHOW IT IN LABEL
    x = e.get()
    if x != "":
        if x.isnumeric() == True:   #SHOW ENTERED VALUE IF INTEGER
            y = devil(x)
            if y == True:
                print("The number you entered is a devil number.")                
                l.config(text="The number you entered is a devil number.", bg="blue")
            else:
                print("The number you entered is NOT a devil number.")                
                l.config(text="The number you entered is NOT a devil number.", bg="blue")
            #print(x)
            e.delete(0, END)
        else:   #SHOW ERROR IF NOT INTEGER
            l.config(text="please enter an integer in the entry.", bg="red")
            print("please enter an integer in the entry.")
            e.delete(0, END)
    else:   #SHOW ERROR IF EMPTY
        l.config(text="please enter something in the entry.", bg="red")
        print("please enter something in the entry.")

############################ T K I N T E R ####################################
b = Button(main, text="Go", bg="lightblue", command=printo)
b.pack(fill=X)

main.mainloop()

给你,伙计。我希望我的代码足够整洁,希望你能帮助我,这一点我毫不怀疑。 谢谢您。在


Tags: thetextyounumberifismainshow
2条回答

{a>在任何地方都能找到匹配的数字,那么

if '666' in '1234666321':
    print("It's a devil's number")

但是,你说666必须是一个“孤独”666,也就是说,正好三个6并排,不多,不少。不是两个,也不是四个。五个{}都出来了。在这种情况下,我将使用tobias_k's regex。在

不过,如果你对regex怀有强烈的仇恨,你可以使用string.partition来实现它:

^{pr2}$

表演情况如下:

>>> x = '''
... import re
... numbas = ['666', '6', '123666', '12366', '66123', '666123', '666666', '6666', '6'*9, '66661236666']
... 
... def devil(x):
...     return re.search(r"(?:^|[^6])(666)(?:[^6]|$)", x) is not None
... '''
>>> import timeit
>>> timeit.timeit('[devil(num) for num in numbas]', setup=x)
13.822128501953557

>>> x = '''
... numbas = ['666', '6', '123666', '12366', '66123', '666123', '666666', '6666', '6'*9, '6666123
666']
... def has_devils_number(num):
...     start, mid, end = num.partition('666')
...     if not mid:
...         return False
...     else:
...         if end == '666':
...             return False
...         elif start.endswith('6') or end.startswith('6'):
...             return has_devils_number(start) or has_devils_number(end)
...         return True
... '''
>>> timeit.timeit('[has_devils_number(num) for num in numbas]', setup=x)
9.843224229989573

我和你一样惊讶。在

您应该为此使用regular expression。类似^{cd1>}的东西似乎有效。这意味着“字符串^{cd2>}或^{cd3>}的开始,不是6^{cd4>},然后是^{cd5>},然后是字符串^{cd6>}以外的其他内容”。

>>> p = r"(?:^|[^6])(666)(?:[^6]|$)"
>>> re.search(p, "123666")
<_sre.SRE_Match at 0x7fe120f12918>
>>> re.search(p, "666123")
<_sre.SRE_Match at 0x7fe120f128a0>
>>> re.search(p, "12366666123")
None

在您的代码中,这应该做到这一点(未测试):

^{pr2}$

如果性能是一个问题(但在您的情况下不应该是这样),您可以预编译regex。

^{pr3}$

时间:

^{pr4}$

相关问题 更多 >