string replacement on python - python-3.x

I want to change the first /E after /V to X and the second /E to Y and the third /E to Z in text files.
/V may be followed by a word other than /E
The number of /E is from 1 to 3.
For example, the following string
AA/V+BB/E+CC/E+DD/E
should be changed as follows:
AA/V+X+Y+Z
This is my code and the results are correct. But I think it's inefficient.
s1 = '1/VV+12/ER+123/EED+1234/EC'
s2 = 'GG/K+AA/V+BB/E+FF/E+CC/E'
for s in [s1, s2]:
morphs = s.split('+')
lst = []
l = ['X','Y','Z']
i = 0
flag = False
while i < len(morphs):
lst.append(morphs[i])
if '/V' in morphs[i]:
for j in range(1, len(morphs)-i):
if '/E' in morphs[i+j]:
lst.append(l.pop(0))
flag = True
else:
lst.append(morphs[i+j])
i = i+j
flag = False
break
if flag:
break
i+=1
print('+'.join(lst))
Results:
1/VV+X+Y+Z
GG/K+AA/V+X+Y+Z

A simple way o do the same will be get the indices of \v and all the ,\e and then just check whether the indices of which e is more than that of V,
If it's so, then replace the E's accordingly as you said you can only have 1,2 or 3 E's in your text..

You can easily implement it in Python:
def format_string(s):
start_index = s.index('/V')
change_to = ['X', 'Y', 'Z']
for c in change_to:
if '/E' in s:
target_index = s.index('/E')
if target_index>start_index:
s = s[:target_index-2] + c + s[target_index + 2:]
return s
s1 = 'AA/V+BB/E+CC/E+DD/E'
s2 = 'AA/V+BB/E+FF/F'
expected1 = 'AA/V+X+Y+Z'
expected2 = 'AA/V+X+FF/F'
print format_string(s1)==expected1
print format_string(s2)==expected2

Related

randomly select two position in a file and swap words

I want to select n pairs of word positions (unique) in a file and swap them. My code is as following, but it never gives me n pairs I am looking for.
My logic is first to sample 2*n elements and create n pairs. Then iterate over the file contents (stored in list) and locate the correct positions and make the swap. It is not working. I have difficulty in understanding where it fails.
with open(rname) as rd:
lines = rd.readlines()
for i in range(len(lines)):
lines[i] = lines[i].strip()
sz = sum(len(x.split()) for x in lines)
chosen = random.sample(range(sz),6000)
result = pairwise(chosen)
for (a,b) in result:
flag1 = 0
flag2 = 0
l = 0
ind1 = 0
m = 0
ind2 = 0
j = 0
for y in range(len(lines)):
if ( (j+len(lines[y].split()) >= a) and (flag1 == 0)):
l = y
ind1 = a - j-1
flag1 = 1
if ( (j+len(lines[y].split()) >= b) and (flag2 == 0)):
m = y
ind2 = b - j-1
flag2 = 1
if ( (flag1 == 1) and (flag2 == 1)):
words1 = lines[l].split()
words2 = lines[m].split()
words1[ind1], words2[ind2] = 'swapped'+words2[ind2], 'swapped'+words1[ind1]
lines[l] = ' '.join(words1)
lines[m] = ' '.join(words2)
break
j += len(lines[y].split())
name ='n_file.txt'
with open(wname,'w') as wd:
for line in lines:
print(line, file=wd)
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return zip(a, b)
For example, consider a file with content
i am here, where are you
it is none of your business
Let us say i choose 2 positions (2,8) (position is defined in terms of the word positions in the file and start with 0 for the first word in the file). My output will look like
i am swappednone where are you
it is swappedhere, of your business
Not a complete solution, but this might give you some ideas:
import random
def swap_pairs(items,n):
"""swaps n distinct pairs of objects in items"""
k = len(items)
indices = random.sample(range(k),2*n)
random.shuffle(indices)
for i in range(n):
s, t = indices[2*i], indices[2*i+1]
items[s], items[t] = items[t], items[s]
This mutates the list in place.
For example, if
words = ['i', 'am', 'here,', 'where', 'are', 'you', 'it', 'is', 'none', 'of', 'your', 'business']
then after
swap_pairs(words,3)
words might be
['you', 'am', 'it', 'none', 'are', 'i', 'here,', 'is', 'where', 'of', 'your', 'business']

I am writing a code based on some formulas;but my if statement does not seem to work(line 33)

