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']
Related
Is there way to split or chunk the dynamic string into fixed size? let me explain:
Suppose:
name = Natalie
Family = David12
length = len(name) #7 bit
length = len(Family) # 7 bit
i want to split the name and family into and merging as :
result=nadatavilid1e2
and again split and extract the the 2 string as
x= Natalie
y= david
another Example:
Name = john
Family= mark
split and merging:
result= jomahnrk
and again split and extract the the 2 string as
x=john
y= mark
.
Remember variable name and family have different size length every time not static! . i hope my question is clear. i have seen some related solution about it like here and here and here and here and here and here and here but none of these work with what im looking for. Any suggestion ?? Thanks
i'm using spyder python 3.6.4
I have try this code split data into two parts:
def split(data):
indices = list(int(x) for x in data[-1:])
data = data[:-1]
rv = []
for i in indices[::-1]:
rv.append(data[-i:])
data=data[:-i]
rv.append(data)
return rv[::-1]
data='Natalie'
x,c=split(str(data))
print (x)
print (c)
Given you have stated names will always be of equal length you could use wrap to split in to 2 char pairs and the zip and chain to join them up. In the split part you can again use wwrap to split in 2 char pairs but if the number of pairs is odd then you need to split the last pair into 2 single entries. something like.
from textwrap import wrap
from itertools import chain
def merge_names(name, family):
name_split = wrap(name, 2)
family_split = wrap(family, 2)
return "".join(chain(*zip(name_split, family_split)))
def split_names(merged_name):
names = ["", ""]
char_pairs = wrap(merged_name, 2)
if len(char_pairs) % 2:
char_pairs.append(char_pairs[-1][1])
char_pairs[-2] = char_pairs[-2][0]
for index, chars in enumerate(char_pairs):
pos = 1 if index % 2 else 0
names[pos] += chars
return names
print(merge_names("john", "mark"))
print(split_names("jomahnrk"))
print(merge_names("stephen", "natalie"))
print(split_names("stnaeptaheline"))
print(merge_names("Natalie", "David12"))
print(split_names("NaDatavilid1e2"))
OUTPUT
jomahnrk
['john', 'mark']
stnaeptaheline
['stephen', 'natalie']
NaDatavilid1e2
['Natalie', 'David12']
Something like:
a = "Eleonora"
b = "James"
l = max(len(a), len(b))
a = a.lower() + " " * (l-len(a))
b = b.lower() + " " * (l-len(b))
n = 2
a = [a[i:i+n] for i in range(0, len(a), n)]
b = [b[i:i+n] for i in range(0, len(b), n)]
ans = "".join(map(lambda xy: "".join(xy), zip(a, b))).replace(" ", "")
Giving for this example:
eljaeomenosra
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)]
Here is my question
count += 1
num = 0
num = num + 1
obs = obs_%d%(count)
mag = mag_%d%(count)
while num < 4:
obsforsim = obs + mag
mylist.append(obsforsim)
for index in mylist:
print index
The above code gives the following results
obs1 = mag1
obs2 = mag2
obs3 = mag3
and so on.
obsforrbd = parentV = {0},format(index)
cmds.dynExpression(nPartilce1,s = obsforrbd,c = 1)
However when i run the code above it only gives me
parentV = obs3 = mag3
not the whole list,it only gives me the last element of the list why is that..??
Thanks.
I'm having difficulty interpreting your question, so I'm just going to base this on the question title.
Let's say you have a list of items (they could be anything, numbers, strings, characters, etc)
myList = [1,2,3,4,"abcd"]
If you do something like:
for i in myList:
print(i)
you will get:
1
2
3
4
"abcd"
If you want to convert this to a string:
myString = ' '.join(myList)
should have:
print(myString)
>"1 2 3 4 abcd"
Now for some explanation:
' ' is a string in python, and strings have certain methods associated with them (functions that can be applied to strings). In this instance, we're calling the .join() method. This method takes a list as an argument, and extracts each element of the list, converts it to a string representation and 'joins' it based on ' ' as a separator. If you wanted a comma separated list representation, just replace ' ' with ','.
I think your indentations wrong ... it should be
while num < 4:
obsforsim = obs + mag
mylist.append(obsforsim)
for index in mylist:
but Im not sure if thats your problem or not
the reason it did not work before is
while num < 4:
obsforsim = obs + mag
#does all loops before here
mylist.append(obsforsim) #appends only last
The usual pythonic way to spit out a list of numbered items would be either the range function:
results = []
for item in range(1, 4):
results.append("obs%i = mag_%i" % (item, item))
> ['obs1 = mag_1', 'obs2 = mag_2', 'ob3= mag_3']
and so on (note in this example you have to pass in the item variable twice to get it to register twice.
If that's to be formatted into something like an expression you could use
'\n'.join(results)
as in the other example to create a single string with the obs = mag pairs on their own lines.
Finally, you can do all that in one line with a list comprehension.
'\n'.join([ "obs%i = mag_%i" % (item, item) for item in range (1, 4)])
As other people have pointed out, while loops are dangerous - its easier to use range
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
i have a code looking like this:
import HTSeq
reference = open('genome.fa','r')
sequences = dict( (s.name, s) for s in HTSeq.FastaReader(reference))
out = open('homopolymers_in_ref','w')
def find_all(a_str,sub):
start = 0
while True:
start = a_str.find(sub, start)
if start == -1: return
yield start
start += len(sub)
homa = 'AAAAAAAAAA'
homc = 'CCCCCCCCCC'
homg = 'GGGGGGGGGG'
homt = 'TTTTTTTTTT'
for key,line in sequences.items():
seq = str(line)
a= list(find_all(seq,homa))
c = list(find_all(seq,homc))
g = list(find_all(seq,homg))
t = list(find_all(seq,homt))
for i in a:
## print i,key,'A'
out.write(str(i)+'\t'+str(key)+'\t'+'A'+'\n')
for i in c:
out.write(str(i)+'\t'+str(key)+'\t'+'C'+'\n')
## print i,key,'C'
for i in g:
out.write(str(i)+'\t'+str(key)+'\t'+'G'+'\n')
for i in t:
out.write(str(i)+'\t'+str(key)+'\t'+'T'+'\n')
out.close()
I used HTSeq to open the reference. What it does - it looks for simple homopolymers of length 10 and outputs start position, chromosome and type (A,C,T,G,).
THE sequence always looks like:
ACCGCTACGATCGATCGAAAAAAAAAAAAAAAAAACGATCGAC
sometimes it contains N
so our homopolymer that we are looking for is:
AAAAAAAAAA (or other composed of only C,G,T)
Basically the help from you is about the find_all function only:
Now what I would like to change is finding the length of each homopolymer. Since, right now if a homopolymer has a length 15, my script can't tell it.
I was thinking of doing it by some sort of regex, namely: find at least 10 bp like now and compute length by adding +1 to it until the next base isn't like those in homopolymer.
Any suggestions how to use a regex to do it in python?
If you want to do this with a regex you can try something like:
>>> import re
>>> seq = 'ACCGCTACGATCGATCGAAAAAAAAAAAAAAAAAACGATCGAC'
>>>
>>> [(m.group(), m.start())
... for m in re.finditer(r'([ACGT])\1{9,}', seq)
... if len(m.group()) >= 10]
[('AAAAAAAAAAAAAAAAAA', 17)]
This produces a list of (sequence, start_index) tuples.