The Wayback Machine - https://web.archive.org/web/20240927060113/https://www.geeksforgeeks.org/python-program-match-string-random-strings-length/
Open In App

Generating random strings until a given string is generated

Last Updated : 26 Oct, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given the string, the task is to generate the same string using the random combination of special character, numbers, and alphabets.

Examples :

Input : GFG
Output :n4W
        mK7
        k1x
        q;;, !g
        .
        .
        .
        .
        .
        GF,
        GFf
        GFp
        GFG

Target matched after 167 iterations


Prerequisite : Generating random Id’s in Python

string.ascii_lowercase, string.digits, string.ascii_uppercase are some of the common string constants present in the string module in Python, which are used here as dictionary. All these string constants are combined with other special characters like ‘ ., !?;:’ and are stored in a variable.

Approach : Simply run two loops and use random function provided by python. It will show all the possible combinations that can be provided by the random function and same thing will be done by the decrypt loop. At the end, it will show the same text as you have inserted when prompted to enter. It will match each random string with the given string. If both index matches then fix that index and iterate for the remaining.

Below is the implementation :




# Python program to generate and match 
# the string from all random strings
# of same length
  
# Importing string, random
# and time modules
import string
import random
import time
  
# all possible characters including 
# lowercase, uppercase and special symbols
possibleCharacters = string.ascii_lowercase + string.digits + 
                     string.ascii_uppercase + ' ., !?;:'
  
# string to be generated
t = "geek"
  
# To take input from user
# t = input(str("Enter your target text: "))
  
attemptThis = ''.join(random.choice(possibleCharacters)
                                for i in range(len(t)))
attemptNext = ''
  
completed = False
iteration = 0
  
# Iterate while completed is false
while completed == False:
    print(attemptThis)
      
    attemptNext = ''
    completed = True
      
    # Fix the index if matches with 
    # the strings to be generated
    for i in range(len(t)):
        if attemptThis[i] != t[i]:
            completed = False
            attemptNext += random.choice(possibleCharacters)
        else:
            attemptNext += t[i]
              
    # increment the iteration 
    iteration += 1
    attemptThis = attemptNext
    time.sleep(0.1)
  
# Driver Code
print("Target matched after " +
      str(iteration) + " iterations")


Output :

FyFJ
.:YZ
aubo
.
.
.
g56G
gk6R
g7Se
gT o
gD d
gXek
g0ek
g ek
.
. 
gUek
giek
geek

Target matched after 168 iterations


Similar Reads

