Changing a string into it's number value in python. [ord()] - python

I am writing a program in python that calculates the number equivalent of a string and prints it. (By number equivalent, I mean a=1 b=2 ... so the seventh letter in the alphabet is converted to the number 7.) So if the word was abc then it would turn out to be 123. And if possible, the numbers (in my example 123) are added. (So in my example the result that is printing would be 6.) I tried doing this letter by letter, using the ord() function. But that ended up being where you type each letter and press enter and then add spaces for empty letters. The code was meant to calculate the number value of each letter in the word, add all of the values, and tell True if the number was 100 or false if it was anything else. Here it is... `
#collect info
ar=raw_input('Letter')
br=raw_input('Letter')
cr=raw_input('Letter')
dr=raw_input('Letter')
er=raw_input('Letter')
fr=raw_input('Letter')
gr=raw_input('Letter')
hr=raw_input('Letter')
ir=raw_input('Letter')
jr=raw_input('Letter')
kr=raw_input('Letter')
lr=raw_input('Letter')
mr=raw_input('Letter')
nr=raw_input('Letter')
#ord it
ap=ord(ar)
bp=ord(br)
cp=ord(cr)
dp=ord(dr)
ep=ord(er)
fp=ord(fr)
gp=ord(gr)
hp=ord(hr)
ip=ord(ir)
jp=ord(jr)
kp=ord(kr)
lp=ord(lr)
mp=ord(mr)
np=ord(nr)
#sub 96
a=(ap-96)
b=(bp-96)
c=(cp-96)
d=(dp-96)
e=(ep-96)
f=(fp-96)
g=(gp-96)
h=(hp-96)
i=(ip-96)
j=(jp-96)
k=(kp-96)
l=(lp-96)
m=(mp-96)
n=(np-96)
#chk for 96
if a==-64:
a=0
if b==-64:
b=0
if c==-64:
c=0
if d==-64:
d=0
if e==-64:
e=0
if f==-64:
f=0
if g==-64:
g=0
if h==-64:
h=0
if i==-64:
i=0
if j==-64:
j=0
if k==-64:
k=0
if l==-64:
l=0
if m==-64:
m=0
if n==-64:
n=0
#add
value=a+b+c+d+e+f+g+h+i+j+k+l+m+n
#spit
if value==100:
print 'True (100)'
if value<100 or value>100:
print 'False (', value, ')'`
I can't figure out how to do this. So, an explanation would be nice, a full code re-write would be enjoyed, but not required.
-Adam
P.S. If there is anything I forgot to add to this question, just tell me.

Assuming everything is lowercase and input is only a-z
sum((ord(c) - ord('a') + 1 for c in s))

>>> from string import lowercase,uppercase
>>> alphabet = lowercase+uppercase
>>> mapper = {c:i for i,c in enumerate(alphabet,start=1)}
>>> aword = "Letter"
>>> sum(mapper[l] for l in aword)
106
Create a dictionary which maps a character c to the position it is in the alphabet i. We then pass sum a generator expression which looks up i for each character in aword, resulting in all the character values being summed.

>>> aword="iabcdefghijklm"
>>> value=sum(map(ord,aword),(1-ord("a"))*len(aword))
>>> print value==100, value
True 100
>>>

Related

How to assign specific integer to individual character in word?

I am quite new to Python so I hope someone can point me in the right direction with my question.
I want to assign a specific numeric value (integer) to a character/letter in a word (i.e. given input).
For example:
My input is ‘vase’
v= 5
a= 2
s= 7
e= 1
So now I want to calculate the “word value” by for example addition, multiplication or division or something (e.g. from ‘vase’ to the total word value, which is an integer).
When I google , I keep finding dictionary examples, but they all seem to work from the idea that a=1, b=2, c=3 etc.
How would I be able to assign self chosen values to individual characters and then calculate with these numbers?
Edit: I should have been more clear. I want to calculate values based on the complete word. So I want to set up values for individual letters which can be used to transform any string input (in this case ‘vase’) into a final value per word.
I am not sure I understand your question and what you are trying to do. If I run the maths based on the number proviuded I see
>>> 5+2+7+1%2
15
>>>
If I assign the values to the characters v a s e as you show and use the characters I get the same answer
>>>
>>> v=5
>>> a=2
>>> s=7
>>> e=1
>>> word_val = v+a+s+e%2
>>> print(word_val)
15
>>>
Like the first comment said, make your own dictionary. This is what it will look like, try to run this code:
import random
i = input().strip()
d = {}
for c in i:
d[c] = random.randint(0,26)
print(d)
# Functions on the word, suppose add
sum = 0
for c in i:
sum = sum + d[c]
print(sum)

