首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >CodeWars kata元音1

CodeWars kata元音1
EN

Stack Overflow用户
提问于 2022-11-04 20:19:18
回答 1查看 55关注 0票数 -1

代码似乎没有替换字符串中的非元音字符。

代码语言:javascript
运行
复制
def vowel_one(s):
    not_vowel = '0'
    
    vowels = {'a':'1', 
              'e':'1', 
              'i':'1', 
              'o':'1', 
              'u':'1'}
    #dictionary with keys as vowels, and their values as 1
    s = s.lower() #changing list to lowercase
    vowelsList = list(s)
        
    for index, item in enumerate(vowelsList): #counter, instead of doing i+=1, using enumerate
        for key, value in vowels.items():
            if item == key: #if character in string is equal to key in dictionary
                vowelsList[index] = value #at the indexes of such characters, replace them with dictionary key values
                if item != key and item != '1':
                    vowelsList[index] = not_vowel
        
    return ("".join(vowelsList)) #removes brackets and ','

例如,"vowelOne“的结果应该是: 01010101,而不是: v1w1l1n1,为什么另一个如果语句不工作呢?我设想,如果给定列表(vowelsList)中的项不等于字典(元音)中的任何键,那么它应该替换为'0‘。如果我不嵌套If语句,那么我只会得到0。

指向kata:https://www.codewars.com/kata/580751a40b5a777a200000a1/的链接

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-04 20:27:33

如果所有的值都是1.

  • You,则不需要字典,不需要两个for loops,这只会增加complexity.

  • You不需要将string转换为list.

的时间

这是我的密码:

代码语言:javascript
运行
复制
def vowel_one(s):
    vowels = ['a', 'e','i', 'o', 'u'] # simple list
    #dictionary with keys as vowels, and their values as 1
    s = s.lower() #changing list to lowercase
    for i in s: # Iterating through every value
        if i in vowels: # Check if sub-string in vowels
            s = s.replace(i, '1')
        else: # If not vowel replace with 0
            s = s.replace(i, '0')
    return s
print(vowel_one("vowelOne"))

编辑:,如果您想省略spaces,可以添加一个elif条件。尝试:

代码语言:javascript
运行
复制
def vowel_one(s):
    vowels = ['a', 'e','i', 'o', 'u'] # simple list
    #dictionary with keys as vowels, and their values as 1
    s = s.lower() #changing list to lowercase
    for i in s: # Iterating through every value
        if i in vowels: # Check if sub-string in vowels
            s = s.replace(i, '1')
        elif not i.isspace(): # If not vowel and space replace with 0
            s = s.replace(i, '0')
    return s
print(vowel_one("Mudith is my name"))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74322549

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档