How to split data and save min value of startTime to variable - python-3.x

i wan't to create the script which can save from csv startTime and endTime to variable, for example i have different startTime values(11:59:12, 11:59:19, 11:59:22) and different endTime values (12:59:12, 12:59:19, 12:59:22), i want to store for startTime to varible only lowest one, which has been started early than others and endTime which has been ended last.
So from this examples must be stored to variable startTime = 11:59:12 and endTime = 11:59:22.
Could you tell me please what i gonna do. my script looks right now like that:
import csv
import datetime
import time
data = list(csv.reader(open('C:\\Documents and Settings\\Lemur\\Desktop\\TestResults.csv', 'r')))
startTimeWithoutCp = ""
for x in xrange(4, 13):
cpStartTime = (data[x][6])+ ":" + " " + (data[x][12][10:19])
cpEndTime = (data[x][6])+ ":" + " " + (data[x][13][10:19])
startTimeWithoutCp += (data[x][12][11:19])
#print("CP Start Times is: ", cpStartTime)
#print("CP End Time is: ", cpEndTime)
print(startTimeWithoutCp)
# The output results looks like that:
# 11:59:0811:59:1211:59:1911:59:2211:59:2811:59:3211:59:3711:59:4211:59:47
Could you tell me please, how i can split correctly this results and get minimal value from this list. Thank you!

First of all, I think you should store your time points in a list. Concatenating them into one string (like you do it for startTimeWithoutCp) makes it hard to get back the original times. On individual time points, you can use the fact that strings / characters can be sorted:
>>> a = '11:20:02'
>>> b = '04:34:12'
>>> c = '04:34:14'
>>> sorted([a, b, c])
['04:34:12', '04:34:14', '11:20:02']
>>> min([a, b, c])
'04:34:12'
So given you have your time points in a list, you can just use min() and max().
You can split the long string into its pieces by using Python's slicing notation:
d = '11:59:0811:59:1211:59:1911:59:2211:59:2811:59:3211:59:3711:59:4211:59:47'
print([d[i:i + 8] for i in range(0, len(d), 8)])

Related

Appending max value of a zipped list

I have these three lists:
bankNames = ["bank1","bank2","bank3"]
interestRate = (0.05,0.01,0.08)
namePlusInterest = zip(interestRate,bankNames)
print(max(list(namePlusInterest)))
the print function returns an output of:
(0.08, 'bank3')
I want to be able to split the output into individual variables (for example):
MaxRate = 0.08
MaxBank = 'bank3'
So for later in my code I can say:
print(MaxBank + "has the highest interest rate of" + MaxRate)
You can use tuple unpacking to get each individual element from the tuple:
bankNames = ["bank1", "bank2", "bank3"]
interestRate = (0.05, 0.01, 0.08)
namePlusInterest = zip(interestRate, bankNames)
MaxRate, MaxBank = max(list(namePlusInterest))
print(f"{MaxBank} has the highest interest rate of {MaxRate}")

Python: Average of datetime deltas in a for loop (excel file input)

First time posting, been trying to figure this one out for a bit and feel like I'm either approaching it wrong or over complicating it.
Goal: Ingest excel sheet with 2 columns of dates, find the difference of time between the dates per row, then find the average of all the differences.
I'm using openpyxl to do this, as it's an xlsx. The date values in the cell come out in the '%Y-%m-%d %H:%M:%S' format.
Here's what I have at the moment:
Excel_File = 'C:\Some\File\Location'
wb = load_workbook(Excel_File)
Data_Tab = wb['SheetA']
Dates_A = Data_Tab['A']
Dates_B = Data_Tab{'B']
for A, B in zip(Dates_A[1:], Dates_B[1:]):
A_str = str(A.value) #converting to string to convert to datetime since I couldn't find another way to do this
B_str = str(B.value)
A_conv = datetime.datetime.strptime(A_str,'%Y-%m-%d %H:%M:%S')
B_conv = datetime.datetime.strptime(B_str,'%Y-%m-%d %H:%M:%S')
A_B_Delta = B_conv - A_conv
Where I've gotten stuck is how to add all the A_B_Deltas together and get an average.
I would need to figure out how to get the total to input into average, which I guess I could just increment a variable to get this number. Such as:
Total_Count = 0
Total_Count += 1
But how do I add the deltas to get an average?
I have tried adding them to a variable with no success at this point. I also tried setting a empty datetime object variable but that doesn't appear to be possible as it'll just error out.
A_B_Delta = 0 # Initialize variable
denominator = 0 # Initialize variable
for A, B in zip(Dates_A[1:], Dates_B[1:]):
A_str = str(A.value)
B_str = str(B.value)
A_conv = datetime.datetime.strptime(A_str,'%Y-%m-%d %H:%M:%S')
B_conv = datetime.datetime.strptime(B_str,'%Y-%m-%d %H:%M:%S')
A_B_Delta += B_conv - A_conv # Use += to increment variable
denominator += 1 # Use += to increment variable
average = A_B_Delta / denominator # Compute average after the for loop
Initializing A_B_Delta and incrementing it sum up all the time difference. There are many ways you can get the denominator to compute the average.

