Hello guys i got a homework where i get a string and basically i should change the letters in it then return it backward:
A --> T
T --> A
G --> C
C --> G
Here is my code :
def dnaComplement(s):
newWord = ""
for x in s:
if x == "T":
newWord.join('A')
elif x == "A":
newWord.join('T')
elif x == "C":
newWord.join('G')
elif x == "G":
newWord.join('C')
return newWord[::-1]
the input is: ACCGGGTTTT
Your effort so far has got a minor issue with it.
You are using newWord.join('X') in an attempt to add the new character to the string. This doesn't work in the way you are attempting to use it. Read again how join functions in the official documentation.
Instead, you can use the += operator to append the characters to the end of your newWord string:
newWord += 'X'
Your code then becomes:
def dnaComplement(s):
newWord = ""
for x in s:
if x == "T":
newWord += 'A'
elif x == "A":
newWord += 'T'
elif x == "C":
newWord += 'G'
elif x == "G":
newWord += 'C'
return newWord[::-1]
print(dnaComplement('ACCGGGTTTT'))
Output:
AAAACCCGGT
This is the reverse of TGGCCCAAA which is stored in newWord until you return it from dnaComplement.
newWord.join(...) doesn't change the value of network, but rather returns a new string.
So to begin with, you would need to do something like network = newWord.join(...).
That being said, here is a cleaner way IMO:
d = {'T': 'A',
'A': 'T',
'C': 'G',
'G': 'C'
}
def dnaComplement(s):
return ''.join(d[x] for x in s[::-1])
Related
We assume curr_player to be 'X'.
Output should be 'O', and vice-versa
(is my code correct?)
#my code
def switchPlayer(curr_player):
if curr_player == "X" or curr_player == "x":
print("your Player 'O' ")
return curr_player
if curr_player == "O" or curr_player == "o":
print("your Player 'X' ")
return curr_player
switchPlayer("X")
You want to return the opposite of what it currently is. Something else I changed was the way you compare the strings. Instead of checking for uppercase and lowercase, you can convert the string to lowercase first, and you only need to compare it one time.
if (curr_player.lower() == 'x'):
return 'O'
if (curr_player.lower() == 'o'):
return 'X'
This code can also be simplified to this:
return 'O' if curr_player.lower() == 'x' else 'X'
def switchPlayer(curr_player):
if curr_player == "X" or curr_player == "x":
curr_player="O"
return curr_player
if curr_player == "O" or curr_player == "o":
curr_player="X"
return curr_player
inp=input("input the current player")
a=switchPlayer(inp)
print("returned player",a)
I have been trying to get below result out of this Program but for some reason it is not giving the required output.
Required Results:
Input1 : bbaasssrppoccbaaacbaba Output1 : ['bbaa','sssrppoccbaaa','cba','ba']
Input2: hjgAvjhjKLhbfvbZSF Output2 :['h', 'jgA', 'vjh', 'jK', 'L', 'hb', 'f','vbZSF']
What i am getting
Output: ['bbaa', 'sssrppoccbaaa', 'cba'] & Output: ['h', 'jgA', 'vjh', 'jK', 'L', 'hb', 'f'] from below code which is not getting last substring "ba" & "vbZSF".
s1 = 'bbaasssrppoccbaaacbaba'
# s1 = 'hjgAvjhjKLhbfvbZSF'
decSub = ''
listSub = []
i= 0
while i < len(s1):
current = s1[i]
previous = s1[i] if i == 0 else s1[i-1]
if ord(current) <= ord(previous):
decSub += current
else:
listSub.append(decSub)
decSub = ''
decSub += current
i +=1
print(listSub)
It would be great if somebody could suggest a fix or a better way to achieve this result.Thanks in advance
You just need to append the missing decSub in the list.
Updated Code:
s1 = 'bbaasssrppoccbaaacbaba'
# s1 = 'hjgAvjhjKLhbfvbZSF'
decSub = ''
listSub = []
i= 0
while i < len(s1):
current = s1[i]
previous = s1[i] if i == 0 else s1[i-1]
if ord(current) <= ord(previous):
decSub += current
else:
listSub.append(decSub)
decSub = ''
decSub += current
i += 1
listSub.append(decSub)
print(listSub)
Output:
# s1 = 'bbaasssrppoccbaaacbaba'
['bbaa', 'sssrppoccbaaa', 'cba', 'ba']
# s1 = 'hjgAvjhjKLhbfvbZSF'
['h', 'jgA', 'vjh', 'jK', 'L', 'hb', 'f', 'vbZSF']
while loop is better choice for iterations without arbitrary boundaries - in your case for loop is probably a better choice.
Try the following instead:
from typing import List
def split_special(txt: str) -> List[str]:
if len(txt) == 0:
return []
res = [txt[0]]
prev = ord(txt[0])
for l in map(ord, txt[1:]):
if prev >= l:
res[-1] += chr(l)
else:
res.append(chr(l))
prev = l
return res
Outputs:
>>> print(Input1)
bbaasssrppoccbaaacbaba
>>> print(split_special(Input1))
['bbaa', 'sssrppoccbaaa', 'cba', 'ba']
>>> print(Input2)
hjgAvjhjKLhbfvbZSF
>>> print(split_special(Input2))
['h', 'jgA', 'vjh', 'jK', 'L', 'hb', 'f', 'vbZSF']
I'm trying to convert Excel file with polish chars such as "ęśążćółń" to normal letters "esazcoln". Firstly I've menaged to convert xlsx file to txt, then:
f = open("PATH_TO_TXT_FILE")
r = f.read()
r.upper()
new_word = ""
for char in r:
if char == "Ą":
new_word += "A"
elif char == "Ć":
new_word += "C"
elif char == "Ę":
new_word += "E"
elif char == "Ł":
new_word += "L"
elif char == "Ó":
new_word += "O"
elif char == "Ż" "Ź":
new_word += "Z"
elif char == "Ź":
new_word += "Z"
elif char == "Ś":
new_word += "S"
else:
new_word += char
encoded_bytes = r.encode('utf-8', "replace")
decoded = encoded_bytes.decode(
"cp1252", "replace")
print(decoded)
in file is written : asdżółć
Output: asdżółć
I'd like to recive: asdzolc
Is there anybody who can help me?
I can't find the stack overflow page from which I got the pattern/sub template, but this is the general idea:
#!/usr/bin/env python3
# coding: UTF-8
import re
mapping = {
'Ą': 'A',
'Ć': 'C',
'Ę': 'E',
'Ł': 'L',
'Ó': 'O',
'Ż': 'Z',
'Ź': 'Z',
'Ś': 'S',
'ą': 'a',
'ć': 'c',
'ę': 'e',
'ł': 'l',
'ó': 'o',
'ż': 'z',
'ź': 'z',
'ś': 's',
}
pattern = re.compile("|".join(mapping.keys()))
def replace_by_mapping(text):
return pattern.sub(lambda m: mapping[re.escape(m.group(0))], text)
if __name__ == '__main__':
with open('polish_test.txt', 'r') as f:
contents = f.read()
contents = replace_by_mapping(contents)
print(contents)
I am trying to calculate the avarage grade of a subject. but when i print the function i get printed None.
And i do not know how to fix it.
Ive tried returning the value instead then printing the function, but it wont work.
def karakterKonversjon(bokstav):
if bokstav == 'A':
return 6
if bokstav == 'B':
return 5
if bokstav == 'C':
return 4
if bokstav == 'D':
return 3
if bokstav == 'E':
return 2
if bokstav == 'F':
return 1
def konversjonTilBokstav(tall):
if tall == 6:
return 'A'
if tall == 5:
return 'B'
if tall == 4:
return 'C'
if tall == 3:
return 'D'
if tall == 2:
return 'E'
if tall == 1:
return 'F'
def beregnSnitt():
nummer_karakter = 0
suM = 0
for i in emner:
if emner[i] != "":
tall_karakter = eksamen.karakterKonversjon(emner[i])
suM += (tall_karakter * studiepoeng)
suM /= totalPoeng
rundetSvar = eksamen.normal_round(suM)
eksamen.konversjonTilBokstav(rundetSvar)
print(rundetSvar)
def normal_round(suM):
if (float (suM) < 5):
print(math.floor(suM))
else:
print(math.ceil(suM))
THe result i am expecting is
4
C
But i am getting
4
None
I made a few modifications to your code:
(I assume you are importing math in the eksamen file)
def karakterKonversjon(bokstav): # make this function more efficient
atof = ['A','B','C','D','E','F']
for i in range(len(atof)):
if bokstav.upper() == atof[i]:
return len(atof) - i
def konversjonTilBokstav(tall): # make this function more efficient
atof = ['A','B','C','D','E','F']
for i in range(1,7):
if tall == i:
return atof[len(atof)-i]
def beregnSnitt():
nummer_karakter = 0
suM = 0
for i in range(len(emner)): # if enmer == "enmer"(for example) you cannot reference enmer['e'] without raising an error
if emner[i] != "":
tall_karakter = eksamen.karakterKonversjon(emner[i])
suM += (tall_karakter * studiepoeng)
suM /= totalPoeng
rundetSvar = eksamen.normal_round(suM)
eksamen.konversjonTilBokstav(rundetSvar)
print(rundetSvar)
def normal_round(suM):
if (float (suM) < 5):
print(math.floor(suM))
else:
print(math.ceil(suM))
apart from the differences i made, your code should work well however i cannot test without knowing what enmer is (i assume it's a string) or what studiepoeng is.
the function konversjonTilBokstav did work fine for me. But what I have included in the code snippet should be less spaghetti code
Im trying to do reverse transcription of a DNA sequence by reversing a string then find its corresponding pair ( if an 'A' appears then switch with a 'T') and return a new string that is 'reverse transcribed'. The loop seems to work only partially and not go through to the elif statements. I've tried two ways and have the same problem:
def structures(seq):
revlist = seq[::-1]
for item in revlist:
if item == 'A':
return revlist.replace('A','T',1000)
elif item == 'T':
return revlist.replace('T','A',1000)
elif item == 'G':
return revlist.replace('G','C',1000)
elif item == 'C':
return revlist.replace('C','G',1000)
else:
pass
structures('ATTTGCCCTA')
# below is the second way I'm trying to code it
def structures(seq):
revlist = seq[::-1]
old = ['A','T','G','C']
new = ['T','A','C','G']
for item in revlist:
if item == 'A':
return revlist.replace(old[0],new[0])
elif item == 'T':
return revlist.replace(old[1],new[1])
elif item == 'G':
return revlist.replace(old[2],new[2])
elif item == 'C':
return revlist.replace(old[3],new[3])
else:
pass
structures('ATTTGCCCTA')
The method str.replace is meant to replace a single substring by another substring. Keep in mind that having multiple str.replace calls is inefficient since it means traversing your string many times while one would suffice.
To translate characters, you should use str.translate.
def dna_complement(dna):
translation = str.maketrans({'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'})
return dna.translate(translation)[::-1]
print(dna_complement('AGTC'))
Output
GACT
def structures(dna):
revlist = ''
for item in dna:
if item == 'A':
revlist = 'T' + revlist
elif item == 'C':
revlist = 'G' + revlist
elif item == 'G':
revlist = 'C' + revlist
elif item == 'T':
revlist = 'A' + revlist
return revlist
This code seems to work good. Instead of reversing the list, I researched another way of adding the information in reverse order which equates to the same thing. Credit to github