Reordering character triplets in Python - python-3.x

I've been trying to solve this homework problem for days, but can't seem to fix it. I started my study halfway through the first semester, so I can't ask the teacher yet and I hope you guys can help me. It's not for grades, I just want to know how.
I need to write a program that reads a string and converts the triplets abc into bca. Per group of three you need to do this. For examplekatzonbecomesatkonz`.
The closest I've gotten is this:
string=(input("Give a string: "))
for i in range(0, len(string)-2):
a = string[i]
b = string[i + 1]
c = string[i + 2]
new_string= b, c, a
i+=3
print(new_string)
The output is:
('a', 't', 'k')
('t', 'z', 'a')
('z', 'o', 't')
('o', 'n', 'z')

The code below converts for example "abc" to "bca". It works for any string containing triplets. Now, if input is "abcd", it is converted to "bcad". If you input "katzon", it is converted to "atkonz". This is what I understood from your question.
stringX = input()
# create list of words in the string
listX = stringX.split(" ")
listY = []
# create list of triplets and non-triplets
for word in listX:
listY += [[word[i:i+3] for i in range(0, len(word), 3)]]
# convert triplets, for example: "abc" -> "bca"
for listZ in listY:
for item in listZ:
if len(item)==3:
listZ[listZ.index(item)] = listZ[listZ.index(item)][1:] + listZ[listZ.index(item)][0]
listY[listY.index(listZ)] = "".join(listZ)
# create final string
stringY = " ".join(listY)
print(stringY)

Related

Adding an x in front of and after words in a list

It's basic as far as Python goes, but I need to create a function List of words as an input parameter and outputs them as a single String formatted as a sentence with a period at the end and lower case 'x's around each word.
e.g.
Input: ["This", "is", "a", "sentence"]
Returns: "xThisx xisx xax xsentencex.
I think I need a for loop, but I keep getting errors in trying them.
Thanks in advance!
The closest I've come is through:
quote = ["This","is","a","sentence"]
def problem3(quote):
blue='x x '.join(quote)
return(blue)
which returns "Thisx x isx x ax x sentence"
quote = ["This","is","a","sentence"]
s = ""
for word in quote:
s = s + "x" + word + "x "
s = s[:-1]
print(s)
Out[17]: 'xThisx xisx xax xsentencex'
list_ = ["This", "is", "a", "sentence"]
string =''
for item in list_:
string += ' x' +item+'x'
string = string.strip()
print(string)
Map the initial list
>>> list_ = ["This", "is", "a", "sentence"]
>>> newlist = list(map(lambda word: f"x{word}x", list_))
>>> print(newlist)
['xThisx', 'xisx', 'xax', 'xsentencex']
And then reduce it to get the complete sentence
>>> import functools
>>> result = functools.reduce(lambda a,b : f"{a} {b}", newlist2)
>>> print(result)
xThisx xisx xax xsentencex

Printing a list where values are in a specific distance from each other using Python

I have a list,
A = ['A','B','C','D','E','F','G','H']
if user input x = 4, then I need an output that shows every value that is 4 distance away from each other.
If starting from 'A' after printing values that are 4 distance away from each other ie: {'A', 'E'}, the code should iterate back and start from 'B' to print all values from there ie: {'B', 'F'}
No number can be in more than one group
Any help is going to be appreciated since I am very new to python.
this is what I have done
x = input("enter the number to divide with: ")
A = ['A','B','C','D','E','F','G','H']
print("Team A is divided by " +x+ " groups")
print("---------------------")
out = [A[i] for i in range(0, len(A), int(x))]
print(out)
My code is printing only the following when user input x =4
{'A', 'E'}
But I need it to look like the following
{'A', 'E'}
{'B', 'F'}
{'C', 'G'}
{'D', 'H'}
what am I doing wrong?
Use zip:
out = list(zip(A, A[x:]))
For example:
x = 4 # int(input("enter the number to divide with: "))
A = ['A','B','C','D','E','F','G','H']
print(f"Team A is divided by {x} groups")
print("---------------------")
out = list(zip(A, A[x:]))
print(out)
Outputs:
[('A', 'E'), ('B', 'F'), ('C', 'G'), ('D', 'H')]
Here you have the live example
If you want to keep the comprehension:
out = [(A[i], A[i+x]) for i in range(0, len(A)-x)]
**You can find my answer below.
def goutham(alist):
for passchar in range(0,len(alist)-4):
i = alist[passchar]
j = alist[passchar+4]
print("{"+i+","+j+"}")
j = 0
alist = ['a','b','c','d','e','f','g','h']
goutham(alist)

How do I join portions of a list in Python

Trying to join only portions of a large list that has numbers in it. For example:
h = ['9 This is the way this is the way 10 to program a string 11 to program a string']
##I've tried...
h[0].split()
z = []
h = ['9', 'This', 'is', 'the', 'way', 'this', 'is', 'the', 'way', '10', 'to', 'program', 'a', 'string', '11', 'to', 'program', 'a', 'string']
for i in h:
while i != '10':
z.append(i)
But the program runs an infinite loop. I've also tried if statements, if i != '10' then z.append(i). Basically, I have large portions of scripture that is in a list as a single string and I'd like to quickly extract the verses and put them in their own separate list. Thank you
Edit: I've tried...
h= ['9 nfnf dhhd snsn nana na 10 hfhf gkg utu 11 oeoe ldd sss', 'kgk hfh']
y = h[0].split()
print (y)
z = []
for i in y:
if i != "10":
z.append(i)
break
print (z)
Output is the split list and 'z' prints '9' only. I've also changed the break to the correct indentation for the 'for' loop
First of all, use the result you get from h[0].split(). You can do this by using h = h[0].split()
Now, lets get to the loop. It's going into an infinite loop because the for loop is picking the first i which is "9" and then while i != "10", it keeps appending i to z. i will never equal "10". Thus, the infinite loop. I think what you want here is:
for i in h:
if i != "10":
z.append(i)
else:
break
This will append every value of h into z until i is equal to "10". Let me know if you need more help and I'll be happy to edit!
Try this for extracting all numbers in z:
h = ['9 This is the way this is the way 10 to program a string 11 to program a string']
##I've tried...
h = h[0].split()
z = []
for i in h:
try:
z.append(eval(i))
except:
pass
print z
output:
[9, 10, 11]
[Finished in 0.0s]

How to test if an input has only specific characters

Im trying to make a script that tests id there are characters in the input that are not A, T, C, G and if there are than the input is false.
I dont have any clue how to start. I would love if someone could help.
Thanks!
The following function can check a string to find out if it only contains the characters A, T, C, and G.
def check_string(code):
return all(character in {'A', 'T', 'C', 'G'} for character in code)
Expressed using sets:
The list function takes a string and returns a list of its characters. The set function takes a list and returns a set (with duplicates discarded).
>>> def check_string(code):
... return set(list('ACTG')).issuperset(set(list(code)))
...
>>> check_string('IT')
False
>>> check_string('ACTG')
True
>>> check_string('')
True
>>> check_string('ACT')
True
output = True
nucl_dict = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
n = input("Insert DNA seqence: ").upper()
for c in n:
if(c in ("A", "T", "C", "G")):
output = False
if(output == False):
print('Issue detected please try again')
print(n)
print(''.join(nucl_dict.get(nucl, nucl) for nucl in n))
else:
print("All good")

Difficulty Reading Text from Excel file

I'm working on a project where I am trying to search large amounts of text from an excel file for keywords. These keywords are citations in their various formats, (e.g. XXXXXX, YYYY), and then also to search the text for citations which contain the last name of the author. In excel, the C column is the authors last names, and the D column is the text of the writing. I am working with xlrd, but I do not know how to use the items from list "L" search the items in list "L1". Ultimately, I need to search list "L1" (the text) for citations, and then search L1 again for citations which have the same name as the corresponding cell in L, (e.g. C3 = Smith, must search D3 for any citation which has the name Smith). Any help with this, or other tips/methods for my task would be greatly appreciated!
Here is my current code for searching the excel file.
from xlrd import open_workbook,cellname
book = open_workbook("C:\Python27\Doc\Book3.xls")
sheet = book.sheet_by_index(0)
for year in xrange(1900,2014):
citation = str(year) or str(year) + ')' or '(' + str(year) + ')' or str(year) + ';'
firstc = sheet.col_values(2)
secondc = sheet.col_values(3)
L = [firstc]
L1 = [secondc]
if citation in L1:
print 'citation ' + str(year)
if L in L1:
print 'self-cite ' + str(year)
for item in L1:
if citation in item:
print item
I am somewhat of a novice at python and I apologize for bothering you all, but I have had difficulty finding pre-written topics on searching text files. Thank you!
Best
You can't look if L (which is a list) is in L1. You can look to see if the items in L are in L1. For example:
>>> s = 'abcde'
>>> b = ['a', 'f', 'g', 'b']
>>> b
['a', 'f', 'g', 'b']
>>> for i in b:
... if i in s:
... print i
... else:
... print "nope"
...
a
nope
nope
b
>>>
If you have two lists, you'll need to loop over both, with a nested for loop:
for i in b:
for j in L1:
do stuff
Hope that gives you a start.
ETA:
You can use enumerate to get the index of the item you're looping on currently and use that to get into the right row in the second list:
>>> b = ['a', 'f', 'g', 'b']
>>> L1 = ['worda', 'words including b', 'many many words', 'a lot more words']
>>> for i, j in enumerate(b):
... if j in L1[i]:
... print j
... else:
... print i, j
a
1 f
2 g
3 b
>>>
Combine that with row_values and you might have what you need.

Resources