user1465662
user1465662

Reputation: 13

comparing to lists in the exact location each in python

I have 2 lists:

Gigits_List and Guesses_list.

I need to compare them and find where there are Bulls and Cows (just like the real game)

for example: if one list is ['1', '3', '4', '6'] and the second list is ['2', '3', '6', '4']. So the are "2C 1B" 2 COW and 1 BULL

    #setting the secret length
    Secret_Length = int(raw_input("the secret length"))

    #setting the secret base
    Secret_Base = int(raw_input("secret base_between 6-10"))

    #getting the secret from the user
    Secret = str(raw_input("enter the secret"))

    #checking if the secret in the right length
    if (int(len(Secret)) != Secret_Length):
        print "ERROR"
        sys.exit()

    Gigits_List = []
    #checking if the number in the right base
    for Each_Digigt in Secret:
        Gigits_List.append(Each_Digigt)
        if (int(Each_Digigt)>Secret_Base-1):
            print "ERROR"
            sys.exit

    #getting a guess from the user
    Guess = str(raw_input("enter the guess"))

    Guesses_list = []
    for Each_Guess in Guess:
        Guesses_list.append(Each_Guess)

Upvotes: 1

Views: 109

Answers (2)

Luyi Tian
Luyi Tian

Reputation: 371

B=0
C=0
list1 = ['1', '2', '3', '3']#target list
list2 = ['1', '3', '3', '3']#guess list
rest_val_1 = []
rest_val_2 = []
for val_1,val_2 in zip(list1,list2):
   if val_1 == val_2: B+=1
   else:
      rest_val_1.append(val_1)
      rest_val_2.append(val_2)
if not rest_val_2:print "YOU WIN"
else:
   for val_2 in rest_val_2:
      if val_2 in rest_val_1:
          C+=1

use list1[:i - removed] + list1[i - removed + 1:] is fine. But list[:] create a new list everytime so it cost more time.

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239653

list1 = ['1', '2', '3', '3']
list2 = ['1', '3', '3', '3']

cow, bull, removed = 0, 0, 0
for i in range(len(list1)):
    if list1[i - removed] == list2[i - removed]:
        bull += 1
        list1 = list1[:i - removed] + list1[i - removed + 1:]
        list2 = list2[:i - removed] + list2[i - removed + 1:]
        removed += 1
for i in range(len(list2)):
    if list2[i] in list1:
        cow += 1
print cow, bull

Output

0 3

Upvotes: 1

Related Questions