Repeat string with a specific pattern without slicing

I'm working on a pretty annoying Python assignment and I'm lost. These are the requirements:
Ask for input.
For each character in the saved string I need to output said string with a certain modification. For example, if the input is abcd the output looks like this:
abcd
bcda
cdab
dabc
I.e. there are len(input) lines, each line begins with the next input[i] character and repeats to the length of the original input.
I should not use slicing, it's loop practice (T_T). No functions or packages. Loops only.
I made a working script that looks like this:
w = input('Type a word:')
w2 = ''
for i, char in enumerate(w):
w2 = w[i:]+w[:i]
print(w2)
It's neat and short. But it will be marked down for slicing. Can Python loop gurus please help me remake it into loops? Thanks so much in advance!
You can use indexing into the original string using a modulo on itself:
w = "aword"
lw = len(w)
for offset in range(lw):
for character in range(lw):
print(w[(offset+character) % lw], end="")
print()
Output:
aword
worda
ordaw
rdawo
dawor
If your sum of offset and character overshoots the amount of characters the modulo operation wraps it around.
If you can't slice strings, you can append and pop lists. So, convert the string to a list and work with list methods.
>>> test = "abcd"
>>> l = list(test)
>>> for _ in range(len(l)):
... print("".join(l))
... l.append(l.pop(0))
...
abcd
bcda
cdab
dabc
Just for fun another one:
s = 'aword'
ss = s * 2 # 'awordaword'
for i in range(len(s)):
for j in range(len(s)):
print(ss[i+j], end='')
print()
Output:
aword
worda
ordaw
rdawo
dawor

How to compare words in two lists according to same order in python?(I have def a function)

Recently, I def a function which can compare two words in each wordlist. However, I also found some problems here.
def printcorrectletters():
x=0
for letters in correctanswer:
for letters2 in userinput:
if letters == letters2:
x = x+1
break
return x
In this function, if the correctanswer='HUNTING', and I input 'GHUNTIN', it will show 6 letters are correct. However, I want it compare words' letters 1 by 1. So, it should march 0. For example, 'H' will match first letter of userinput.. and so on.
I also think another function which can solve it by using 'zip'. However, our TA ask me to finish it without things like 'zip'.
If the strings are different lengths, you want to compare each letter of the shorter string:
shortest_length = min(len(correctanswer), len(userinput))
min just gives you the minimum of two or more values. You could code it yourself as:
def min(a, b):
return a if a < b else b
You can index a character in a string, using [index]:
>>> 'Guanfong'[3]
n
So you can loop over all the letter indices:
correct = 0
for index in range(shortest_length):
if correctanswer[index] == userinput[index]:
correct += 1
If you did use zip and sum:
correct = sum(1 for (correct_char, user_char) in zip(correctanswer, userinput)
if correct_char == user_char)
Python provides great facilities for simplifying ideas and for communicating with the computer and programmers (including yourself, tomorrow).
Without zip you can use enumerate() to loop over elements of correctanswer , and get index and element at the same time. Example -
def printcorrectletters():
x=0
for i, letter in enumerate(correctanswer):
if i < len(userinput) and letter == userinput[i]:
x = x+1
return x
Or if even enumerate() is not allowed, simply use range() loop till len(correctanswer) and get elements from each index.

reversing a string, if it contains only mirrorable letters

