Locating specific keys and corresponding values in dictionary - python

I wrote the following piece of code:
def all_di(fl):
dmm = {}
for k in range(2):
for i in fl:
for m in range (len(i)-1):
temp = i[m:m+k+1]
if temp in dmm:
dmm[temp] += 1.0
else:
dmm[temp] = 1.0
## return dmm
p = raw_input("Enter a 2 AA long seq:")
sum = 0
for x,y in dmm.iteritems():
if x == p:
n1 = y
for l,m in dmm.iteritems():
if l[0] == p[0]:
sum = sum + m
print float(n1)/float(sum)
all_di(inh)
if inh = {'VE':16,'GF':19,'VF':23,'GG' :2}
The code works as follows:
Enter a 2 AA long seq: VE
result will be = 16/(16+23) = 0.41
How it works: the function searches the dictionary dmm for the key similar to the one entered in input (example taken here 'VE'). It stores its value and then searches for all the key-value pairs that have the 1st letter in common and adds all its values and returns a fraction.
VE = 16
**V**E + **V**F = 39
= 16/39 = 0.41
What I want: keeping the function intact, I want to have a secondary dictionary that iterates for every key-value pair in the dictionary and stores the fractional values of it in a different dictionary such that:
new_dict = {'VE' : 0.41, 'GF':0.90,'VF':0.51, 'GG': 0.09}
I don't want to remove the print statement as it is the output for my program. I however need the new_dict for further work.

def all_di(fl,p=0):
dmm = {}
interactive = p == 0
if interactive:
p = raw_input("Enter a 2 AA long seq:")
if p in fl:
numer = fl[p]
denom = 0.0
for t in fl:
if t[0] == p[0]:
denom = denom + fl[t]
if interactive:
print numer / denom
return numer / denom
inh = {'VE':16,'GF':19,'VF':23,'GG' :2}
all_di(inh)
new_dict = {x:all_di(inh, x) for x in inh}
print new_dict

Related

I want to add the variable name

Is there any solution to my problem??
My code:-
import random
for val in range(1,201):
val = str(val)
a + val = random.randint(0,99)
b + val = random.randint(0,99)
c + val = random.randint(0,99)
I want result to be a1 = random number, b2 = random number, c3 = random number and so on upto 200
Thanks for any assistance in advance
You could use dictionaries.
import string
letters = list(string.ascii_lowercase)
dictVars = {y[0]+str(x+1):y[1] for x,y in enumerate(zip(letters,list(range(1,3))))}
output
{'a1': 1, 'b2': 2}
Then search through this to find each variables value
print(dictVars['a1'])
output
1
Just use arrays instead
a = []
b = []
c = []
for val in range(1,41):
a.append(1)
b.append(2)
c.append(3)
Access using a[n-1] for any value of n in the range

Conditional Probability- Python

