2014-05-06 53 views
1

我尝试创建一个函数,它会生成随机的int值,并且在值出现两次之后,函数应返回所有生成的int值的数量。 我必须使用字典。python:正确使用字典

这是我到目前为止的代码:

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

存在为'快译通[ 'F']'你永远不分配它 – TehTris

+1

尝试字典[F]没有这样的事; 'f'是指文字字符串f,而不是变量/迭代器f –

回答

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 - 最好是使用另一个名字,因为这个的。

+0

最后它的工作原理:) 非常感谢! 工作代码: DEF重复(A,B): dicti = {} d = B-A + 2 有效范围内的C(1,d): dicti并[c] =随机的。 randint(a,b) for f in dicti: if c!= f and dicti [f] == dicti [c]: return c – elo

0

这不是你的问题的答案。 @Lattyware告诉你这个问题。但是我不能将代码放在评论中,所以我将其作为答案发布。

您的代码使用了奇怪的变量名,这使得代码更难理解。我建议你使用变量名来帮助读者理解程序。

我已经改变了您的变量名称并添加了评论。我也加入了一个“文档字符串”,但我并不真正理解这个函数,所以我没有真正写出文档信息。

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