简体   繁体   English

python,不同的代码结果

[英]python , different result of code

Where is the mistake in my first function? 我的第一个职能中的错误在哪里? I have this: 我有这个:

def fun(str):    
    for vowel in str:
        if vowel in 'aeiouAEIOU':
            return len(vowel)

def fun(str):
    return len([vowel for vowel in str if vowel in 'aeiouAEIOU'])

print fun("halloo")

The results for the two functions are different. 这两个函数的结果不同。 I must return the number of vowels the string contains. 我必须返回字符串包含的元音数量。

In your first function you immediately return when you find a vowel, and you returned the length of that one vowel. 在第一个函数中,找到元音后立即返回,并且返回了该元音的长度。 The result is always either 1 (vowel found) or None (no vowel found). 结果始终为1 (找到元音)或None (没有找到元音)。

If you wanted to count the number of vowels, you'd have to use a new variable to track that count: 如果要计算元音的数量,则必须使用一个新变量来跟踪该数量:

def fun(str):
    count = 0
    for vowel in str:
        if vowel in 'aeiouAEIOU':
            count += 1
    return count

The second function produces a list of all the vowels first, then takes the length of that list. 第二个函数首先生成所有元音的列表,然后获取该列表的长度。 You could use: 您可以使用:

def fun(str):
    return sum(1 for vowel in str if vowel in 'aeiouAEIOU')

to not even produce a list, just a vowel count. 甚至没有产生一个列表,只是一个元音计数。

In this function, when you reach a vowel, you're returning the length of vowel (a single character) - which is always going to be 1 (or if it drops off the end of the function None ): 在此功能中,到达元音时,您将返回vowel的长度(单个字符),该长度始终为1 (或者如果它落在函数None的末尾):

def fun(str):    
    for vowel in str:
        if vowel in 'aeiouAEIOU':
            return len(vowel)

While in this one, you're building up a list of all vowels and taking the length: 在本教程中,您将建立所有元音的列表,并取其长度:

def fun(str):
    return len([vowel for vowel in str if vowel in 'aeiouAEIOU'])

Note that str is a builtin type, it'd be better to call your parameter text to avoid any potential headaches (not necessarily in this function, but for future reference) in the future. 请注意, str是内置类型,最好调用参数text以避免将来出现任何潜在的麻烦(不一定在此函数中,但供将来参考)。

Ultimately, you can write this as (with a more descriptive name and parameter): 最终,您可以将其写为(具有更具描述性的名称和参数):

def vowel_count(text):
    return sum(1 for ch in text.lower() if ch in 'aeiou')

Your first code will return 1 or None : 您的第一个代码将return 1None

def fun(str):
  for vowel in str:
    if vowel in 'aeiouAEIOU':
      return len(vowel)

print fun('111') # return None
print fun('abc') # return 1

Your Second code will be ok to return the number of char(s) in vowel. 您的第二个代码可以返回元音中的字符数。

Use count method of string. 使用字符串的count方法。 Time complexity is O(N) * 5 时间复杂度为O(N) * 5

code: 码:

def countVowel(input):
    input = input.lower()    
    count = input.count("a") + input.count("e") + input.count("i") +\
    input.count("o") + input.count("u") 
    return count

print "Result:- ", countVowel("halloo")
print "Result:- ", countVowel("halloo HELLOO A ")

output: 输出:

$ python test.py
Result:-  3
Result:-  7

By collections module. collections模块。 Time complexity is O(N) * 5 时间复杂度为O(N) * 5

code: 码:

import collections

def countVowel(input):
    input = input.lower()
    info = collections.Counter(input)  #`O(N) * 5` 
    count = info["a"] + info["e"] + info["i"] + info["o"] + info["u"]
    return count

print "Result:- ", countVowel("halloo")
print "Result:- ", countVowel("halloo HELLOO A ")

output: 输出:

$ python test.py
Result:-  3
Result:-  7

By regular expression 用正则表达式

code: 码:

import re

def countVowel(input):
    input = input.lower()
    count = len(re.findall("a|e|i|o|u", input))
    return count

print "Result:- ", countVowel("halloo")
print "Result:- ", countVowel("halloo HELLOO A ")

output: 输出:

$ python test.py
Result:-  3
Result:-  7

Time Complexity O(N)*1 时间复杂度O(N)*1

code: 码:

def countVowel(input):
    input = input.lower()
    count = 0
    for i in input:
        if "aeiou".__contains__(i):
            count += 1
    return count

print "Result:- ", countVowel("halloo")
print "Result:- ", countVowel("halloo HELLOO A ")

output: 输出:

$ python test.py
Result:-  3
Result:-  7

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

相关问题 将代码放在脚本中时,控制台中的Python代码具有不同的结果 - Python code in console has different result when code is placed in a script python中页面源代码的结果与网站页面源代码不同 - The result of page source code in python is different to website page source code 为什么运行python解释器和python代码之间的结果不同? - why the result is different between running python interpreter and python code? 运行Python代码时,Cmd和Git bash有不同的结果 - Cmd and Git bash have a different result when run a Python code python代码中耦合ODE的结果与mathematica不同 - result of coupled ODE in python code is different from mathematica 书中代码示例的不同结果:Python for Data Analysis - Different result of code example on book: Python for Data Analysis Python 网页抓取问题 - 结果与源代码不同 - Python web scraping problems - result different from soruce code 编码和序列化代码给出不同的结果 C# 和 Python - Encoding and Serialization Code Gives Different Result C# and Python 为什么Python和Node.js的HMAC结果在此代码中有所不同? - Why Python and Node.js's HMAC result is different in this code? 将 javascript 的 md5 hash 代码转换为 Python 返回不同的结果 - Convert md5 hash code of javascript to Python return different result
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM