1

I am an amateur to Python, I have made a program that will encode a long string of characters and output 6 characters.

def token (n):
    if n < 10:
        return chr( ord( '0' ) + (n) )
    if n in range (10, 36):
        return chr( ord( 'A' ) - 10 + (n))
    if n in range (37, 62):
        return chr( ord( 'a' ) - 36 + (n))
    if n is 62:
        return '-'
    if n is 63:
        return '+'

The token turns a number(n) into a character. Upper and lower case letters including the characters "-" and "+".

def encode (n):
    a = n // 1 % 64
    b = n // 64 % 64
    c = n // 64 ** 2 % 64
    d = n // 64 ** 3 % 64
    e = n // 64 ** 4 % 64
    f = n // 64 ** 5 % 64
    return (token(a) + token(b) + token(c) + token(d) + token(e) + token(f))

This is the rest of the encode.

print(encode(1234567890))
'IBWb91'

Again, is there a way to create an order for the six characters for the output?

This is what I have so far. I got this from an existing question.

How can I reorder a list in python?

mylist = ['a','b','c','d','e','f',]
myorder = [6,5,4,3,2,1]
mylist = [ mylist[i] for i in myorder]

But...it gives me this:

IndexError: list index out of range

What I want to happen:

>>> print(mylist)
['f','e','d','c','b','a'] 

I am totally new to this. Please help :)

Community
  • 1
  • 1
eshing10
  • 11
  • 4

3 Answers3

2

If you just want to reverse the list, just call the reverse method or reversed function:

>>> mylist = ['a','b','c','d','e','f']
>>> list(reversed(mylist))
['f', 'e', 'd', 'c', 'b', 'a']

If you want to do it the hard way, you can, but you have to use indices that are actually in the list:

>>> [i for i, e in enumerate(mylist)]
[0, 1, 2, 3, 4, 5]

Those are the indices in the list. 6 is not one of them. So if you try to use mylist[6] you're going to get an IndexError. What you probably wanted was [5, 4, 3, 2, 1, 0].

abarnert
  • 354,177
  • 51
  • 601
  • 671
1

Lists in python are indexed starting from 0, not from 1. If you want to reorder an n-element list with the method you show, you therefore need to have a list containing the numbers 0,1,...,n - 1, as trying to access element n of an n-element list will give an error, as the index will be outside of the expected range.

For example, with what you gave,

mylist = ['a','b','c','d','e','f']
myorder = [5,4,3,2,1,0]
mylist = [mylist[i] for i in myorder]
qaphla
  • 4,707
  • 3
  • 20
  • 31
1

The order has to be zero-indexed. That's how python lists work - the first element is mylist[0], the second element is mylist[1], etc. Therefore, it should be [5,4,3,2,1,0].

Trein
  • 3,658
  • 27
  • 36