Preorder result for the following binary search tree - tree-traversal

I was wondering about the preorder result of the following binary search tree, as Im not sure how to approach the right side of the tree.
Thanks!
8
/ \
3 10
/ \ \
1 6 14
/ \ / /
0 2 4 13

The result is [8, 3, 1, 0, 2, 6, 4, 10, 14, 13]. You can use this website: http://www.cs.armstrong.edu/liang/animation/web/BST.html to create your tree first, and then select preorder option to get the result.

Related

How to check if positional indexes in a list exists in section of corresponding DataFrame

I have a DataFrame like this:
Date A B C
2021-08-20 1 2 3
2021-08-21 2 3 4
2021-08-22 3 4 5
2021-08-23 4 5 6
2021-08-24 7 8 9
2021-08-25 10 11 12
2021-08-26 11 12 13
2021-08-28 12 13 14
My "target" section is dates from 2021-08-21 to 2021-08-24.
Now I have a list of positional indices:
A = [0, 1, 3, 4, 6, 7]
What I'm trying to do is create a new list of indices that correspond to the indices only in my target section, and then find the total number of elements in the new list.
Target answer:
new_list = [1, 3, 4]
print(len(new_list))
3
I've tried this so far:
new_list = []
df_range = df.loc['2021-08-21':'2021-08-24']
for data_idx in A:
if data_idx == df_range.iloc[data_idx]:
new_list.append(data_idx)
print(len(new_list))
But I get IndexErrors (single positional indexer is out-of-bounds) or Key errors (for a similar attempt). I believe what's erroring is when the program tries to locate the indexes outside of this range?
Thank you in advance and sorry if anything is confusing. I know there should be an easy way to do this but I just can't figure it out.
IIUC:
A = [0, 1, 3, 4, 6, 7]
df["tmp"] = range(len(df))
x = df.loc["2021-08-21":"2021-08-24"]
print(x.loc[x["tmp"].isin(A), "tmp"].to_list())
Prints:
[1, 3, 4]
If 'Date' is in the index of the dataframe and the datatype is datetime index, then we can use pd.Index.get_indexer and use set operations to find intersection.
#Copy dataframe from question above
df = pd.read_clipboard(index_col=[0])
df.index = pd.to_datetime(df.index)
idx = df.index.get_indexer(pd.date_range('2021-08-21', '2021-08-24', freq='D'))
A = [0, 1, 3, 4, 6, 7]
overlap = set(A) & set(idx)
print(f'{overlap=} and {len(overlap)=}')
Output:
overlap={1, 3, 4} and len(overlap)=3
If I understood the question, you're wanting to have a list with corresponding indexes to your df_range? If so these two approaches are commonly used for that
new_list = []
df_range = df.loc['2021-08-21':'2021-08-24']
for i, v in enumerate(df_range):
new_list.append(i)
for i in range(len(df_range)):
new_list.append(i)

Python 3.x : I'm out of range

I'm asking to have some help cause I believe I know why I'm out of range but I don't know out to solved it. Thanks you :D
#Import input.
from pathlib import Path
test = Path(r'C:\Users\Helphy\Desktop\Perso\GitHub\Advent_of_Code_2021\Day_3\Input.txt').read_text().split("\n")
#Defined some variable
temp = []
finalnumtemp = []
finalnum = []
f_num = []
zero = 0
one = 0
for t in range(len(test)):
for j in range(len(test)):
temp = list(test[j])
print(temp)
finalnumtemp.append(temp[j])
print(finalnumtemp)
"""for i in range(len(finalnumtemp)):
if int(finalnumtemp[i]) == 0:
zero += 1
else:
one += 1
if zero > one:
finalnum.append(0)
else:
finalnum.append(1)
zero == 0
one == 0
finalnumtemp = []
print(finalnum)"""
Input :
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
error: An exception has occurred: IndexError
list index out of range
File "C: \ Users \ Helphy \ Desktop \ Perso \ GitHub \ Advent_of_Code_2021 \ Day_3 \ Day_3.py", line 16, in <module>
finalnumtemp.append (temp [j])
What to solve? What did you intend for the program to achieve?
You have an error because...
j goes from 0 to len(test), that is, 12
test[j] as temp has only 5 elements.
To select among the digits in temp, the index should be something of 0, 1, 2, 3, 4 (first, second, third, ... from the left) or -1, -2, -3, -4, -5 (first, second, third, ... from the right).
To append the first of temp to finalnumtemp, fix
finalnumtemp.append(temp[j])
to
finalnumtemp.append(temp[0])
Maybe you should look into list comprehension. I know it is maybe a bit daunting at first but I personally found it to make much more sense than nested for loops after I had gotten the hang of them. You could convert your strings of zeros and ones into lists of separate integers in a single line:
numbers = [[int(char) for char in line] for line in test]
[[0, 0, 1, 0, 0], [1, 1, 1, 1, 0], ... , [0, 0, 0, 1, 0], [0, 1, 0, 1, 0]]
And then fetch the first number (or any number really):
first_num = [num[0] for num in numbers]
[0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0]
And even perform operations on the lists if you wish:
sum_num = [sum(num) for num in numbers]
[1, 4, 3, 4, 3, 4, 3, 3, 1, 3, 1, 2]
Nested for loops can get real messy real quick. I know this isn't the actual answer to the question, but I thought it might be helpful regardless.

