How to print change from previous printed line? - python-3.x

I have a function that reads temperatures from a device. After printing the temperature, I'd like to print the change in temperature from the previous printed line. Is there an easy way to do this?
While i < 50000:
T = getTemps()
print(T)
print(deltaT) # <-- I want to do this

I think you can keep the previous temperature as a separate variable, and once you print the delta, you can reassign previous one with the current one, because anyway with next loop you will get new value;
t = getTemps()
tPrevious = t
while i < 50000:
t = getTemps()
print(t)
print(t - tPrevious)
tPrevious = t

I think somethink like that
prev_T = 0 # Default value for first iteration
i = 0
while i < 50000:
T = getTemps()
print(T)
print(T - prev_T)
prev_T = T
i += 1

Related

Python. Trying to write a function called one_frame. Does not seem to work. Help would be greatly appreciated

As of right now, this is my code:
def get_orf(DNA):
codon = ''
if(DNA[0:3] == 'ATG'):
codon = DNA[0:3]
for x in range(3,len(DNA)+1,3):
if DNA[x:x+3] == "TAG" or DNA[x:x+3] == "TAA" or DNA[x:x+3] == "TGA":
return codon
else: codon = codon + DNA[x:x+3]
if codon[-3:] in ["TAG", "TAA", "TGA"]:
return codon
else: return 'No ORF'
def one_frame(DNA):
x = 0
ORFlist = []
while x < len(DNA):
codon = DNA[x:]
if DNA.startswith('ATG'):
get_orf(DNA[x:])
if codon:
ORFlist.append(codon)
x += len(codon)
return(ORFlist)
get_orf function works fine but my one_frame function doesn't work.
The one_frame function is supposed to take a DNA string as input. It searches that
string from left to right in multiples of three nucleotides–that is, in a single reading frame. When
it hits a start codon “ATG" it calls get_orf on the slice of the string beginning at that start codon
(until the end) to get back an ORF. That ORF is added to a list of ORFs and then the function skips
ahead in the DNA string to the point right after the ORF that we just found and starts looking for
the next ORF. This is repeated until we’ve traversed the entire DNA string.
I can see a few obvious problems but not sure exactly what you want so hope this helps. Firstly your for loop in one_frame will never end unless DNA starts with 'ATG'. I think you want to check codon.startswith instead of DNA.startswith. You also need to do the x+= command outside of the if statement, or it will never be updated when you don't hit 'ATG' and so your loop will continue forever. You're also not using the value of get_orf at all.
I think this will do the trick,
def one_frame(DNA):
x = 0
ORFlist = []
while x < len(DNA):
codon = DNA[x:]
# Check codon instead of DNA
if codon.startswith('ATG'):
# Record the return value of get_orf
orf_return_value = get_orf(DNA[x:])
if orf_return_value:
ORFlist.append(orf_return_value)
x += len(orf_return_value)
# Increment by 3 if we don't hit ATG
else:
x += 3
return(ORFlist)

choose the middle in merge sort

I was trying to complete a merge sort in Python. I found when I use middle = (len(x)-1)//2, the right part was in infinity loop and never reached the base case, but if I changed middle = len(x)//2, it worked normally. So why?
The solution does lie in the middle variable. After abit of experimenting I found that using middle = len(alist)//2 fixes the whole program. Despite this not being technically mathematical, it does seem to work.
You could also increase efficiency by replacing the if and else at the start of the mergesort() function with a simple if len(alist) > 1: and then return alist at the end of the function, rather than at the end of each if and else, if that makes sense. (This would also mean you can just replace the com variable with alist).
For reference, heres my code (some variables are renamed):
from random import shuffle
### INIT ###
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
shuffle(arr)
print("Starting List: " + str(arr))
### SORT ###
# Merge
def merge(left,right):
sorted = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
sorted.append(left[i])
i += 1
else:
sorted.append(right[j])
j += 1
sorted += right[j:]
sorted += left[i:]
return sorted
# Decomposition
def sort(arr):
#print(arr)
if len(arr) > 1:
middle = len(arr)//2
left = sort(arr[:middle])
right = sort(arr[middle:])
arr = merge(left, right)
return arr
arr = sort(arr)
print("Ending List: " + str(arr))

Making a variable a 'less than' value?

i'm really new to Python and am completely stuck
is there any way to make the less than value a variable
for example
x = int(input ("Input a value for x: "))
i = 1
while i < x:
x += i
i += 1
else:
print ("here is your new number:", x,)
whenever i use this, nothing happens
thanks for your help
It's not technically true to say that nothing happens, plenty is happening.
However, one thing that's not happening is the thing that generates the output (unless you enter a value less than or equal to one).
The while..else construct will only execute the else block if the while block did not do any iterations.
So, if you want output after the loop regardless of whether the loop body executes, get rid of the else and unindent the print.
The other thing that's not happening is the exit condition of the loop itself. If i starts out less than x (and they're both positive to start with), adding i to x then adding 1 to i will never give you a situation where i is not less than x.
Think about (for example):
x i Description
----- ----- -----------
3 1 Initial state
4 2 x += i; i += 1;
6 3 x += i; i += 1;
9 4 x += i; i += 1;
13 5 x += i; i += 1;
18 6 x += i; i += 1;
24 7 x += i; i += 1;
31 8 x += i; i += 1;
You can see that x is increasing at a faster rate than i, hence i < x will always be true.
How you fix that depends entirely on what you're trying to achieve. Since you have described your problem in terms of the code, your code matches perfectly your requirements. Hence, since you state it's not working as you expected, it appears your requirements may need some work :-)
I would suggest stating, in English, what you're trying to achieve here, and we can then suggest where your implementation has gone wrong.
What you wrote will result in an infinite loop if i < x in the beginning. So it will never reach the print statement that you hope it will. Plus, I also believe that you have to delete the else and indent the print statement.

