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
  Process finished with exit code 137 (interrupted by signal 9: SIGKILL) erdemath 2 9,387 Apr-18-2022, 08:40 PM
Last Post: erdemath
  Need to fix SyntaxError in cycle try alexfrol86 14 3,058 Mar-27-2022, 07:53 AM
Last Post: stevendaprano
  Trying to cycle through a list of charcters pooky2483 12 4,316 Sep-28-2020, 06:55 AM
Last Post: pooky2483
  Cycle of numpy variables Zero01 0 1,537 Jul-31-2020, 11:58 AM
Last Post: Zero01
  stop cycle while windows11 1 1,971 May-16-2020, 03:17 PM
Last Post: deanhystad
  Some help with Classes and the random module please? :) AlluminumFoil 2 2,134 Jan-08-2020, 11:03 PM
Last Post: AlluminumFoil
  Can't Get Random Module! Pls Help! VictorVictus 1 7,052 Aug-24-2019, 10:20 AM
Last Post: snippsat
  Occurrences using FOR and IF cycle P86 2 2,476 Jul-29-2019, 04:37 PM
Last Post: ThomasL
  pool map cycle skorost5 5 3,755 Apr-07-2019, 09:21 AM
Last Post: skorost5
  Question about the Random Module Exsul 1 1,964 Mar-13-2019, 02:06 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

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