Python Forum
<while> cycle is not interrupted when using the <random>module
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
<while> cycle is not interrupted when using the <random>module
#1
Hello everyone, idea to count how many attempts module random takes before <==> to original string
unfortunatelly <while> not interrupted((((
import random

str_org = "ABC"
arr = ['A', 'B','C']
str_pat = []

for i in range(len(arr)):
    str_pat.append(random.choice(arr))

result = "".join(str_pat)

count = 0

while result != str_org:
    count += 1
    if result==str_org:
        break
    print(count)
Error:
////////////////////// Run concole example: 56 197257 197258 197259 197260 197261 197262 ......
Reply
#2
The result string and its str_pat does not change in the while loop.
They are assigned values before the loop and from that point on never change.
Reply
#3
You're only picking the random string once at the beginning of the program.

After you go into the while loop, result never changes, so assuming it didn't match the first time, it will never match.

Also, you don't need the separate list arr. The initial string str_org can be used as an iterator for random.choice and to tell the for loop how many times to pick.
Reply
#4
Thank you for assistance, i solved the problem as bellow:
import random

str_org = "ABC"
arr = ['A', 'B', 'C']
str_pat = []

result=""

count = 0

while result != str_org:

    for i in range(len(arr)):
        str_pat.append(random.choice(arr))
    result = "".join(str_pat)
    count += 1
    if result==str_org:
        print(count)
        break
        
    else:
        result=""
        str_pat=[]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Assigning cycle values in a list nmancini 3 1,022 Sep-16-2024, 09:35 PM
Last Post: deanhystad
  "Random" module is not working as expected Genericgamemaker 1 983 Jul-25-2024, 04:46 PM
Last Post: Gribouillis
  Writing a cycle to find the nearest point from the array Tysrusko 0 817 May-10-2024, 11:49 AM
Last Post: Tysrusko
  Process finished with exit code 137 (interrupted by signal 9: SIGKILL) erdemath 2 12,304 Apr-18-2022, 08:40 PM
Last Post: erdemath
  Need to fix SyntaxError in cycle try alexfrol86 14 6,043 Mar-27-2022, 07:53 AM
Last Post: stevendaprano
  Trying to cycle through a list of charcters pooky2483 12 6,596 Sep-28-2020, 06:55 AM
Last Post: pooky2483
  Cycle of numpy variables Zero01 0 2,080 Jul-31-2020, 11:58 AM
Last Post: Zero01
  stop cycle while windows11 1 2,660 May-16-2020, 03:17 PM
Last Post: deanhystad
  Some help with Classes and the random module please? :) AlluminumFoil 2 2,800 Jan-08-2020, 11:03 PM
Last Post: AlluminumFoil
  Can't Get Random Module! Pls Help! VictorVictus 1 9,121 Aug-24-2019, 10:20 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020