here is the question. No this is not homework this is self taught.
I am attempting the following question:
The mirror image of string vow is string wov, and the mirror image wood is string boow. The mirror image of string bed cannot be represented as a string, however, because the mirror image of e is not a valid character.
The characters in the alphabet whose mirror image is a valid character are: b, d, i, o, v, w, and x. Develop function mirror() that takes a string and returns its mirror image but only if the mirror image can be represented using letters in the alphabet.
**My Code **
def mirror(word):
'''returns mirror image of word but if it can be represented
using letters in the alphabet'''
for i in range (0,len(word)):
if i == 'bdiovwx':
print(str(word.reverse))
else:
print ('NOPE')
the result i am getting is nothing. As in i execute the program and nothing prints.
Any thoughts?
Thank you
You don't need a for loop for this. Essentially, you are testing if all the characters of the word belong to one of the characters in 'bdiovwx', and so, you can just check fr exactly that - the subset relationship amongst the set of characters in word, and 'bdiovwx'.
Also, strings do not have a reverse method in python, so you can use the trick "string"[::-1] to print its reverse.
def mirror(word):
'''
returns mirror image of word but if it can be represented
using letters in the alphabet
'''
if set(word).issubset(set('bdiovwx')):
print(word[::-1])
else:
print ('NOPE')
By fixing your algorithm, you can get the results. You just need to loop through the items, add all the elements to set and compare it later if it's included in the set of alphabets u defined 'bdiovwx' , notFound is used to stop the iteration when you found variable that doesn't belong to the accepted set u defined 'bdiovwx'
word[::-1] produces the reversed word
def mirror(word):
'''returns mirror image of word but if it can be represented
using letters in the alphabet'''
i,notFound=0,True
D=set()
while notFound and i < len(list(word)):
if word[i] not in list('bdiovwx'):
notFound= False
D.add(word[i])
i+=1
if notFound and D.issubset(set(list('bdiovwx'))):
print word[::-1]
else:
print ('NOPE')
You can also use ALL operator, to verify that all the characthers in word are in 'bdiovwx', if it's True, then print the inverse, else; you print None
def mirror(word):
if all(x for x in list(word) if x in list('bdiovwx')):
print word[::-1]
else:
print ('NOPE')
Note that 'd' reflects a 'b' and 'b' reflects a 'd' in the mirror :)
def mirror(word):
letters = list("bdiovwx")
reflect_letters = list("dbiovwx")
if set(word).issubset(letters):
print ''.join([reflect_letters[letters.index(x)] for x in word[::-1]])
else:
print "NOPE!"

How to count characters in a string? (python)

# -*- coding:UTF-8 -*-
str= "Green tree"
scr= "e"
cstr= len(str)
n=0
a=0
while n < cstr:
if str[n] == scr:
print(len(scr))
n=n+1
I have to count "e" in -str- string, but when I run this script I get
1
1
1
1
instead of 4.
What's the problem?
First of all, don't use str as a variable name, it will mask the built-in name.
As for counting characters in a string, just use the str.count() method:
>>> s = "Green tree"
>>> s.count("e")
4
If you are just interested in understanding why your current code doesn't work, you are printing 1 four times because you will find four occurrences of 'e', and when an occurrence is found you are printing len(scr) which is always 1.
Instead of printing len(scr) in your if block, you should be incrementing a counter that keeps track of the total number of occurrences found, it looks like you set up a variable a that you aren't using, so the smallest change to your code to get it to work would be the following (however as noted above, str.count() is a better approach):
str= "Green tree"
scr= "e"
cstr= len(str)
n=0
a=0
while n < cstr:
if str[n] == scr:
a+=1
n=n+1
print(a)
Use the count method:
>>> st="Green tree"
>>> st.count('e')
4
If the count method is broken on your Python ;-), you can use a for loop:
st="Green tree"
tgt='e'
i=0
for c in st:
if c==tgt: i+=1
print i
# 4
If you really want a while loop:
idx=0
i=0
while idx<len(st):
if st[idx]==tgt: i+=1
idx+=1
print i
But, this being Python, a more 'Pythonic' approach if your count method broken is to use sum on a generator expression:
>>> sum(1 for c in st if c=='e')
4
scr= "e"
##
print(len(scr))
For why it's doing this, it's doing what you asked, and printing the length of the variable scr, which is always one.
You're best to use the str.count() method as others mentioned, or increment a counter yourself manually.

Categories