Python,嵌套循环到函数break - pass - continue - return

时间:2015-03-11 23:33:01

标签: python

您好我是一个孤立的爱好开发者。 我的知识有限。 这是一次我试过109次的运动(我的耻辱) 我觉得一些帮助会教会我很多。 这是运动: 定义一个函数postalValidate(S),它首先检查S是否代表有效的邮政编码:

  • 首先删除所有空格;
  • 其余部分必须为L#L#L#形式,其中L为字母(小写或大写),#为数字。
  • 如果S不是有效的邮政编码,则返回布尔值False。
  • 如果S有效,请以漂亮格式L#L#L#返回相同邮政编码的版本,其中每个L为大写。

这是众多试验中的一个:

def postalValidate(S):
    for x in S:
        if x == " ":
            S = S.remove(x)
            if x.isalpha():
                x = x.upper()
                if x.isalpha() or ix.isdigit():
                    if ((S.index(x) % 2 == 0) and x.isalpha()) or ((S.index(x) % 2 != 0) and x.isdigit()):
                        pass
                    else:
                        print(False)
                        break
                        return(False)
                else:
                    print(False)
                    break
                    return(False)
            elif x.isdigit:
                pass
            else:
                print(False)
                break
                return(False)

        elif x.isalpha():
            if S.index(x) % 2:
                pass
            else:
                break
                return(False)
        elif x.isdigit():
            if S.index(x) % 2 == 1:
                pass
            else:
                break
                return(False)
        else:
            break
            return(False)
            pass
    print(S)
    return(S)

我的错误的原因是什么。这是我错过的一些基础知识。 欢迎所有教学答案!

5 个答案:

答案 0 :(得分:1)

我可以告诉你,简单地将字符串拆分成数组会更有效率,然后只检查每个字符的类型。你可以使用单个for循环来完成它,并且只需要一个模数条件来确定它是否在奇数或偶数索引中。您也可以简单地使用6个if语句。

总的来说,它看起来像 拆分字符串 因为(我少于6) 检查是偶数还是奇数。 如果是偶数字母,请检查此索引是否为char 如果是奇数 - ,请检查此索引是否为数字

如果有帮助,请告诉我。

答案 1 :(得分:1)

迈克的建议:正则表达式很好;不幸的是,我的答案中存在一些问题,这些问题没有作为评论格式化:

  1. 你仍然需要删除空格(并且它不清楚但不能统治 这些空间可以存在于字母内部(例如A1 B2 C3 会有效)
  2. 如果它有效,你应该返回一个清理过的版本。
  3. 我可以建议:

    vals = re.findall(r'([a-zA-Z]\d)', string) # this returns an array of all the pairs of letter + number.
    if len(vals) != 3: # if there aren't exactly 3 pairs, this isn't valid
      return false
    return "".join([v[0].upper+v[1] for v in vals] #uppercase the letter, and combine the 3 pairs as a string
    

答案 2 :(得分:1)

你的程序比它需要的更复杂。

您已经列出了要执行的步骤,让我们将它们转换为Python代码:

def postalValidate(S):
    # first, delete all spaces
    S = ''.join(S.split())

    # the remainder must be of the form L#L#L# where L are letters (in either lower or upper case) and # are numbers.
    # If S is not a valid postal code, return the boolean False.
    if len(S) != 6:
        return False
    if not (all(S[i].isalpha() for i in [0, 2, 4]) and
            all(S[i].isdigit() for i in [1, 3, 5])):
        return False

    # If S is valid, return a version of the same postal code in the nice format L#L#L# where each L is capital.
    return S.upper()

有很多方法可以用更少的代码做同样的事情,但我想保持简单。

编辑:使用方法从此question的答案中显示的字符串中删除所有空格。

答案 3 :(得分:0)

import string

# Create translation table:
#   convert lowercase to uppercase, and remove spaces
TRANS = str.maketrans(string.ascii_lowercase, string.ascii_uppercase, " ")

# char identity tests
TESTS = [str.isalpha, str.isdigit] * 3

def postal_validate(s):
    # clean string
    s = s.translate(TRANS)
    # test whether it is a valid postal code
    if len(s) == 6 and all(test(ch) for ch,test in zip(s, TESTS)):
        # if so, return it
        return s
    else:
        # otherwise return False
        return False

答案 4 :(得分:0)

"""this is my code:"""

    def simplifier(S):
    S = str(S)
    x = " "
    S = S.replace(x, "")
    return(S)
def majusculiser(S):
    S = str(S)
    for x in S:
        if str(x).isalpha():
            S = (S.replace(x, x.upper()))
    return(S)
def purifier(S):
    S = str(S)
    for x in S:

        if (not x.isdigit()) and (not x.isalpha()):
            return(False)
    else:
        return(S)
def verifier_les_impairs(S):
    S = str(S)
    l = len(S)
    for x in range (0, l, 2):
        if not str(x).isalpha:
            return(False)
        else:
            return(S)
def verifier_les_pairs(S):
    S = str(S)
    l = len(S)
    for x in range (1, l, 2):
        if not str(S[x]).isdigit():
            return(False)
        else:
            return(S)
def postalValidate(S):
    S = simplifier(S)
    if True:
        S = purifier(S)
        S = majusculiser(S)
        if (len(S) + 1) % 2 == 0:
            return(False)
        if True:
            S = verifier_les_impairs(S)
            if True:
                S = verifier_les_pairs(S)
                if True:

                    return(S)
                else:
                    return(False)
            else:
                return(False)
        else:
            return(False)
print(postalValidate('n2l 3g1z'),
postalValidate('postal'),
postalValidate('H0H0H0H0'),
postalValidate(' e3g 7k 0 l5G 6'),
postalValidate('5/ B?7t8'))

Very length but very easy.
相关问题