Printing range of numbers without using loop? - python

Can someone explain to me how this code works ? It prints numbers from 0 to 100, but I cannot understand how.
print(*range(True,ord("e")))

ord accepts a character and returns the ASCII code. In this case "e" returns 101. The *range is unpacking the iterable that range creates. Enabling you to print out the values from True (1) to 101 - 1.
I found this out by googling each piece of code individually. Type in "ord python" then another search was "star range python". These searches lead to information you are seeking.

print(*range(True,ord("e")))
Firstly, print() means that we are displaying some information on the screen.
Secondly, the * indicates that there may be more than one object to be printed.
Now, think of the True as a 0. True does nothing. The ord("e") means where is e in the Unicode. It returns that number, which is 101. Now, range(start, end) means every value between the start value (0), and end value (1).

Related

python for loop syntax error with len (I can't publish this question without the weird title)

for(j in range(len(queries))):
this line gives me a syntax error, what is wrong with it?
By the way, queries is a list variable
As pointed out by #Mime and by the error you're getting, the syntax of your for loop is incorrect. The right one is
for j in range(len(queries)):
Using just one parameter in the range() function will make you iterate from 0 to the number you have put as parameter minus one, in this case the lenght of queries minus one. Using range(0, len(queries)) achive the same.
You can also use range(start, stop, step) with three parameters:
start Optional. An integer number specifying at which position to start. Default is 0
stop Required. An integer number specifying at
which position to stop (not included).
step Optional. An integer
number specifying the incrementation. Default is 1
You can also use j as a variable inside the loop which will be something like 0,1,2,...,len(queries)-1
More on for loop on the official Python documentation

Recursively search word in a matrix of characters

I'm trying to write a program for a homework using recursion to search for a word in a matrix (2x2 or more), it can be going from left to right or from up to down (no other directions), for example if I am searching for ab , in the matrix [['a','b'],['c','d']], the program should return in what direction the word is written (across), the starting index(0), ending index(2), and the index of the row or column(0).
My problem is that I have the idea of the recursion but, I can't implement it. I tried to break the problem down into more little proplems, like searching for the word in a given row, I started by thinking of the smallest case which is 2x2 matrix, at the first row and column, I need to search one to the right and one to the bottom of the first char, and check if they are equal to my given string, then give my recursion function a smaller problem with the index+1. However I can't think of what to make my function return at the base case of the recursion, been trying to solve it and think of ways to do it for two days, and I can't code what I think about or draw.
Note that I can't use any loops, I would really appreciate it if somone could push me in the right direction, any help would be pretty much appreciated, thanks in advance.
Edit: more examples: for input of matrix : [['a','b','c'],['d','e','f'],['g','h','i']] the outputs are:
with the string ab : across,0,0,2
with the string be : down,1,0,2
with the string ghi: across,2,0,3
I assume that the word we are looking for could be found starting from any place but we can move up to down or left to right only.
In that case, you should have a function that takes the start index and a direction and then the function keeps moving in the given direction starting from the given index and keeps moving until it doesn't find a mismatch, and it just returns true or false based on the match of the given string.
Now you need to call this function for each and every index of the matrix along with two directions up to down and left to right, and at any index, if you get the output of the function as true then you have found your answer.
This is a very basic idea to work, next it depends on you how you want to optimize the things in this method only.
Update:
To avoid using the loops.
The other way I can think of is that the function which we have defined now takes the row, column, and the string to find. So at each call, you will first check if the character at the given row and column matches the first character of the given string if so then it calls the two more functions, one in the right direction and the other in the down direction, along with the string with the first character removed.
Now to check all the columns of the matrix, you will anyway call the function in down and right direction with the exact same string.
The base case will be that if you reach the end of the string then you have found the answer and you will return True, otherwise False.
One more thing to notice here is that if any of the 4 function calls gives you a True response then the current row/column will also return True.
Cheers!

Python __add__ magic method with integers

When i am tring this:
>>> "a".__add__("b")
'ab'
It is working. But this
>>> 1.__add__(2)
SyntaxError: invalid syntax
is not working.
And this is working:
>>> 1 .__add__(2) # notice that space after 1
3
What is going here? Is it about variable naming rules and is python thinks I am trying to create variable when I am not using space?
Python parser is intentionally kept dumb and simple. When it sees 1., it thinks you are midway through a floating point number, and 1._ is not a valid number (or more correctly, 1. is a valid float, and you can't follow a value by _: "a" __add__("b") is also an error). Thus, anything that makes it clear that . is not a part of the number helps: having a space before the dot, as you discovered (since space is not found in numbers, Python abandons the idea of a float and goes with integral syntax). Parentheses would also help: (1).__add__(2). Adding another dot does as well: 1..__add__(2) (here, 1. is a valid number, then .__add__ does the usual thing).
The python lexical parser tries to interpret an integer followed by a dot as a floating point number. To avoid this ambiguity, you have to add an extra space.
For comparison, the same code works without problem on a double:
>>> 4.23.__add__(2)
6.23
It also works if you put the int in parentheses:
>>> (5).__add__(4)
9
When you use 1. the interpreter think you started writing float number (you can see in the IDE (atleast Pycharm) the dot is blue, not white). The space tell it to treat 1. as a complete number, 1.0. 1..__add__(2) will also do the trick.

what is output of following code? if it is empty string then please explain why?

I declare a string variable and want to access some characters with the help of slicing operators but it showing empty str as output.
please explain why it is showing empty.
I tried to print with different end index it works for all others but fails when end index becomes 0.
s='0123456789'
print(s[2:-1:-1])
In Python slicing, -1 means "the last element". So for a 10-character string, it's equivalent to 9. And then since your step is -1, you are slicing in the wrong way, so the result becomes empty.
If you want '210', you can go with s[2::-1], although it's a bit inconvenient when your end is a variable. There are multiple workarounds, though, like s[0:3][::-1].
See:
>>> s='0123456789'
>>> print(s[2:-1:-1])
>>> print(s[-1:2:-1])
9876543
The reason that the first statement isn't printing anything is because the start is already less than the end - if you were to continue to step -1, you would go out of the bounds of the array. Keep in mind that s[-1] resolves to s[len(s) - 1].
Or, in other words, if I told you to start at the second index of the array and go frontwards until you hit the last index of the array, it wouldn't make sense. After all, if you go frontwards, you're going towards the front of the array, not the back.
Meanwhile, if I switch those commands around - "start at the last index, and go frontwards until you hit the second index" - that makes perfect sense.
First argument means start_index, second means end_index (empty means until end iteration), third is step.
Your expected output: 210
s='0123456789'
print(s[2::-1])
output:
210

String slices/substrings/ranges in Python

I'm newbie in Python and I would like to know something that I found very curious.
Let's say I have this:
s = "hello"
Then:
s[1:4] prints "ell" which makes sense...
and then s[3:-1] prints 'l' only that does makes sense too..
But!
s[-1:3] which is same range but backwards returns an empty string ''... and s[1:10] or s[1:-20] is not throwing an error at all.. which.. from my point of view, it should produce an error right? A typical out-of-bounds error.. :S
My conclusion is that the range are always from left to right, I would like to confirm with the community if this is as I'm saying or not.
Thanks!
s[-1:3] returns the empty string because there is nothing in that range. It is requesting the range from the last character, to the third character, moving to the right, but the last character is already past the third character.
Ranges are by default left to right.
There are extended slices which can reverse the step, or change it's size. So s[-1:3:-1] will give you just 'o'. The last -1 in that slice is telling you that the slice should move from right to left.
Slices won't throw errors if you request a range that isn't in the string, they just return an empty string for those positions.
Ranges are "clamped" to the extent of the string... i.e.
s[:10]
will return the first 10 characters, or less if the string is not long enough.
A negative index means starting counting from the end, so s[-3:] takes the last three characters (or less if the string is shorter).
You can have range backward but you need to use an explicit step, like
s[10:5:-1]
You can also simply get the reverse of a string with
s[::-1]
or the string composed by taking all chars in even position with
s[::2]

Categories

Resources