2

I am struggling with an idea I want put into a python script. I'm not even sure how to ask the most appropriate question as I've been surfing through the net trying to find what I want with no luck.

Basically, I have a script that does a simple calculation:

divider = int(math.ceil(df.scale / 3000))

This is because I want ' divider' to return the value divided by 3000 and always rounded up. I want to use that value to help me return letters.

So, it goes like this:

if 1 returns then I want a to return 'A' if 2 returns, then I want to create 'A', 'B' if 3 returns, then I want to create 'A', 'B', 'C' and so on....

My end result is, that I want to save some files. 'divider' will determine how many files I want to save and then each file will recursively be named with the letter in it (i.e. FileA, FileB, FileC...)

Ok, I know my question isn't exactly well put together, but I'm struggling with the logic, so if you need some clarity, please let me know.

2 Answers 2

6

Do you mean something like:

for i in range(int(math.ceil(df.scale / 3000))):
  # i will contain 0, 1, 2, ...
  # letter will contain 'A', 'B', 'C', ...
  letter = chr(ord('A') + i)

Or if you need the actual list:

[chr(ord('A') + i) for i in range(int(math.ceil(df.scale / 3000)))]

You can also use string.ascii_uppercase for a list of uppercase letters and slice it as you need:

from string import ascii_uppercase

print list(ascii_uppercase)[:int(math.ceil(df.scale / 3000))]
Sign up to request clarification or add additional context in comments.

1 Comment

Niklas. Thanks for interpreting my gibberish question and coming up with exactly what I had in mind!
3

Because it's the end of the day for me, here's another approach which generalizes to more than 26 files, spreadsheet-column-name style:

import string, itertools

def name_generator(min_length=1, alphabet=string.ascii_uppercase):
    for length in itertools.count(min_length):
        for chars in itertools.product(alphabet, repeat=length):
            yield ''.join(chars)

def get_names(n):
    return list(itertools.islice(name_generator(), 0, n))

which gives

>>> get_names(1)
['A']
>>> get_names(3)
['A', 'B', 'C']
>>> get_names(30)
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD']

1 Comment

Thanks DSM. I like the define function approach. I had thought about using one when trying to calculate my end result and I still just might do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.