Finding location of specified substring in a specified string (MATLAB)

I have a simple question that I need help on. My code,I believe, is almost complete but im having trouble with the a specific line of code.
I have an assignment question (2 parts) that asks me to find whether a protein (string), has the specified motif (substring) at that particular location (location). This is the first part, and the function and code looks like this:
function output = Motif_Match(motif,protein,location)
%This code wil print a '1' if the motif occurs in the protein starting
at the given location, else it wil print a '0'
for k = 1:location %Iterates through specified location
if protein(1, [k, k+1]) == motif; % if the location matches the protein and motif
output = 1;
else
output = 0;
end
end
This part I was able to get correctly, and example of this is as follows:
p = 'MGNAAAAKKGN'
m = 'GN'
Motif_Match(m,p,2)
ans =
1
The second part of the question, which I am stuck on, is to take the motif and protein and return a vector containing the locations at which the motif occurs in the protein. To do this, I am using calls to my previous code and I am not supposed to use any functions that make this easy such as strfind, find, hist, strcmp etc.
My code for this, so far, is:
function output = Motif_Find(motif,protein)
[r,c] = size(protein)
output = zeros(r,c)
for k = 1:c-1
if Motif_Match(motif,protein,k) == 1;
output(k) = protein(k)
else
output = [];
end
end
I belive something is wrong at line 6 of this code. My thinking on this is that I want the output to give me the locations to me and that this code on this line is incorrect, but I can't seem to think of anything else. An example of what should happen is as follows:
p = 'MGNAAAAKKGN';
m = 'GN';
Motif_Find(m,p)
ans =
2 10
So my question is, how can I get my code to give me the locations? I've been stuck on this for quite a while and can't seem to get anywhere with this. Any help will be greatly appreciated!
Thank you all!
you are very close.
output(k) = protein(k)
should be
output(k) = k
This is because we want just the location K of the match. Using protien(k) will gives us the character at position K in the protein string.
Also the very last thing I would do is only return the nonzero elements. The easiest way is to just use the find command with no arguments besides the vector/matrix
so after your loop just do this
output = find(output); %returns only non zero elements
edit
I just noticed another problem output = []; means set output to an empty array. this isn't what you want i think what you meant was output(k) = 0; this is why you weren't getting the result you expected. But REALLY since you already made the whole array zeros, you don't need that at all. all together, the code should look like this. I also replaced your size with length since your proteins are linear sequences, not 2d matricies
function output = Motif_Find(motif,protein)
protein_len = length(protein)
motif_len = length(motif)
output = zeros(1,protein_len)
%notice here I changed this to motif_length. think of it this way, if the
%length is 4, we don't need to search the last 3,2,or 1 protein groups
for k = 1:protein_len-motif_len + 1
if Motif_Match(motif,protein,k) == 1;
output(k) = k;
%we don't really need these lines, since the array already has zeros
%else
% output(k) = 0;
end
end
%returns only nonzero elements
output = find(output);

Binary search code not working

Good afternoon everyone,
I'm trying to sort out names which are already sorted in alphabetical order. I can't figure out why my program isn't working. Any tips or pointers would be nice. Thanks.
def main():
names = ['Ava Fiscer', 'Bob White', 'Chris Rich', 'Danielle Porter', 'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle', 'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']
input('Please enter the name to be searched: ', )
binarySearch
main()
def binarySearch(names):
first = 0
last = len(names) - 1
position = -1
found = False
while not found and first <= last:
middle = (first + last) / 2
if names[middle] == value:
found = True
position = middle
elif arr[middle] > value:
last = middle -1
else:
first = middle + 1
return position
What does it mean that the program isn't working? Is it a syntax error or is the problem in the wrong results?
With the code you pasted, there are several indentation problems, but besides that, lines:
input('Please enter the name to be searched: ', )
binarySearch
are also syntactically incorrect, the comma is redundant and only the function name appearing just like that is plain wrong. If you are interested in the correctness of your algorithm, it seems alright, but the boundaries can always be tricky. My code below is working and syntactically correct, if you find it helpful. (names are numbers, but that is irrelevant in this case)
names = [1,2,4,5,6,8,9]
def bs(n):
start = 0
end = len(names)
while end - start > 0:
m = (start+end)/2
if names[m] == n:
return m
elif n < names[m]:
end = m
else:
start = m + 1
return -1
print (bs(1))
print (bs(6))
print (bs(9))
print (bs(3))
print (bs(10))
print (bs(-8))
Another thing I would like to point out is that this kind of binary search is already in the python standard library, the bisect module. However, if you are writing your own for practice or for any other reason that is just fine.
if you are using python 3.* then you are going to want to change
m = (start+end)/2
to
m = (start+end)//2
When you do /2 it outputs a float in 3.*

Resources