【发布时间】:2013-10-14 18:43:44
【问题描述】:
这三个功能是我的学习指南的一部分,非常感谢一些帮助。 在每种情况下,该函数都会返回一个值(所以使用 return 语句):它不会打印该值(没有 print 语句)或改变(更改其值)它的任何参数。
1) repl 函数接受三个参数: ◦old 是任何值; ◦new 是任何值; ◦xs 是一个列表。
Example:
>>> repl('zebra', 'donkey', ['mule', 'horse', 'zebra', 'sheep', 'zebra'])
['mule', 'horse', 'donkey', 'sheep', 'donkey']
它返回一个新列表,该列表通过将 xs 中的每个 old 替换为 new 来形成。
它不能改变列表 xs;即,从函数返回后,为 xs 提供的实际参数必须是之前的。
>>> friends = ['jules', 'james', 'janet', 'jerry']
>>> repl('james', 'henry', friends)
['jules', 'henry', 'janet', 'jerry']
>>> friends
['jules', 'james', 'janet', 'jerry']
2) 搜索功能在列表中查找值。它需要两个参数: ◦y 是要搜索的值。 ◦xs 是正在搜索的列表。
如果出现,则返回 xs 中第一次出现 y 的索引; -1 否则。
Examples:
>>> words = ['four', 'very', 'black', 'sheep']
>>> search('four', words)
0
>>> search('sheep', words)
3
>>> search('horse', words)
-1
3) doubles 函数得到一个数字列表,并返回一个新列表,其中包含给定列表中每个数字的双精度数。
Example:
>>> doubles([1, 3, 7, 10])
[2, 6, 14, 20]
它不能改变给定的列表:
>>> salaries = [5000, 7500, 15000]
>>> doubles(salaries)
[10000, 15000, 30000]
>>> salaries
[5000, 7500, 15000]
这将在不使用除 append 之外的任何列表方法的情况下完成。 (特别是,您不能将索引或计数用于搜索功能。)
虽然您可以使用 list len 函数以及列表操作 +、*、索引、切片和 == 来比较列表或元素。您将需要使用其中的一些,但不是全部。
非常感谢我在介绍中提到的任何帮助。
到目前为止,我只有。
def repl (find, replacement, s):
newString = ''
for c in s:
if c != find:
newString = newString + c
else:
newString = newString + replacement
return newString
def search(y, xs):
n = len(xs)
for i in range(n):
if xs[i] == y:
return i
return -1
和....
def search(key,my_list):
if key in my_list:
return my_list.index(key)
else:
return
我不确定 else 语句之后需要返回什么。
【问题讨论】:
-
我没有得到示例中所示的正确答案。还有最后两个问题的代码我还没有编译。我正在尝试用这个来刷新我的记忆,并且在记住正确的解决方案时遇到了一些麻烦。
-
您可以使用您在此处添加的详细信息编辑您的帖子吗?您将有更好的机会找到正确的答案