W = int(input('Enter weight:'))
b = [1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0]
AR = [1, 2, 3, 4, 5]
T = [50.99238, 50.05062, 49.07943, 48.05919, 47.00952, 45.92061, 44.79246, 43.62507, 42.42825, 41.18238, 39.90708, 38.60235, 37.24857, 35.86536, 34.4331, 32.97141, 31.48029, 29.94012, 28.37052, 26.76168, 25.1136]
CL = [1.0]
CD = [0.5]
clmax = 2
n = 0
z = 0
while b[n] < 2.1 :
while AR[z]< 5.1:
cl = CL[n]
cd = CD[z]
s = ((b[n]*b[n])/AR[z])
V = ((2*W*9.81)/(1.2*s*clmax) ** 0.5)*1.1
vlof = V/1.41
Vlof = round(vlof)
D = 0.5*cd*1.2*Vlof*Vlof*s
L = 0.5*cl*1.2*Vlof*Vlof*s
a = (9.81/W)*(T[Vlof]-D-O.O5(W-L))
Sg = (V*V)/(2*a)
if Sg <= 30:
print('IT WILL TAKEOFF')
else:
print('It will NOT takeoff')
t/c = int(input('t/c ratio is:'))
l = int(input('Taper ratio is:'))
f = 0.005(1+1.5*((l-0.6)**2))
e = (1/((1+0.12*V*V*0.003*0.003)(1+(0.142+(f*AR[z]*(10*t/c)**0.33)
+(0.1/(4+AR[z])**0.8))
if z <= 5: # line 33 #
z +=1
else :
break
n+=1
OUTPUT:
File "<ipython-input-49-d7d52927efb2>", line 33
if z <= 5:
^
SyntaxError: invalid syntax
This is a code which should tell me whether my aircraft will takeoff or not (on the input of a weight)
I cannot seem to understand the reason why is this syntax invalid ?
There are several errors in the code you provided. I tried to clean it up as best as I could. The following does not cause an error by default. This does not mean that the code does what it is supposed to do. You should still check that.
Your lists like CL and CD do not contain enough elements for most cases which will cause IndexError: list index out of range. You should extend those lists or use a different kind of logic to make sure this does not happen.
W = int(input('Enter weight:'))
b = [1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0]
AR = [1, 2, 3, 4, 5]
T = [
50.99238, 50.05062, 49.07943, 48.05919, 47.00952, 45.92061, 44.79246,
43.62507, 42.42825, 41.18238, 39.90708, 38.60235, 37.24857, 35.86536,
34.4331, 32.97141, 31.48029, 29.94012, 28.37052, 26.76168, 25.1136
]
CL = [1.0]
CD = [0.5]
clmax = 2
n = 0
z = 0
while b[n] < 2.1:
while AR[z] < 5.1:
cl = CL[n]
cd = CD[z]
s = ((b[n]*b[n])/AR[z])
V = ((2*W*9.81)/(1.2*s*clmax) ** 0.5)*1.1
vlof = V/1.41
Vlof = round(vlof)
D = 0.5*cd*1.2*Vlof*Vlof*s
L = 0.5*cl*1.2*Vlof*Vlof*s
# O.O5 -> 0.05*: you used the letter 'O' instead of '0' (zero). also
# you always have to use * if you want to multiply something. you
# cannot leave it out.
a = (9.81/W)*(T[Vlof]-D-0.05*(W-L))
Sg = (V*V)/(2*a)
if Sg <= 30:
print('IT WILL TAKEOFF')
else:
print('It will NOT takeoff')
# t/c -> t_c: you cannot use special characters when defining
# variables. best stick to lower- and upper-case letters,
# the underscore and numbers.
t_c = int(input('t/c ratio is:'))
l = int(input('Taper ratio is:'))
# a whole lot of closing parentheses and '*' were missing here. also
# cleaned up the formatting
f = 0.005*(1+1.5*((l-0.6)**2))
e = (
1 / (
(1+0.12*V*V*0.003*0.003)*(
1 + (
0.142+(f*AR[z]*(10*t_c)**0.33)
+ (0.1/(4+AR[z])**0.8)
)
)
)
)
# in Python, space has meaning. it determines which part of the code
# is executed at which level in the routine. you cannot chose it
# arbitrarily.
if z <= 5:
z += 1
else:
break
n += 1

List Comprehension to avoid multiple loop creation

Can I avoid creating multiple loops for populating "c" as listed in the code below and instead shorten the length of the code? (Maybe through list comprehensions, or other means)
n,m = input().split()
a = [input().split() for i in range(0,int(n))]
b = [input().split() for i in range(0,int(m))]
c = []
for i in b:
if i in a:
c.append(list((y+1) for y, e in enumerate(a) if e == i))
else:c.append([-1])
for i in c:
print(*i)
sample input --> ("5 2" and then separated lines)
5 2
a
a
b
a
b
a
b
Shorter code but I'm not sure its easier to understand. Anyway, here it goes:
n,m = input().split()
A = [input().strip() for _ in range(int(n))]
B = [input().strip() for _ in range(int(m))]
C = [ [(idx + 1) for idx, s_B in enumerate(A) if s_B == s] if s in A else [-1] for s in B ]
for lst in C:
print(*lst)

Can't convert a string into a list of integers

I am trying to make a program in python that identifies whether a square is a magic square or not and i am having trouble getting the user input into a list. I understand that my code could be more efficient but I am very new to python.
column_1 = (0,3)
column_2 = (0,3)
column_3 = (0,3)
column_4 = (0,3)
row_1 = [int(i) for i in input('input row 1 with spaces inbetween numbers: ').split(' ')]
row_2 = [int(i) for i in input('input row 2 with spaces inbetween numbers: ').split(' ')]
row_3 = [int(i) for i in input('input row 3 with spaces inbetween numbers: ').split(' ')]
row_4 = [int(i) for i in input('input row 4 with spaces inbetween numbers: ').split(' ')]
column_1[0].append(row_1[0])
column_1[1].append(row_2[0])
column_1[2].append(row_3[0])
column_1[3].append(row_4[0])
column_2[0] = row_1[1]
column_2[1] = row_2[1]
column_2[2] = row_3[1]
column_2[3] = row_4[1]
column_3[0] = row_1[2]
column_3[1] = row_2[2]
column_3[2] = row_3[2]
column_3[3] = row_4[2]
column_4[0] = row_1[3]
column_4[1] = row_2[3]
column_4[2] = row_3[3]
column_4[3] = row_4[3]
diagonal_left_to_right[0] = column_1[0]
diagonal_left_to_right[1] = column_2[1]
diagonal_left_to_right[2] = column_3[2]
diagonal_left_to_right[3] = column_4[3]
diagonal_right_to_left[0] = column_4[0]
diagonal_right_to_left[1] = column_3[1]
diagonal_right_to_left[2] = column_2[2]
diagonal_right_to_left[3] = column_1[3]
sum_row_1 = sum(row_1)
sum_row_2 = sum(row_2)
sum_row_3 = sum(row_3)
sum_row_4 = sum(row_4)
sum_col_1 = sum(column_1)
sum_col_2 = sum(column_2)
sum_col_3 = sum(column_3)
sum_col_4 = sum(column_4)
sum_dag_l2r = sum(diagonal_left_to_right)
sum_dag_r2l = sum(diagonal_right_to_left)
if sum_row_1 == sum_row_2 == sum_row_3 == sum_row_4 == sum_col_1 == sum_col_2 == sum_col_3 == sum_col_4 == sum_dag_r2l == sum_dag_l2r:
print('magic')
else:
print('not magic')
I keep getting error messages that 'int' object has no attribute 'append'
I have tried a lot of different methods that I found on this website and none of them have worked for various reasons.
I am open to all suggestions, anything will help me.
Thanks
You first define column_1 as tuple (with 2 integer values, one at index 0 and one at index 1). The append method cannot work on column_1[0], which is like doing 0.append(). You probably did not intend to create a tuple, but a list with certain dimensions.
You can assign the values to columns and diagonals with this list notation:
column_1 = [row_1[0], row_2[0], row_3[0], row_4[0]]
column_2 = [row_1[1], row_2[1], row_3[1], row_4[1]]
column_3 = [row_1[2], row_2[2], row_3[2], row_4[2]]
column_4 = [row_1[3], row_2[3], row_3[3], row_4[3]]
diagonal_left_to_right = [column_1[0],column_2[1],column_3[2],column_4[3]]
diagonal_right_to_left = [column_4[0],column_3[1],column_2[2], column_1[3]]

Print nested list elements one after another

I have a list with several nested lists inside like this:
MyMasterListwithListsInside = [List1,List2,List3,List4]
List1 = [f,e,g,t]
List2 = [t,r,e,y]
List3 = [g,k,f,k]
List4 = [o,y,[t,y]]
I am trying to have an output files like that looks like this this:
file 1
f or List1[1] \n
t or List2[1] \n
g or List3[1] \n
o or List4[1] \n
file 2
e or List1[2] \n
r or List2[2] \n
k or List3[2]\n
y or List4[2]\n
file 3
g or List1[3] \n
e or List2[3] \n
f or List3[3] \n
t or List4[3][1] \n
y or List4[3][2] \n
So far I have tried:
for x in a:
with open("whatever","a", encoding="utf-8") as file:
file.write("\n")
for y in x:
if y is not None:
file.write("\n")
file.write(y)
x.remove(y)
for f in ok:
file.write("\n")
file.write(f)
ok.remove(f)
for k in kok:
file.write("\n")
file.write(k)
kok.remove(k)
for s in sok:
file.write("\n")
file.write(s)
sok.remove(s)
for o in yok:
for ik in o:
if ik is not None:
file.write("\n")
file.write(ik)
else:
yok.remove(o)
else:
print("Done!")
I have also tried several combinations of different indentations. None of them work. Either I get List1[1:4],List2[1:4],... etc. like output or List1[1],List2[1],List3[1:4],... etc. At one point I managed to find the write combination of indenting, but then I had a syntax error, and while I was debugging, I lost the correct form. However I am sure there is more elegant solution than making a leader of "for"s.
My actual data is a list which contains several nested lists, each containing ten elements. One of them also contains 10 nested lists. I can also compromise to a format that looks like this:
f or List1[1] \n
t or List2[1] \n
g or List3[1] \n
o or List4[1] \n
e or List1[2] \n
r or List2[2] \n
k or List3[2]\n
y or List4[2]\n
g or List1[3] \n
e or List2[3] \n
f or List3[3] \n
t or List4[3][1] \n
y or List4[3][2] \n
Thanks in Advance
You could do something recursive like this (psuedocode):
for each position in a
printPosition()
function printPosition(arrays, position)
for each element in array
if array[position] != array
print array[position]
else
for each position
printPosition()
Does that make sense to you?
The solution was with itertools after all. Here is my overall function:
def metin_işle_Page(Kök):
sayfa1 = BeautifulSoup(Kök, "lxml") # Page with 10 results
sayfa = sayfa1.find_all("result") # Each of them are seperate xml #files,
#with json data in between and
#each of them having the same structure
başlıklar2 = [x.find("title") for x in sayfa]
başlıklar = [x.get_text() for x in başlıklar2] # A list for their titles 10 elements
print("Başlıklar Alındı")
kayıt_kaynağı2 = [x.find("recordsourceinfo") for x in sayfa] # a list for their id
kayıtUrl = [link.get("landingpage") for link in kayıt_kaynağı2]
kayıt_id = [link.get_text(strip=True) for link in kayıt_kaynağı2]
print("kayıt id ve ilgili urller alındı")
nesne_tipi4 = [x.find("objecttype") for x in sayfa] # another list with 10 elements
nesne_tipi = [x.get_text(strip=True) for x in nesne_tipi4]
print("nesne tipleri alındı")
malzeme3 = [x.find("material") for x in sayfa] # you get the idea ..........
malzeme = [x.get_text(strip=True) for x in malzeme3]
print("malzemeler alındı")
boyut3 = [x.find("dimensions") for x in sayfa]
boyut2 = [x.prettify(formatter="minimal") for x in boyut3]
boyut = [x.strip() for x in boyut2]
print("boyutlar alındı")
tarihi2 = [x.find("origindating") for x in sayfa]
kaynak_tarihi2 = [x.get_text(strip=True) for x in tarihi2]
kaynak_tarihi = [x.strip() for x in kaynak_tarihi2]
print("kaynak tarihleri alındı")
eski_Yer2 = [x.find("ancientfindspot") for x in sayfa]
eski_yer1 = [x.get_text("|", strip=True) for x in eski_Yer2]
eski_yer = [x.strip() for x in eski_yer1]
print("Eserin ait olduğu yer alındı")
modern_yer3 = [x.find("modernfindspot") for x in sayfa]
modern_yer1 = [x.get_text(strip=True) for x in modern_yer3]
modern_yer = [x.strip() for x in modern_yer1]
print("Eserin bulunduğu modern yer alındı")
modern_ülke3 = [x.find("moderncountry") for x in sayfa]
modern_ülke1 = [x.get_text(strip=True) for x in modern_ülke3]
modern_ülke = [x.strip() for x in modern_ülke1]
print("Eserlerin bulunduğu ülkeler alındı")
korunma_ülkesi3 = [x.find("conservationcountry") for x in sayfa]
korunma_ülkesi1 = [x.get_text("|", strip=True) for x in korunma_ülkesi3]
korunma_ülkesi = [x.strip() for x in korunma_ülkesi1]
print("Eserin korunduğu ülkeler alındı")
müzesi3 = [x.find("museum") for x in sayfa]
müzesi1 = [x.get_text("|", strip=True) for x in müzesi3]
müzesi = [x.strip() for x in müzesi1]
print("Eserin korunduğu Müze alındı")
yazıttipi3 = [x.find("inscriptiontype") for x in sayfa]
yazıttipi2 = [x.get_text(strip=True) for x in yazıttipi3]
yazıt_tipi = [x.strip() for x in yazıttipi2]
print("Yazıt tipleri alındı")
yazıt_tekniği3 = [x.find("engravingtechnique") for x in sayfa]
yazıt_tekniği2 = [x.get_text(strip=True) for x in yazıt_tekniği3]
yazıt_tekniği = [x.strip() for x in yazıt_tekniği2]
print("yazıt teknikleri alındı")
metin_normal2 = [x.find("text") for x in sayfa]
metin_normal1 = [x.get_text(strip=True) for x in metin_normal2]
metin_normal = [x.strip()for x in metin_normal1]
print("Metinler alındı")
metin_epidoc3 = [x.find("textepidoc") for x in sayfa]
metin_epidoc2 = [x.prettify(formatter="minimal") for x in metin_epidoc3]
metin_epidoc = [x.strip() for x in metin_epidoc2]
print("Epidoc metinleri alındı")
kaynakça3 = [x.find_all("bibliography") for x in sayfa] # Here is the
#tricky part for every list so far there was only 1 element beneath the tag
#corresponding in each results, but for this tag, there are
#sometimes 2 or more elements
kaynakça4 = [] # I made a new list in order to match the number of other lists.
for x in kaynakça3: # list containing more than one elements
kaynaklar = [] # some empty list
for y in x: # since x, a list of "bibliography" element for each element
# of sayfa,a list of "result" elements, i call y, each attestation of
# bibliography in x.
adf1 = y.get_text(strip=True) # I took the text of each attestation
#and reproduce them in another list. This way I got rid of the tags
# plus it is difficult to work with a Result Set, and less difficult
# to work with a list
adf = adf1.strip()
kaynaklar.append(adf)
kaynakça4.append(kaynaklar)
kaynakça = []
for g in kaynakça4: # here I tried to join together the nested lists within
# the nested list element, so that I would have at most two level of nested
#lists.
zip(g)
kaynakça.append(g)
Genel_sayfa = [] # Then I created a master list and appended my processed
Genel_sayfa.append(başlıklar) #elements within it.
Genel_sayfa.append(kayıt_id)
Genel_sayfa.append(kayıtUrl)
Genel_sayfa.append(nesne_tipi)
Genel_sayfa.append(malzeme)
Genel_sayfa.append(boyut)
Genel_sayfa.append(kaynak_tarihi)
Genel_sayfa.append(eski_yer)
Genel_sayfa.append(modern_yer)
Genel_sayfa.append(modern_ülke)
Genel_sayfa.append(korunma_ülkesi)
Genel_sayfa.append(yazıt_tekniği)
Genel_sayfa.append(yazıt_tipi)
Genel_sayfa.append(metin_normal)
Genel_sayfa.append(metin_epidoc)
Genel_sayfa.append(kaynakça)
Sıralı = itertools.chain.from_iterable(zip(* Genel_sayfa)) #used iterate tools
sayfasayısı = list(range(0,112)) #over the lists which contain the same number
for SayfaNo in sayfasayısı: #of elements
with open("TümSayfa" + str(SayfaNo), "a", encoding="utf-8") as sonuç:
sonuç.write("\n")
for k in Sıralı:
sonuç.write("\n")
sonuç.write("\n")
afrc = str(k) #to assure that there was no problem in the output
sonuç.write("\n") # I changed the chain object to string
sonuç.write(afrc)
sonuç.close()

Resources