I'm working on this python problem:
Given a sequence of the DNA bases {A, C, G, T}, stored as a string, returns a conditional probability table in a data structure such that one base (b1) can be looked up, and then a second (b2), to get the probability p(b2 | b1) of the second base occurring immediately after the first. (Assumes the length of seq is >= 3, and that the probability of any b1 and b2 which have never been seen together is 0. Ignores the probability that b1 will be followed by the end of the string.)
You may use the collections module, but no other libraries.
However I'm running into a roadblock:
word = 'ATCGATTGAGCTCTAGCG'
def dna_prob2(seq):
tbl = dict()
levels = set(word)
freq = dict.fromkeys(levels, 0)
for i in seq:
freq[i] += 1
for i in levels:
tbl[i] = {x:0 for x in levels}
lastlevel = ''
for i in tbl:
if lastlevel != '':
tbl[lastlevel][i] += 1
lastlevel = i
for i in tbl:
print(i,tbl[i][i] / freq[i])
return tbl
tbl['T']['T'] / freq[i]
Basically, the end result is supposed to be the final line tbl you see above. However, when I try to do that in print(i,tbl[i][i] /freq[i), and run dna_prob2(word), I get 0.0s for everything.
Wondering if anyone here can help out.
Thanks!
I am not sure what it is your code is doing, but this works:
def makeprobs(word):
singles = {}
probs = {}
thedict={}
ll = len(word)
for i in range(ll-1):
x1 = word[i]
x2 = word[i+1]
singles[x1] = singles.get(x1, 0)+1.0
thedict[(x1, x2)] = thedict.get((x1, x2), 0)+1.0
for i in thedict:
probs[i] = thedict[i]/singles[i[0]]
return probs
I finally got back to my professor. This is what it was trying to accomplish:
word = 'ATCGATTGAGCTCTAGCG'
def dna_prob2(seq):
tbl = dict()
levels = set(seq)
freq = dict.fromkeys(levels, 0)
for i in seq:
freq[i] += 1
for i in levels:
tbl[i] = {x:0 for x in levels}
lastlevel = ''
for i in seq:
if lastlevel != '':
tbl[lastlevel][i] += 1
lastlevel = i
return tbl, freq
condfreq, freq = dna_prob2(word)
print(condfreq['T']['T']/freq['T'])
print(condfreq['G']['A']/freq['A'])
print(condfreq['C']['G']/freq['G'])
Hope this helps.

Python custom comparator to sort a specific list

I have an input list like [1,2,2,1,6] the task in hand is to sort by the frequency. I have solved this question and am getting the output as [1,2,6].
But the caveat is that if two of the numbers have the same count like count(1) == count(2). So the desired output is [2,1,6]
then in the output array, 2 must come before 1 as 2 > 1.
So for the input [1,1,2,2,3,3] the output should be [3,2,1]. The counts are the same so they got sorted by their actual values.
This is what I did
input format:
number of Test cases
The list input.
def fun(l):
d = {}
for i in l:
if i in d:
d[i] += 1
else:
d[i] = 1
d1 = sorted(d,key = lambda k: d[k], reverse=True)
return d1
try:
test = int(input())
ans = []
while test:
l = [int(x) for x in input().split()]
ans.append(fun(l))
test -= 1
for i in ans:
for j in i:
print(j, end = " ")
print()
except:
pass
I think that this can help you. I added reverse parameter that is setting by default to True, because that gives the solution, but I wrote in the code where you can edit this as you may.
Here is the code:
from collections import defaultdict # To use a dictionary, but initialized with a default value
def fun(l, reverse = True):
d = defaultdict(int)
# Add count
for i in l:
d[i] += 1
# Create a dictionary where keys are values
new_d = defaultdict(list)
for key,value in d.items():
new_d[value].append(key)
# Get frequencies
list_freq = list(new_d.keys())
list_freq.sort(reverse = reverse) #YOU CAN CHANGE THIS
list_freq
# Add numbers in decreasing order by frequency
# If two integers have the same frequency, the greater number goes first
ordered_list = []
for number in list_freq:
values_number = new_d[number]
values_number.sort(reverse = reverse) # YOU CAN CHANGE THIS
ordered_list.extend(values_number)
return ordered_list
Examples:
l = [1,2,2,1,6]
fun(l)
#Output [2,1,6]
I hope this can help you!

Python 2D array with same values

I am a beginner programmer and I am doing a task for school. The task is to assign 4 constant variables and then use a code to work out the value. Each value has a corresponding letter and the program is asking the user to type in 5 numbers then the program will return the word. The code is the following:
array = [["L","N"], #define the 2d array, L=Letters, N=Numbers
["-","-"]] #line for space
a = 2#define the variables
b = 1
c = 7
d = 4
e = (a*b)+b#calcualtions
f = c+b
g = (d/a)-b
h = c*a
i = a+b+d
j = c-a
k = c-d*f
l = c+a
m = (c*a)-b
n = a*d
o = a+d-b
p = (c*d)-a*(b+d)
q = a*(c+(d-b))
r = (d*d)-b
s = r-f-g
array.append(["e",e])
array.append(["f",f])
array.append(["g",g])#append all the calculations
array.append(["h",h])
array.append(["i",i])
array.append(["j",j])
array.append(["k",k])
array.append(["l",l])
array.append(["m",m])
array.append(["n",n])
array.append(["o",o])
array.append(["p",p])
array.append(["q",q])
array.append(["r",r])
array.append(["s",s])
def answer():
len_row = len(array)
number_input = int(input("Enter number: "))
for i in range(len_row):
if number_input == (array[i][1]):
return array[i][0]
break
one_let = answer()
two_let = answer()
thr_let = answer()
fou_let = answer()
fiv_let = answer()
print(one_let,two_let,thr_let,fou_let,fiv_let)
The numbers that I am meant to put in are 6, 18,, 7, 8, and 3.
The word that prints is "spife" and the word that is meant to be printed is "spine". The problem is that there are two letters that have a variable of 8 and Python gets the first one only. Is there a way to print out the two seperate words but first with the first variable in a 2D array and second with the second 2D array? i.e spife then spine
Thank you for your help ahead, I am just a beginner! :)
Yes you can do it but is a bit tricky the secret is to use itertools.product on the list of letters that could have each of the five values.
First you need to use a better data structure such as a dict, (in this case a collection.defaltdict) to hold the letters that have some value. You can do this way:
import collections
import itertools
a = 2#define the variables
b = 1
c = 7
d = 4
e = (a*b)+b#calcualtions
f = c+b
g = (d/a)-b
h = c*a
i = a+b+d
j = c-a
k = c-d*f
l = c+a
m = (c*a)-b
n = a*d
o = a+d-b
p = (c*d)-a*(b+d)
q = a*(c+(d-b))
r = (d*d)-b
s = r-f-g
dat = collections.defaultdict(list)
for c in "abcdefghijklmnopqrs":
dat[eval(c)].append(c)
Now in dat you have a list of letters that match some number, for example
print(dat[6])
print(dat[18])
print(dat[7])
print(dat[8])
print(dat[3])
Outputs:
['s']
['p']
['i']
['f', 'n']
['e']
OK, then you need to change answerto return a list of letters, and collect the user input:
def answer():
number_input = int(input("Enter number: "))
return dat[number_input]
letts = [answer() for _ in range(5)] #collect five answers of the user
And the final magic is done here:
for s in map(lambda x: "".join(x),itertools.product(*letts)):
print(s)
Now if you are confused then study:
collections
collections.defaultdict
itertools
itertools.product
str.join

