choose variable via input (python) - python

i wanna choose the variable via an input
a=1
b=2
c=3
x=input("a/b/c")
The Idea is now that the calculation is 7 times 1 and therefore the solution: 7
solution=7*a
print(solution)
But python recognizes the input as string not as a variable. How do i change that?

You need to create a 'lookup table' that will map the chars to numbers.
lookup = {'a':1,'b':2,'c':3}
x=input("a/b/c: ")
value = lookup.get(x)
if value is None:
print('invalid input')
else:
print(f'Solution is {7 * value}')

You can turn a string into a variable like this.
a = 1
b = 2
c = 3
x = input("a/b/c: ")
x = locals()[x]
solution = 7 * x
print(solution)

Related

Python - multiple combinations maths question

I'm trying to make a program that lists all the 64 codons/triplet base sequences of DNA...
In more mathematical terms, there are 4 letters: A, T, G and C.
I want to list all possible outcomes where there are three letters of each and a letter can be used multiple times but I have no idea how!
I know there are 64 possibilities and I wrote them all down on paper but I want to write a program that generates all of them for me instead of me typing up all 64!
Currently, I am at this point but I have most surely overcomplicated it and I am stuck:
list = ['A','T','G','C']
list2 = []
y = 0
x = 1
z = 2
skip = False
back = False
for i in range(4):
print(list[y],list[y],list[y])
if i == 0:
skip = True
else:
y=y+1
for i in range(16):
print(list[y],list[y],list[x])
print(list[y],list[x], list[x])
print(list[y],list[x], list[y])
print(list[y],list[x], list[z])
if i == 0:
skip = True
elif z == 3:
back = True
x = x+1
elif back == True:
z = z-1
x = x-1
else:
x = x+1
z = z+1
Any help would be much appreciated!!!!
You should really be using itertools.product for this.
from itertools import product
l = ['A','T','G','C']
combos = list(product(l,repeat=3 ))
# all 64 combinations
Since this produces an iterator, you don't need to wrap it in list() if you're just going to loop over it. (Also, don't name your list list — it clobbers the build-in).
If you want a list of strings you can join() them as John Coleman shows in a comment under your question.
list_of_strings = ["".join(c) for c in product(l,repeat=3) ]
Look for for pemuations with repetitions there tons of code available for Python .
I would just use library , if you want to see how they implemented it look inside the library . These guys usually do it very efficiency
import itertools
x = [1, 2, 3, 4, 5, 6]
[p for p in itertools.product(x, repeat=2)]

is this the method for comparing an interger which i made it str to check if is a string List?

i am trying to compare an "i" counter whitch is interger with a list whitch inludes str numbers , and add it in a string variable
LPL = ["1","2","3"]
f = str()
for i in range (x):
if str(i) == LPL[i]:
f+=str(i)
i expected the f variable had the result of the comparsion: f = 123
List index starts from 0:
LPL = ["1","2","3"]
s = ""
for i in range(1,len(LPL)+1):
if i == int(LPL[i-1]):
s+=str(i)
print(s)
Note that you should use a range from a number to a number and also that python indexes starts from 0, so you need to adapt the code in a way like:
LPL = ["1","2","3"]
f = str()
for i in range (1, len(LPL)+1):
### note that your LPL[0] == 1 and not LPL[1] == 1, so you need to decreasee a number here, that's why a +1 in the range too
if str(i) == LPL[i-1]:
f+=str(i)
### OUTPUT
>>> f
'123'
Perhaps I missing something, but if you wish to combine the elements of the list, either by conjoining strings or adding integers, consider using reduce:
LPL = ["1","2","3"]
LPL2 = [1,2,3]
f = reduce(lambda a,b : a+b, LPL) # "123"
f_int = reduce(lambda a,b : a+b, LPL) # 6

Random.choice not working correctly python

I have the following code for example:
n = ['321','243','780']
b = ['12','56','90']
a = ['178', '765', '111']
E = input('Enter Word...')
qw = 1
Code = ('')
E_ready = [E[no:no+qw] for no in range(0, len(E), qw)]
for code in E_Ready:
letter = random.choice(code)
Code += letter
If you enter the word 'nba' then it will output as 'nba', I want it to output with random elements from each letter's respective list so for example '32112178'
As Willem van Onsem correctly mentioned in the comments:
"...that is really bad design, call-by-name is rather unsafe. You better use a dictionary."
So, try this:
n = {'option1':'321','option2':'243','option3':'780'}
letter = random.choice(list(n.values()))
Or, shorter, as Chris has mentioned:
d = {'n':[321, 243, 780]}
letter = random.choice(d['n'])
Results from print(letter) (on both options):
321
321
780
243
etc..
EDIT:
How to add extra variables:
n = 'n'
d = {n:[321, 243, 780]}
letter = random.choice(d[n])
q = 'q'
d[q] = [600, 234, 180]
new_letter = random.choice(d[q])
Now print(new_letter) gives:
234
180
180
600
etc..
SECOND EDIT (which btw is pure bonus since the question turned into a completely different one then first asked.. therefor, it is left unoptimized. Yet, working nonetheless..):
import random
d = {'n':[321, 243, 780], 'b':['12','56','90'], 'a':['178', '765', '111']}
E = input('Enter Word...')
inputword = list(E)
for key in d.keys():
if key in inputword:
for i in range(len(inputword)):
if inputword[i] == key:
try:
inputword[i] = str(random.choice(d[key]))
except:
pass
result = ''.join(inputword)
print(result)
If input = nba then output = 32190111
If input = nhhsygbbvvra then output = 321hhsyg5690vvr178
Etc..
Okay, you have a few fundamental issues.
When you want to assign one variable to another then you wouldn't put it in quotes.
So it should be:
code = n
But actually I'm wondering why you need the variable code at all.
You could simply do
import random
code = [ '321', '243', '780' ]
letter = random.choice(code)
print letter
I agree with the comment, it is better to use something like:
d = {'n':[mylist]}
letter = random.choice(d['n'])
the problem is that random.choice works on strings too... it simply considers them to be a list of characters. in your case the code variable and n are supposed to be exactly the same but are in fact not. You could also do
n = [list]
code = n ## only makes any sense, if there
## is a procedure assigns it based on some condition
letter = random.choice(code)

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

Python divide user in put by 4

How can I divide the user input by 4?
example = input("Enter input")
so abcdefghjklmnopqrstu is 20 characters and I want to divide them by 4 so Ill have 5 characters list then I will append them all into a newlist?
I am new to python and using Python IDLE 3.3
I would like to get the total of user's input character then divided them by 4 so when I want to append them to a list it would look something like this
list = [abcde],[ghijk],[lmnop],[qrstu]
Here is my current code
user = input('ENTER TEXT: ')
user.upper()
print('Decrypting message: ', user)
for i in range(0, len(user), 4):
temp.append(user[i:i+4])
for i in range(0, len(user), 1):
print(temp[i])
You could use textwrap.wrap() for this:
>>> import textwrap
>>> s = "abcdefghjklmnopqrstu"
>>> textwrap.wrap(s, len(s)/4)
['abcde', 'fghjk', 'lmnop', 'qrstu']
In case you don't want to use any library, can achieve it using loop:
a = "abcdefghijklmnopqrstu"
l = len(a); i = 0; r = []
while i < l and len(a) >= 4:
r.append(a[:l/4])
a = a[l/4:]
i += l/4
print (r)
['abcde', 'fghij', 'klmno', 'pqrst']

Categories