我尝试创建一个函数,它生成随机的int值,并且在值出现两次之后,函数应该返回所有生成的int值的数量。 我必须使用字典。
到目前为止,这是我的代码:
def repeat(a,b):
dict={}
d=b-a+2
for c in range(1,d):
dict['c']=random.randint(a,b)
for f in dict:
if dict['f']==dict['c']:
return c
第一个问题:它没有用。
>>> repeat(1,5)
Traceback (most recent call last):
File "<pyshell#144>", line 1, in <module>
repeat(1,5)
File "<pyshell#143>", line 7, in repeat
if dict['f']==dict['c']:
KeyError: 'f'
第二个问题:if dict['f']==dict['c']:
在第一步中应该是真的,因为两个值都是相同的。
我无法在不将密钥与自身进行比较的情况下找到比较所有值的智能方法。
抱歉我的英文不好,它有点生锈,谢谢你的时间。
答案 0 :(得分:2)
将变量名称括在引号中会使它们成为字符串 - Python正在寻找字母f的键,而不是f
变量中带整数的键。
只需正常使用变量,它应该按预期工作:
def repeat(a, b):
stored = {}
d = b - a + 2
for c in range(1, d):
stored[c] = random.randint(a, b)
for f in stored:
if stored[f] == stored[c]:
return c
另请注意,您通过命名变量dict()
来遮蔽内置函数dict
- 因此最好使用其他名称。
答案 1 :(得分:0)
这不是你问题的真正答案。 @Lattyware告诉你这个问题。但是我不能将代码放在评论中,所以我将其作为答案发布。
您的代码使用了奇怪的变量名,这使得代码更难理解。我建议你使用变量名来帮助读者理解程序。
我已经更改了您的变量名称并添加了注释。我还输入了一个“doc string”,但我并不真正理解这个函数,所以我实际上并没有写一个文档消息。
def repeat(a,b): # short names are okay for a,b as they are just two numbers
"""
This is the "doc string". You should put in here a short summary of what the function
does. I won't write one because I don't understand what you are trying to do.
"""
# do not use built-in names from Python as variable names! So don't use "dict"
# I often use "d" as a short name for a dictionary if there is only one dictionary.
# However, I like @Lattyware's name "stored" so I will use it as well.
stored={}
# You only used "d" once, and it's the upper bound of a range; might as well just
# put the upper bound inside the call to range(). If the calculation was really long
# and difficult I might still use the variable, but this calculation is simple.
# I guess you can use "c" in the loop, but usually I use "n" for number if the loop
# is making a series of numbers to use. If it is making a series of indexes I use "i".
for n in range(1,b-a+2):
stored[n]=random.randint(a,b)
# Any for loop that loops over a dictionary is looping over the keys.
for key in stored:
# I don't understand what you are trying to do. This loop will always terminate
# the first time through (when n == 1). The line above this for loop assigns
# a value to stored[n], and n will be equal to 1 on the first loop; then this
# test will trivially succeed.
if stored[key] == stored[n]:
return n