The "buildSelect" function provided in this white paper generates error when I try to apply it to a select statement.
tidy:{ssr/[;("\"~~";"~~\"");("";"")] $[","=first x;1_x;x]};
strBrk:{y,(";" sv x),z};
//replace k representation with equivalent q keyword
kreplace:{[x] $[`=qval:.q?x;x;"~~",string[qval],"~~"]};
funcK:{$[0=t:type x;.z.s each x;t<100h;x;kreplace x]};
//replace eg ,`FD`ABC`DEF with "enlist`FD`ABC`DEF"
ereplace:{"~~enlist",(.Q.s1 first x),"~~"};
ereptest:{((0=type x) & (1=count x) & (11=type first x)) | ((11=type x)
&(1=count x))};
funcEn:{$[ereptest x;ereplace x;0=type x;.z.s each x;x]};
basic:{tidy .Q.s1 funcK funcEn x};
addbraks:{"(",x,")"};
//where clause needs to be a list of where clauses, so if only one where
clause need to enlist.
stringify:{$[(0=type x) & 1=count x;"enlist ";""],basic x};
//if a dictionary apply to both, keys and values
ab:{$[(0=count x) | -1=type x;.Q.s1 x;99=type x;(addbraks stringify key x
),"!",stringify value x;stringify x]};
inner:{[x]
idxs:2 3 4 5 6 inter ainds:til count x;
x:#[x;idxs;'[ab;eval]];
if[6 in idxs;x[6]:ssr/[;("hopen";"hclose");("iasc";"idesc")] x[6]];
//for select statements within select statements
x[1]:$[-11=type x 1;x 1;[idxs,:1;.z.s x 1]];
x:#[x;ainds except idxs;string];
x[0],strBrk[1_x;"[";"]"]
};
buildSelect:{[x]
inner parse x
};
Got the following error message when applying buildSelect to a simple select statement:
ERROR: 'length
(incompatible lengths (different lengths of operands for synchronized operation or table columns lengths are not the same)
The issue seems to be with the select statement you are providing to the buildSelect function. I fyou remove the back tick the function now runs.
q)buildSelect"update idx:til count clock from `clock"
'length
[3] /home/lholmes/qsqltofunctional.q:23: inner:
if[6 in idxs;x[6]:ssr/[;("hopen";"hclose");("iasc";"idesc")] x[6]];
x[1]:$[-11=type x 1;x 1;[idxs,:1;.z.s x 1]];
^
x:#[x;ainds except idxs;string];
q))\
q)buildSelect"update idx:til count clock from clock"
"![clock;();0b;(enlist`idx)!enlist (til;(count;`clock))]"
This will produce the following:
q)t:([]time:10#.z.p)
q)update idx:i from t
time idx
---------------------------------
2019.06.19D08:39:15.720370000 0
2019.06.19D08:39:15.720370000 1
2019.06.19D08:39:15.720370000 2
2019.06.19D08:39:15.720370000 3
2019.06.19D08:39:15.720370000 4
2019.06.19D08:39:15.720370000 5
2019.06.19D08:39:15.720370000 6
2019.06.19D08:39:15.720370000 7
2019.06.19D08:39:15.720370000 8
2019.06.19D08:39:15.720370000 9
Hope this helps, if you have any additional questions feel free to ask.
For your clock table you dont even need command selectBuild. Q function parse will do the job. Simplify your code be leveraging virtual column i
parse "update idx:i from clock"
modified output:
![`clock; (); 0b; enlist[`idx]!enlist `i]
also, I recommend using
clock: update idx:i from clock
instead of
update idx:i from `clock
as the buildSelect does not handle the second form. Also, your code will run with a local clock table.
The reason why it doesn't work is that buildSelect is only expecting to be passed in tables by value in the parse tree, i.e., the element at the index 1 is expected to be an atomic symbol, not an enlist symbol, which is the case for parsing updates by name.
q)parse "update col1:val from tab"
!
`tab
()
0b
(,`col1)!,`val
q)parse "update col1:val from `tab"
!
,`tab
()
0b
(,`col1)!,`val
This causes issues at the following line in inner
x[1]:$[-11=type x 1;x 1;[idxs,:1;.z.s x 1]];
A more robust buildSelect can be made by the following adjustment
inner:{[x]
idxs:2 3 4 5 6 inter ainds:til count x;
x:#[x;idxs;'[ab;eval]];
if[6 in idxs;x[6]:ssr/[;("hopen";"hclose");("iasc";"idesc")] x[6]];
//for select statements within select statements
x[1]:$[-11=type x 1;x 1;$[11h=type x 1;[idxs,:1;"`",string first x 1];[idxs,:1;.z.s x 1]]];
x:#[x;ainds except idxs;string];
x[0],strBrk[1_x;"[";"]"]
};
Which will then allow for the following
q)buildSelect "update col1:val from `tab"
"![`tab;();0b;(enlist`col1)!enlist`val]"
q)buildSelect "update col1:val from tab"
"![tab;();0b;(enlist`col1)!enlist`val]"
Related
I'm new to programming, and I don't understand why this code returns the binary number of the input.
x = int(input())
while x > 0:
print(x % 2, end='')
x = x // 2
For example, when I enter 6, I expect it to return 0 (6 % 2 = 0, 0 // 2 = 0), but it returns 011.
I stated contemplating this because, in an assignment, we're supposed to use this coding to help us reverse the output (while using a string) but I don't know how to reverse it when I don't know why it works.
The answer of 011 is correct for your code, just trace it thru. You start with 6%2 so you get a 0. Then 6 floor 2 is 3, which is then the x for the next iteration so it becomes 3%2 which is 1 and the final iteration creates the last 1. Remember that you're not changing the value of x in the print statement, it only changes in the last line.
Thanks for stopping by. So I've been learning about recursion on w3schools.com, and everything made sense, until I looked at the example they gave :
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
I understand everything in the code but this:
why is the result like this:
Recursion Example Results
1
3
6
10
15
21
In the sense of, why are the numbers listed from small to big?
OOhhh...actually, you know what? While writing this I think I understand now...
It's kinnda like 6+(5+(4+(3+(2+(1+(0)))))) right?
And that's why it types out the small ones first, from the 'deepest' recursion...
Interesting.
But now another question comes up:
else
result = 0
return result
So essentially:
return 0
Right?
Then why does the program not print 0orNone?
Thanks for looking into this.
Since you already answered your first question yourself (by the way, it's perfectly fine to post an answer to your own question as an answer here, for the benefit of others who may have a similar problem in the future), here's an answer to your second question:
The return statement is outside of the if-else clauses. So it returns whatever the result currently is, regardless of the above condition.
To get a better feeling for how this works, try to follow the flow of execution for two different calls of the function:
tri_recursion(0) calls the function with k=0. This means the if-condition is false, so the following indented code block (two lines here) is skipped, and the else statement is executed instead. So the value 0 is assigned to result. Nothing is printed, because there is no print statement here. Then the function returns result, which is 0 here.
tri_recursion(1) calls the function with k=1. This means the if-condition is true, so the following indented code block gets executed. So result gets the value 1 + tri_recursion(0), which includes the function call that takes us to point 1 above. After everything under 1. has happened, the function has returned 0, so result is now 1 + 0 = 1. We move on to the next line, which prints result, so it prints 1. The else clause is skipped, because the condition had been found to be true above. The function returns result, which is still 1.
In general, when you are struggling to understand the flow of execution, especially with recursive functions as in this example, it's often more helpful to have the print() calls at the beginning and end of the function, not somewhere in the middle. And especially with recursive functions or other nested function calls, we may cleverly add some space characters to highlight the hierarchy and see more readily which return value belongs to which function call:
def tri_recursion(k):
print(' ' * (6 - k) + 'calling tri_recursion() with k =', k)
if(k > 0):
result = k + tri_recursion(k - 1)
else:
result = 0
print(' ' * (6 - k) + 'returning', result)
return result
print('Recursion Example Results\n')
tri_recursion(6)
Recursion Example Results
calling tri_recursion() with k = 6
calling tri_recursion() with k = 5
calling tri_recursion() with k = 4
calling tri_recursion() with k = 3
calling tri_recursion() with k = 2
calling tri_recursion() with k = 1
calling tri_recursion() with k = 0
returning 0
returning 1
returning 3
returning 6
returning 10
returning 15
returning 21
21
I am new to python programming. Why does this code does not work?
# Print out 2,5,8,11 using `for` loop and `range()`.
for x in range (2,12):
print (x)
x=x+3
I know the following will make the program work
# Print out 2,5,8,11 using `for` loop and `range()`.
for x in range (2,12,3):
print (x)
But I can't understand why the first one doesn't give the desired result whereas the equivalent code would work in C++/C.
Even you try to increment x as x=x+3, it is being changed in every iteration, and take the new value from 2 to 12, depending upon how many iteration has been progressed( if the loop is in 4th cycle, then x will be updated as 4 at the start of the 4th cycle). Even if you've placed x=x+3before the print statement, what it will do is simply printing "iteration + 3"
for x in range (2,12):
print (x)
x=x+3
So this code will produce an output like this;
5
6
7
8
9
10
11
12
13
14
So, there is no way to update x and then use this updated version in next iteration when you are using a for loop in Python.
You cannot increment the value of x when using range() function. There are two ways you can get your desired output.
First Method :
print [x for x in range(2,12,3)]
Second Method :
for x in range(2,12, 3):
print(x)
I'm working on my final for a class I'm taking(Python 3) im stuck at this part.
he gave us a file with numbers inside of it. we opened it and add those numbers to a list.
"Create a function called makeOdd() that returns an integer value. This function should take in any integer and reduce it down to an odd number by dividing it in half until it becomes an odd number.
o For example 10 would be cut in half to 5.
o 9 is already odd, so it would stay 9.
o But 12 would be cut in half to 6, and then cut in half again to 3.
o While 16 would be cut to 8 which gets cut to 4 which gets cut to 2 which gets cut to 1.
Apply this function to every number in the array. "
I have tried to search the internet but i have not clue where to even begin with this one. any help would be nice.
Here my whole final so far:
#imports needed to run this code.
from Final_Functions import *
#Defines empty list
myList = []
sumthing = 0
sortList = []
oddList = []
count = 0
#Starts the Final Project with my name,class, and quarter
intro()
print("***************************************************************",'\n')
#Opens the data file and reads it then places the intrager into a list we can use later.
with open('FinalData.Data', 'r') as f:
myList = [line.strip() for line in f]
print("File Read Complete",'\n')
#Finds the Sum and Adverage of this list from FinalData.Data
print("*******************sum and avg*********************************")
for oneLine in myList:
tempNum = int(oneLine)
sumthing = sumthing + tempNum
avg = sumthing /1111
print("The Sum of the List is:",sumthing)
print("The Adverage of the List is:",avg,'\n')
print("***************************************************************",'\n')
#finds and prints off the first Ten and the last ten numbers in the list
firstTen(myList)
lastTen(myList)
print("***************************************************************",'\n')
#Lest sort the list then find the first and last ten numbers in this list
sortList = myList
sortList.sort()
firstTen(sortList)
lastTen(sortList)
print("****************************************************************",'\n')
Language:Python 3
I don't want to give you the answer outright, so I'm going to talk you through the process and let you generate your own code.
You can't solve this problem in a single step. You need to divide repeatedly and check the value every time to see if it's odd.
Broadly speaking, when you need to repeat a process there are two ways to proceed; looping and recursion. (Ok, there are lots, but those are the most common)
When looping, you'd check if the current number x is odd. If not, halve it and check again. Once the loop has completed, x will be your result.
If using recursion, have a function that takes x. If it's odd, simply return x, otherwise call the function again, passing in x/2.
Either of those methods will solve your problem and both are fundamental concepts.
adding to what #Basic said, never do import * is a bad practice and is a potential source of problem later on...
looks like you are still confuse in this simple matter, you want to given a number X reduce it to a odd number by dividing it by 2, right? then ask yourself how I do this by hand? the answer is what #Basic said you first ask "X is a even number?" if the answer is No then I and done reducing this number, but if the answer is Yes then the next step dividing it by 2 and save the result in X, then repeat this process until you get to the desire result. Hint: use a while
to answer your question about
for num in myList:
if num != 0:
num = float(num)
num / 2
the problem here is that you don't save the result of the division, to do that is as simple as this
for num in myList:
if num != 0:
num = float(num)
num = num / 2
So I have a matrix like:
1 2 3 4
0 3 4 1
7 3 4 5
And I want to select a row,then use this row to do stuff on it such as sorting it with some algorithms;I made this so far:
def row_management(matrix):
theline = input('wich line?') #enter row number
thelist = [matrix[theline]] #go take the right row of the matrix
menu_thelist(thelist) #supossed to use the row and take it to the list management menu
However, when I run this, it always return an error "[matrix[theline]] TypeError: list indices must be integers, not str" and I don't get it.
The input call returns a str type, so it can not be used directly as index to the list inmatrix[theline], which is also what the error message says. Instead do:
matrix[int(theline)]
Needed to convert to int
theline = int(input('wich line?'))
And also
thelist = matrix[theline]
the have [1,2,3] and not [[1,2,3]](wich cause further problem)