Python numeric values for letters in string [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am having trouble solving the following question,
Q: Given a string find out the total sum of all the numbers.
Values are as A-1, B-10, C-100, D-1000, E-10000.
Ex. DDBC. Answer is 1000+1000+10+100 = 2110.

There are lots of ways to go about this.
Here's one idea:
Make a lookup that maps letters to the their values. Something like:
import string
lookup = {s: 10**i for i,s in enumerate(string.ascii_uppercase)}
Lookup will be a dictionary like:
{
'A': 1,
'B': 10,
'C': 100,
'D': 1000,
'E': 10000,
'F': 100000,
...
}
With that you can use a comprehension and take the sum:
>> s = "DDBC"
>> sum(lookup[l] for l in s)
2110
This, of course, assumes your string is all uppercase, like the example you posted.

just deduce the power of 10 by the position of the letter:
s = "DDBC"
result = sum(10**(ord(c)-ord('A')) for c in s)
result: 2110
You can filter out lowercase letters & other chars easily, but that complexifies a little bit:
result = sum(10**(ord(c.upper())-ord('A')) for c in s if c.isalpha())

Try searching the string, and every instance of that letter occurring causes you to add to total.
For instance:
total = 0
input_string = input()
for i in len(input_string):
if input_string[i] == "A":
total += 1
and then you can repeat that for the other instances of the other characters.
Hope I helped!

Related

I want to create a function where for every word of the alphabet [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I want to create a function where for every word of the alphabet the user uses for an input, the console returns the following:
a = 0
b = 00
c - 000
And sow on...
Example: Sow if the user put the input of "abc", the console will print out: 000000
In my code, i can't seem to add the letters, hers the code:
def codifier():
userImp = input(str("write a word: "))
if userImp == "a":
print("0")
else:
userImp == "b"
print("00")
print(userImp)
codifier()
MY question is how would you write the code?
Make a dictionary mapping characters to the symbol you want.
>>> m = {'a':'0','b':'00', 'c':'000'}
Then use it along with a user's input
>>> r = input('??')
??ab
>>> ''.join(m[c] for c in r)
'000'
>>> r = input('??')
??ac
>>> ''.join(m[c] for c in r)
'0000'
>>> r = input('??')
??abc
>>> ''.join(m[c] for c in r)
'000000'
>>>
Here is a simple program that does what you are asking for:
def codifier():
userImp = input(str("write a word: "))
for char in userImp:
print(end="0" * (ord(char) - ord('a') + 1))
codifier()

How to duplicate numbers in string n times? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have this string (61,62,63,64) and i want to tranform the string into (61,61,62,62,62,62,63,64).
I want to duplicate the numbers in the string n times, the 61 i want to duplicate twice, the 62 i want to duplicate four times, how do i code something that duplicates a number in the string n times?
Can you possible do something like have annother string that tells the computer how many times to duplicate each number? (61, 62, 63, 64,) (2,4,1,1)
if both your inputs are strings:
a = '(61, 62, 63, 64,)'
b = '(2,4,1,1)'
a = [i for i in a[1:-1].strip().replace(" ","").split(",")]
a.remove('')
b = [int(i) for i in b[1:-1].strip().replace(" ","").split(",")]
result = "("
for i in range(len(b)):
for j in range(b[i]):
result += a[i]
result += ", "
result = result.strip()[:-1]+")"
print(result)
Here is a possible solution (if rep is a string and not a tuple, you just need to do rep = eval(rep)):
s = "(61,62,63,64)"
rep = (2,4,1,1)
# convert the string to a tuple
t = eval(s)
# compute the result as a tuple
result = tuple(x for i, x in enumerate(t) for _ in range(rep[i]))
# convert the result into a string
result = str(result)
If you want something more compact:
s = "(61,62,63,64)"
rep = (2,4,1,1)
result = str(tuple(x for i, x in enumerate(eval(s)) for _ in range(rep[i])))
Be careful with using eval!! Check this question for more info.

How can I generate all possible words with a specified set of characters? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I play to HackNet game and i have to guess a word to bypass a firewall.
The key makes 6 characters long and contains the letters K,K,K,U,A,N.
What is the simplest way to generate all possible combinations either in bash or in python ? (bonus point for bash)
Here is a backtracking-based solution in Python:
db = {"K" : 3, "U" : 1, "A" : 1, "N" : 1}
N = 6
def possibilities(v):
l = []
for k in db.keys():
if v.count(k) < db[k]:
l.append(k)
return l
def generateImpl(a):
if len(a) < N:
lst = []
for c in possibilities(a):
lst += generateImpl(a+[c])
return lst
else:
return [''.join(a)]
def generate():
return generateImpl([])
Just run generate() to obtain a list of possible words.
You have 6 letters and need to find a combination of 6 letters. If you are not using the same character in ['K','K','K','U','A','N'] again and again, then there is only 1 permutation.
If you can use the same character again and again, you can use the following code to generate all possible combinations.
import itertools
y = itertools.combinations_with_replacement(['K','U','A','N'],6)
for i in list(y):
print(i)

Compare values stored in variables, then print the variable name [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have tried to use the max code but it printed out the largest number not the variable name.
a=3
b=4
c=7
d=6
e=8
max(a,b,c,d,e)
this is the code I've tried but it printed 8 instead of e.
forgot to add that my values for a b c etc came from a loop so im not suppose to know their values myself...
You need to use a dictionary or a named tuple to do something like that.
>>> my_list = {'a': 1, 'b': 2, 'c': 3}
>>> max(my_list, key=my_list.get)
'c'
Let me know if there are any other methods.
Try this
dct={'a':3 ,'b':4 ,'c':7 ,'d':6 ,'e':8}
for i, j in dct.iteritems():
if j == max(dct.values()):
print i
From this question, there seems to be a way to retrieve the name of your variable (see caveat below before using):
a = 3
b = 4
c = 7
d = 6
e = 8
m = max(a, b, c, d, e)
for k, v in list(locals().items()):
if v is m:
v_as_str = k
break
v_as_str
output:
'e'
Caveat:
This may work if you can be sure that there are no other (unrelated) variables with the same value as the max of a to e
somewhere in your code, and appearing earlier in the locals.
Thanks to #D.Everhard & #asongtoruin in the comments

Creating my own string functions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
def tlower(str1):
list = list(str1)
final = ''
for char in range(0,len(str1)):
if list[char] in UPPERCASE:
for ascii in range(0,len(UPPERCASE)):
if list[char] == UPPERCASE[ascii]:
list[char] = LOWERCASE[ascii]
final += list[char]
return final
NOTE - UPPERCASE and LOWERCASE are strings of all upper/lowercase letters
NOTE - can NOT use any string functions built into python (Replace, etc..)
I have this function to turn any string into all lower case, (Yes i know there is a built in function..) But compared to my other string functions I have created, this is fairly long, any better approach I should take to do doing this?
UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
def to_lower(s, trans=dict(zip(UPPERCASE, LOWERCASE))):
return ''.join(trans.get(ch,ch) for ch in s)
print to_lower('This Is a TEST') # => 'this is a test'
Edit:
zip() takes two lists and returns pairs of values, ie
zip('ABC', 'abc') # => [('A','a'), ('B','b'), ('C','c')]
dict() makes a dictionary - in this case,
{'A':'a', 'B':'b', 'C':'c'}
trans.get(x, y) is a more compact way of saying as trans[x] if x in trans else y. In this case, "if you have a lowercase version of this letter, return it, otherwise give back the original letter".
and if you don't like .join, how about reduce?
from operator import add
def to_lower(s, trans=dict(zip(UPPERCASE, LOWERCASE))):
return reduce(add, (trans.get(ch,ch) for ch in s), '')
For completeness:
def to_lower(string):
ords = (ord(c) for c in string)
return ''.join(chr(o + 32 * (65 <= o <= 90)) for o in ords)

Categories