I want to add the variable name - python

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

Related

I am trying to create a function that inputs a name and outputs a rank. what is the best way to create that function?

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
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())
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
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())
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

How can i return if inside def

enter = ('255.255.0.0')
def ff (s):
s = s.split('.')
B1 = str(bin(int(s[0])))
B2 = str(bin(int(s[1])))
B3 = str(bin(int(s[2])))
B4 = str(bin(int(s[3])))
s = B1[2:],B2[2:],B3[2:],B4[2:]
for i in s:
if len(i) < 8:
i = 8 - len(i)
r =i * '0'
return s
print(ff(enter))
what is wrong in above code? i need the output should be like the [11111111,11111111,00000000,0000000]
Bazingaa pointed out the problem of your code and offered a fix. Here is another way to fix your problem:
def ff (s):
s = s.split('.')
s = [bin(int(x)) for x in s] # ['0b11111111', '0b11111111', '0b0', '0b0']
s = [x[2:] for x in s] # ['11111111', '11111111', '0', '0']
s = [x.zfill(8) for x in s] # ['11111111', '11111111', '00000000', '00000000']
return s
Or we can combine those lines together:
def ip_to_binary(ip):
return [bin(int(x))[2:].zfill(8) for x in ip.split('.')]
Notes
The key here is to use the zfill method, which is part of a string object
The function bin returns a string, so we don't need to call str to convert it to string again
Please avoid using cryptic names such as ff, s, ... They makes the code harder to understand
Avoid using parentheses unnecessarily: enter = ('255.255.0.0') is the same as enter = '255.255.0.0'
You were close. The problem was that you were not updating your s for the 0 values when len(j) < 8.
The fix is that you convert your tuple s to a list and then update the values for 0 as follows. I have commented the modified lines.
enter = ('255.255.0.0')
def ff (s):
s = s.split('.')
B1 = str(bin(int(s[0])))
B2 = str(bin(int(s[1])))
B3 = str(bin(int(s[2])))
B4 = str(bin(int(s[3])))
s = B1[2:],B2[2:],B3[2:],B4[2:]
s = list(s) # Convert tuple to list
for i, j in enumerate(s): # Enumerate to access index for modifying
if len(j) < 8:
j = 8 - len(j)
s[i] = j * '0'
return s
print(ff(enter))
# ['11111111', '11111111', '0000000', '0000000']

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

Locating specific keys and corresponding values in dictionary

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

Python: Replace ith occurence of x with ith element in list

Suppose we have a string a = "01000111000011" with n=5 "1"s. The ith "1", I would like to replace with the ith character in "ORANGE".
My result should look like:
b = "0O000RAN0000GE"
What could be the finest way to solve this problem in Python? Is it possible to bind an index to each substitution?
Many thanks!
Helga
Tons of answers/ways to do it. Mine uses a fundamental assumption that your #of 1s is equal to the length of the word you are subsituting.
a = "01000111000011"
a = a.replace("1", "%s")
b = "ORANGE"
print a % tuple(b)
Or the pythonic 1 liner ;)
print "01000111000011".replace("1", "%s") % tuple("ORANGE")
a = '01000111000011'
for char in 'ORANGE':
a = a.replace('1', char, 1)
Or:
b = iter('ORANGE')
a = ''.join(next(b) if i == '1' else i for i in '01000111000011')
Or:
import re
a = re.sub('1', lambda x, b=iter('ORANGE'): b.next(), '01000111000011')
s_iter = iter("ORANGE")
"".join(next(s_iter) if c == "1" else c for c in "01000111000011")
If the number of 1's in your source string doesn't match the length of your replacement string you can use this solution:
def helper(source, replacement):
i = 0
for c in source:
if c == '1' and i < len(replacement):
yield replacement[i]
i += 1
else:
yield c
a = '010001110001101010101'
b = 'ORANGE'
a = ''.join(helper(a, b)) # => '0O000RAN000GE01010101'
Improving on bluepnume's solution:
>>> from itertools import chain, repeat
>>> b = chain('ORANGE', repeat(None))
>>> a = ''.join((next(b) or c) if c == '1' else c for c in '010001110000110101')
>>> a
'0O000RAN0000GE0101'
[EDIT]
Or even simpler:
>>> from itertools import chain, repeat
>>> b = chain('ORANGE', repeat('1'))
>>> a = ''.join(next(b) if c == '1' else c for c in '010001110000110101')
>>> a
'0O000RAN0000GE0101'
[EDIT] #2
Also this works:
import re
>>> r = 'ORANGE'
>>> s = '010001110000110101'
>>> re.sub('1', lambda _,c=iter(r):next(c), s, len(r))
'0O000RAN0000GE0101'

Categories