宿題のためにこれをやっていますが、これがどのように機能するのか理解していないので、手順を説明すると多くの助けになります。 質問は分かりにくいので、理解して試してみることはできませんでした。 ここに3つの部分に分かれた質問があります。 次のスーパークラスが指定されています。これを変更しないでください。Pythonはクラスを使って作業をしています。
class Container(object):
""" Holds hashable objects. Objects may occur 0 or more times """
def __init__(self):
""" Creates a new container with no objects in it. I.e., any object
occurs 0 times in self. """
self.vals = {}
def insert(self, e):
""" assumes e is hashable
Increases the number times e occurs in self by 1. """
try:
self.vals[e] += 1
except:
self.vals[e] = 1
def __str__(self):
s = ""
for i in sorted(self.vals.keys()):
if self.vals[i] != 0:
s += str(i)+":"+str(self.vals[i])+"\n"
return s
以下の仕様を実装するクラスを作成します。コンテナのメソッドをオーバーライドしないでください。第二の部分、例えば、D1 =バッグ()
d1.insert(4)
d1.insert(4)
print(d1)
d1.remove(2)
print(d1)
prints 4:2
4:2
•例えば、D1 =バッグ()
d1.insert(4)
d1.insert(4)
d1.insert(4)
print(d1.count(2))
print(d1.count(4))
prints 0
3
class Bag(Container):
def remove(self, e):
""" assumes e is hashable
If e occurs one or more times in self, reduces the number of
times it occurs in self by 1. Otherwise does nothing. """
# write code here
def count(self, e):
""" assumes e is hashable
Returns the number of times e occurs in self. """
# write code here
•:
における方法を書きますb1とb2がバッグであれば、b1 + b2は2つのバッグの結合を表す新しいバッグを与える。例えば
•、=バッグ()
a.insert(4)
a.insert(3)
b = Bag()
b.insert(4)
print(a+b)
prints 3:1
4:2
第三部分:
以下の仕様を実装するクラスを記述します。コンテナのメソッドをオーバーライドしないでください。
例えばclass ASet(Container):
def remove(self, e):
"""assumes e is hashable
removes e from self"""
# write code here
def is_in(self, e):
"""assumes e is hashable
returns True if e has been inserted in self and
not subsequently removed, and False otherwise."""
# write code here
•、D1 = ASET()
d1.insert(4)
d1.insert(4)
d1.remove(2)
print(d1)
d1.remove(4)
print(d1)
prints 4:2 # from d1.remove(2) print
# (empty) from d1.remove(4) print
• For example, d1 = ASet()
d1.insert(4)
print(d1.is_in(4))
d1.insert(5)
print(d1.is_in(5))
d1.remove(5)
print(d1.is_in(5))
prints True
True
False
ありがとうございました。
インデントを修正します。 – Rahul
これはあなたの教授やTAの質問によく似ています。基本的にはここで設定した問題全体をダンプするだけです。特定のものに絞って、これを解決しようとする試みを少なくとも示すことができれば、それはトピックになるかもしれません。それ以外の場合は、これは広すぎます。 –
3番目の部分は正しいですか? –