pygramador
pygramador

Reputation: 3

slicing dynamically in python

I have a Python 3.x script which only has the following function:

from random import random

def slicer(longitude):
    alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    result = ""
    x = 0

    for i in range(1, int(longitude)):
        x = int(62 * random())
        if x == 0:
            x += 1
        else:
            # get a random letter from alphabet, seem this is the problem > (alphabet[x:1]):
            string_section = alphabet[x:1]
            result = result + string_section
    return result

print(str(slicer(10)))  # get a 10 digit string

But this code doesn't work, and I'm stuck...

Is s[x:1] permitted, where x is a changing value from a for loop?

If not, is there another method that will accomplish the same result? Thanks for help.

Upvotes: 0

Views: 1075

Answers (3)

Amanda
Amanda

Reputation: 12737

The problem is that x is almost always less than 1, so [x:1] is a meaningless range. If I just do:

alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
alphabet[32:1]

I can see that python returns nothing. So your script is continually adding nothing to result -- what you need is alphabet[x] to take that position from the alphabet. And since alphabet[0] is a, you don't need to add 1 if x is 0. (In your implementation, you'll never return an "a" and "b" is about twice as likely to come up than any other letter).

from random import random

def slicer(longitude):
    alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    result = ""
    x = 0

    for i in range(1, int(longitude)):
        x = int(62 * random())
        string_section = alphabet[x]
        result = result + string_section
    return result

print(str(slicer(10)))  # get a 10 digit string

But ....

If you want to make sure you don't repeat letters, you can just use random.sample():

import random

def slicer(longitude):
    alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    result = random.sample(alphabet,longitude)
    return result

print(''.join(slicer(10)))  # Produces a list, use .join() to print a string

Upvotes: 0

ely
ely

Reputation: 77404

You may access a single character from the alphabet at random position x simply with alphabet[x]. Note that x must be in the range [0, len(alphabet)-1] to be a valid index, so you might want to use math.floor instead of int when turning the random value into an integer to serve as an index.

Alternatively, you can use random.choice for longitude number of times:

result = ''
for i in xrange(longitude):
    result += random.choice(alphabet)
return result

Upvotes: 2

Yeray Diaz
Yeray Diaz

Reputation: 1770

If you're trying to get a single character you don't need slice, a simple indexing would do alphabet[x].

Upvotes: 0

Related Questions