2

I'm attempting to replicate the attached piece of C# code in Python, but unfortunately I know a lot less about Python than I do with the former. The code essentially generates a list of 2 character/digit values e.g. aa, ab, ac, ad, etc. It includes combinations of A-Z, a-z, and 0-9.

I've looked into django.utils.crypto module, but that creates a randomised output, and the output from my C# code gives the exact amount of combinations when run. This is what I tried with Django's module:

get_random_string(length=2, 
allowed_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')

Other options I tried do something similar, so I'm at a bit of a loss. I know the basics of Python, but unfortunately I haven't found enough to be able to replicate my C# code in Python. The C# code:

var alpha = 
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var q = alpha.Select(x => x.ToString());
int size = 2;
for (int i = 0; i < size - 1; i++)
    q = q.SelectMany(x => alphabet, (x, y) => x + y);

foreach (var item in q)
    Console.WriteLine(item);

Converted into python, the function should generate about 62^2 combinations of the values in 2 digit integers.

1 Answers1

1

Here's an example

alpha = 'abc'
from itertools import permutations, combinations_with_replacement
[''.join(i) for i in list(set(combinations_with_replacement(alpha, 2)) | set(permutations(alpha, 2)))]

# Output -> ['ab', 'ba', 'aa', 'cc', 'bb', 'cb', 'ac', 'ca', 'bc']  which is 3^2

Now create alpha as suggested by @Adam Feor in comment

import string 
alpha = string.ascii_letters + string.digits 
print(alpha)
Output -> abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
meW
  • 3,832
  • 7
  • 27
  • 1
    You can also import the string module which contains ascii_letters and digits to get the characters you want. characters = string.ascii_letters + string.digits – Adam Feor Jan 02 '19 at 09:23
  • This is what I was looking for, thanks! Although I'm attempting to run this code but it doesn't seem to output when I attempt to print. I'm probably missing something simple here (not great with Python). –  Jan 02 '19 at 09:47
  • @AlexGho store the last line which goes like `[''.join..` into a variable say `out = [''.join..` and then use `print(out)` – meW Jan 02 '19 at 09:52