Printing out values from a function - python-2.7

Ok so the issue with my program is that for some reason when I run it the variables at the bottom come out as "None" instead of the count of the amount of ATG's in the original strings of HumanDNA, MouseDNA, and UnknownDNA. I couldn't add the part where i define these DNA's because of their length and was difficult for me to add it. How can I change it so instead it outputs the amount of times the substring is found in the original string as a variable that is outside the function and can output it in the format I have at the bottom.
def countCodon(string, substring):
i = string.find(substring)
def compareDNA(string1, string2):
string1 = raw_input("Enter string 1: ")
string2 = raw_input("Enter string 2: ")
Hamming = 0
for ch1, ch2 in zip(string1, string2):
if ch1 != ch2:
Hamming += 1
l = len(string1)
similarity_score = ((l - Hamming)/(l))
print similarity_score
HD = countCodon(humanDNA, "ATG")
MD = countCodon(mouseDNA, "ATG")
UD = countCodon(unknownDNA, "ATG")
print "Mouse: ", HD
print "Human: ", MD
print "Unknown: ", UD
MU = compareDNA(mouseDNA, unknownDNA)
HU = compareDNA(humanDNA, unknownDNA)
if MU != HU and MU > HU:
print "mouse"
elif MU != HU and MU < HU:
print "human"
elif MU == HU:
print "identity cannot be determined"
EDIT: Added the messed up part of the second function running into a similar problem.

countCodon() has no return value so HD = None
Moreover from https://docs.python.org/2/library/string.html
string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.
So countCodon() is giving you the index where the string "ATG" first appears, not the number of times it is present.

Related

how to remove empty spaces between '=' and values in fortran

I read data from a file and parse them to store in some variables. Data are written as below in the file,
INT_VALUE = 17 # Valid Integer
INT_VALUE1 23
INT_VALUE2 = 00012
INT_VALUE3 -2
INT_VALUE4 -33
In some places there are spaces and '=' in some other places. While reading I get my stream%val with '='and my value comes as ' = 17' of which I need to remove = and the spaces between '=' symbol and the first number and store as a valid number.
In some other cases there might be spaces between the numbers which should be an error.
Invalid values will be any non integer/real values with special characters. For example,
INT_VALUE13 34=5434
INT_VALUE14 -23 45-33
INT_VALUE15 = 23-45*665Rtre
INT_VALUE16 -23.4
INT_VALUE17 1.4E9r23
INT_VALUE18 -5.D-3.3
INT_VALUE19 233 ddf
INT_VALUE20 -87 dfsdf
INT_VALUE21 = rtmr,t23./
How do I remove the spaces in fortran?
My function is,
character(60) function sweep_blanks(in_str)
character(*), intent(in) :: in_str
character(60) :: out_str
character :: ch
integer :: j
out_str = " "
do j=1, len_trim(in_str)
ch = in_str(j:j)
if (ch .ne. " ") then
out_str = trim(out_str) // ch
endif
sweep_blanks = out_str
end do
end function sweep_blanks
This removes all blanks irrespective of in the middle or at the end or at the beginning which doesn't help.
You can do this using the two functions index and adjustl.
index finds the location of a substring within a string;
adjustl makes leading blanks trailing blanks.
integer idx
idx = INDEX(instring, '=')+1
outstring = ADJUSTL(instring(idx:))
So, given the input string
instring = ' = 17'
the index result will be 2, giving idx value 3. instring(3:) has the value ' 17' from which adjustl' returns '17 '
Given the input string
instring = ' -33'
without the '=' the index result will be 0.

Why python shows same index value for same character in a string?

I am trying to print all the occurences of character 'p' in a string "python program".It shows same index value as 0 both 'p's in the string instead of 0 and 7.
str = raw_input("enter a string:")
sub = raw_input("enter a sub string:")
for i in str:
if i.lower() == sub.lower():
print i, str.index(i)
Output :
enter a string:python program
enter a sub string:p
p 0
p 0
Here is a suggestion for a solution:
sub = raw_input("enter the sub string you're looking for: ")
string = raw_input("enter the text you're looking in: ")
def get_next(text, sub):
for i in range(len(text)+1):
pos = text.find(sub, i)
if pos == -1 : #if no occurrences, do nothing
break
if i == pos: #would print the sub and the pos only if pointer in correct position
print sub, pos
get_next(string, sub)
You can have a while loop instead of a function, but I think a function would be more convenient if you want to use the code several times.

Python: Trying to loop through a string to find matching characters

I am trying to create a simple "guess the word" game in Python. My output is something like:
String: _____ _____
Guess a word: 'e'
String:_e__o __e_e
Guess a word: 'h'
(and so on)
String: hello there
I have a function to do this, and within this function I have this code:
def guessing(word):
count = 0
blanks = "_" * len(word)
letters_used = "" #empty string
while count<len(word):
guess = raw_input("Guess a letter:")
blanks = list(blanks)
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz "):
print "Please only guess letters!"
#Checks if guess is found in word
if guess in word and guess not in letters_used:
x = word.index(guess)
for x in blanks:
blanks[x] = guess
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-counter
print "There are", str(word.count(guess)) + str(guess)
guess is the raw input I get from the user for a guess, and letters_used is just a collection of guesses that the user has already input. What I'm trying to do is loop through blanks based on the word.index(guess). Unfortunately, this returns:
Guess a letter: e
e___
Yes, there are 1e
Help would be much appreciated!
Your code was almost correct. There were few mistakes which I have corrected:
def find_all(needle, haystack):
"""
Finds all occurances of the string `needle` in the string `haystack`
To be invoked like this - `list(find_all('l', 'hello'))` => #[2, 3]
"""
start = 0
while True:
start = haystack.find(needle, start)
if start == -1: return
yield start
start += 1
def guessing(word):
letters_uncovered_count = 0
blanks = "_" * len(word)
blanks = list(blanks)
letters_used = ""
while letters_uncovered_count < len(word):
guess = raw_input("Guess a letter:")
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz"):
print "Please only guess letters!"
if guess in letters_used:
print("This character has already been guessed correctly before!")
continue
#Checks if guess is found in word
if guess in word:
guess_positions = list(find_all(guess, word))
for guess_position in guess_positions:
blanks[x] = guess
letters_uncovered_count += 1
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-letters_uncovered_count
print "There are", str(word.count(guess)) + str(guess)
else:
print("Wrong guess! Try again!")

Multiple Errors in Hangman program

I've been teaching my self to program in python lately and decided to make this game. I have been successful for the majority of it except for a few things
When an incorrect letter is inputted, the letter is appended to the wrong letter array for as many spots in the gamespace array that the userletter does equal.Example: if I type in "the" for the wordtarget, I get t, h and e printed 2 times into wrong letter array. No matter what the letter gets out into wrong letter array
Code:
wordTarget = raw_input("enter word here: ").lower ()
gameSpace = ["_"] * Len(wordTarget)
wrongLetter = []
def main():
for x in range(0, len(wordTarget)):
while (gameSpace[x] != wordTarget[x]):
getLetter()
for i in range(0,len(wordTarget)):
if (wordTarget[i] == userLetter):
gameSpace[i] = userLetter
elif (wordTarget[i] != userLetter):
print "letter is incorrect, try again"
wrongLetter.append(userLetter)
print ("Incorrect Letters: %s" % wrongLetter)
print ("Correct Letters: %s" % gameSpace)
if (gameSpace == wordTarget):
print "Congratulations! You won"
main()
I'm guessing the problem lies with the for loops I'm running and the way I'm checking for right answer but can't figure it out.
The loop checking the letter seems to be your issue. Try replacing it with:
position = 0
ptr = wordTarget.find(userLetter, position)
while ptr != -1:
gameSpace[ptr] = userLetter
position = ptr + 1
ptr = wordTarget.find(userLetter, position)
if position == 0: # no match ever found
print "letter is incorrect, try again"
wrongLetter.append(userLetter)
Also replace the original for loop with while ("".join(gameSpace) != wordTarget):, and you should be good to go.

Python's min() function does not work with raw_input converted to float

[Running on Xubuntu 12.04 LTS, Python 2.7]
Hey. I am struggling a bit with this assignment. It is from book about learning Python but I am probably missing something here. I do not require complete answer but a hint what should I do would be much better than copy/paste it.
My goal now is to create code that counts Smallest number so far from all the user inputs. I know that it has to do something with an impossibility of using min() and "for loops" for float numbers/single numbers as it is necessary to have some list but I do not have any idea what to do now..
Count = 0
Total = 0
Smallest = None #Or maybe I should use something like Smallest = []?
while True:
user = raw_input("Enter number, when you are finished enter done or press enter: ")
if len (user) < 1: break
if user == "done":
print "Done entered, program executed!"
break
try:
fuser = float(user)
print "Valid input.", "Your input:", fuser
except:
print "Invalid input.", "Your input:", user
continue
Count = Count + 1
Total = Total + fuser
#Smallest = None
#for i in [Total]:
#if Smallest is None or itervar < Smallest:
#Smallest = i
# As you can see I've been simply trying to find some way (code with # obviously doesn't work at all...)
#print "Min: ", Smallest
print "Count: ",Count
print "Total number: ",Total
try:
print "Average:", Total/Count
except:
print "NOT AVAILABLE"
Thank you very much for tips and hints on what to do next.
The easiest way may be:
Smallest = []
...
Smallest.append( float( user ) )
and then the total is sum( Smallest ), the smallest is min( Smallest ) and the number is len( Smallest ). You are storing all the intermediate values, which is not really necessary, but I think here is the simplest.