Appending max value of a zipped list - python-3.x

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}")

Related

Find sequences of minimum 3 values that differ only by 0.5%

lets say I have a list like [1,2,1.5,2,1.99,2.01,4] and I want my function to find the sequence [2,1.99,2.01] and build a new list of it. This can happen multiple times while looping over the initial list. I hope my problem is understandable.
Thanks in advance
This is my attempt:
import itertools
Support = []
Liste1 = [1,2,1.5,2,1.99,2.01,4]
Liste2 = Liste1[1:]
Liste1.pop(-1)
for S1,S2 in itertools.zip_longest(Liste1, Liste2):
if S2<=1.05*S1 and S2>=0.95*S1:
Support.append(S1)
The problem is that this loop will compare the value to the value before and not to the first value which was detected as the start of a series.
Layer1 = [round(x,2) for x in list(data["Close"])]
Layer2 = Layer1[0:1]
Layer1.pop(0)
Layer3 = []
Layer4 = []
for element in Layer1:
if element < 1.01*Layer2[0] and element > 0.99*Layer2[0]:
Layer2.append(element)
if len(Layer2)>= 6:
Layer3.extend(Layer2)
Layer4.append(statistics.mean(Layer3))
Layer3.clear()
Layer2.clear()
Layer2.append(element)
else:
Layer2.clear()
Layer2.append(element)
R_S = sorted([round(s,2) for s in Layer4])
R_S_clean = R_S[0:1]
R_S.pop(0)
for element in R_S:
if element >= 1.01*R_S_clean[-1] or element <= 0.99*R_S_clean[-1]:
R_S_clean.append(element)
R_S_clean_rev = reversed(R_S_clean)
for element in R_S_clean_rev:
if element < Price:
Support = element
Delta_S = str(abs(round((100-((100/element)*Price)),2))) + "%"
break
else:
Support = "/"
Delta_S = "/"
for element in R_S_clean:
if element > Price:
Resistance = element
Delta_R = str(abs(round((100-((100/element)*Price)),2))) + "%"
break
else:
Resistance = "/"
Delta_R = "/"
This is my workaround, time will tell if the performance is good enough.

Read N number of random lines from a text file / Python

I'm currently reading from a "collection" file which holds all possible outcomes, of type int, which I read into a DataFrame.
cycle = 19380816
pull = 10000000
sample = rand.sample(range(cycle),cycle-pull)
new_df = pd.read_csv('collection.txt', skiprows = sample, sep = " ", names = ['a1','b1','c1','a2','b2','c2','a3','b3','c3','a4','b4','c4','a5','b5','c5'], header = None)
Of course the sample cannot be greater than the length of the actual file.
I want to randomly pull lines which exceed the length of lines in the file.
In this case, where "pull > cycle".
Essentially a
rand.choice, 'of line in "collections.txt"', N times
Is there a way to do this using pd.read_csv?
You can always read in the entire dataframe, then take n samples (with replacement, using rand.choices) from the row indices and then use iloc to grab the new sampled dataframe.
# cycle = 19380816
pull = 10000000
whole_df = pd.read_csv('collection.txt', sep = " ", names = ['a1','b1','c1','a2','b2','c2','a3','b3','c3','a4','b4','c4','a5','b5','c5'], header = None)
i_sample = rand.choices(range(len(whole_df)), k=pull)
new_df = whole_df.iloc[i_sample]

How to split data and save min value of startTime to variable

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)])

Averaging a list from a file and also find the min and max rate of change between each index Python

We received a file called USPopulation.txt, with instructions that basically say line 1 in the file is the year 1950 and the last line being 1990. we needed to store the data in a list and do 3 things with said data.
Find the average(somewhat easy i think i have this down)
Find the maximum rate of change in any 1 year
Find the minimum rate of change in any 1 year
The Average of the numbers code taken from a past program
list_of_numbers = []
with open('USPopulation.txt') as f:
for line in f:
if line.strip():
list_of_numbers.append(int(line.strip()))
print('Total ',len(list_of_numbers))
print('Average ',1.0 * sum(list_of_numbers) / len(list_of_numbers))
I need to combine the other elements and have no idea how any help would be great
The rate of change is the difference between two subsequent values in the list. To get that value, you basically need to store the previous value and compare it to the current one.
One way of doing this would be to simply loop through your list, and collect those values:
previous = None:
ratesOfChange = []
for num in list_of_numbers:
if previous:
ratesOfChange.append(abs(num - previous))
previous = num
Getting the maximum and minimum is then as easy as calling max() and min() on the ratesOfChange list.
Of course to improve this a bit, you might want to consider collecting those values while parsing the file already (so you save the second loop through the list). And you could even note down the minimum and maximum at the same time to save another loop through it (both max and min will loop over the list).
if USPopulation.txt is like
1950=10000
1951=10005
1952=10030
then by converting the above lines into dictionary so that one can access each year and its corresponding population
file1 = open("USPopulation.txt", "r+")
years_dict = dict()
arr = []
class population:
def __init__(self):<br>
self.average = 0
self.maximum = 0
self.minimum = 0
def average_method(self):
try:
for line in file1.readlines():
value1 = line.split('=', 1)
years_dict[value1[0]] = int(value1[1])
length_of_dictionary = len(years_dict.keys())
for values in years_dict.values():
self.average = self.average + values
self.average = (1.0 * self.average / length_of_dictionary)
except:
print "not able to read the lines from the file"
def maximum_method(self):
try:
i = 0
for year in range(1950, 1952):
arr.insert(i, (years_dict[str(year + 1)] - years_dict[str(year)]))
i = i + 1
self.minimum = min(arr)
self.maximum = max(arr)
except:
print "not able to insert the element"
obj = population()
obj.average_method()
obj.maximum_method()
print "Average of population: " + str(obj.average)
print "maximum rate of change: " + str(obj.maximum)
print "minimum rate of change: " + str(obj.minimum)

Is it possible to concatenate a string with series of number?

I have a string (eg. 'STA') and I want to make a cell array that will be a concatenation of my sting with a numbers from 1 to X.
I want the code to do something like the fore loop here below:
for i = 1:Num
a = [{a} {strcat('STA',num2str(i))}]
end
I want the end results to be in the form of {<1xNum cell>}
a = 'STA1' 'STA2' 'STA3' ...
(I want to set this to a uitable in the ColumnFormat array)
ColumnFormat = {{a},... % 1
'numeric',... % 2
'numeric'}; % 3
I'm not sure about starting with STA1, but this should get you a list that starts with STA (from which I guess you could remove the first entry).
N = 5;
[X{1:N+1}] = deal('STA');
a = genvarname(X);
a = a(2:end);
You can do it with combination of NUM2STR (converts numbers to strings), CELLSTR (converts strings to cell array), STRTRIM (removes extra spaces)and STRCAT (combines with another string) functions.
You need (:) to make sure the numeric vector is column.
x = 1:Num;
a = strcat( 'STA', strtrim( cellstr( num2str(x(:)) ) ) );
As an alternative for matrix with more dimensions I have this helper function:
function c = num2cellstr(xx, varargin)
%Converts matrix of numeric data to cell array of strings
c = cellfun(#(x) num2str(x,varargin{:}), num2cell(xx), 'UniformOutput', false);
Try this:
N = 10;
a = cell(1,N);
for i = 1:N
a(i) = {['STA',num2str(i)]};
end

Resources