2014-05-06 93 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