I have python code which it will generate random values like
JAY5uFy4F
This is the first output when I run the python script.
This is my code:
a= []
n=1
c=1
c2=3
Start= 10**(n-1)
End= (10**n)-1
while 1 :
Num= random.randint(Start,End)
Text= string.ascii_letters
txt=''.join(random.choice(Text) for i in range(c))
txt2=''.join(random.choice(Text) for i in range(c2))
def Value():
V= random.randint(3,6)
vl= (f"JAY{V}{txt2}{Num}{txt}")
return (vl)
passwd =Value()
if (passwd) not in (a):
a.append (passwd)
print(a)
else:
break
I know the code above will generate the sentence "JAY..." randomly but what I want is to get [az][AZ] after the word "JAY..."
For example:
JAY5abc1d
JAY5bcd1e
JAY5cde1f
etc.
and also uppercase characters
JAY5Abc1d
JAY5Bcd1e
JAY5Cde1f
until z, then when it reaches the last character the number changes
JAY5Abc2d
JAY5Bcd2e
JAY5Cde2f
I'd use itertools.product to iterate deterministically, rather than using a randomized algorithm.
Something like would seem to do what you want:
import itertools
from string import ascii_letters
def make_options(n, c1, c2):
parts = [
['JAY'],
map(str, range(3, 7)),
*([ascii_letters] * c1),
map(str, range(10**(n-1), 10**n)),
*([ascii_letters] * c2),
]
for cs in itertools.product(*parts):
yield ''.join(cs)
I'm using an iterator because this will be a long list, and trying to keep the whole thing in memory at once will probably fail.
If you keep your parameters in the small part of the space, you can easily get an array out of this by doing:
a = list(make_options(1, 1, 1))
but note that this is already 97k entries.
Related
I want to write a function that get two integers. The integers indicate how many strings of either of the two chars appears in a string.
For example:
my_func(x,y): x amount of 'u' and y amount of 'r'.
my_func(2,3) is a string 'uurrr'
And the goal of the function is to write all the possible combinations of that string without changing the amount of x,y and every rearrangement is different:
Example:
my_func(1,1) will return: 'ru', 'ur'
my_func(1,2) will return: 'urr', 'rur', 'rru'
my_func(2,2) will return: 'uurr', 'ruru', 'rruu','urur', 'ruur', 'urru'
What I tried without covering all cases:
RIGHT = 'r'
UP = 'u'
def factorial(m):
if m>1:
return factorial(m-1)*m
else:
return 1
def binom(n,k):
return int(factorial(n)/(factorial(k)*factorial(n-k)))
def up_and_right(n, k, lst):
if n-k == 1 or n-k==-1 or n-k == 0 or n==1 or k==1:
num_of_ver = n+k
else:
num_of_ver = binom(n+k,2)
first_way_to_target = RIGHT*n + UP*k
lst.append(first_way_to_target)
way_to_target = first_way_to_target
for i in range(num_of_ver-1):
for j in range(n+k-1,0,-1):
if way_to_target[j]==UP and way_to_target[j-1]==RIGHT:
way_to_target = list(way_to_target)
way_to_target[j-1] = UP
way_to_target[j] = RIGHT
way_to_target = ''.join(way_to_target)
lst.append(way_to_target)
return lst
Thanks in advance!
Use itertools.permutations to get all the rearrangements, make a set of them to eliminate duplicates (because e.g. swapping two rs around counts as a separate permutation but doesn't change anything), and then join them back into strings because permutations returns character tuples instead.
This demonstration at the REPL should give you enough to write your function:
>>> import itertools
>>> [''.join(p) for p in set(itertools.permutations('u' * 2 + 'r' * 2))]
['uurr', 'ruur', 'ruru', 'rruu', 'urur', 'urru']
I am making a small program that guesses a password.
I am making this program just for the purpose of learning, I want to improve my python skills by making a program that have a real meaning.
for example:
using_characts = "abcdefghijklmnopqrstuvwxyz" # I have other characters in my alphabetic system
What I want to do is something like this:
for char in myCharacters:
print(char)
for char_1 in myCharacters:
print(char + char_1)
for char_2 in myCharacters:
print(char + char_1 + char_2)
...etc
which makes this method non dynamic, and hard in the same time.
the output should be something like this:
a
b
c
d
e
f
..etc
aa
ab
ac
..etc
ba
bb
bc
..etc
You can use itertools.product but you should really limit yourself with a small number. Generating cartesian product for higher numbers can take really long time:
from itertools import chain, product
chars = "abcdefghijklmnopqrstuvwxyz"
limit = 2
for perm in chain.from_iterable(product(chars, repeat=i) for i in range(1, limit+1)):
print("".join(perm))
a
b
c
.
.
.
aa
ab
ac
.
.
.
zy
zz
Here you go, this will work. Let me know if you want me to explain any part.
import itertools
using_characts = "abc"
for str_length in range(1,len(using_characts)+1):
for q in itertools.product(using_characts,repeat=str_length):
print("".join(q))
So, the other answers have given you code that will probably work, but I wanted to explain a general approach. This algorithm uses a stack to keep track of the next things that need to be generated, and continues generating until it reaches the maximum length that you've specified.
from collections import deque
from typing import Deque, Iterator, Optional
def generate_next_strings(chars: str, base: str = "") -> Iterator[str]:
# This function appends each letter of a given alphabet to the given base.
# At its first run, it will generate all the single-length letters of the
# alphabet, since the default base is the empty string.
for c in chars:
yield f"{base}{c}"
def generate_all_strings(chars: str, maxlen: Optional[int] = None) -> Iterator[str]:
# We "seed" the stack with a generator. This generator will produce all the
# single-length letters of the alphabet, as noted above.
stack: Deque[Iterator[str]] = deque([generate_next_strings(chars)])
# While there are still items (generators) in the stack...
while stack:
# ...pop the next one off for processing.
next_strings: Iterator[str] = stack.popleft()
# Take each item from the generator that we popped off,
for string in next_strings:
# and send it back to the caller. This is a single "result."
yield string
# If we're still generating strings -- that is, we haven't reached
# our maximum length -- we add more generators to the stack for the
# next length of strings.
if maxlen is None or len(string) < maxlen:
stack.append(generate_next_strings(chars, string))
You can try it using print("\n".join(generate_all_strings("abc", maxlen=5))).
The following code will give you all combinations with lengths between 1 and max_length - 1:
import itertools
combs = []
for i in range(1, max_length):
c = [list(x) for x in itertools.combinations(using_characts, i)]
combs.extend(c)
I need to make sequence of random strings, which increase(decrease) for alphabetic oder. For example: "ajikfk45kJDk", "bFJIPH7CDd", "c".
The simplest thing to do is to create N random strings and then sort them.
So, how do you create a random string? Well, you haven't specified what your rule is, but your three examples are strings of 1 to 12 characters taken from the set of ASCII lowercase, uppercase, and digits, so let's do that.
length = random.randrange(1, 13)
letters = random.choices(string.ascii_letters + string.digits, k=length)
string = ''.join(letters)
So, just do this N times, then sort it.
Putting it together:
chars = string.ascii_letters + string.digits
def make_string():
return ''.join(random.choices(chars, k=random.randrange(1, 13)))
def make_n_strings(n):
return sorted(make_string() for _ in range(n))
This should be simple enough that you can customize it however you want. Want case-insensitive sorting? Just add key=str.upper to the sorted. Want some other distribution of lengths? Just replace the randrange. And so on.
You can use the chr() Python 3 function in a loop while generating random number in the ASCII category range you want.
You can find all the ASCII categories here or on Wikipedia.
For exemple :
chr(99)
-> equals c
More information about the chr() function on Python 3 official documentation.
The simplest way I can think of is
from random import randint
a = ''.join(sorted([chr(randint(33,127)) for i in range(randint(1,20))], reverse = False))
print(a)
reverse = True makes it descending
There's a lot of ways to do that, and this an easy and simple example to do that in Python 3 using Ascii char codes:-
from random import randint
def generateString(minLength, maxLength):
result = "";
resultLength = randint(minLength, maxLength)
for i in range(resultLength):
charType = randint(1,3)
if(charType == 1):
#number
result += chr(randint(48, 57))
elif(charType == 2):
#upper letter
result += chr(randint(65, 90))
elif(charType == 3):
#lower letter
result += chr(randint(97, 122))
return result;
#Example
print(generateString(1,20))
I am trying to create a loop where I can generate string using loop. What I am trying to achieve is that I want to create a small collection of strings starting from 1 character to up to 5 characters.
So, starting from sting 1, I want to go to 55555 but this is number so it seems easy if I just add them, but when it comes to alpha numeric, it gets tricky.
Here is explanation,
I have collection of alpha-numeric chars as string s = "123ABC" and what I want to do is that I want to create all possible 1 character string out of it, so I will have 1,2,3,A,B,C and after that I want to add one more digit in length of string so I can get 11, 12, 13 and so on until I get all possible combination out of it up to CA, CB, CC and I want to get it up to CCCCCC. I am confused in loop because I can get it to generate a temp sting but looping inside to rotate characters is tricky,
this is what I have done so far,
i = 0
strr = "123ABC"
while i < len(strr):
t = strr[0] * (i+1)
for q in range(0, len(t)):
# Here I need help to rotate more
pass
i += 1
Can anyone explain me or point me to resource where I can find solution for it?
You may want to use itertools.permutations function:
import itertools
chars = '123ABC'
for i in xrange(1, len(chars)+1):
print list(itertools.permutations(chars, i))
EDIT:
To get a list of strings, try this:
import itertools
chars = '123ABC'
strings = []
for i in xrange(1, len(chars)+1):
strings.extend(''.join(x) for x in itertools.permutations(chars, i))
This is a nested loop. Different depths of recursion produce all possible combinations.
strr = "123ABC"
def prod(items, level):
if level == 0:
yield []
else:
for first in items:
for rest in prod(items, level-1):
yield [first] + rest
for ln in range(1, len(strr)+1):
print("length:", ln)
for s in prod(strr, ln):
print(''.join(s))
It is also called cartesian product and there is a corresponding function in itertools.
This is not probably a common question but I want to CREATE duplicates and INSERT it randomly in my String. Just like the following example.
I have this file :
AppleStrawberryBananaCitrusOrange
And I expected this kind of output :
trusppleStrawbeApplertrusryBananaCitrusOrangepple
In this case my program randomly select a substring of length '4' : 'pple' and 'trus' and duplicates him 'twice(2)' before the insertion.
I think that I could run the program by using the fonction copy with copy.copy() and copy.insert() but I don't really know how to use it randomly.
For the moment;I just write the part of the code for read and write and something else:
import copy
chain='*'
contain = ''
file= raw_input ('Filename:')
x = open(file,'r')
for line in x:
if not(chain in line):
contain+=line
e=copy.copy(contain[4:8])
f=copy.copy(contain[8:12])
y = open('copi','w')
y.write(contain)
y.write(f)
x.close()
Result:
AppleStrawberryBananaCitrusOrange
awbe
As you can see; it doesn't really work like I want. :(
Thanks for your help
Not sure if I understand what you are trying to do.
You'll probably need a library for random selection:
import random
Now here is your input string:
s = "AppleStrawberryBananaCitrusOrange"
print s
You can use random.randint to select a random position and extract a 4-character word:
i = random.randint(0, len(s) - 4)
w = s[i:i+4]
print w
Finally, you can select two more random positions and insert the word via string concatenation:
for j in range(2):
i = random.randint(0, len(s) - 4)
s = s[:i] + w + s[i:]
print s
Output:
AppleStrawberryBananaCitrusOrange
yBan
ApyBanpleSyBantrawberryBananaCitrusOrange