简体   繁体   中英

How Can I Compare A 4 Digit Variable To A List Of 4 Digit Numbers And Determine If They Have The Exact Same Numbers, Regardless Of Order?

I have been trying to create a program that will break a 4 digit code by listing all possible codes. The code, 1234 and 4321 will both work as they have the same numbers. Just as 7125 and 2157 will work.

I have tried comparing the variable with the numbers in the list, but have only been able to do it with, for example, 1234 as the variable and 1234 as the number in the list.

codes1example = [1240, 1241, 0214]
variable1example = 4120

I am not on my normal computer so I cannot post the comparing code, but it is probably easy to make.

With my original code, it would disregard any numbers in the list that is the same as the variable. But I cannot get past this, I cannot make it so it does not matter the order.

One approach is to convert the int to str and sort them and then do the comparison.

Ex:

codes1example = [1240, 1241, 2014]
variable1example = 4120

temp = map(sorted, (map(str, codes1example)))
if sorted(str(variable1example)) in temp:
    print("Ok!")
else:
    print("No!!!")

#-->Ok!

WUse the set structure:

for n in codes1example:
   if not set(str(variable1example)).symmetric_difference(set(str(n))):
      print(variable1example, n)

This should work:

codes1example = [1240, 1241, 214]
variable1example = 4120

def matchable(code):
     return sorted(str(code).zfill(4))

[c for c in codes1example if matchable(c) == matchable(variable1example)]

# [1240, 214]

This converts each item into a strong with left zero padding, then sorts the digits in the string to standardize them, then compares those. After sorting, these will actually be lists of digits as strings, but the comparison should work fine.

Note that I had to drop the leading zero from 214 when entering it as an integer, because the leading 0 causes it to be interpreted as an octal literal (0214 == decimal 140). I assume your real code has proper bits that should be interpreted as 4-digit decimal numbers. If you are storing your numbers as strings instead, you can skip the str() step.

Edit: updated code to correct the catch mentioned in Justin comment

you will get invalid token error if you start a number with zero like in your list 0214 , but you can store it as a text, below is an example of how to achieve this:

codes1example = ['1240', '1241', '0214', '5678']
variable1example = '4120'

for code in codes1example:
    match = [c for c in variable1example if c in code ]
    if ''.join(match) == variable1example: 
        print (code)
        # rest of your code

output:

1240
0214

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM