How to print horizontally instead of vertically? - python

I wrote a script that is supposed to print an answer to a specific input horizontally.
For example if the input is:
TTACTGGCAT
It should print:
TTACTGGCAT
AATGACCGTA
My code:
x = 0
n = input("Insert DNA seqence: ")
print(n.upper())
while x < len(n):
if 'T' in n[x]:
print('A')
if 'G' in n[x]:
print('C')
if 'C' in n[x]:
print('G')
if 'A' in n[x]:
print('T')
x = x + 1

I assume you want to do something like this:
nucl_dict = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
n = input("Insert DNA seqence: ").upper()
print(n)
print(''.join(nucl_dict.get(nucl, nucl) for nucl in n))
nucl_dict defines which nucleotides are complementary.
This joins the characters for the corresponding nucleotides into a string and prints the result.
If the character is not a valid nucleotide, the character is simply added without a change to the complementary string. get tries to find the value given the first argument as a key (in this case each character in n) and if the key does not exist uses the second argument (in this case the same character).

You should concat everything in a string and after the loops end print it.

You can use the end parameter like print(some_var, end='') to not print ending newline after each call. In your loop you would want to print new line, so just run without the end parameter there. See print documentation.

Related

Remove dulpicates from a string

I wrote this code which consists of an input of two words and outputs the letters in the second word which are in the exact position as the first word in uppercase and the characters in the first and second word but not in the exact position as the first in lowercase.The code works for two of my test cases but fails on the third when i input duplicate letters as the second word.
If i input zabbz and cbbxb it outputs .bB.b but there are only 2 b's in the first word,the output should be '.bB..' .Please assist if you can.
Here is my code:
sec=list(input().upper())
guess=list(input().upper())
output=['.']*len(guess)
letters=''
for i in range(len(guess)-1,-1,-1):
if guess[i]==sec[i]:
output[i]=guess[i]
sec[i]=guess[i]=0
for i in range (len(guess)):
if guess[i] in sec and guess[i]!=0:
output[i]=guess[i].lower()
for letter in output:
letters=letters+letter
print(letters)
To remove duplicates I use something like this:
start_array = []
final_array = []
for i in start_array:
if start_array[i] in final_array:
#DO nothing its a duplicate and continue
continue
else:
final_array.append(start_array[i])
This checks each entry in the array and checks if that entry is in the final array and if it is it continues. Otherwise, it will append. This is assuming you changed all cases to upper().
Using list.count(item) method will allow u to verify that there are the same amount of letters in your output list as in your sec list and not more. Here is an example :
if guess[i] in sec and sec.count(guess[i]) > output.count(guess[i])+output.count(guess[i].upper()):
output[i] = guess[i].lower()
here is an example that i made real quick if you want to test it :
sec = list(input().upper())
guess = list(input().upper())
output = ["." for i in range(len(guess))]
for i in range(len(guess)):
if guess[i] == sec[i]:
output[i] = guess[i]
elif guess[i] in sec and sec.count(guess[i]) > output.count(guess[i])+output.count(guess[i].upper()):
output[i] = guess[i].lower()
output = "".join(output)
print(output)
also i noticed you were doing some string concatenation for the final result but if you want a simpler way to create a string from a list there is the "".join(list) method that allows you to join all elements in the list seperated by the str specified(in that case, seperated by nothing)

How do I alternate the cases of letters/words in a list?

I need to convert the "letter_guessed" input to lower case, if it's uppercase and if an uppercase letter already exists inside the list as a lower case it will return false but I can't get it to work.
I have tried using isupper(), upper ,islower(), lower() in many ways. I am pretty sure that I am doing something wrong with "if" but can't get it right.
def check_valid_input(letter_guessed, old_letters_guessed):
while True:
""" will work only if you enter one letter and do not contain special letters other then the abc
and if its all ready been entered it will show false """
if len(letter_guessed) == 1 and letter_guessed not in old_letters_guessed :
"""if the letter is one letter and not already inside old_letter_guessed only then continue """
old_letters_guessed.append(letter_guessed)
print("True")
letter_guessed = input(" : ")
else:
""" if its wrong input will print False Try again and if the input is correct it will go back to " if " """
#old_letters_guessed.append(letter_guessed)
print(False, 'Try again')
old_letters_guessed.sort()
print('->'.join(old_letters_guessed))
letter_guessed = input(" : ")
#if letter_guessed is letter_guessed.isupper()
new = input()
old = []
check_valid_input(new,old)
Everything sting has a method called swapcase which swaps between upper and lower case. So:
"TEST".swapcase()
Would become
"test"
I'd suggest using that instead of your if statements.
use a for loop to iterate over all elements in the list with the .swapcase() function common to all strings
list = ['some', 'words', 'in a list']
for word in list:
print(word.swapcase())

