所以我像草一样绿色,学习如何像计算机科学家那样思考编程:学习python 3.我能够回答这个问题(见下文),但我担心我错过了这一课.
编写一个函数(称为insert_at_end),它将为所有三个函数传递(返回前面给出两个参数的粗体):
test(insert_at_end(5, [1, 3, 4, 6]), **[1, 3, 4, 6, 5]**)
test(insert_at_end('x', 'abc'), **'abcx'**)
test(insert_at_end(5, (1, 3, 4, 6)), **(1, 3, 4, 6, 5)**)
Run Code Online (Sandbox Code Playgroud)
本书给出了这样的提示:"这些练习很好地说明了序列抽象是通用的,(因为切片,索引和连接是如此通用),因此可以编写适用于所有序列类型的通用函数."
这个版本没有在线解决方案(我可以找到),但在我找到了某人对该文本的早期版本(对于python 2.7)的答案,他们这样做了:
def encapsulate(val, seq):
if type(seq) == type(""):
return str(val)
if type(seq) == type([]):
return [val]
return (val,)
def insert_at_end(val, seq):
return seq + encapsulate(val, seq)
Run Code Online (Sandbox Code Playgroud)
这似乎是通过区分列表和字符串来解决问题......违背提示.那怎么样有没有办法回答这个问题(以及大约10个类似的问题)而没有区分?即不使用"type()"
Python 3.3添加了__qualname__允许人们获取函数的限定名称(想想module.submodule.class.function)或类似名称的属性.
有没有办法在Python 2.6和2.7中重现这个属性?
class Cls:
counter = 0
def __init__(self, name):
self.name = name
self.counter += 1
def count(self):
return self.counter
Run Code Online (Sandbox Code Playgroud)
我正在学习python,我想要的是一个静态计数器,它计算类实例化的次数,但每次创建实例时counter都会重新创建并且count()函数总是返回1.我想要一些java中的东西看起来像这样
public class Cls {
private static int counter = 0;
private String name;
public Cls(String name) {
this.name = name;
counter ++;
}
public static int count(){
return counter;
}
}
Run Code Online (Sandbox Code Playgroud) 我一直在努力学习python并以某种方式提出以下代码:
for item in list:
while list.count(item)!=1:
list.remove(item)
Run Code Online (Sandbox Code Playgroud)
我想知道这种编码是否可以在c ++中完成.(使用for循环的列表长度,同时减小其大小)如果没有,有人可以告诉我为什么吗?
谢谢!