list object not callable project euler 59

I am trying to do project euler problem 59, i am having an issue in that one of the necessary methods won't work as the program returns:
xorNum = test(f,j)
TypeError: 'list' object is not callable.
Both f and j are integers and when I used the test method with two random integers, it worked perfectly. Does anyone have any ideas why it may not be working?
def main():
cipherText = """79,59,12,2,79,35,8,28,20,2,3,68,8,9,68,45,0,12,9,67,68,4,7,5,23,27,1,21,79,85,78,79,85,71,38,10,71,27,12,2,79,6,2,8,13,9,1,13,9,8,68,19,7,1,71,56,11,21,11,68,6,3,22,2,14,0,30,79,1,31,6,23,19,10,0,73,79,44,2,79,19,6,28,68,16,6,16,15,79,35,8,11,72,71,14,10,3,79,12,2,79,19,6,28,68,32,0,0,73,79,86,71,39,1,71,24,5,20,79,13,9,79,16,15,10,68,5,10,3,14,1,10,14,1,3,71,24,13,19,7,68,32,0,0,73,79,87,71,39,1,71,12,22,2,14,16,2,11,68,2,25,1,21,22,16,15,6,10,0,79,16,15,10,22,2,79,13,20,65,68,41,0,16,15,6,10,0,79,1,31,6,23,19,28,68,19,7,5,19,79,12,2,79,0,14,11,10,64,27,68,10,14,15,2,65,68,83,79,40,14,9,1,71,6,16,20,10,8,1,79,19,6,28,68,14,1,68,15,6,9,75,79,5,9,11,68,19,7,13,20,79,8,14,9,1,71,8,13,17,10,23,71,3,13,0,7,16,71,27,11,71,10,18,2,29,29,8,1,1,73,79,81,71,59,12,2,79,8,14,8,12,19,79,23,15,6,10,2,28,68,19,7,22,8,26,3,15,79,16,15,10,68,3,14,22,12,1,1,20,28,72,71,14,10,3,79,16,15,10,68,3,14,22,12,1,1,20,28,68,4,14,10,71,1,1,17,10,22,71,10,28,19,6,10,0,26,13,20,7,68,14,27,74,71,89,68,32,0,0,71,28,1,9,27,68,45,0,12,9,79,16,15,10,68,37,14,20,19,6,23,19,79,83,71,27,11,71,27,1,11,3,68,2,25,1,21,22,11,9,10,68,6,13,11,18,27,68,19,7,1,71,3,13,0,7,16,71,28,11,71,27,12,6,27,68,2,25,1,21,22,11,9,10,68,10,6,3,15,27,68,5,10,8,14,10,18,2,79,6,2,12,5,18,28,1,71,0,2,71,7,13,20,79,16,2,28,16,14,2,11,9,22,74,71,87,68,45,0,12,9,79,12,14,2,23,2,3,2,71,24,5,20,79,10,8,27,68,19,7,1,71,3,13,0,7,16,92,79,12,2,79,19,6,28,68,8,1,8,30,79,5,71,24,13,19,1,1,20,28,68,19,0,68,19,7,1,71,3,13,0,7,16,73,79,93,71,59,12,2,79,11,9,10,68,16,7,11,71,6,23,71,27,12,2,79,16,21,26,1,71,3,13,0,7,16,75,79,19,15,0,68,0,6,18,2,28,68,11,6,3,15,27,68,19,0,68,2,25,1,21,22,11,9,10,72,71,24,5,20,79,3,8,6,10,0,79,16,8,79,7,8,2,1,71,6,10,19,0,68,19,7,1,71,24,11,21,3,0,73,79,85,87,79,38,18,27,68,6,3,16,15,0,17,0,7,68,19,7,1,71,24,11,21,3,0,71,24,5,20,79,9,6,11,1,71,27,12,21,0,17,0,7,68,15,6,9,75,79,16,15,10,68,16,0,22,11,11,68,3,6,0,9,72,16,71,29,1,4,0,3,9,6,30,2,79,12,14,2,68,16,7,1,9,79,12,2,79,7,6,2,1,73,79,85,86,79,33,17,10,10,71,6,10,71,7,13,20,79,11,16,1,68,11,14,10,3,79,5,9,11,68,6,2,11,9,8,68,15,6,23,71,0,19,9,79,20,2,0,20,11,10,72,71,7,1,71,24,5,20,79,10,8,27,68,6,12,7,2,31,16,2,11,74,71,94,86,71,45,17,19,79,16,8,79,5,11,3,68,16,7,11,71,13,1,11,6,1,17,10,0,71,7,13,10,79,5,9,11,68,6,12,7,2,31,16,2,11,68,15,6,9,75,79,12,2,79,3,6,25,1,71,27,12,2,79,22,14,8,12,19,79,16,8,79,6,2,12,11,10,10,68,4,7,13,11,11,22,2,1,68,8,9,68,32,0,0,73,79,85,84,79,48,15,10,29,71,14,22,2,79,22,2,13,11,21,1,69,71,59,12,14,28,68,14,28,68,9,0,16,71,14,68,23,7,29,20,6,7,6,3,68,5,6,22,19,7,68,21,10,23,18,3,16,14,1,3,71,9,22,8,2,68,15,26,9,6,1,68,23,14,23,20,6,11,9,79,11,21,79,20,11,14,10,75,79,16,15,6,23,71,29,1,5,6,22,19,7,68,4,0,9,2,28,68,1,29,11,10,79,35,8,11,74,86,91,68,52,0,68,19,7,1,71,56,11,21,11,68,5,10,7,6,2,1,71,7,17,10,14,10,71,14,10,3,79,8,14,25,1,3,79,12,2,29,1,71,0,10,71,10,5,21,27,12,71,14,9,8,1,3,71,26,23,73,79,44,2,79,19,6,28,68,1,26,8,11,79,11,1,79,17,9,9,5,14,3,13,9,8,68,11,0,18,2,79,5,9,11,68,1,14,13,19,7,2,18,3,10,2,28,23,73,79,37,9,11,68,16,10,68,15,14,18,2,79,23,2,10,10,71,7,13,20,79,3,11,0,22,30,67,68,19,7,1,71,8,8,8,29,29,71,0,2,71,27,12,2,79,11,9,3,29,71,60,11,9,79,11,1,79,16,15,10,68,33,14,16,15,10,22,73"""
asciiDict = {} #create ascii table dictionary with number as key
asciiDict2 = {} #reverse key value of above dictionary
for char in range(256):
keyVal = "%d: %c" % (char, char)
slicer = keyVal.index(':')
key = keyVal[0:slicer]
val = keyVal[slicer+2:]
asciiDict[int(key)] = val
for key in asciiDict.keys():
newVal = asciiDict[key]
asciiDict2[newVal] = key
newlist = [int(n) for n in cipherText.split(',')]
#convert cipher text into list of numbers
listOfThreeChars = []
for n in range(len(newlist)):
listOfThreeChars.append(newlist[n:n+3])
#create list of groups of three consecutive numbers in cipherText
mostCommonDict = mostCommon(listOfThreeChars)
mostFrequent3 = mostCommonDict[max(mostCommonDict.keys())]
#most common three consecutive numbers, if the key is right these
#numbers will become a common three letter word such as 'the'
print testCipher(asciiDict,asciiDict2, 'jhd', mostFrequent3)
def testCipher(asciiDict,asciiDict2, cipherKey, cipherExtract):
cipherKeyAscii = []
test = []
output = []
for k in cipherKey:
asciiNum = asciiDict2[k]
cipherKeyAscii.append(asciiNum)
print cipherKeyAscii
for i in range(len(cipherKeyAscii)):
f,j = cipherKeyAscii[i],cipherExtract[i]
print type(f), type(j),f,j
xorNum = test(f,j) #HERE IS WHERE THE PROBLEM IS
test.append(xorNum)
for final in test:
letter = asciiDict[final]
output.append(letter)
return output
def mostCommon(lst): #find most common three consecutive number combinations in text
dic = {}
for three in lst:
key = three
count = []
for n in lst:
if n == key:
count.append(1)
dic[len(count)] = key
return dic
#return max(set(sum(lst, [])), key=sum(lst, []).count)
def toBinary(decimalNumber):
quotient = 1
remainder = 0
tmpNum = decimalNumber
finalNumberList = []
n = ""
#e.g. take 14...
while quotient != 0:
remainder = decimalNumber % 2 #14 % 2 = 0
quotient = decimalNumber / 2 #14 / 2 = 7
decimalNumber = quotient # 7 % 2 = 1 and so on...
finalNumberList.insert( 0, remainder )
# Used because all numbers are in a list, i.e. convert to string
for num in finalNumberList:
n += str( num )
return n
def XOR(number1, number2):
number1List = []
number2List = []
XORoutput = []
for i in str(number1): #turn both binary numbers into lists
number1List.append(int(i))
for i in str(number2):
number2List.append(int(i))
if len(number1List)>len(number2List): #make sure they are same lengths
diff = len(number1List) - len(number2List)
for i in range(diff):
number2List.insert(0,0)
for i in range(len(number1List)): #XOR it
if number1List[i] == number2List[i]:
XORoutput.append(0)
if number1List[i] != number2List[i]:
XORoutput.append(1)
num = int(''.join(map(str,XORoutput))) #turn XOR list into int
return num
def test(num1, num2): #convert input to binary and xor and return to integer
print num1,num2
bin1 = toBinary(num1) #turn to binary
bin2 = toBinary(num2)
xor = XOR(bin1,bin2) #XOR
output = int(str(xor),2) #return to number
return output
if __name__ == "__main__":
#print main.__doc__
main()
You set test to a list; you cannot have both a function and a list use the same name:
def main():
# other code
test = []
# more code
for i in range(len(cipherKeyAscii)):
# more irrelevant code
xorNum = test(f,j)
test.append(xorNum)
masking the function test(). You even use test as a list again on the very next line.
Rename the list, or rename the function. Most of all, pick better, clearer names for your variables.
You defined test to be a list. You also defined it to be a function. De-conflict your names and you should be good to go.

Categories