python TypeError: can only concatenate str (not "int") to str

import time
for i in range(2,6):
start = time.time()
n=i
end = time.time()
print(n)
time_cost=end-start
print(type(time_cost))
print('totally cost for '+n+'*'+n,str(time_cost))
I use str to change type for time_cost, but still have error
The problem here is that n is still an int when you try to concatenate it with 'totally cost for '
You must replace the last print statement with this:
print('totally cost for '+str(n)+'*'+str(n), str(time_cost))
It is also fine if you don't call str() on time_cost since it is a different parameter and thus print() automatically converts it. n is not converted since is concatenated explicitly using a + operator.
So final print can be:
print('totally cost for '+str(n)+'*'+str(n), time_cost)

String search keep returning empty in python

I have kept trying to get my code to work but I keep getting blank output and I am not allowed to import anything e.g. RE:
choc1 =' outf.write("/# " + str(number) + " #/ " + line) #lots of cake(#) lovers here'
EC = choc1
ECout = EC
out = ""
for x in ECout :
if x!="#[a-z,A-Z]":
x = x.replace(x,"")
out += x
if out== '#lots of cake(#) lovers here':
print("well done Lucy")
else:
print(out)
I must be really stupid as this should be simple - I need to return '#lots of cake(#) lovers here' but I'm stuck on this assignment.
Any help would be greatly appreciated.
Thanks in advance - Jemma
Looking at your for loop, you are examining each character in a string individually, and comparing this to a string that is several characters long. Is this what you intended? Consider:
>>> a = "abc"
>>> for x in a:
... print(x)
...
a
b
c
Perhaps you meant to take each character, and compare that character to each character separately in the other string with a slightly different statement?

How can I insert spaces at certain locations in a string (Python 2.7)?

I've found many related questions, and a couple that have at least helped me get this far. My goal is to have a function that receives a string and an arbitrary number of integers. I want the function to return that string with spaces inserted at the points given in the arguments. I will use this function with many different strings that will have varying numbers of inserts and insert locations.
This is an example of what I'd like to produce:
Input a string like 'ATGCATGCATGCATGC' and indexes (e.g. 4, 7). The output should be 'ATGCA TGC ATGCATGC'.
This is the function that has given me the closest results so far:
def breakRNA(seqRNA, *breakPoint):
n = 0
for i in seqRNA:
n += 1
for i in breakPoint:
if i == n:
seqRNA = seqRNA[n:] + ' ' + seqRNA[:n]
return seqRNA
The return string, however, is transposed out of order. Example:
>>> test = breakRNA('AAAAAAAAAAAAAAAAAAAAAAAAAAATTTTTGGGGGGGGCCCCCCCCCC', 5, 8, 14)
>>> test
>>> 'TTTTTGGGGGGGGCCCCCCCCCC AAAAA AAAAAAAA AAAAAAAAAAAAAA'
I am a day-1 beginner so any advice is appreciated. Thank you.
String are indexed like list in Python.
For example consider the following:
test_string = "azertyuiop"
print test_string[0] #will return 'a'
print test_string[0:2] #will return 'az'
So getting back to your problem:
def insert_space(string, integer):
return string[0:integer] + ' ' + string[integer:]
Hope this is what you are looking for
def breakRNA(seqRNA, *breakPoint):
seqRNAList = []
noOfBreakPoints = len(breakPoint)
for breakPt in range(noOfBreakPoints):
for index in breakPoint:
seqRNAList.append(seqRNA[:index])
seqRNA = seqRNA[index:]
break
return seqRNAList
test = breakRNA('AAAAAAAAAAAAAAAAAAAAAAAAAAATTTTTGGGGGGGGCCCCCCCCCC', 5, 8, 14)
print test
This will return you alist then you can create a string out of it using join function.
simbol = input('Enter a character:\n')
triangle_n = int(input('Enter triangle height:\n'))
print('')
for i in range (triangle_n ):
for j in range(i+1):
print(simbol [0],end=' ')
print()
string_name = string_name[starting index:ending index] + ' ' + string_name[starting index:ending index]
example:
product_rating = '4.56888 rating 256156 reviews'
product_rating = product_rating[0:3] + ' ' + product_rating[3:]
output
'4.5 6888 rating 256156 reviews'
If ending index is not mentioned its default value will be till the end of string.
Note indexing will start from 0 and 0:3 means it will take 0 to 2.

Resources