简体   繁体   中英

Need help with editing code in Python

I have only recently started to program in python. This is my first experience in programming.

This is the problem from code academy . I basically need to:

"Write a function called fizz_count that takes a list x as input and returns the count of the string "fizz" in that list.

For example, fizz_count(["fizz","buzz","fizz"]) should return 2. "

Here is my code:

def fizz_count(x): 
    count = 0
    for a in x:
        if a == "fizz":
           return fizz_count(x) == 1 + count
        else:
           return fizz_count(x) == count

But this does not work. Where am I wrong?

You appear to be using recursive programming but you are not understanding how that should work.

You are calling your function recursively, but recursive counting requires you to divide your problem into subproblems; solve one and delegate the rest to the recursive call, or split up the set into subproblems until you have a small set you know how to solve. You however are trying to solve the subproblem for all elements in the list instead, then passing the whole list to the recursive call. This just leads to an infinite recursion exception because you only ever look at the same problem set.

A recursive version would be:

def fizz_count(x):
    if not x:
        return 0
    return (1 if x[0] == 'fizz' else 0) + fizz_count(x[1:])

This just looks at the first element and delegates counting of the rest of the list to the recursive call. If the list is empty, 0 is returned.

Subdividing up the list into halves is another option, returning only when the list is empty or has just one element:

def fizz_count(x):
    lenx = len(x)
    if not lenx:
        return 0
    if lenx == 1:
        return (1 if x[0] == 'fizz' else 0)
    return fizz_count(x[:lenx//2]) + fizz_count(x[lenx//2:])

If you wanted to loop over the list and count that way (without recursion), increment count and only return when you completed the loop:

def fizz_count(x):
    count = 0
    for a in x:
        if a == 'fizz':
            count += 1
    return count

However, the simplest solution is to use the standard list.count() function:

def fizz_count(x):
    return x.count('fizz')

and be done with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM