Aza Aza - 6 months ago 50
Python Question

Python Compare two lists and return matches of same number in same order in a more pythonic way

Unsure why this got voted down there is no other answer to this question on Stack.
- All other example use sets and this is the only method on here that shows how to identify that the same int is in the same location in another list.

Thanks MegaBytes for the answer:

x = [3,5,6,7]
y = [3,5,7,9]
compare_order = [1 if i==j else 0 for i, j in zip(x,y)]
#returns [1,1,0,0]

looking for a more pythonic way for (replacing the if statements) determining if the elements of my two lists are in the same order. I have sliced the two lists and turned the elements into d1 etc as below. Cant use sets only want to know if the Nth of list1 == Nth list2

roll = random.sample(range(1,9), 4)
r1 = roll[0:1]
r2 = roll[1:2]
r3 = roll[2:3]
r4 = roll[3:4]
choice = int(1243)
SliceChoice = [int(x) for x in str(choice)]
d1 = SliceChoice[0:1]
d2 = SliceChoice[1:2]
d3 = SliceChoice[2:3]
d4 = SliceChoice[3:4]

x = []
if d1 == r1:
print ('got one')
x = x + 1
if d2 == r2:
print ('got one')
x = x + 1
if d3 == r3:
print ('got one')
x = x + 1
if d4 == r4:
print ('got one')
x =x + 1

if x == (4):
print('well done')

ok so its been a while so I thought I should post my final version thanks for all your assistance.

import random

def start():
""" this function is used to initialise the users interaction with the game
Primarily this functions allows the user to see the rules of the game or play the game"""
print ('Mastermind, what would you like to do now?\n')
print ('Type 1 for rules')
print ('Type 2 to play')
path = input('Type your selection 1 or 2: ')
if path == '1':
print ('Great lets look at the rules')
elif path == '2':
print('Great lets play some Mastermind!\n')
print('that was not a valid response there is only one hidden option that is not a 1 or a 2')

def rules():
"""This just prints out the rules to the user."""
print ('The rules are as follows:\n')
print ('1)Mastermind will craft you a 4 digit number that will contain all unique numbers from 1-9, there is no 0s.\n')
print ('2)You will have 12 attempts to guess the correct number.\n')
print ('3)Whites represent a correct number that is not in the correct order\n')
print ('4)Reds represent a correct number in the correct order.\n')
print ('5)If you enter a single number or the same number during a guess it will consume 1 of your 12 guesses.\n')
print ('6)to WIN you must guess the 4 numbers in the correct order.\n')
print ('7)If you run out of guesses the game will end and you lose.\n')
print ('8)if you make a guess that has letters or more than 4 digits you will lose a turn.')

def makeRandomWhenGameStarts():
"""A random 4 digit number is required this is created as its own
variable that can be passed in at the start of the game, this allows the user
to guess multiple times against the one number."""

#generate a 4 digit number
num = random.sample(range(1,9), 4)

#roll is the random 4 digit number as an int supplied to the other functions
roll = int(''.join(map(str,num)))

return roll

def begingame():
"""This is the main game function. primarily using the while loop, the makeRandomWhenGameStarts variable is
passed in anbd then an exception handling text input is used to ask the user for their guees """
print ('please select 4 numbers')

#bring in the random generated number for the user to guess.
roll = makeRandomWhenGameStarts()
whiteResults = []
redResults = []
collectScore = []
guessNo = 0

#setup the while loop to end eventually with 12 guesses finishing on the 0th guess.
guesses = 12
while (guesses > 0 ):
guessNo = guessNo + 1
#choice = int(2468) #int(input("4 digit number"))
choice = int(input("Please try a 4 digit number: "))
if not (1000 <= choice <= 9999):
raise ValueError()
except ValueError:
print('That was not a valid number, you lost a turn anyway!')
print ( "Your choice is", choice)

#Use for loops to transform the random number and player guess into lists
SliceChoice = [int(x) for x in str(choice)]
ranRoll = [int(x) for x in str(roll)]

#Take the individual digits and assign them a variable as an identifier of what order they exist in.
d1Guess = SliceChoice[0:1]
d2Guess = SliceChoice[1:2]
d3Guess = SliceChoice[2:3]
d4Guess = SliceChoice[3:4]

#combine the sliced elements into a list
playGuess = (d1Guess+d2Guess+d3Guess+d4Guess)

#Set reds and whites to zero for while loop turns
nRed = 0
nWhite = 0

#For debugging use these print statements to compare the guess from the random roll
# print(playGuess, 'player guess')
# print(ranRoll,'random roll')

#Use for loops to count the white pegs and red pegs
nWhitePegs = len([i for i in playGuess if i in ranRoll])
nRedPegs = sum([1 if i==j else 0 for i, j in zip(playGuess,ranRoll)])

print ('Oh Mastermind that was a good try! ')

#Take the results of redpegs and package as turnResultsRed
TurnResultsRed = (nRedPegs)

#Take the results of whitepegs and remove duplication (-RedPegs) package as TurnResultsWhite
TurnResultsWhite = ( nWhitePegs - nRedPegs) #nWhite-nRed

#Create a unified list with the first element being the guess number
# using guessNo as an index and storing the players choice and results to feedback at the end
totalResults = ( guessNo,choice , TurnResultsWhite ,TurnResultsRed)

# collectScore = collectScore + totalResults for each turn build a list of results for the 12 guesses

#End the while loop if the player has success with 4 reds
if nRed == (4):
print('Congratulations you are a Mastermind!')

#Return the results of the guess to the user
print ('You got:',TurnResultsWhite,'Whites and',TurnResultsRed,'Red\n')

#remove 1 value from guesses so the guess counter "counts down"
guesses = guesses -1
print ('You have', guesses, "guesses left!")

#First action outside the while loop tell the player the answer and advise them Game Over
print('Game Over!')
print('The answer was', roll)

#At the end of the game give the player back their results as a list
for x in collectScore:
print ('Guess',x[0],'was',x[1],':','you got', x[2],'Red','and', x[3],'Whites')

if __name__ == '__main__':

Answer Source

Try This one:

x = [3,5,6,7]
y = [5, 7, 9]
compare_order = [1 if i==j else 0 for i, j in zip(x,y)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download