Write a function that takes a string parameter and returns a new string with all the letters of the alphabet that are not in the argument string

Write a function called missing_letters that takes a string parameter and returns a new string with all the letters of the alphabet that are not in the argument string. The letters in the returned string should be in alphabetical order.
It should also use the global variable alphabet. It should use this global variable directly, not through an argument or a local copy. It should loop over the letters in alphabet to determine which are missing from the input parameter.
The function missing_letters should combine the list of missing letters into a string and return that string.
Write a loop over the strings in list test_miss and call missing_letters with each string. Print a line for each string listing the missing letters. For example, for the string "aaa", the output should be the following.
aaa is missing letters bcdefghijklmnopqrstuvwxyz
I tried my best to solve this. The program is working but not giving
the desired output.
test_miss = ["b","zzz"]
def missing_letters(s):
missingAlphabets = ""
global alphabet
for c in s:
i=0
while i < len(alphabet):
if alphabet[i] not in c:
missingAlphabets += alphabet[i]
i += 1
sortedmissingAlphabetslists = sorted(missingAlphabets)
sortedmissingAlphabets = ''.join(sortedmissingAlphabetslists)
return sortedmissingAlphabets
for i in test_miss:
print('{} is missing letters {}'.format(i,missing_letters(i)))
the program is giving appropriate output for any string with a single character, like - "b"
that is: b is missing letters acdefghijklmnopqrstuvwxyz
But for a string with multiple characters, like: "zzz" the output is:
zzz is missing letters aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyy
But I want:
zzz is missing letters abcdefghijklmnopqrstuvwxy
The set type already handles most of the work for you.
import string
def missing_letters(s):
return ''.join(sorted(set(string.lowercase) - set(s)))
If x and y are sets, then x - y is the set of items present in x but not in y. One you have the set of missing characters, you can sort them and re-join the sorted elements into a single string.
>>> set('abc') - set('a')
set(['c', 'b'])
>>> sorted(_)
['b', 'c']
>>> ''.join(_)
'bc'
Keeping with the spirit of what you have already defined. The issue is that you are testing each letter in the missing_letters function more than once. So you just want to check if the character (from the alphabet) is in the string. So take out the extra for loop which loops through the letters in the argument - like such
alphabet = 'abcdefghijklmnopqrstuvwxyz'
test_miss = ["b","zzz"]
def missing_letters(s):
missingAlphabets = ""
global alphabet
i = 0
while i < len(alphabet):
if alphabet[i] not in s:
missingAlphabets += alphabet[i]
i += 1
sortedmissingAlphabetslists = sorted(missingAlphabets)
sortedmissingAlphabets = ''.join(sortedmissingAlphabetslists)
return sortedmissingAlphabets
for i in test_miss:
print('{} is missing letters {}'.format(i,missing_letters(i)))
b is missing letters acdefghijklmnopqrstuvwxyz
zzz is missing letters abcdefghijklmnopqrstuvwxy
def has_duplicates(t):
t= histogram(t)
for i in t:
a=(t[i])
if a > 1:
return True
else:
return False
for i in test_dups:
f = has_duplicates(i)
if f == True:
print(i +' '+ 'has duplicates')
else:
print(i +' '+ 'has no duplicates')

Why do I get this error on python and how do I fix it? (loops and strings)

My code suppose to take a string to a function and then switch the caps of each char in there from h to H and E to e
but I somewhat get an error in my if s
why is that?
This is the error messege:
chr = str[i]
TypeError: string indices must be integers, not str
My code is:
def CapsChanger(str):
i = str[0]
for i in str :
chr = str[i]
if((ord(chr) > 46) and (ord(chr) < 91)):
str[i].upper()
if((ord(chr) > 96) and (ord(chr) < 126)):
str[i].lower()
print str
str = raw_input()
CapsChanger(str)
input()
When you do for i in str, in each iteration i represents that actual character, not the index. So you don't need to do chr = str[i] - i is already that character.
import string
def invertCase(text):
## Creating a list where results will be stored
results = list()
## This will contain the abc in upper and lowercase: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abc = string.lowercase + string.uppercase
## Looping each letter of the received text
for letter in text:
## If the current letter of the loop exists in our abc variable contents, it means it's a letter and not a symbol or space
## So we can apply upper() or lower() to the letter.
if letter in abc:
## If the letter is currently uppercase, then we turn it into lowercase
if letter.isupper():
results.append(letter.lower())
## If the letter is currently lowercase, then we turn it into uppercase
else:
results.append(letter.upper())
## The current letter of the loop is not in our abc variable so it could be anything but a letter
## So we just append it to our results list
else:
results.append(letter)
## Once the loop finishes we just join every item in the list to make the final string and return it
return ''.join(results)
print invertCase('SoMeOnE Is hAvING fUN')
Output:
sOmEoNe iS HaVing Fun
The variable i is already a 1 character string because the for loop processes strings this way. Also, when you call str[i].upper(), it needs to either be assigned to something, or printed out, otherwise the character is never actually changed in place. .lower() and .upper() also have a behaviour which already checks the range for you, and returns the same characters. Eg. if it already uppercase, or a number, upper() will just return the same character.
Your function can be simplified as follows:
import sys
def CapsChanger(str):
for i in str:
sys.stdout.write (i.lower() if (i.upper() == i) else i.upper())
print
str = raw_input()
CapsChanger(str)
sys.stdout.write is used to avoid printing out extra spaces. The ternary operator is used to switch case in one shot:
<value1> if <condition> else <value2>
i is a string, not index. If You need index use enumerate:
for idx, i in str:
print idx, i
Insted of ord(chr) use string that represent a letter.
Insted of two if conditions use Chained Comparisons.
def CapsChanger(str):
out = []
for idx,chr in enumerate(str):
if 'Z' >= chr >= 'A':
out.append(chr.lower())
elif 'z' >= chr >= 'a':
out.append(chr.upper())
print(''.join(out))

