main_col = ['Name', 'Age', 'Gender']
main_row = [['Peter', 18, 'M'], ['Sam', 20, 'M'], ['Carol', 19, 'F'], ['Malcom', 21, 'M'], ['Oliver', 25, 'M'], ['Mellisa', 21, 'F'], ['Minreva', 18, 'F'], ['Bruce', 23, 'M'], ['Clarke', 24, 'M'], ['Zuck', 22, 'M'], ['Slade', 23, 'M'], ['Wade', 21, 'M'], ['Felicity', 22, 'F'], ['Selena', 23, 'F'], ['Ra\'s Al Gul',700, 'M']]
I am trying to make a program where main_col are column names and main_row have row information for each column (in a 2d list).
How can I write a piece of code for a search query which can search row where:
Name = 'Carol' and Age = 19.
Name = 'Carol' and Gender = 'F'
Age= 22 or Gender = 'M'
The following code is giving result for the 3rd part:-
search = {'Age' : 22, 'Gender' : 'M'}
for i in search:
idx = main_col.index(i)
for j in main_row:
if(j[idx] == search[i]):
print(j)
You could give this a try, its somewhat complicated but should get the job done:
AND = 'and'
OR = 'or'
# Check if the array is a match
def is_found(value, aggregator, search_terms):
if aggregator == AND:
is_found = True
for col, val in search_terms.items():
if value[val['idx']] != val['val']:
is_found = False
break
else:
is_found = False
for col, val in search_terms.items():
if value[val['idx']] == val['val']:
is_found = True
break
return is_found
# Perform the search
def search(columns, values, aggregator, search_filters):
# Format the search values into something we can use
# {
# 'col': { 'idx': <column index>, 'val': <search value> }
# }
search_terms = {
col: { 'idx': columns.index(col), 'val': val }
for col, val in search_filters.items()
}
return [
val
for val in values
if is_found(val, aggregator, search_terms)
]
if __name__ == "__main__":
main_col = ['Name', 'Age', 'Gender']
main_row = [['Peter', 18, 'M'], ['Sam', 20, 'M'], ['Carol', 19, 'F'], ['Malcom', 21, 'M'], ['Oliver', 25, 'M'], ['Mellisa', 21, 'F'], ['Minreva', 18, 'F'], ['Bruce', 23, 'M'], ['Clarke', 24, 'M'], ['Zuck', 22, 'M'], ['Slade', 23, 'M'], ['Wade', 21, 'M'], ['Felicity', 22, 'F'], ['Selena', 23, 'F'], ['Ra\'s Al Gul',700, 'M']]
search_filter = {
'Age': 22, 'Gender': 'M'
}
print(search(main_col, main_row, OR ,search_filter))
search_filter = {
'Name': 'Carol', 'Age': 19
}
print(search(main_col, main_row, AND ,search_filter))
If you want to stick with your pattern, this is an option:
search = {'Age' : 21, 'Gender' : 'M'}
idxs = [ (main_col.index(key), val) for key, val in search.items()]
tmp = [ set(tuple(person) for person in main_row if person[i] == v) for i, v in idxs ]
res = set.intersection(*tmp)
#=> {('Wade', 21, 'M'), ('Malcom', 21, 'M')}
NOTE: I used intersection to return AND, but you can customise to any of the operation available on set (https://docs.python.org/3.7/library/stdtypes.html#set): union, intersection, difference, ...
You can convert to a handy method:
def lookup(search, main_row, main_col):
idxs = [ (main_col.index(key), val) for key, val in search.items()]
tmp = [ set(tuple(person) for person in main_row if person[i] == v) for i, v in idxs ]
return set.intersection(*tmp)
lookup({'Age' : 21}, main_row, main_col)
#=> {('Wade', 21, 'M'), ('Mellisa', 21, 'F'), ('Malcom', 21, 'M')}
lookup({'Age' : 21, 'Gender' : 'M'}, main_row, main_col)
#=> {('Malcom', 21, 'M'), ('Wade', 21, 'M')}
lookup({'Age' : 21, 'Gender' : 'M', 'Name': 'Malcom'}, main_row, main_col)
#=> {('Malcom', 21, 'M')}
Anyway, I'd suggest to use a dict from main_row:
main_row = [['Peter', 18, 'M'], ['Sam', 20, 'M'], ['Carol', 19, 'F'], ['Malcom', 21, 'M'], ['Oliver', 25, 'M'], ['Mellisa', 21, 'F'], ['Minreva', 18, 'F'], ['Bruce', 23, 'M'], ['Clarke', 24, 'M'], ['Zuck', 22, 'M'], ['Slade', 23, 'M'], ['Wade', 21, 'M'], ['Felicity', 22, 'F'], ['Selena', 23, 'F'], ['Ra\'s Al Gul',700, 'M'], ['Oliver', 31, 'M']]
This builds the dictionary people, leaving apart the first list of headers:
people = [ {'name':name, 'age':age, 'gender':gender} for name, age, gender in main_row]
#=> [{'name': 'Peter', 'age': 18, 'gender': 'M'}, {'name': 'Sam', 'age': 20, 'gender': 'M'}, ....
Then you can query for example in this way:
next(person for person in people if person['name'] == "Oliver" and person['age'] == 31 )
#=> {'name': 'Oliver', 'age': 31, 'gender': 'M'}
the_21_years_old = [ person for person in people if person['age'] == 21 ]
#=> [{'name': 'Malcom', 'age': 21, 'gender': 'M'}, {'name': 'Mellisa', 'age': 21, 'gender': 'F'}, {'name': 'Wade', 'age': 21, 'gender': 'M'}]
You can the do whatever you need with the returned "records":
for person in the_21_years_old:
print(person['name'], person['age'])
# Malcom 21
# Mellisa 21
# Wade 21
Related
I have a list of strings and integers:
students = ['Janet', 21, 'Bill', 19, 'Amanda', 22, 'Mike', 25, 'Susan', 24, 'Jen', 29, 'Sara', 30, 'Maria', 18, 'Kathy', 20, 'Andrew', 27]
I need to make a dictionary called peoples, that takes each name and maps it to their age, which is the integer after it. I thought I would have to iterate over the list, but I've had no luck. Here is what I have so far:
students = ['Janet', 21, 'Bill', 19, 'Amanda', 22, 'Mike', 25, 'Susan', 24, 'Jen', 29, 'Sara', 30, 'Maria', 18, 'Kathy', 20, 'Andrew', 27]
people = {}
for i in students:
if type(i) is int == False:
#here I would take i and make it a key in the dictionary, then map the following integer to its value
students = ['Janet', 21, 'Bill', 19, 'Amanda', 22, 'Mike', 25, 'Susan', 24, 'Jen', 29, 'Sara', 30, 'Maria', 18, 'Kathy', 20, 'Andrew', 27]
print(dict(zip(students[::2], students[1::2])))
Prints:
{'Janet': 21, 'Bill': 19, 'Amanda': 22, 'Mike': 25, 'Susan': 24, 'Jen': 29, 'Sara': 30, 'Maria': 18, 'Kathy': 20, 'Andrew': 27}
dict([x for x in zip(*[iter(students)]*2)])
dict = {}
for i in range(len(students)//2):
dict[student[i]] = dict[student[i+1]]
Here is a working example code:
data = {'name': ['Joe', 'Mike', 'Jack', 'Hack', 'David', 'Marry', 'Wansi', 'Sidy', 'Jason', 'Even'],
'age': [25, 32, 18, np.nan, 15, 20, 41, np.nan, 37, 32],
'gender': [1, 0, 1, 1, 0, 1, 0, 0, 1, 0],
'isMarried': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=labels)
print(df)
print("---------------------------")
obj = df[df["age"]>40].index.format()
print("obj is",type(obj))
I hope obj as a string (), but the above result is list().
What should I do to correct it ?
You can simply put obj = obj[0] and it will then become a string
data = {'name': ['Joe', 'Mike', 'Jack', 'Hack', 'David', 'Marry', 'Wansi', 'Sidy', 'Jason', 'Even'],
'age': [25, 32, 18, np.nan, 15, 20, 41, np.nan, 37, 32],
'gender': [1, 0, 1, 1, 0, 1, 0, 0, 1, 0],
'isMarried': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=labels)
print(df)
print("---------------------------")
obj = df[df["age"]>40].index.format()
obj = obj[0]
print("obj is",type(obj))
obj = df[df["age"]>40].index.format()[0]
print("obj is",obj,type(obj))
obj is g <class 'str'>
I have a list [T20, T5, T10, T1, T2, T8, T16, T17, T9, T4, T12, T13, T18]
I have stripped out the T's, coverted to integer type and sorted the list to get this:
sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]
I'm looping over the list and checking if the next number to current number is in numerical sequence. If not I want to insert a "V" in its position.
So eventually the list should look like: [1, 2, V, 4, 5, V, V, 8, 9, 10, V, 12, 13, V, V, 16, 17, 18, V, 20]
However, I'm not able to insert the exact no of V's at the right positions.
def arrange_tickets(tickets_list):
ids=[]
for item in tickets_list:
new_str=item.strip("T")
ids.append(int(new_str))
sorted_ids = sorted(ids)
temp_ids = []
print("Sorted: ",sorted_ids)
#size = len(sorted_ids)
for i in range(len(sorted_ids)-1):
temp_ids.append(sorted_ids[i])
if sorted_ids[i]+1 != sorted_ids[i+1] :
temp_ids.insert(i+1,"V")
print(temp_ids)
#print(sorted_ids)
tickets_list = ['T20', 'T5', 'T10', 'T1', 'T2', 'T8', 'T16', 'T17', 'T9', 'T4', 'T12', 'T13', 'T18']
print("Ticket ids of all the available students :")
print(tickets_list)
result=arrange_tickets(tickets_list)
Actual Result: [1, 2, 'V', 4, 'V', 5, 8, 'V', 9, 'V', 10, 12, 'V', 13, 16, 17, 18]
Expected Result: [T1, T2, V, T4, T5, V, V, T8, T9, T10, V, T12, T13, V, V, T16, T17, T18, V, T20]
Here is a list comprehension which gets you what you want:
sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]
a = sorted_ids[0]
b = sorted_ids[-1]
nums = set(sorted_ids)
expected = ["T" + str(i) if i in nums else 'V' for i in range(a,b+1)]
print(expected)
Output:
['T1', 'T2', 'V', 'T4', 'T5', 'V', 'V', 'T8', 'T9', 'T10', 'V', 'T12', 'T13', 'V', 'V', 'T16', 'T17', 'T18', 'V', 'T20']
Here is a solution:
sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]
def arrange(inList):
newList = []
newList.append('T'+str(inList[0]))
for i in range(1,len(inList)):
diff = inList[i] - inList[i-1]
if diff > 1:
for d in range(diff-1):
newList.append('V')
newList.append('T'+str(inList[i]))
else:
newList.append('T'+str(inList[i]))
return newList
print(arrange(sorted_ids))
Output:
['T1', 'T2', 'V', 'T4', 'T5', 'V', 'V', 'T8', 'T9', 'T10', 'V', 'T12', 'T13', 'V', 'V', 'T16', 'T17', 'T18', 'V', 'T20']
Here's another solution worth considering:
sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]
for i in range(min(sorted_ids), max(sorted_ids)):
if sorted_ids[i] != i + 1:
sorted_ids.insert(i, 'V')
final_list = [ "T" + str(x) if isinstance(x, int) else x for x in sorted_ids]
result:
['T1', 'T2', 'V', 'T4', 'T5', 'V', 'V', 'T8', 'T9', 'T10', 'V', 'T12', 'T13', 'V', 'V', 'T16', 'T17', 'T18', 'V', 'T20']
temp_ids.insert(i+1,"V")
This is the troublesome statement.
Update your code in following way
temp_ids=[]
for i in range(len(sorted_ids)-1):
temp_ids.append(sorted_ids[i])
if sorted_ids[i]+1 != sorted_ids[i+1] :
for i in range(sorted_ids[i+1]-sorted_ids[i]-1):
temp_ids.append("V") # appends as many V's as required
temp_ids.append(sorted_ids[-1]) # appends last element
This should work
Suppose sorted array is [1,2,6]
So our desired output should be [1,2,'V','V','V',6]. So every time
sorted_ids[i]+1 != sorted_ids[i+1]
condition holds, we will have to append few numbers of V's. Now to determine how many V's we append, see that between 2 and 6 , 3 V's will be appended. So in general we append (sorted_ids[i+1] - sorted[i] -1) V's.
Now see this line
for i in range(len(sorted_ids)-1):
Because of this line, our list only runs for [1,2] in [1,2,6] , and we never append 6 in our For Loop, so after exiting For Loop it was appended.
First consider what ids should be in the list, assuming they start from 1 and end with the largest one present. Then check if each expected id is actually present, and if not put a "V" there. As a side-effect this also sorts the list.
def arrange_tickets(tickets_list):
ids = [int(ticket[1:]) for ticket in tickets_list]
expected_ids = range(1, max(ids) + 1)
return ["T%d" % n if n in ids else "V" for n in expected_ids]
tickets_list = ['T20', 'T5', 'T10', 'T1', 'T2', 'T8', 'T16', 'T17', 'T9', 'T4', 'T12', 'T13', 'T18']
print("Ticket ids of all the available students :")
print(tickets_list)
result=arrange_tickets(tickets_list)
print(result)
result:
Ticket ids of all the available students :
['T20', 'T5', 'T10', 'T1', 'T2', 'T8', 'T16', 'T17', 'T9', 'T4', 'T12', 'T13', 'T18']
['T1', 'T2', 'V', 'T4', 'T5', 'V', 'V', 'T8', 'T9', 'T10', 'V', 'T12', 'T13', 'V', 'V', 'T16', 'T17', 'T18', 'V', 'T20']
You can use this itertools recipe to first group consecutive numbers:
from itertools import groupby
from operator import itemgetter
def groupby_consecutive(lst):
for _, g in groupby(enumerate(lst), lambda x: x[0] - x[1]):
yield list(map(itemgetter(1), g))
sorted_ids = [1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]
print(list(groupby_consecutive(lst=sorted_ids)))
# [[1, 2], [4, 5], [8, 9, 10], [12, 13], [16, 17, 18], [20]]
Then you can make a function that gets the interspersing V values from the previous groupings:
def interperse(lst):
for x, y in zip(lst, lst[1:]):
yield ["V"] * (y[0] - x[-1] - 1)
groups = list(groupby_consecutive(lst))
print(list(interperse(groups)))
# [['V'], ['V', 'V'], ['V'], ['V', 'V'], ['V']]
Then you can finally zip the above results together:
def add_prefix(lst, prefix):
return [prefix + str(x) for x in lst]
def create_sequences(lst, prefix='T'):
groups = list(groupby_consecutive(lst))
between = list(interperse(groups))
result = add_prefix(groups[0], prefix)
for x, y in zip(between, groups[1:]):
result.extend(x + add_prefix(y, prefix))
return result
sorted_ids = [1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]
print(create_sequences(lst=sorted_ids))
# ['T1', 'T2', 'V', 'T4', 'T5', 'V', 'V', 'T8', 'T9', 'T10', 'V', 'T12', 'T13', 'V', 'V', 'T16', 'T17', 'T18', 'V', 'T20']
In one shot, directly form the original array
array = ['T20', 'T5', 'T10', 'T1', 'T2', 'T8', 'T16', 'T17', 'T9', 'T4', 'T12', 'T13', 'T18']
You can define a method that does all the job:
def add_vs_between_not_cons(array):
iterable = sorted(array, key= lambda x: int(x[1:]))
i, size = 0, len(iterable)
while i < size:
delta = int(iterable[i][1:]) - int(iterable[i-1][1:])
for _ in range(delta-1):
yield "V"
yield iterable[i]
i += 1
So, you can call:
print(list(add_vs_between_not_cons(array)))
#=> ['T1', 'T2', 'V', 'T4', 'T5', 'V', 'V', 'T8', 'T9', 'T10', 'V', 'T12', 'T13', 'V', 'V', 'T16', 'T17', 'T18', 'V', 'T20']
my solution for infytq queries:
def arrange_tickets(tickets_list):
ids = [int(ticket[1:]) for ticket in tickets_list]
expected_ids = range(1, max(ids) + 1)
listt=["T%d" % n if n in ids else "V" for n in expected_ids]
list1=listt[0:10]
list2=listt[11:]
for i in range(10):
if 'V' in list2:
list2.remove('V')
for j in range(0,len(list2)):
for n, i in enumerate(list1):
if i == 'V':
list1[n] = list2[j]
j+=1
return list1
tickets_list = ['T5','T7','T1','T2','T8','T15','T17','T19','T6','T12','T13']
print("Ticket ids of all the available students :")
print(tickets_list)
result=arrange_tickets(tickets_list)
print()
print("Ticket ids of the ten students in Group-1:")
print(result[0:10])
I have this 2 lists as input:
list1 = [['A', 14, 'I', 10, 20], ['B', 15, 'S', 30, 40], ['C', 16, 'F', 50, 60]]
list2 = [['A', 14, 'Y', 0, 200], ['B', 15, 'M', 0, 400], ['C', 17, 'G', 0, 600]]
and my desired output will be this:
finalList = [['A', 14, 'Y', 10, 200], ['B', 15, 'M', 30, 400], ['C', 16, 'F', 50, 60],['C', 17, 'G', 0, 600]]
Using this function:
def custom_merge(list1, list2):
finalList = []
for sub1, sub2 in zip(list1, list2):
if sub1[1]==sub2[1]:
out = sub1.copy()
out[2] = sub2[2]
out[4] = sub2[4]
finalList.append(out)
else:
finalList.append(sub1)
finalList.append(sub2)
return finalList
I will get indeed my desired output, but what if I switch positions (list2[1] and list2[2]) and my list2:
list2 = [['A', 14, 'Y', 0, 200], ['C', 17, 'G', 0, 600], ['B', 15, 'M', 0, 400]]
Then the output will be this:
[['A', 14, 'Y', 10, 200], ['B', 15, 'S', 30, 40], ['C', 17, 'G', 0, 600], ['C', 16, 'F', 50, 60], ['B', 15, 'M', 0, 400]]
(notice the extra ['B', 15, 'M', 0, 400])
What I have to modify in my function in order to get my first desired output if my lists have a different order in my list of lists!? I use python 3. Thank you!
LATER EDIT:
Merge rules:
When list1[listindex][1] == list2[listindex][1] (ex: when 14==14), replace in list1 -> list2[2] and list2[4] (ex: 'Y' and 200) and if not just add the unmatched list from list2 to list1 as it is (like in my desired output) and also keep the ones that are in list1 that aren't matched(ex: ['C', 16, 'F', 50, 60])
To be noted that list1 and list2 can have different len (list1 can have more lists than list2 or vice versa)
EDIT.2
I found this:
def combine(list1,list2):
combined_list = list1 + list2
final_dict = {tuple(i[:2]):tuple(i[2:]) for i in combined_list}
merged_list = [list(k) + list (final_dict[k]) for k in final_dict]
return merged_list
^^ That could work, still testing!
You can sort the lists by the first element in the sublists before merging them.
def custom_merge(list1, list2):
finalList = []
for sub1, sub2 in zip(sorted(list1), sorted(list2)):
if sub1[1]==sub2[1]:
out = sub1.copy()
out[2] = sub2[2]
out[4] = sub2[4]
finalList.append(out)
else:
finalList.append(sub1)
finalList.append(sub2)
return finalList
tests:
list1 = [['A', 14, 'I', 10, 20], ['B', 15, 'S', 30, 40], ['C', 16, 'F', 50, 60]]
list2 = [['A', 14, 'Y', 0, 200], ['C', 17, 'G', 0, 600], ['B', 15, 'M', 0, 400]]
custom_merge(list1, list2)
# returns:
[['A', 14, 'Y', 10, 200],
['B', 15, 'M', 30, 400],
['C', 16, 'F', 50, 60],
['C', 17, 'G', 0, 600]]
Reference: Is there a faster way of converting a number to a name?
In the question referenced above, a solution was found for turning a numbe into a name. This question asks just the opposite. How can you convert a name back into a number? So far, this is what I have:
>>> import string
>>> HEAD_CHAR = ''.join(sorted(string.ascii_letters + '_'))
>>> TAIL_CHAR = ''.join(sorted(string.digits + HEAD_CHAR))
>>> HEAD_BASE, TAIL_BASE = len(HEAD_CHAR), len(TAIL_CHAR)
>>> def number_to_name(number):
"Convert a number into a valid identifier."
if number < HEAD_BASE:
return HEAD_CHAR[number]
q, r = divmod(number - HEAD_BASE, TAIL_BASE)
return number_to_name(q) + TAIL_CHAR[r]
>>> [number_to_name(n) for n in range(117)]
['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', '_', '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', 'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'A_', 'Aa', 'Ab', 'Ac', 'Ad', 'Ae', 'Af', 'Ag', 'Ah', 'Ai', 'Aj', 'Ak', 'Al', 'Am', 'An', 'Ao', 'Ap', 'Aq', 'Ar', 'As', 'At', 'Au', 'Av', 'Aw', 'Ax', 'Ay', 'Az', 'B0']
>>> def name_to_number(name):
assert name, 'Name must exist!'
head, *tail = name
number = HEAD_CHAR.index(head)
for position, char in enumerate(tail):
if position:
number *= TAIL_BASE
else:
number += HEAD_BASE
number += TAIL_CHAR.index(char)
return number
>>> [name_to_number(number_to_name(n)) for n in range(117)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 54]
The function number_to_name works perfectly, and name_to_number works up until it gets to number 116. At that point, the function returns 54 instead. Does anyone see the code's problem?
Solution based on recursive's answer:
import string
HEAD_CHAR = ''.join(sorted(string.ascii_letters + '_'))
TAIL_CHAR = ''.join(sorted(string.digits + HEAD_CHAR))
HEAD_BASE, TAIL_BASE = len(HEAD_CHAR), len(TAIL_CHAR)
def name_to_number(name):
if not name.isidentifier():
raise ValueError('Name must be a Python identifier!')
head, *tail = name
number = HEAD_CHAR.index(head)
for char in tail:
number *= TAIL_BASE
number += TAIL_CHAR.index(char)
return number + sum(HEAD_BASE * TAIL_BASE ** p for p in range(len(tail)))
Unfortunately, these identifiers don't yield to traditional constant base encoding techniques. For example "A" acts like a zero, but leading "A"s change the value. In normal number systems leading zeroes do not. There could be multiple approaches, but I settled on one that calculates the total number of identifiers with fewer digits, and starts from that.
def name_to_number(name):
assert name, 'Name must exist!'
skipped = sum(HEAD_BASE * TAIL_BASE ** i for i in range(len(name) - 1))
val = reduce(
lambda a,b: a * TAIL_BASE + TAIL_CHAR.index(b),
name[1:],
HEAD_CHAR.index(name[0]))
return val + skipped