This question already has answers here:
Understanding slicing
(38 answers)
Closed 7 years ago.
hello = "Hello there"
print(hello[10:0:-1])
This outputs:
ereht olle
And I can't figure out how or why.
print(hello[10:0:-2])
And this one outputs:
eetol
Could someone please help me to understand what the [10:0:-1] is actually doing?
Thanks!
The notation is in order start, stop and step. So you start at index ten, go to index zero where the endpoint is exclusive with a step of negative two, meaning backwards two. Here is a diagram of indices:
# -------------------------------------------------------------------
# | H | e | l | l | o | | t | h | e | r | e |
# -------------------------------------------------------------------
# X 5 4 3 2 1
Related
I have this query :
MyTable.objects.filter(date=date).exclude(starthour__range=(start, end), endhour__range=(start, end))
But I want exclude the queries that starthour__range=(start, end) AND endhour__range=(start, end) not OR. I think in this case the OR is used.
Could you help me please ?
Thank you very much !
This is consequence of De Morgan's law [wiki], this specifies that ¬ (x ∧ y) is ¬ x ∨ ¬ y. This thus means that the negation of x and y, is not x or not y. Indeed, if we take a look at the truth table:
x | y | x ∧ y | ¬x | ¬y | ¬(x ∧ y) | ¬x ∨ ¬y
---+---+-------+----+----+----------+---------
0 | 0 | 0 | 1 | 1 | 1 | 1
0 | 1 | 0 | 1 | 0 | 1 | 1
1 | 0 | 0 | 0 | 1 | 1 | 1
1 | 1 | 1 | 0 | 0 | 0 | 0
So excluding items where both the starthour is in the(start, end) range and endhour is in the (start, end) range, is logically equivalent to allowing items where the starthour is not in the range, or where the endhour is not in the range.
Using and logic
You can thus make a disjunction in the .exclude(…) call to filter out items that satisfy one of the two conditions, or thus retain objects that do not satisfy any of the two conditions:
MyTable.objects.filter(date=date).exclude(
Q(starthour__range=(start, end)) | Q(endhour__range=(start, end))
)
Overlap logic
Based on your query however, you are looking for overlap, not for such range checks. It will not be sufficient to validate the starthour and endhour. If you want to check if two things overlap. Indeed, imagine that an event starts at 08:00 and ends at 18:00, and you filter for a range with 09:00 and 17:00, then both the starthour and endhour are not in the range, but still the events overlap.
Two ranges [s1, e1] and [s2, e2] do not overlap if s1≥ e2, or s2≥ e1. The negation, the condition when the two overlap is thus: s1< e2 and s2< e1. We thus can exclude the items that overlap with:
# records that do not overlap
MyTable.objects.filter(date=date).exclude(
starthour__lt=end, endhour__lt=start
)
This question already has answers here:
Why are str.count('') and len(str) giving different output?
(3 answers)
Closed 2 years ago.
I have a question, if I have
h = "hello world"
print (h.count(''))
That prints 12.
But if i do
print (h[11])
I get an IndexError: string index out of range
I don't understand the reason.
What does the count function count when passing an empty string?
The reason it prints 12 is that there are empty strings in between every letter, and at both sides. Here is a diagram:
All empty strings!
^h^e^l^l^o^ ^w^o^r^l^d^
it looks weird, but every ^ is an empty sn empty string, and if you count them, there are 12.
The reason you are getting the error is that a string is just an array of characters, so it is zero-indexed, meaning that the first element is index 0, the second at index 1, and so on. Here is a diagram:
-------------------------------------
a | b | c | d | e | f | g | h | i | j
-------------------------------------
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
-------------------------------------
As you can see, the tenth element (j), is at index 9, so trying to get index 10 would result in an error.
The String Hello World Can only be indexed up to 10. Remember that indexes start at zero
H the first character is 0
and d at the end is 10
when you do count(''), it includes a blank space after and before the String, so it adds two extra increments.
So you can do len(h)-1 or (h.count('')-2) to show the last element of the strings index.
Note len() shows how many elements are in a list not the index of the last one. The last element of a string or list is len()-1
I have looked at many similar sources to this question but can't seem to find an answer that solves my problem.
I am using python3.7.1 and sqlite3 to essentially create quizzes. I have an array of questions which I have inserted into a table, with a 'Class_name' and 'quizNumber' using this code example:
quizQuestion = ['1 + 1 =', '2 + 2 =', '3 + 3 =',...]
quizNumber = (1)
quizClass = ('6D')
for question in quizQuestions:
cursor.execute( "INSERT INTO set_questionsTbl (QuizNumber, Class_name, Question) VALUES (?,?,?)", (quizNumber,quizClass,question))
This code works fine and the table(set_questionsTbl) looks like this:
QuizNumber | Class_name | Question | Answer
-------------------------------------------
1 | 6D | 1 + 1 = |
1 | 6D | 2 + 2 = |
1 | 6D | 3 + 3 = |
etc..
I also have an array of answers:
quizAnswers = [2,4,6,...]
The problem that occurs is when trying to update the table with the answers so it looks like this:
QuizNumber | Class_name | Question | Answer
-------------------------------------------
1 | 6D | 1 + 1 = | 2
1 | 6D | 2 + 2 = | 4
1 | 6D | 3 + 3 = | 6
etc...
The code I tried was this:
for answer in quizAnswers:
cursor.execute("UPDATE set_questionsTbl SET Answer = (?) ", (answer,))
This didn't work as with every loop the previous inputted answer got overwritten leaving me with this:
QuizNumber | Class_name | Question | Answer
-------------------------------------------
1 | 6D | 1 + 1 = | 6
1 | 6D | 2 + 2 = | 6
1 | 6D | 3 + 3 = | 6
etc...
I have also tried joining the loops together but that doesn't work, table looks like:
QuizNumber | Class_name | Question | Answer
-------------------------------------------
1 | 6D | 1 + 1 = | 2
1 | 6D | 2 + 2 = | 2
1 | 6D | 3 + 3 = | 2
1 | 6D | 1 + 1 = | 4
1 | 6D | 2 + 2 = | 4
1 | 6D | 3 + 3 = | 4
1 | 6D | 1 + 1 = | 6
1 | 6D | 2 + 2 = | 6
1 | 6D | 3 + 3 = | 6
I have tried to correct this many times and searched many different examples but couldn't seem to find a solution. So how do I loop through each question and update the answer with each answer in quizAnswers?
I am new to stack overflow so I may have missed a question similar to this, if so please link it.
The point you are missing is, that you instruct your database to update all records with the answer in the current iteration of the loop.Your example:
quizAnswers = [2,4,6]
for answer in quizAnswers:
cursor.execute("UPDATE set_questionsTbl SET Answer = (?) ", (answer,))
basically does:
set Answer for *all* records to 2
set Answer for *all* records to 4
set Answer for *all* records to 6
Your database does not understand the meaning of the data you put into the tables. For the DB, the questions you inserted into the Question column of your set_questionsTbl are just sequences of characters. It has no means of evaluating the equation in Question in order to set a value in Answer only if that value is the result of the equation.
You need to tell your DB which answer to set for which question(s).
You need to give your query criteria, that a record must meet for the update operation to be applied to it. That's what WHERE clauses are for.
Following your example, you'll want to create a correlation between questions and their respective answers. The below is one way to do that.
First, create a list of tuples. Each tuple contains an answer in the first element, the second element holds the corresponding question (this needs to be the exact value you inserted into the Question column).
quiz_question_answers = [(2, '1 + 1 ='), (4, '2 + 2 ='), (6, '3 + 3 =')]
Then you can iterate over that list of tuples to execute the UPDATE query in your cursor:
for q_a in quiz_question_answers:
cursor.execute("UPDATE set_questionsTbl SET Answer = ? WHERE Question = ?", (q_a[0], q_a[1]))
This will update the answer in all records that have the specific equation in Question. Records with different Class_name and/or QuizNumber - a record like this for example:
QuizNumber | Class_name | Question | Answer
-------------------------------------------
4 | 5A | 1 + 1 = |
- will be updated as well, because the only criteria, the Question equaling 1 + 1 =, is met for this record also.
If you want the answers to be set only for questions of quiz number 1 for class 6D, you'll have to add more restrictive criteria to your query, e.g.:
quiz_question_answers = [(2, '1 + 1 =', 1, '6D'), (4, '2 + 2 =', 1, '6D'), (6, '3 + 3 =', 1, '6D')]
for q_a in quiz_question_answers:
cursor.execute("UPDATE set_questionsTbl "
"SET Answer = ? "
"WHERE Question = ? "
"AND QuizNumber = ? "
"AND Class_name = ?",
(q_a[0], q_a[1], q_a[2], q_a[3]))
With this particular solution (using a list of tuples with the query parameters in the correct order) you can also use executemany to let the cursor do the loop over the list of parameter tuples for you:
quiz_question_answers = [(2, '1 + 1 ='), (4, '2 + 2 ='), (6, '3 + 3 =')]
cursor.executemany("UPDATE set_questionsTbl SET Answer = ? WHERE Question = ?", quiz_question_answers)
Here's some further reading on WHERE clauses specifically for SQLite.
You should have a unique ID for at least one of the fields in your table. That way when you execute the answer update, you could add a WHERE clause, e.g:
cursor.execute( "UPDATE set_questionsTbl SET answer=? WHERE unique_id=?", (answer,uniqueId))
and that way not all of your records will be updated.
This question already has answers here:
What does |= (ior) do in Python?
(11 answers)
Closed 4 years ago.
I tried printing various integers (ie. int | int ) multiple times and I can't seem to establish a working pattern of values. How does 1|2 return 3, but 2|3 also returns 3?
Bitwise operators in Python work in the same way as in other languages. So, if you know how it works in C then you know how it works in Python. For this particular example, 1 is represented by binary 0001 and 2 by 0010. Operator OR (|) looks at each bit in the two numbers at the same position and compares them. If any bit is 1 then it keeps 1 at that position in the result:
1: | 2: result:
----------------
0 or 0 = 0
0 or 0 = 0
0 or 1 = 1
1 or 0 = 1
So the result (in binary format) is 0011 or, in base 10, 0011->3.
Check wikipedia.
A bitwise OR takes two bit patterns of equal length and performs the
logical inclusive OR operation on each pair of corresponding bits. The
result in each position is 0 if both bits are 0, while otherwise the
result is 1.
So, 1|2: 001 | 010 = 011 (3 dec)
and 2|3: 010 | 011 = 011 (3 dec)
0001 = 1 0010 = 2 so 0001 | 0010 = 0011 = 3. 0010 | 0011 = 0011 = 3.
| is the OR operation.
x | y Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.
https://wiki.python.org/moin/BitwiseOperators
In your example, it is useful to look at the bit representation of an integer by the bin() function:
>>> bin(1), bin(2), bin(3)
('0b1', '0b10', '0b11')
So 1 is 01, 2 is 10 and 3 is 11. Therefore the bitwise OR operator applies to each pair of bits from right to left as: 1|2 is 01|10 = 11, 2|3 is 10|11 = 11
(0 or 1 gives 1, 1 or 1 gives 1)
I got a print_backward function code online, but I am so confusing
about how it works and its output.
The below is my code.
def print_backward(num):
if num == 10:
return
num += 1
print(num)
print_backward(num)
print("yeah")
print(num)
print()
print_backward(6)
The below is output.
7
8
9
10
yeah
10
yeah
9
yeah
8
yeah
7
I can understand how it prints from 7 to 10, since each time it call
recursively, num += 1.
But I am confusing, once num achieves 10, the print_backward should
return, then done. It should not print yeah 10, yeah 9, yeah 8, yeah
7. Why this code has called return, how it still can print? How this code works to print backward, which means why I called print(num), it
can print from 10 to 7?
Function call is actually a stack operation. And recursion is a special case of function call.
Every time you call a function, the Return Address will be push into a stack, and when the function return, the program will pop the Return address from the top of stack, and program continue to execute from there. You can have a look at the official description about call stack in wikipedia.
For your example, print_backward(7) call first, and then the next command will push into the stack, and then when you call the print_backward(8), the next command will be pushed into the stack again, so after 4 recursion call, the stack will be like this:
+-------------------------+ <--- Stack top
| num = 10, print("yeah") | \
| num = 9, print("yeah") | |
| num = 8, print("yeah") | > Call stack
| num = 7, print("yeah") | |
+-------------------------+ /
The criteria hit the if condition num == 10: when calling from print_backward(10). The program execute return statement, the Return address from the stack top will be pop, and program starts from there, that means, print('yeah') for num = 10 will be execute. After finished call for print_backward(10), the stack will pop another Return Address from the stack, and print('yeah') in print_backward(9) will be executed. This operation will be ended when the stack is empty, that means ,there is no more function return.
On the first runs, the code does not go further than the inner call to print_backward(num), that is 4 times (like an infinite recursion)
When the argument reaches 10, all the functions return and it goes further, printing the original num+1 with which they were called.
The highest numbers are printed first because the calls where the number is higher return first.
The function calling happens through stack.
You call print_backward on 6. So stack will have 6.
Now you call it on 7 ---> So stack has 6,7 where 7 is top.
Now you call it on 8 ----> So stack is 6,7,8
Now on 9, So stack is 6,7,8,9
Now on 10, So stack is 6,7,8,9,10.
Now when function returns , it pops from stack.
So, you were in function with parameter 10. So, you called return and it gets popped from stack. Now stack is 6,7,8,9.
Now it prints "yeah" and 10 (because num is 9 and we did num = num + 1 before).
Now it returns and pops 9. Now stack is 6,7,8
Now it prints yeah and 9 because num is 8 and we did num = num +1 before).
Similarly, it prints other as well.
For your case - print_backward(6) it took 4 calls (recursively) to hit return criteria i.e. if num == 10 - during those calls the function printed:
7 # print_backward(6) - first call we made
8 # print_backward(7) - recursive
9 # print_backward(8) - recursive
10 # print_backward(9) - recursive - inner most, where the return is executed
For next recursive call print_backward(10) the return condition gets true, and the function starts returning (starting from the inner most call) - as result the lines below the recursive call (line 6) get called i.e.
yeah # 4th call (inner most) returned
10
yeah # 3rd call returned
9
yeah # 2nd call returned
8
yeah # 1st call returned
7
The call stack view visualization 'd be:
print_backward(6)
| 7 # num += 1 and then print(num)
| print_backward(7)
| | 8
| | print_backward(8)
| | | 9
| | | print_backward(9)
| | | | 10
| | | | | print_backward(10)
| | | | | | return
| | | | yeah # print("yeah")
| | | | 10 # print(num)
| | | | () # print()
| | | yeah
| | | 9
| | | ()
| | yeah
| | 8
| | ()
| yeah
| 7
| ()
when print_backward(6) is called then
1 check for 10
2 increase 6 by one num = 7
3 print 7
4 call backward with 7
for 6 print_backward is not completed yet and print_backward(7) is pushed on the top of stack. The remaining part
print("yeah")
print(7)
will execute at last when the recursive call is completed. I am skipping check 10 in the below steps. Will include that in last steps.
5 increase 7 by one num = 8
6 print 8
7 call backward with 8 (7 not completed)
8 increase 8 by one num = 9
9 print 9
10 call backward with 9 (8 not completed)
11 increase 9 by one num = 10
12 print 10
return is encountered
13 call backward with 10 (9 not completed)
14 check for 10 and return. 9 will continue for the execution.
15 in the execution of 9 num is 10 so yeah is printed and then 10 is printed and print_backward for 9 is completed. Similarly for 8 num is 9 which print yeah followed by 9 and so on.