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)
Related
I have a programm that returns too many results, so i want to take only the useful results that are above the average. My question is in a string length N that is produced from alphabet of k letters, how many times in average all substrings length m occurs? For example in the string "abcbbbbcbabcabcbcab" of alphabet {a,b,c} how many times in average all the substrings of length 3 occurs, abc occurs 3 times, bbb occurs 2 times (i count it even if they overlap), and so on. Or is there a way to know it from python (where my code is) before executing the programm?
Do you want to count the substrings in a specific string, or do you want the theoretical average in the general case? The probability that a string with length m of an alphabet with k characters occurs at any given position is 1/(k^m), so if your string is N characters long, that would make an expected number of occurrences of(N-m+1)/(k^m) (-m+1 because the string can not appear in the last m-1 positions). Another way to see this is as the number of substrings of length m (N-m+1) divided by the number of different such substrings (k^m).
You can calculate the average counts for your example, to see whether the formula gets to about the right result. Of course, one should not expect too much, as it's a very small sample size...
>>> s = "abcbbbbcbabcabcbcab"
>>> N = len(s)
>>> k = 3
>>> m = 3
For this, the formula gives us
>>> (N-m+1)/(k**m)
0.6296296296296297
We can count the occurrences for all the three-letter strings using itertools.product and a count function (str.count will not count overlapping strings correctly):
>>> count = lambda x: sum(s[i:i+m] == x for i in range(len(s)))
>>> X = [''.join(cs) for cs in itertools.product("abc", repeat=3)]
>>> counts = [count(x) for x in X]
In this case, this gives you exactly the same result as the formula. (I'm just as surprised as you.)
>>> sum(counts)/len(counts)
0.6296296296296297
So I'm a freshman comp sci major. I'm taking a class that teaches Python. This is my assignment:
Create a function that takes a string and a list as parameters. The string should contain the first ten letters of the alphabet and the list should contain the corresponding numbers for each letter. Zip the string and list into a list of tuples that pair each letter and number. The function should then print the number and corresponding letter respectively on separate lines. Hint: Use the zip function and a loop!
This is what I have so far:
def alpha(letter, number):
letter = "abcdefghij"
number = [1,2,3,4,5,6,7,8,9,10]
return zip(letter, number)
print alpha(letter, number)
The problem I have is an error on line 5 that says 'letter' is not defined. I feel like there should be a for loop but, I don't know how to incorporate it. Please help me.
zip works on iterables (strings and lists are both iterables), so you don't need a for loop to generate the pairs as zip is essentially doing that for loop for you. It looks like you want a for loop to print the pairs however.
Your code is a little bit confused, you'd generally want to define your variables outside of the function and make the function as generic as possible:
def alpha(letter, number):
for pair in zip(letter, number):
print pair[0], pair[1]
letter = "abcdefghij"
number = [1,2,3,4,5,6,7,8,9,10]
alpha(letter, number)
The error you are having is due to the scope of the variables. You are defining letter and number inside of the function, so when you call alpha(letter,number) they have not been defined.
For printing the result you could iterate the result of zip, as in the following example:
def alpha(letters, numbers):
for c,n in zip(letters,numbers):
print c,n
letters = "abcdefghij"
numbers = range(1,11)
alpha(letters, numbers)
Output:
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
I'm currently trying to make a cipher program, here is my code;
import string
import random
matrix = []
codedmessage = []
letter = "ABCDEF"
message = input("Enter message to be encoded:\n").upper().replace(' ', '')
print ('---MESSAGE---\n', message)
newlist = list(string.ascii_uppercase + string.digits)
random.shuffle(newlist)
print ('---MATRIX---')
for x in range(0,len(newlist),6):
matrix.append(list(newlist[x:x+6]))
for letter in message:
for y, vector in matrix:
for s, member in vector:
if letter == member:
codedmessage.append(letter[x], letter[y])
for i in range(len(matrix)):
print(matrix[i])
However, when I compile this I get the error;
for y, vector in matrix: ValueError: too many values to unpack
(expected 2)
Can anyone shed some light on this as to why it is happening and give a solution?
Thanks
matrix.append(list(newlist[x:x+6]))
You append 6 element lists to matrix, but you try to unpack them into two variables later:
for y, vector in matrix:
The numbers have to match.
Currently you matrix looks like [ [4,3,2,6,3,2], [2,1,6,8,9,2], ... ]. How is python supposed to unpack one of the elements, for example [4,3,2,6,3,2] into y and vector? What should go where? (For possible solutions see the other answers, they were faster. I don't understand what behaviour is expected anyway.)
Also you cannot index a character:
codedmessage.append(letter[x], letter[y])
previously you assigned a single character to letter, here:
for letter in message:
because message is a string. You probably confuse names as you already have assigned a string to letter initially: letter = "ABCDEF" Probably you want to use two different names.
append does only take one argument, too. Again I don't know what you expect, but I guess it should be either codedmessage.append([letter[x], letter[y]]) or codedmessage += [letter[x], letter[y]].
I also highly doubt that you want to use x in codedmessage.append(letter[x], letter[y]) because you only used x in another independent loop as iteration variable.
Each element of matrix is a list of six items, so if you only provide two variable names on the left-hand side, Python doesn't know what to do with the other four.
However, you can (in Python 3) unpack back into a list like this:
>>> a, *b = [1,2,3,4,5,6]
>>> a
1
>>> b
[2, 3, 4, 5, 6]
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
>>>
I'm looking for help on a function that takes a string, and replaces every character in that string in every way. I'm not quite sure how to word my question so that it makes sense so I'll show you what it's supposed to do.
stars('1')
returns ['*']
stars('12')
returns ['*1', '1*', '**']
stars('123')
returns ['*23', '1*3', '12*', '**3', '*2*', '**1', '***']
stars('1234')
returns ['*234', '1*34', '12*4', '123*', '**34', '*2*4', '*23*', '1**4', '1*3*',
'12**', '***4', '**3*', '*2**', '1***', '****']
Did that all out by hand, but even if I made a mistake, you should get the idea of what I'm looking for now. The final case (all *'s) isn't required but I put it in there to make sure the problem was understood.
Here is what I've come up with so far but it doesn't quite work.
def stars(n):
lst = []
length = len(n)
for j in xrange(0, length):
p = list(n)
for k in xrange(j, length):
p[k] = '*'
lst += [''.join(p)]
return lst
Output:
'1' returns ['*']
'12' returns ['*2', '**', '1*']
'123' returns ['*23', '**3', '***', '1*3', '1**', '12*']
'1234' returns ['*234', '**34', '***4', '****', '1*34', '1**4', '1***', '12*4', '12**', '123*']
Any help would be greatly appreciated. Would like this answered in Python if possible, but if you don't know Python, then pseudocode or another language would be acceptable. If it's written clearly, I'm sure I could convert it into Python on my own.
I think the canonical approach in Python would be to use the itertools module:
>>> from itertools import product, cycle
>>> s = 'abcde'
>>> [''.join(chars) for chars in product(*zip(s, cycle('*')))]
['abcde', 'abcd*', 'abc*e', 'abc**', 'ab*de', 'ab*d*', 'ab**e', 'ab***',
'a*cde', 'a*cd*', 'a*c*e', 'a*c**', 'a**de', 'a**d*', 'a***e', 'a****',
'*bcde', '*bcd*', '*bc*e', '*bc**', '*b*de', '*b*d*', '*b**e', '*b***',
'**cde', '**cd*', '**c*e', '**c**', '***de', '***d*', '****e', '*****']
and then you could just toss the first one without any stars, but that might seem a little magical.
ISTM you have two other approaches if you don't want to use the built-in Cartesian product function: you can use recursion, or you can take advantage of the fact that you want to turn each star on and off, a binary switch. That means with n letters you'll have 2^n (-1, if you remove the no-star case) possibilities to return, and whether or not to put a star somewhere corresponds to whether or not the corresponding bit in the number is set (e.g. for 'abc' you'd loop from 1 to 7 inclusive, 1 = 001 so you'd put a star in the last place, 7 = 111 so you'd put a star everywhere, etc.)
This last one is pretty simple to implement, so I'll leave that for you. :^)
You can look at this as a problem of finding and iterating over all subsequences of characters in your original string. (For every subsequence, replace the characters in it by '*', and leave the rest alone).
For a given subsequence, each character is either in it or not, so for an N-character string, there are 2^N subsequences. Probably the easiest way to iterate over them is to iterate over the integers from 0 to (2^N)-1, and use their binary representations as the indications of whether the character should be replaced or not
For N=3, it looks like this:
0 000 abc
1 001 ab*
2 010 a*c
3 011 a**
4 100 *bc
5 101 *b*
6 110 **c
7 111 ***
In Python, you could do it like this:
def stars(input):
l = len(input)
for i in xrange(2**l):
yield ''.join([('*' if i&(2**(l-pos-1)) else ch) for pos, ch in enumerate(input)])
Try it out:
>>> print list(stars('abc'))
['abc', 'ab*', 'a*c', 'a**', '*bc', '*b*', '**c', '***']
Here's a way using combinations :
from itertools import combinations
def stars(str):
N,L = len(str), []
for k in range(0,N+1):
for com in combinations(range(N),k):
S = list(str)
for x in com: S[x] = '*'
L.append(''.join(S))
return L
Try it out:
>>> stars('abc')
['abc', '*bc', 'a*c', 'ab*', '**c', '*b*', 'a**', '***']
>>> stars('1234')
['1234', '*234', '1*34', '12*4', '123*', '**34', '*2*4', '*23*', '1**4', '1*3*', '12**', '***4', '**3*', '*2**', '1***', '****']
Or specific to Python see this function: http://docs.python.org/2/library/itertools.html#itertools.combinations