如何使我的 smash 函数运行并返回我的合并列表?

huangapple go评论65阅读模式
英文:

How can I get my smash function to run and return my combined list?

问题

我正在尝试完成CodeWars上的Sentence Smash Kata,我对编程还很陌生,我想知道为什么我的代码没有正确运行。
我的代码

def smash(words):
    a = ['hello', 'world', 'this', 'is', 'great']
    return " ".join(a)

smash("")

我无法删除"words"参数,但我认为我必须实例化它,但我不知道应该如何做。我曾尝试用引号替换参数,虽然代码运行了,但我的测试都没有通过。

英文:

I'm attempting to get through the Sentence Smash Kata on CodeWars, I'm pretty new to coding and I am wondering why my code isn't properly running.
My code

def smash(words):
    a  = ['hello', 'world', 'this', 'is', 'great']
    return " ".join(a)
    
smash("")

I can't remove the "words" parameter and I think I have to instantiate it but I don't know in what way I should do that. I thought substituting the argument for quotes would work and it did run but none of my tests passed.

答案1

得分: 0

def smash(words) 定义了一个接受名为'words'的参数的函数。

smash("") 调用该函数并将一个空字符串传递给'words'参数。

尝试这个,看看是否有帮助澄清问题:

def smash(words):
    return " ".join(words)
    
smash(['hello', 'world', 'this', 'is', 'great'])
英文:

def smash(words) defines a function that accepts some argument named 'words'.

smash("") calls that function and passes an empty string to the words argument.

Try this and see if it helps clear things up:

def smash(words):
    return " ".join(words)
    
smash(['hello', 'world', 'this', 'is', 'great'])

答案2

得分: 0

当您定义一个函数时,括号内的一切都是参数(或参数,可能有一些特定的技术区别,但通常两者都可以)。这些是在函数的作用域内可用的变量,它们在您调用函数时根据括号内的内容进行设置。

这个框架允许您创建通用的函数,然后根据传入的内容执行特定的操作。

在您的情况下,您可能想要的是这样的:

def smash(words):
    return ' '.join(words)

my_words = ['hello', 'world', 'this', 'is', 'great']

smash(my_words)

在函数的作用域内,您有一个名为 words 的变量,并尝试用一个空格 ' ' 将这些片段连接起来。

然后,在函数的作用域之外,您声明了一个具有实际的、具体的单词列表的变量,然后使用该具体的列表调用函数。

英文:

When you define a function, everything within the (...) is an argument (or a parameter, there is probably some specific technical distinction, but either is generally fine). Those are variables that are then usable within the scope of the function, and they are set when you call the function with whatever you have in the () when you call.

This framework allows you to make the general function and then do specific things with it based on what you pass in.

In your case, what you probably want is this:

def smash(words):
    return ' '.join(words)

my_words = ['hello', 'world', 'this', 'is', 'great']

smash(my_words)

In the scope of the function, you have the variable words and you attempt to join the pieces with a ' ' inbetween.

Then, outside the scope of the function, you declare a variable with an actual, concrete list of words, and then call the function using that concrete list.

huangapple
  • 本文由 发表于 2023年6月9日 02:32:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76434763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定