Building 'Find' function in Python

I have been learning Python (as my first language) from "How to Think Like a Computer Scientist: Learning with Python". This open book teaches mostly through examples and I prefer to read the goal and build the program on my own, rather than actually reading the program code provided in the book.
However, I am struggling with creating a function which will search for a specific character in a given string and return how many times that character was counted.
The code I wrote is:
def find(s, x): #find s in x
s = raw_input("Enter what you wish to find: ")
x = raw_input("Where to search? ")
count = 0
for l in x: #loop through every letter in x
if l == s:
count += 1
else:
print count
However, when I run this code, I get the error "name 's' is not defined".
The code in the book has a slightly different goal: it searches for a specific character in a string, but instead of counting how many times the character was found, it returns the position of the character in the string.
def find(strng, ch, start=0, step=1):
index = start
while 0 <= index < len(strng):
if strng[index] == ch:
return index
index += step
return -1
I don't really understand this code, actually.
However, even when I run the code, for example, to search for 'a' in 'banana', I get the error name 'banana' is not defined.
What is wrong with my code? Could please someone explain me how the code provided in the book works?
1: There are a couple things wrong with this code. The function takes in two parameters, s and x, then immediately throws them away by overwriting those variables with user input. In your for loop, every time you encounter a character that isn't s you print the count. You should try to separate different ideas in your code into different methods so that you can reuse code more easily.
Break down your code into small, simple ideas. If the purpose of find is to count the instances of a character in a string, it shouldn't also be handling user interaction. If you take out the raw_input and printing, you can simplify this function to:
def find(s, x): #find s in x
count = 0
for l in x: #loop through every letter in x
if l == s:
count += 1
return count
Now all it does it take in a character and a string and return the number of times the character appears in the string.
Now you can do your user interaction outside of the function
char = raw_input("Enter what you wish to find: ")
string = raw_input("Where to search?: )
print char + " appears " + `find(char, string)` + " times in " + string
2: The goal of this function is to find the first place where ch is found when walking through the characters strng from a starting position with a specified step. It takes in ch, strng, a position to start searching, and a step size. If the start is 0 and the step is 1, it will check every character. If the start is 2 it will check all but the first 2 characters, if the step is 2 it will check every other character, etc. This works by starting looking at the start index (index = start), then looping while the index is at least 0 and less than the length of the string. Since python is 0-indexed, the last character in the string has an index of one less than the length of the string, so this just restricts you from trying to check invalid indices. For each iteration of the loop, the code checks if the character at the current index is ch, in which case it returns the index (this is the first time it found the character). Every time it doesn't find the character at the current index, it increments the index by the step and tries again until it goes past the last character. When this happens it exits the loop and returns -1, a sentinel value which indicates that we didn't find the character in the string.
def find(strng, ch, start=0, step=1):
index = start
while 0 <= index < len(strng):
if strng[index] == ch:
return index
index += step
return -1
3: I'm guessing you passed some invalid parameters. strng should be a string, ch should be a single character, and start and step should be integers.
Try this. I took the parameters out of your function, moved the print command out of the else block and out of the for loop, and then wrote the last line to call the function.
def find(): #find s in x
s = raw_input("Enter what you wish to find: ")
x = raw_input("Where to search? ")
count = 0
for l in x: #loop through every letter in x
if l == s:
count += 1
print count
find()
It seems like you're taking in inputs s and x twice - once through the function arguments and once through raw input. Modify the function to do either one (say only from raw input - see below). Also, you only need to print out the count once, so you can place the print statement in the outermost indent level in the function.
def find(): #find s in x
s = raw_input("Enter what you wish to find: ")
x = raw_input("Where to search? ")
count = 0
for l in x: #loop through every letter in x
if l == s:
count += 1
print count

Categories

Resources