How to replace x to a random number - python

If someone could help me make a minor script I would be more than happy, GGI20-xxxxxxx output should be GGI20-2562626 for example

Just change the digits according to number of xxxx's
import random
string = 'GGI20-xxxxxxx'
random_number = random.randint(1000000, 9999999)
result = string.replace("xxxxxxx", str(random_number))
print(result)
# OUTPUT
# GGI20-6187815
# GGI20-5790829

I suppose you need to replace all the x's in a string with a random number:
import random
def replaceXs(s):
result = ''
for c in s:
if c == 'x':
result += str(random.randrange(0, 10))
else:
result += c
return result

Why not just use the random library to generate a random integer with the right number of digits?
import random
def random_GGI20():
result = f'GGI20-{random.randint(1000000, 9999999)}'
return result
random_GGI20()
random_GGI20()
random_GGI20()
Note: this solution works if it's allowable to reuse numbers. If the GGI20-xxxxxxx results must be unique, this is more complex.

Here is a possible answer for your problem
input_string = 'GGI20-xxxxxxx'
import random
def replace_val(input_str):
str_list = list(input_str)
str_list = [str(i).replace('x',str(random.randint(0,9))) for i in str_list]
return ''.join(str_list)
replace_val(input_string)
o/p : 'GGI20-3428855' (it will vary as result will be random)
`

You could generate a random number using random(), convert to a string, and then replace however many x's your input has with an appropriate substring of the digits in the random number string.
inp = "GGI20-xxxxxxx"
output = re.sub(r'\bx+', lambda x: str(random())[2:len(x.group(0)) + 1], inp)
print(output) # GGI20-966494

import random
def random_gen():
return f"GGI20-{random.randint(1000000, 9999999)}"
print(random_gen())

this is much simple to understand
import random
#text type=string
text="GGI20-xxxxxxx"
#convert string into list to perform required operation
text_list=list(text)
#do a loop till we replace all x with randome number
#note here index method return a error if x not found hence we used try except block
while True:
try:
#this index('x') method raise an error when all x are replaced
text_list[text_list.index('x')]=str(random.randint(0,10))
except:
#create temporary string s to save output in it
s=""
#convert list to string
s=s.join(text_list)
break #break is important for finite looping
print("input text :"+text)
#save output result into main text variable
text=s
print("final output :"+text)
print("done")

Related

"Terminated due to timeout" status - Hackerank

Consider an array of numeric strings where each string is a positive
number with anywhere from 1 to 106 digits. Sort the array's elements in
non-decreasing, or ascending order of their integer values and return
the sorted array.
Example
Return the array ['1', '3', '150', '200'].
My code gets terminated due to timeout, How can I correct it?
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'bigSorting' function below.
#
# The function is expected to return a STRING_ARRAY.
# The function accepts STRING_ARRAY unsorted as parameter.
#
def bigSorting(unsorted):
unsorted = map(int,unsorted)
unsorted =sorted(unsorted)
unsorted = map(str, unsorted)
return unsorted;
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
unsorted = []
for _ in range(n):
unsorted_item = input()
unsorted.append(unsorted_item)
result = bigSorting(unsorted)
fptr.write('\n'.join(result))
fptr.write('\n')
fptr.close()
i tried reducing code, but it still says like that
its reduced the time but still say not enough.
You don't need to convert to and from int. You can sort numeric strings by first sorting by length, then sorting strings with equal length lexicographically (as long as there are no leading zeroes).
def bigsorting(unsorted):
return sorted(unsorted, key = lambda x: (len(x), x))

How to concatenate all the numbers in a list?

For clarification, I don't just only want a random letter word. I need the random numbers in my code later on also.
I made the following code which gives a random 7 letter word.
Here is the code:-
import random
key_num = []
for initial_num in range(7):
key_num.append(random.randrange(1,26))
def value(n):
return (chr(int(n) + 64))
print value(key_num[0]) + value(key_num[1]) + value(key_num[2]) + value(key_num[3]) + value(key_num[4]) + value(key_num[5]) + value(key_num[6])
My question is there any better way to concatenate the word using the random numbers?
import string
word = "".join(random.choice(string.ascii_lowercase) for _ in range(string_length)]
Is how i would make a random string
There are many different ways to solve this and also improve your code. You should definitely checkout str.join and list comprehensions.
If you want to stick to your original code as much as possible, how about this basic solution:
import random
key_num = []
for initial_num in range(7):
key_num.append(random.randrange(1,26))
def value(n):
return (chr(int(n) + 64))
# so far unchanged, here comes the new bit:
print ''.join(value(k) for k in key_num)
You've tagged your question Python2.7. If you can use Python3 instead, you can use random.choices to make things rather simple:
from string import ascii_lowercase
from random import choices
print ("".join(choices(ascii_lowercase,k=7)))
If you're stuck in Python2, you can implement a (simplistic) random.choices thus:
from random import choice
def choices(s,k=1):
return [choice(s) for _ in xrange(k)]
You can achieve concatenation in a single for loop. Try Below Code:
import random
key_num = []
for initial_num in range(7):
key_num.append(random.randrange(1,26))
def value(n):
return (chr(int(n) + 64))
final_string = ""
for i in range(7): # Range of Numbers you want
final_string += value(key_num[i]) # Concatenate random character
print final_string
this is a way:
from random import randrange
from string import ascii_lowercase
def random_str(length=7):
return ''.join(ascii_lowercase[randrange(len(ascii_lowercase))] for _ in range(length))
ascii_lowercase is just 'abcdefghijklmnopqrstuvwxyz'; i select a random entry from that and join the single letters with str.join.
...actually random.choice is better suited for that. see this answer.

Return Alternating Letters With the Same Length From two Strings

there was a similar question asked on here but they wanted the remaining letters returned if one word was longer. I'm trying to return the same number of characters for both strings.
Here's my code:
def one_each(st, dum):
total = ""
for i in (st, dm):
total += i
return total
x = one_each("bofa", "BOFAAAA")
print(x)
It doesn't work but I'm trying to get this desired output:
>>>bBoOfFaA
How would I go about solving this? Thank you!
str.join with zip is possible, since zip only iterates pairwise up to the shortest iterable. You can combine with itertools.chain to flatten an iterable of tuples:
from itertools import chain
def one_each(st, dum):
return ''.join(chain.from_iterable(zip(st, dum)))
x = one_each("bofa", "BOFAAAA")
print(x)
bBoOfFaA
I'd probably do something like this
s1 = "abc"
s2 = "123"
ret = "".join(a+b for a,b in zip(s1, s2))
print (ret)
Here's a short way of doing it.
def one_each(short, long):
if len(short) > len(long):
short, long = long, short # Swap if the input is in incorrect order
index = 0
new_string = ""
for character in short:
new_string += character + long[index]
index += 1
return new_string
x = one_each("bofa", "BOFAAAA") # returns bBoOfFaA
print(x)
It might show wrong results when you enter x = one_each("abcdefghij", "ABCD") i.e when the small letters are longer than capital letters, but that can be easily fixed if you alter the case of each letter of the output.

How to generate random increasing or decreasing strings in python?

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))

Manipulating string to repeat based on the length of another string

I am working on a python project, where I am required to include an input, and another value (which will be manipulated).
For example,
If I enter the string 'StackOverflow', and a value to be manipulated of 'test', the program will make the manipulatable variable equal to the number of characters, by repeating and trimming the string. This means that 'StackOverflow' and 'test' would output 'testtesttestt'.
This is the code I have so far:
originalinput = input("Please enter an input: ")
manipulateinput = input("Please enter an input to be manipulated: ")
while len(manipulateinput) < len(originalinput):
And I was thinking of including a for loop to continue the rest, but am not sure how I would use this to effectively manipulate the string. Any help would be appreciated, Thanks.
An itertools.cycle approach:
from itertools import cycle
s1 = 'Test'
s2 = 'StackOverflow'
result = ''.join(a for a, b in zip(cycle(s1), s2))
Given you mention plaintext - a is your key and b will be the character in the plaintext - so you can use this to also handily manipuate the pairing...
I'm taking a guess you're going to end up with something like:
result = ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(cycle(s1), s2))
# '\x07\x11\x12\x17?*\x05\x11&\x03\x1f\x1b#'
original = ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(cycle(s1), result))
# StackOverflow
There are some good, Pythonic solutions here... but if your goal is to understand while loops rather than the itertools module, they won't help. In that case, perhaps you just need to consider how to grow a string with the + operator and trim it with a slice:
originalinput = input("Please enter an input: ")
manipulateinput = input("Please enter an input to be manipulated: ")
output = ''
while len(output) < len(originalinput):
output += manipulateinput
output = output[:len(originalinput)]
(Note that this sort of string manipulation is generally frowned upon in real Python code, and you should probably use one of the others (for example, Reut Sharabani's answer).
Try something like this:
def trim_to_fit(to_trim, to_fit):
# calculate how many times the string needs
# to be self - concatenated
times_to_concatenate = len(to_fit) // len(to_trim) + 1
# slice the string to fit the target
return (to_trim * times_to_concatenate)[:len(to_fit)]
It uses slicing, and the fact that a multiplication of a X and a string in python concatenates the string X times.
Output:
>>> trim_to_fit('test', 'stackoverflow')
'testtesttestt'
You can also create an endless circular generator over the string:
# improved by Rick Teachey
def circular_gen(txt):
while True:
for c in txt:
yield c
And to use it:
>>> gen = circular_gen('test')
>>> gen_it = [next(gen) for _ in range(len('stackoverflow'))]
>>> ''.join(gen_it)
'testtesttestt'
What you need is a way to get each character out of your manipulateinput string over and over again, and so that you don't run out of characters.
You can do this by multiplying the string so it is repeated as many times as you need:
mystring = 'string'
assert 2 * mystring == 'stringstring'
But how many times to repeat it? Well, you get the length of a string using len:
assert len(mystring) == 6
So to make sure your string is at least as long as the other string, you can do this:
import math.ceil # the ceiling function
timestorepeat = ceil(len(originalinput)/len(manipulateinput))
newmanipulateinput = timestorepeat * manipulateinput
Another way to do it would be using int division, or //:
timestorepeat = len(originalinput)//len(manipulateinput) + 1
newmanipulateinput = timestorepeat * manipulateinput
Now you can use a for loop without running out of characters:
result = '' # start your result with an empty string
for character in newmanipulateinput:
# test to see if you've reached the target length yet
if len(result) == len(originalinput):
break
# update your result with the next character
result += character
# note you can concatenate strings in python with a + operator
print(result)

Categories