2016-12-16 167 views
1

所以我一直在這個問題上待了一段時間,並且在搜索多個其他問題之後找不到我需要的答案。檢查列表中的某些元素是否相同

我已經設置了一個任務來創建一個4位數的隨機數發生器,然後用戶必須嘗試猜測數字。每次嘗試他們都會說明他們有多少號碼,他們是在哪個位置。 此外,號碼需要處於正確的位置。

這是我當前的代碼。

import random as r 
def GetNumber(): 
    number = [r.randint(0, 9), r.randint(0, 9), r.randint(0, 9), r.randint(0, 9)] 
    return number 

def Choices(): 
    randomNumber = GetNumber() 
    userChoice = list(input("Enter 4 numbers\n")) #Allows the user to input a number 4 digits long 
    userChoice = [int(i) for i in userChoice] 
    if userChoice == randomNumber: 
     print("Congratulations! You chose the right number") 

感謝提前:)

+2

爲什麼不'r.randint(1000,9999)'如果你想要一個4位數的隨機數? –

+0

所以你正在嘗試編碼的主腦遊戲..到目前爲止您的代碼是非常好的。你也可以單獨做。 –

+0

@Chris_Rands我也希望第一個數字的機會是0 – Jake

回答

1

這是我的承擔。

import random as r 


def GetNumber(): 
    return [r.randint(0, 9) for i in range(4)] 


def Choices(): 
    randomNumber = GetNumber() 
    userChoice = [int(i) for i in list(input("Enter 4 numbers\n"))] 
    n = 0 
    while userChoice != randomNumber: 
     hits = [str(i+1) for i in range(4) if userChoice[i] == randomNumber[i]] 
     if hits: 
      print('You got position(s) {} correct'.format(', '.join(hits))) 
     else: 
      print('You got all of them wrong!') 
     userChoice = [int(i) for i in list(input("Enter 4 numbers\n"))] 
     n += 1 
    print("Congratulations! You found the right number in {} turns!!".format(n)) 

Choices() 

該代碼已重構了一下循環,直到用戶實際找到密碼。這只是一個框架,您可以嘗試一下,並嘗試根據用戶交互或其他方面進一步優化它。

如果有什麼不清楚的地方,請告訴我。乾杯!

+0

感謝您的快速回復,給它一個測試,它完美的工作 – Jake

+0

@ Tobias_k的回答也非常有趣。您可能需要將兩者融合,向用戶提供錯誤位置的正確數字提示 –

1

可以zip隨機數和用戶的選擇和比較對:無論

>>> number = [4, 3, 9, 1] 
>>> choice = [1, 3, 4, 1] 
>>> [n == c for n, c in zip(number, choice)] 
[False, True, False, True] 
>>> sum(n == c for n, c in zip(number, choice)) 
2 

要獲得匹配的號碼的總數,其位置,您可以通過Counter提供號碼和用戶的選擇,並與&交叉:

>>> from collections import Counter 
>>> Counter(number) & Counter(choice) 
Counter({1: 1, 3: 1, 4: 1}) 
>>> sum((Counter(number) & Counter(choice)).values()) 
3 
+0

'sum(n == c for n,c in zip(number,choice))'returned 2 is beautiful –

-1
import random as r 
def GetNumber(): 
    number = r.randint(0000, 9999) 
    return str(number).zfill(4) 

def Choices(): 
    randomNumber = GetNumber() 
    print type(randomNumber),randomNumber 
    userChoice = str(input("Enter 4 numbers\n")).strip("\n") #Allows the user to input a number 4 digits long 
    for a,b in zip(userChoice,randomNumber): 
     if not a==b: 
     print "{0} not match {1}".format(a,b) 
    if userChoice==randomNumber: 
     print "Congratulations! You chose the right number" 

Choices() 
+3

好吧,它不會做問題的問題,它是一個純粹的代碼答案,沒有任何解釋,它在Python 3中將無法正常工作,並且無理由地創建一個元素列表。 – interjay

+0

@interjay thx,我解決了這個問題,但我一直在尋找問題並解決當前問題,我的意思是這不是代碼複習 –

+2

你在這裏發佈的代碼應該是很好的代碼,因爲這是人們從中學到的東西。無論如何,你已經修復了我列出的其中一個問題,但是這仍然沒有實際做問題的要求(檢查哪些數字是正確的)。 – interjay

0

我認爲這個關鍵是使用一串數字而不是數字數據類型。這是一個工作示例。你可以通過比較數字來做到這一點,但在這種情況下,我們並不在乎數字的價值,就像字符的模式一樣。

from random import choice 
from string import digits 


def is_digits(string): 
    """Return true if all characters are digits, otherwise false""" 

    return all([char.isdigit() for char in string]) 


def get_number(length): 
    """Return a string of digits with the number of characters equal to length""" 

    return ''.join(choice(digits) for i in range(length)) 


def guess(): 
    """Receive and evaluate guesses for match to randomly generated number""" 

    guess = '' 
    miss_char = '-' 
    miss_message = 'Try again.' 
    win_message = 'Congratulations! You chose the right number.' 
    answer_length = 4 
    answer = get_number(answer_length) 
    while guess != answer: 
     guess = raw_input('Enter {0} numbers: '.format(len(answer))) 
     if len(guess) != len(answer) or is_digits(guess) is False: 
      continue 
     matches = [answer[i] 
        if answer[i] == guess[i] 
        else miss_char 
        for i in range(len(answer))] 
     matches_string = ''.join(matches) 
     message_base = 'Matched digits: {0}.'.format(matches_string) 
     if guess != answer: 
      print(' '.join([message_base, miss_message])) 
      guess = '' 
     else: 
      print(' '.join([message_base, win_message])) 

guess() 
相關問題