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']
Related
I have a string and I need to replace "e" with "x" one at a time. For e.g.
x = "three"
Then the expected output is:
("thrxe", "threx")
and if I have 3 characters to replace, for e.g.
y = "threee"
Then the expected output will be:
("thrxee", "threxe", "threex")
I have tried this:
x.replace("e", "x", 1) # -> 'thrxe'
But not sure how to return the second string "threx".
Try this
x = "threee"
# build a generator expression that yields the position of "e"s
# change "e"s with "x" according to location of "e"s yielded from the genexp
[f"{x[:i]}x{x[i+1:]}" for i in (i for i, e in enumerate(x) if e=='e')]
['thrxee', 'threxe', 'threex']
You could use a generator to replace e with x sequentially through the string. For example:
def replace(string, old, new):
l = len(old)
start = 0
while start != -1:
start = string.find(old, start + l)
if start != -1:
yield string[:start] + new + string[start + l:]
z = replace('threee', 'e', 'x')
for s in z:
print(s)
Output:
thrxee
threxe
threex
Note I've generalised the code to allow for arbitrary length match and replacement strings, if you don't need that just replace l (len(old)) with 1.
def replace(string,old,new):
f = string.index(old)
l = list(string)
i = 0
for a in range(string.count(old)):
l[f] = new
yield ''.join(l)
l[f]=old
try:
f = string.index(old,f+1)
except ValueError:
pass
i+=1
z = replace('threee', 'e', 'x')
for a in z:
print(a)
OUTPUT
thrxee
threxe
threex
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
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.
import re
import math
def encode(n, strng):
for z in range (n):
temp = []
spcPos = []
for i , x in enumerate(strng):
if x == ' ':
spcPos.append(i)
strng = re.sub(' ', '', strng)
for i in range (len(strng)):
temp.append(strng[i - n])
temp2 = []
ezEnu = 0
for i in temp:
if ezEnu in (spcPos):
temp2.append(' ')
ezEnu += 1
temp2.append(i)
ezEnu += 1
temp2 = ''.join(temp2)
temp2 = temp2.split()
temp = []
withSpc = []
withSpc2 = []
oglen = []
for i in temp2:
oglen.append(len(i))
for x in range (math.ceil(n / len(i))):
withSpc.append(i)
withSpc2.append(''.join(withSpc))
withSpc = []
newa = []
for i, x in enumerate(withSpc2):
for y in range(int(oglen[i])):
newa.append(x[y - n])
temp2 = []
ezEnu = 0
for i in newa:
if ezEnu in (spcPos):
temp2.append(' ')
ezEnu += 1
temp2.append(i)
ezEnu += 1
strng = ''.join(temp2)
return(''.join([str(n), ' ', strng]))
How can I take a string, and make it so the escape sequences are treated as regular characters?
I have this function encode that takes a string and encodes it. The problem is when I receive strings that have a / in or any escape sequence, it ignores them and does not treat it as part of the message to encode.
I have no control over the strings that come into the function, they are predefined.
From what I understand r'' only works on new strings.
Thanks :)
depending on what you want exactly you might check whether this is sufficient for your use case.
def encode(n, strng):
return repr(strng)[1:-1]
I have a list like this:
a = [c0001203, c0334, c0000456, c034554, c00034506]. I need to remove 'c' and all 0 after 'c', until the data starts with a number. The length of each data is variable. The output should be like this:
a = [1203, 334, 456, 34506]. How can I do it without using regular expression?
Thank you.
You can drop the c and then .strip() the 0's like:
Code:
b = [x[1:].lstrip('0') for x in a]
Test Code:
a = ['c0001203', 'c0334', 'c0000456', 'c034554', 'c00034506']
b = [x[1:].lstrip('0') for x in a]
print(b)
Results:
['1203', '334', '456', '34554', '34506']
start iterating from index=1 (ignore 0th index) until you find a non-zero character. store the sub_string starting from non-zero character till the end
def process(str_arr):
ind = 0
res = []
while(ind < len(str_arr)):
cur_str = str_arr[ind]
ind_2 = 1
while(ind_2 < len(cur_str)):
char = cur_str[ind_2]
if(char != '0'):
res.append(cur_str[ind_2:len(cur_str)])
break;
ind_2 = ind_2+1
ind = ind+1
return res
ret = process(['c0001203', 'c0334', 'c0000456', 'c034554', 'c00034506'])
print(ret)
Output :
['1203', '334', '456', '34554', '34506']