GERRR
GERRR

Reputation: 5

Random Simulation of 20 Die Throws

Trying to simulate 20 dice throws randomly, the code needs to enclose with parenthesis a value that is the same, the parenthesis appear, but I am missing something on my formula, any advise can greatly help, eg:

1 ( 4 1 ) 2 3 6 1 4 3 2 6 6 6 5 6 2 1 3 5 3 # incorrect
1 4 1 2 3 6 1 4 3 2 ( 6 6 6 ) 5 6 2 1 3 5 3 # this is a correct example 
def main():

    exampleList = [ ]

    for i in range(20):
        exampleList.append(randint(1, 6))
    print(exampleList)
    print(list(range(0,20)))

    max_count = 0
    run_count = 0

    matched = False #inRun = False           
    # find max run
    for rollValue in exampleList:
      #print(rollValue)
      if run_count == 19:
          print()

      else:          
          print("-------")
          print("Roll Value %s" % exampleList[run_count])
          print("Position   %s" % run_count)
          print("Next Roll value %s" % exampleList[run_count + 1])
          if exampleList[run_count] == exampleList[run_count + 1]:
             matched = True
             print("------->>>matched")
          else:
             matched = False#inRun = False
          run_count += 1

      if rollValue < 19:
          if exampleList[rollValue] == exampleList[rollValue + 1]:
             run_count += 1
          if matched == False:
              matched == True
              run_count = rollValue

          else:
            matched = False
          if run_count > max_count:
             run_count = 1
    # print sequence
    for rollValue in range(20):
       if rollValue == run_count:
               print("(", exampleList[rollValue], end = " ")

       elif rollValue == run_count + max_count + 1:
            print(exampleList[rollValue], ")", end = " ")

       else:
            print(exampleList[rollValue], end = " ")            
main()

Upvotes: 0

Views: 95

Answers (5)

Persixty
Persixty

Reputation: 8579

The logical error is that you're confusing "the index where the run starts" with "the length of the (last) run".

You need a variable like max_run_start_index.

Look at the code:

if rollValue == run_count:
    print("(", exampleList[rollValue], end = " ")

Read it back to yourself 'if the index of the next output is equal to the length of the last run, output open bracket before it'.

So if the length of the last run is 3 the longest run starts at index 3? Surely not...

I'm not a Python coder, so you'll need to fix it yourself...

Upvotes: 0

dpwr
dpwr

Reputation: 2812

There are various ways to do this, but this is the most similar to what you were doing already. Basically just iterate over the index of your list of rolls. Each number we examine it to see if it is the same as the one before, if yes, then we increment the count and move on. If not then we add however many of that number were in the count to the output. If there was one, we write it out by itself, if more, in parenthesis.

exampleList = [randint(1, 6) for i in range(20)]

# the current number that could be a potential sequence
current = exampleList[0]
# count for the number of occurences in a sequence (often 1)
count = 1
# The string to outpu
output = ''

# Iterate over the rolls, ignoring the first one
for i in range(1, len(exampleList)):

    if exampleList[i] == current:
        count += 1
    else:
        if count > 1:
            output += ('(' + count * str(current) + ')')
        else:
            output += str(current)
        current = exampleList[i]
        count = 1

# Handle final addition
if count > 1:
    output += ('(' + count * str(current) + ')')
else:
    output += str(current)

print(output)

Output:

64(66)15253(66)2143454(22)

Upvotes: 0

user3483203
user3483203

Reputation: 51165

Here is a solution using regex. This creates a string out of the dice rolls, then finds repeating digits and uses re.sub to add parenthesis.

import re
import random

rolls = ''.join(map(str, [random.choice(range(1, 7)) for _ in range(20)]))
rolls = ' '.join(re.sub(r'(\d)(\1+)', r'(\1\2)', rolls))
print(rolls)

A couple sample runs:

4 1 4 3 4 6 5 2 3 ( 5 5 ) 1 6 4 3 5 2 5 ( 4 4 )
2 ( 1 1 ) 4 1 ( 5 5 ) ( 3 3 ) 6 2 ( 1 1 ) 5 1 4 3 4 ( 5 5 )

Regex explanation:

(                             // start of matching group 1
  \d                          // matches a single digit
)                             // end of matching group 1
(                             // start of matching group 2
  \1+                         // matches group 1, 1 or more times
)                             // end of matching group 2

Upvotes: 2

NZD
NZD

Reputation: 1970

This adds the parenthesis as part of the list:

#!/usr/bin/python

import sys
from random import randint


# add parenthesis as part of the list
def main():

    exampleList = [ ]
    previous = -1
    opened = False

    for i in range(20):
        roll = randint(1, 6)
        if roll == previous:
            if not opened:
                exampleList.insert(-1, '(')
                opened = True
        else:
            if opened:
                exampleList.append(')')
                opened = False
        exampleList.append(roll)
        previous = roll
    if opened:
        exampleList.append(')')
    for item in exampleList:
        sys.stdout.write('{0} '.format(item))
    sys.stdout.write('\n')


if __name__ == '__main__':
    main()

Examples:

( 2 2 ) 4 5 1 2 1 ( 6 6 ) 1 6 1 4 1 ( 6 6 ) 1 6 2 4 
2 ( 6 6 ) ( 1 1 ) 3 2 1 ( 4 4 ) 1 2 5 4 1 5 3 ( 5 5 5 )

Upvotes: 0

msaba92
msaba92

Reputation: 357

There are a number of issues with your code, so it was just quicker to rewrite the whole thing.

def main():
    example_list = []
    for _ in range(20):
        example_list.append(random.randint(1, 6))

    inside = False
    for index in range(len(example_list)):

        try:
            if inside:
                if example_list[index] != example_list[index + 1]:
                    print("%d )" % example_list[index], end=" ")
                    inside = False
                else:
                    print(example_list[index], end=" ")
            else:
                if example_list[index] == example_list[index + 1]:
                    print("( %d" % example_list[index], end=" ")
                    inside = True
                else:
                    print(example_list[index], end=" ")
        except IndexError:
            print("%d" % example_list[index], end=" ")

            if inside:
                print(")")
            else:
                print()

As you can see I keep track of whether I'm inside a parenthesis by using a variable. I look to the next number to guess if I should add a closing parenthesis.

The last case is handled by a try-except.

You could also handle each number by looking forward and backward but that'd require you to add some extra condition for the try-except part so this was just

Upvotes: 0

Related Questions