I am trying to create function that takes an input name and outputs a rank based on the order of the letters it has for example a=1
b=2
name = ab
rank = 3
import string
x = "richard"
y = "donald"
c = "Sam"
numbers = []
for i in range(1,27):
numbers.append(i)
print(numbers)
alphabet_string = string.ascii_lowercase
alphabet_list = list(alphabet_string)
print(alphabet_list)
new_x = list(x)
new_y = list(y)
new_c = list(c)
zip_iterators = zip(alphabet_list,numbers)
dic = list(zip_iterators)
print(dic)
def rank(name):
rank = 0
for l in range(0,len(name)):
for k,v in dic:
if l == k:
v = rank
print(rank)
rank(new_c)
but I failed so far
CodePudding user response:
letter_rank = {letter:rank for rank, letter in enumerate(string.ascii_lowercase, 1)}
def rank(name):
return sum(letter_rank.get(c, 0) for c in name.lower())
CodePudding user response:
You can just use the ascii_lowercase
constant in the string
module:
from string import ascii_lowercase
def rank(x):
total = 0
for char in x:
if char in ascii_lowercase:
total = ascii_lowercase.index(char) 1
return total
print(rank('abc'))
Output: 6
CodePudding user response:
You could use ascii_lowercase.index(letter)
or create a dictionary to lookup the rank of a letter. (My example doesnt't include caps, but you could do so if you wish)
lookup with dictionary
from string import ascii_lowercase
alphabet_lookup = {letter:i 1 for i, letter in enumerate(ascii_lowercase)}
def rank(name):
return sum(alphabet_lookup[c] for c in name.lower())
print(rank('baa')) # outputs 4
str.index
def rank(name):
return sum(ascii_lowercase.index(c) 1 for c in name.lower())
CodePudding user response:
You can use ord()
built-in function and list comprehension to create the function you need as follows:
x = "Villalobos Velasquez Santiago"
def fun(s):
out = 0
for i in s.lower():
if i != " ":
out = (ord(i)-96)
return out
print(fun(x))
Output:
333