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
Related
This question already has answers here:
Accessing the index in 'for' loops
(26 answers)
Closed 1 year ago.
Here I have a list:
some_list = [a','r','p','i','l','a','z','a','r','l','i','i','l','z','p']
I want some function to index each of the characters in the list with an unique index.
So the code should be something like:
for char in some_list:
char_index = some_list.magic_index(char)
print(char_index)
magic_index should be a function that returns a number from 0 to 14 incrementally for each character.
The output should be something like:
0
1
2
3
4
4
5
6
7
8
9
10
11
12
13
14
I know this isn't really indexing each character, but I just want some function to return a value from 0 to 14 for each character, so that each character has their own unique number from 0 to 14.
I know this is kind of a dumb question, it is some how just very hard for me. If someone know how to solve this, please give me some help. Thank you!
Use enumerate and build a map of characters to indices:
>>> magic_index = {c: i for i, c in enumerate(some_list)}.get
>>> magic_index('a')
7
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
numbers = [2,4, 6,8, 11, 23]
popped_numbers = []
for number in numbers:
i = numbers.pop(0)
print(i)
popped_numbers.append(i)
print(numbers)
results
2
4
6
[8, 11, 23]
It is because when you are poping from numbers, then the size of it is actually changing. At the same time the iterator starts from 0 index in the array and increasing. So after picking the first 3 numbers, size of numbers is equal to 3 and iterator is also 3 and the for loop breaks. You can implement it like this:
numbers = [2,4, 6,8, 11, 23]
popped_numbers = []
while len(numbers) > 0:
i = numbers.pop(0)
print(i)
popped_numbers.append(i)
print(numbers)
print(popped_numbers)
Because the pointer, when you pop an element from the numbers list in the loop, the pointer after the third iteration is in third element, at this point the last element in the list.
Like:
Iteration | element | list
__________|_________|_______
1 | 2 | [4,6,8,11,23]
2 | 4 | [6,8,11,23]
3 | 6 | [8,11,23]
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.
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