从一组字符串中查找整数

问题描述 投票:-2回答:1

嗨,我想解决一个问题如下: - 如果I / P为“OZONETOWER”,则O / P为012,即将0的字符串(ZERO)与输入字符串进行比较,当找到时,它出现在输出中,依此类推为1和2.提供参考的输入和输出集: -

I/P:                               O/P:
WEIGHFOXTOURIST                    2468
OURNEONFOE                         114
ETHER                               3

我已经尝试过这个但是这似乎没有给出所有情况的结果。

def puzzle(dic_number,string,key):
    dic_values=0    
    length=len(dic_number)
    for i in dic_number:
        if i in string:
            dic_values+=1
    if dic_values ==length:
        print(key)


dic1={0:"ZERO",1:"ONE",2:"TWO",3:"THREE",4:"FOUR",5:"FIVE",6:"SIX",7:"SEVEN",8:"EIGHT",9:"NINE"}
string=input("Enter number")

for i,j in enumerate(dic1.values()):
    puzzle(j,string,i)
python-3.x puzzle
1个回答
0
投票

以下是实现此目的的一种方法:

numbers = {
    0: "ZERO",
    1: "ONE",
    2: "TWO",
    3: "THREE",
    4: "FOUR",
    5: "FIVE",
    6: "SIX",
    7: "SEVEN",
    8: "EIGHT",
    9: "NINE",
}


def puzzle(s):
    supper = s.upper()
    ret = []
    for n, chrs in numbers.items():
        if all(c in supper for c in chrs):
            ret.append(n)
    return ret


s = input("enter string ")

numbers_found = puzzle(s)
print('numbers found', numbers_found)

输出:

enter string WEIGHFOXTOURIST
numbers found [2, 3, 4, 6, 8]
enter string OURNEONFOE
numbers found [1, 4]
enter string ETHER
numbers found [3]
enter string OZONETOWER
numbers found [0, 1, 2]

注意

有了这个实现

  • 你得到3的额外结果输入WEIGHFOXTOURIST
  • 你得到1, 4而不是1, 1, 4输入OURNEONFOE

编辑

要获得重复匹配,拼图功能必须“消耗”已使用的字符:

def puzzle(s):
    supper = s.upper()
    ret = []
    for n, chrs in numbers.items():
        while True:
            if all(c in supper for c in chrs):
                for c in chrs:
                    supper = supper.replace(c, '', 1)
                ret.append(n)
            else:
                break
    return ret

输出:

enter string WEIGHFOXTOURIST
numbers found [2, 3, 6]
enter string OURNEONFOE
numbers found [1, 1, 4]
enter string ETHER
numbers found [3]
enter string OZONETOWER
numbers found [0, 1, 2]

注意

有了这个实现

  • 你没有得到8输入WEIGHFOXTOURIST的结果

说明:

在这个难题中,当在输入字符串中找到数字的所有字母时,它被认为是“匹配”。

为此,我们通过在字符串的字符上创建list comprehension逐个检查每个字符:

>>> chrs = 'FOUR'
>>> [c for c in chrs]
['F', 'O', 'U', 'R']

对于每个字符,我们使用in来检查它是否在大写的输入字符串中找到:

>>> chrs = 'FOUR'
>>> supper = 'OURNEONFOE'
>>> [c in supper for c in chrs]
[True, True, True, True]

如果找不到某个角色,它将在相应的位置产生一个False

>>> chrs = 'FOUR'
>>> supper = 'OXRNEONFOE'
>>> [c in supper for c in chrs]
[True, True, False, True]

然后用all检查列表中的所有项目是否都是True

>>> chrs = 'FOUR'
>>> supper = 'OURNEONFOE'
>>> all([c in supper for c in chrs])
True
>>> supper = 'OXRNEONFOE'
>>> all([c in supper for c in chrs])
False

因为PEP 289我们可以直接在all中使用生成器表达式

>>> chrs = 'FOUR'
>>> supper = 'OURNEONFOE'
>>> all(c in supper for c in chrs)
True
© www.soinside.com 2019 - 2024. All rights reserved.