Home > OS >  TypeError: makesentence() missing 4 required positional arguments: 'c', 'd', �
TypeError: makesentence() missing 4 required positional arguments: 'c', 'd', �

Time:12-24

My task is: "Use reduce to concatenate all the countries and to produce this sentence: Estonia, Finland, Sweden, Denmark, Norway, and Iceland are north European countries" by using list.

Here are the list and my code:

countries = ['Estonia', 'Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland']
def makesentence(a,b,c,d,e,f):
    return a ","  b  ","  c  ","  d  ","  e  ", and"  f  "are north European countries"

print(reduce(makesentence,countries))

But I'm getting TypeError: makesentence() missing 4 required positional arguments: 'c', 'd', 'e', and 'f'

If I write something like it works with no error:

countries = ['Estonia', 'Finland']
print(reduce(lambda a,b:a "," b "," "are north European countries",countries))

What is the problem? I'm really confused.

CodePudding user response:

reduce() calls the function with two arguments: https://docs.python.org/3/library/functools.html#functools.reduce

But you makesentence() provides 6 - so c, d, e and f are not set.

It is not clear what you want to do.

If you already have a function which takes all the arguments, you can just call it, like:

# python2
print(apply(makesentence,countries))

# python3
print(makesentence(*countries))

You already wrote the version using reduce() in your question.

CodePudding user response:

def makesentence(countries):
    result = ""
    for i in range(len(countries) - 1):
        result  = countries[i]   ", "
    result  = "and"   countries[-1]   "are north European countries"
    return result
countries = ['Estonia', 'Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland']
print(makesentence(countries))

CodePudding user response:

I don't think you need reduce for this. It's this simple:

countries = ['Estonia', 'Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland']

def makesentence(c):
    return ', '.join(c[:-1])   ' and '   c[-1]   ' are north European countries'

print(makesentence(countries))
  • Related