How can I delimit the width of a trendline?

I have these variables:
X = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
Y = (1, 5, 4, 9, 7, 8, 12, 20, 9, 7, 4, 1, 1, 2, 1, 1)
and I want to do a graphic with two visible partitions (X from 1 to 8 and X from 9 to 16). So, I set one dimension X and two expressions IF (X <= 8,Y) and IF (X > 8,Y). It works well and I got this:
Basic graphic
Now I want to include the linear trend line. But, after click in the proper option in the expressions tab, I got this:
Graphic with trend lines
which is not a good thing to see. I wished something like this:
Wished graphic with trend lines
Anyone knows how can I get a graphic like this last picture?
Many thanks in advance.
If you want manually to calculate the linear Regression you have to use these functions LINEST_B and LINEST_M like this:
linest_M(total aggr(Y,X),X)*X+ linest_b(total aggr(Y,X),X)
but with some modifications because you split your expressions.
Here is an example with your data set:
Here is the whole file
from Qliks' help

Numpy arrays: can I multiply only a few elements in the array and not all of them?

I am using Python3 and numpy with matplotlib on a project to get Jupiter's Mass from observational telescope astrometry. I want to take an array of numbers, say from 1 to 10, and multiply only a few of them in order, say 1 to 4, by -1.
So 1 to 4 is now negative and 5 to 10 is still positive. I imagine out put like this:
L = [1,2,3,4,5,6,7,8,9,10]
array_L = np.array(L)
>>>array_L
array([1,2,3,4,5,6,7,8,9,10])
neg = array_L[0:4]
>>>neg
array([1,2,3,4])
Neg = neg * -1
>>>Neg
array([-1,-2,-3,-4])
Now I need a way of combining neg and array_L into a new final array that would output like this:
# pseudo code: Neg + array_L(minus elements 0 to 4) = New_L
New_L = array([-1,-2,-3,-4, 5, 6, 7, 8, 9, 10])
Also I know it may be possible to do a limited element iteration over just the elements I want and not the whole array. I can do some of these operations on the list vs the array if it would make it easier.
You are almost there! Try this:
L = array([1,2,3,4,5,6,7,8,9,10])
L[0:4] *= -1
print(L)
Just like with regular python lists, you can do operations on slices of NumPy arrays to change them in-place:
>>> import numpy
>>> L = [1,2,3,4,5,6,7,8,9,10]
>>> array_L = numpy.array(L)
>>> array_L
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> array_L[0:4] *= -1
>>> array_L
array([-1, -2, -3, -4, 5, 6, 7, 8, 9, 10])

Generate series of 1,1,2,2,3,3,

I've an variable as page number (page) whose values increment by one each time. [Page numbering] But, now I need to customize this numbering to 1,1,2,2,3,3..
Can you suggest any formula for generate this kind of series?
EDIT: (Answer)
After playing with macros and VBA for some time I've figured out a way to generate this type of series for MS word page numbers. This can be easily done with formulas and {Page} variable in word with formula-
{=(({PAGE} + MOD({PAGE},2))/2)}
The answer is simple: (n + 1) / 2
javascript, adapt to suite:
for(i=0; i>yourMaximum; i++){
WriteSomewhere(i + "," + i);
if(i != i - yourMaximum) WriteSomewhere(",");
}
You can do this kind of thing:
for (int i = 0; i < (pages * 2); i++) {
System.out.println((i / 2) + 1);
}
It is late, but it might help someone.
A mathematical answer to the problem:
You do not need to search through all n numbers in order to have a specific result
1 2 3 4 5 6 7 8 9 . . . . . . . n
1 1 2 2 3 3 4 4 5 . . . . . . . f(n)
General formula:
f(n) = ( n - ( (-1) + (-1)^n )/2 )/2
Playing with the first (-1) you can shift the results like this:
f(n) = ( n - ( (3) + (-1)^n )/2 )/2
1 2 3 4 5 6 7 8 9 . . . . . . . n
0 0 1 1 2 2 3 3 4 . . . . . . . f(n)
Python:
(int(x/2+1) for x in itertools.count())
Ruby
(1..10).map {|n| [n,n]}.flatten
=> [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]
or
(1..10).inject([]) {|m,n| m<<n<<n}
=> [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]
or
(1..10*2).map {|n| (1+n)/2}
=> [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]
C#, not a formula but a simplistic algorithm.
int[] pages = new int[2*N];
for(i=0; i<N; i++)
{
page[2*i] = i+1;
page[2*i+1] = i+2;
}
After playing with macros and VBA for some time I've figured out a way to generate this type of series for MS word page numbers. This can be easily done with formulas and {Page} variable in word with formula-
{=(({PAGE} + MOD({PAGE},2))/2)}

Resources