Generating random Id's in Python
In python there are different ways to generate id's. Let's see how different types of Id's can be generated using python without using inbuilt Python libraries. 1. Generating Random Integer as Ids' Code #1 : Print 10 random values of numbers between 1 and 100. C/C++ Code # Python3 code to demonstrate the # random generation of Integer id's import r
2 min read
Generating Random id's using UUID in Python
We had discussed the ways to generate unique id's in Python without using any python inbuilt library in Generating random Id’s in Python In this article we would be using inbuilt functions to generate them. UUID, Universal Unique Identifier, is a python library which helps in generating random objects of 128 bits as ids. It provides the uniqueness
3 min read
Generating random number list in Python
Sometimes, in making programs for gaming or gambling, we come across the task of creating a list all with random numbers in Python. This task is to perform in general using loop and appending the random numbers one by one. But there is always a requirement to perform this in the most concise manner. Let's discuss certain ways in which this can be d
3 min read
Generating Random Integers in Pandas Dataframe
Pandas is the most popular Python library that is used for data analysis. It provides highly optimized performance with back-end source code that is purely written in C or Python. Here we will see how to generate random integers in the Pandas datagram. We will be using the numpy.random.randint() method to generate random integers. Generating Random
3 min read
Random sampling in numpy | random() function
numpy.random.random() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0). Syntax : numpy.random.random(size=None) Parameters : size : [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n *
2 min read
Python Random - random() Function
There are certain situations that involve games or simulations which work on a non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications: Creating pseudo-random numbers on Lottery scratch cardsreCAPTCHA on login forms uses a random number generator to define different numbers and ima
3 min read
NumPy random.noncentral_f() | Get Random Samples from noncentral F distribution
The NumPy random.noncentral_f() method returns the random samples from the noncentral F distribution. Example C/C++ Code import numpy as np import matplotlib.pyplot as plt gfg = np.random.noncentral_f(1.24, 21, 3, 1000) count, bins, ignored = plt.hist(gfg, 50, density = True) plt.show() Output: Syntax Syntax: numpy.random.noncentral_f(dfnum, dfden,
1 min read
Python | Count the elements in a list until an element is a Tuple
In this problem, we need to accept a list. The list can have nested tuples. We need to count the elements in a list until a tuple has been encountered. Examples: Input : [4, 5, 6, 10, (1, 2, 3), 11, 2, 4] Output : 4 Input : [4, (5, 6), 10, (1, 2, 3), 11, 2, 4] Output : 1 Method #1: In this program we will use the concept of isinstance() to verify w
2 min read
Python | Remove and print every third from list until it becomes empty
Given a list of numbers, Your task is to remove and print every third number from a list of numbers until the list becomes empty. Examples: Input : [10, 20, 30, 40, 50, 60, 70, 80, 90] Output : 30 60 90 40 80 50 20 70 10 Explanation: The first third element encountered is 30, after 30 we start the count from 40 for the next third element which is 6
4 min read
Python | Visualize graphs generated in NetworkX using Matplotlib
Prerequisites: Generating Graph using Network X, Matplotlib IntroIn this article, we will be discussing how to plot a graph generated by NetworkX in Python using Matplotlib. NetworkX is not a graph visualizing package but basic drawing with Matplotlib is included in the software package. Step 1 : Import networkx and matplotlib.pyplot in the project
3 min read
Generating Word Cloud in Python
Word Cloud is a data visualization technique used for representing text data in which the size of each word indicates its frequency or importance. Significant textual data points can be highlighted using a word cloud. Word clouds are widely used for analyzing data from social network websites. For generating word cloud in Python, modules needed are
2 min read
Generating Word Cloud in Python | Set 2
Prerequisite: Generating Word Cloud in Python | Set - 1Word Cloud is a data visualization technique used for representing text data in which the size of each word indicates its frequency or importance. Significant textual data points can be highlighted using a word cloud. Word clouds are widely used for analyzing data from social network websites.F
5 min read
Generating subarrays using recursion
Given an array, generate all the possible subarrays of the given array using recursion. Examples: Input : [1, 2, 3] Output : [1], [1, 2], [2], [1, 2, 3], [2, 3], [3] Input : [1, 2] Output : [1], [1, 2], [2] We have discussed iterative program to generate all subarrays. In this post, recursive is discussed. Approach: We use two pointers start and en
6 min read
Generating all possible Subsequences using Recursion including the empty one.
Given an array. The task is to generate and print all of the possible subsequences of the given array using recursion. Examples: Input : [1, 2, 3] Output : [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3], [] Input : [1, 2] Output : [2], [1], [1, 2], [] Approach: For every element in the array, there are two choices, either to include it in the sub
5 min read
Pafy - Generating File Name of Stream
In this article we will see how we can generate file name of given youtube video stream in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Stream is basically available resolution of video is available on youtube. File name is the t
2 min read
Generating Basic Discrete Time Signals
Generating basic discrete-time signals for Discrete-Time Signal ProcessingUnit Step, Unit Impulse, Unit Ramp, exponential signals are very commonly used signals in signal processing to perform various operations. Unit step signal is given byUnit impulse signal is given byUnit ramp signal is given byExponential signal is given by Examples: Input : U
2 min read
Generating dynamic URLs in Flask
Prerequisites: Basics of Flask When creating an application, it's quite cumbersome to hard-code each URL. A better way to resolve this problem is through building Dynamic URLs. Let us briefly understand the meaning of a few common terms first. Dynamic Routing: It is the process of getting dynamic data(variable names) in the URL and then using it.Va
3 min read
Python Program for Generating Lyndon words of length n
Given an integer n and an array of characters S, the task is to generate Lyndon words of length n having characters from S. A Lyndon word is a string which is strictly less than all of its rotations in lexicographic order. For example, the string "012" is a Lyndon word as it is less than its rotations "120" and "201", but "102" is not a Lyndon word
3 min read
Pandas - Generating ranges of timestamps using Python
A timestamp is a string of characters or encrypted or encoded data that identifies the time and date of an event, usually indicating the time and date of day, and is often accurate to a fraction of a second. timestamps are used to maintain track of information. When information was created, transmitted, edited, or removed, it was given a timestamp.
3 min read
Generating Beautiful Code Snippets using Python
When creating technical documentation or tutorials, it can be helpful to include images of code snippets to illustrate specific examples or concepts. However, taking a screenshot of a code file can look unprofessional and hard to read. This article will explore how to convert programming code into beautiful image snippets in Python using the librar
3 min read
Generating meshes in Python
In computer graphics and scientific computing, the mesh is an arrangement of points, lines, and surfaces that outline the shape and structure of a 3D object or surface. Making meshes is a critical process in several industries, such as 3D modelling, simulation, visualization, and gaming. In this article, we'll explore various libraries and techniqu
5 min read
Generating Strong Password using Python
Having a weak password is not good for a system that demands high confidentiality and security of user credentials. It turns out that people find it difficult to make up a strong password that is strong enough to prevent unauthorized users from memorizing it. This article uses a mixture of numbers, alphabets, and other symbols found on the computer
3 min read
Generating Password and OTP in Java
You may go through Generate a One Time Password or Unique Identification URL article before this for better understanding. Many a times we forget our passwords and we opt for Forget password option and within no time we get a new password at our registered email-ID or phone no. to login our account. And every time we get a different password. Somet
5 min read
Reading and Generating QR codes in Python using QRtools
This article aims to introduce the use of the python library: qrtools. This library can be used to both read QR codes and generate them. What are QR codes? QR code, or quick response code, is a trademark for a type of 2 dimensional barcode. 2 dimensional barcodes are similar to one dimensional barcodes, but can store more information per unit area.
5 min read
Generating a Set of Tuples from a List of Tuples in Python
Python provides a versatile set of tools for manipulating data structures, and when it comes to working with tuples, developers often need to extract unique elements or create a set of tuples from a given list. In this article, we will explore some simple and commonly used methods to generate a set of tuples from a list of tuples in Python. Generat
4 min read
Generating hash id's using uuid3() and uuid5() in Python
Python's UUID class defines four functions and each generates different version of UUIDs. Let's see how to generate UUID based on MD5 and SHA-1 hash using uuid3() and uuid5() .Cryptographic hashes can be used to generate different ID's taking NAMESPACE identifier and a string as input. The functions that support cryptographic hash generation are :
2 min read
Python - Random uppercase in Strings
Given a String, the task is to write a Python program to convert its characters to uppercase randomly. Examples: Input : test_str = 'geeksforgeeks' Output : GeeksfORgeeks Explanation : Random elements are converted to Upper case characters. Input : test_str = 'gfg' Output : GFg Explanation : Random elements are converted to Upper case characters.Me
4 min read
Python | Generate Random String of given Length
The issue of generation of random numbers is quite common, but sometimes, we have applications that require us to better that and provide some functionality of generating a random string of digits and alphabets for applications such as passwords. Let's discuss certain ways in which this can be performed in Python. Example: String.ascii_letters retu
2 min read
Python - Find all the strings that are substrings to the given list of strings
Given two lists, the task is to write a Python program to extract all the strings which are possible substring to any of strings in another list. Example: Input : test_list1 = ["Geeksforgeeks", "best", "for", "geeks"], test_list2 = ["Geeks", "win", "or", "learn"] Output : ['Geeks', 'or'] Explanation : "Geeks" occurs in "Geeksforgeeks string as subs
5 min read
Python Program to Generate Random binary string
Given a number n, the task is to generate a random binary string of length n.Examples: Input: 7 Output: Desired length of random binary string is: 1000001 Input: 5 Output: Desired length of random binary string is: 01001 Approach Initialize an empty string, say key Generate a randomly either "0" or "1" using randint function from random package. Ap
2 min read
Article Tags :
Practice Tags :