How is the first element of this empty list 0? - j

Consider:
{. '' NB. makes sense...
</. '' NB. still makes sense....
{. </. '' NB. umm... where did that zero come from?
0
'' -: </. '' NB. and why is it behaving differently from line 1?
1 NB. which is apparently identical to?
What explains these seeming contradictions?

where did that zero came from?
Per NuVoc page for {. (Head):
If y has no items, {. y produces an item of fill atoms.
{.0$0
0
why is it behaving differently
-: returns boolean 1 only if shape and content of its arguments are the same. </.'' is an empty list with no elements and shape 0 (so as ''), whereas {.'' is an atom: $ (Shape of it) gives an empty list:
${.''
$${.''
0
And u: says that it's a space sharacter (ASCII 32):
3 u:{.''
32

Related

Apply edit to strings

I have an practice that gives input and wants to get the 'hello'by deleting letters and if it get print 'YES' and if not print 'NO'.python 3
i write this but i do not know why it is not work sometime
def edit(x):
for h in x:
if h in ('a','q','z','w','s','x','d','c','r','f','v','t','g','b','y','n','u','j','m','i','k','p'):
y = x.replace(h,'')
return y
x =input()
x1='a'.join(x)
y = edit(x1)
if y==('hello'):
print('YES')
elif y.count('l')>=2 and y.count('h')>=1 and y.count('e')>=1 and y.count('o')>=1:
if y.startswith('h') and y.endswith('o'):
y1=y.replace('h','')
if y1.startswith('e'):
y2=y1.replace('e','')
if y2.startswith('l') and y2.endswith('o'):
print('YES')
else:
print('NO')
for example
aahhelllo
YES
asdxhhhellooooo
Process finished with exit code 0
The error is in your edit(x) function. It iterates through characters of the string in the x variable and checks if the character is in the list of 22; if so, it removes all instances of a chosen character from the string and stores a result in the y variable.
Note: on every iteration it takes the x variable; it does not take y, which is a result of the previous modification, but it takes an original input parameter again and again. Finaly, you get y from the last modification performed.
In "aahhelllo" there is only one character to remove: 'a', so only one substitution is done and its result is "hhello", as expected.
OTOH, in "aasdxhhhellooooo" there are four characters to be removed, so:
in the first iteration y is assigned a value of "aasdxhhhellooooo".replace('a','') which is "sdxhhhellooooo";
in the second iteration you remove 'a' again (because it was not deleted from x);
in the third you assign y="aasdxhhhellooooo".replace('s','') which is "aadxhhhellooooo";
and so on, until the last modification done for h=='x', which makes y="aasdxhhhellooooo".replace('x',''), which is "aasdhhhellooooo".
And that is the result returned from edit(x) in the second case.

Unable to Reverse the text using 'for' Loop Function

I want to reverse the string using the Loop & Function. But when I use the following code, it is output the exact same string again. But it suppose to reverse the string. I can't figure out why.
def reversed_word(word):
x=''
for i in range(len(word)):
x+=word[i-len(word)]
print(i-len(word))
return x
a=reversed_word('APPLE')
print(a)
If you look at the output of your debug statement (the print in the function), you'll see you're using the indexes -5 through -1.
Since negative indexes specify the distance from the end of the string, -5 is the A, -4 is the first P, and so on. And, since you're appending these in turn to an originally empty string, you're just adding the letters in the same order they appear in the original.
To add them in the other order, you can simply use len(word) - i - 1 as the index, giving the sequence (len-1) .. 0 (rather than -len .. -1, which equates to 0 .. (len-1)):
def reversed_word(word):
result = ""
for i in range(len(word)):
result += word[len(word) - i - 1]
return result
Another alternative is to realise you don't need to use an index at all since iterating over a string gives it to you one character at a time. However, since it gives you those characters in order, you need to adjust how you build the reversed string, by prefixing each character rather than appending:
def reverse_string(word):
result = ""
for char in word:
result = char + result
return result
This builds up the reversed string (from APPLE) as A, PA, PPA, LPPA and ELPPA.
Of course, you could also go fully Pythonic:
def reverse_string(word):
return "".join([word[i] for i in range(len(word), -1, -1)])
This uses list comprehension to create a list of characters in the original string (in reverse order) then just joins that list into a single string (with an empty separator).
Probably not something I'd hand in for classwork (unless I wanted to annoy the marker) but you should be aware that that's how professional Pythonistas usually tackle the problem.
Let's say your word is python.
You loop will then iterate over the values 0 through 5, since len(word) == 6.
When i is 0, i-len(word) is -6 (note carefully that this value is negative). You'll note that word[-6] is the character six places to the left from the end of the string, which is p.
Similarly, when i is 1, i-len(word) is -5, and word[i-len(word)] is y.
This pattern continues for each iteration of your loop.
It looks like you intend to use positive indices to step backward through the string with each iteration. To obtain this behavior, try using the expression len(word)-i-1 to index your string.
def reversed_word(word):
reversed = ''
for i in range(len(word)-1, -1, -1):
reversed += word[i]
return reversed
print(reversed_word("apple"))

Why x='b'*4 is greater than y='a'*5 in Python?

I do not remember where I saw this code but I had made a note of this and now I got back to it and I do not get why the result is "greater".
x='b'*4
y='a'*5
if x == y:
print("Equal")
elif x<y:
print("Less")
elif x>y:
print("Greater")
Is this a matter of index?
The REPL usually helps with these kinds of questions:
>>> 'b'*4 > 'a'*5
True
>>> 'b'*4
'bbbb'
>>> 'a'*5
'aaaaa'
>>> 'bbbb' > 'aaaaa'
True
So the question is really why 'bbbb' > 'aaaaa' is true. The answer is because they are strings, and strings are compared in alphabetical order. If these were words in a dictionary, 'bbbb' would appear after 'aaaaa'.
Because
'b'*4 equals 'bbbb'
and a*5 equals 'aaaaa'
'b' has a greater unicode value than 'a'
"b" will always be greater than "a" * n, because string comparison works by comparing the very first character of the string with their ASCII value.
It doesn't matter how many "a"'s there are, because b will always be greater than the first "a" in the string.
However, if the first character are identical, then it will compare the next character, and so on.

I am confuse about this code can someone explain

Changing Duplicate characters in a string to ) and non duplicate to (.
I have tried 2 for loops but it doesn't work. I am beginner in coding therefore I cant understand this complex code can someone explain.
def duplicate_encode(word):
return (lambda w: ''.join(('(', ')')[c in w[:i] + w[i+1:]] for i, c in enumerate(w)))(word.lower())
print(duplicate_encode("rEcede"))
Input: "Mercedes Bench"
Output: ()())()((()()(
As said in a comment, I think this is bad coding practice and should be avoided. But it can serve as an example of code reading. So I'll give it a try here. (First you should read about lambda if you're not familiar with it.)
First, look at the matching parentheses and try to find the "deepest" parts:
The top one is: lambda w: ''.join(('(', ')')[c in w[:i] + w[i+1:]] for i, c in enumerate(w))) applied to word.lower().
Then we have ('(', ')')[c in w[:i] + w[i+1:]] for i, c in enumerate(w)) in place of three dots inside ''.join(...).
enumerate(w), where w is a string, will produce an enumerate object that can be iterated to get tuples of form (i,c), where i is the index of the letter c. Try running for x in enumerate(w): print(x) for different strings w in order to get a feel for it.
The ('(', ')')[c in w[:i] + w[i+1:]] for i, c in enumerate(w)) will then produce a generator object by iterating through the tuples of letters of w and the respective indices that will consist of only ')' and '(' that will be then concatenated by ''.join(...) into the final output string. Let's break it down further.
[c in w[:i] + w[i+1:]] will always evaluate to either [True] or [False] (see 6 as to why). Now, ('(', ')')[False] will return '(' and ('(', ')')[True] will return ')' (something I learned right now by typing it out to see what happens).
For any letter in w there will be a tuple in the generator object (see point 4), (i, c). The [c in w[:i] + w[i+1:]] will first take two substrings of w. The first one will include all the letters up to the position i (where the current letter is located) and the second will include all the letters after the current letter. These two substrings are then concatenated. Then c in part will just check if the current letter is in the resulting string, effectively checking if the letter c appears at some other part of the string as well. For example for a w = 'aba' and second tuple from enumerate('aba'), that is (1, 'b'), w[:i] will be equal to 'aba'[:1] which is 'a' and w[i+1:] will be equal to 'aba'[:1] which is equal to 'a', concatenated we get a string 'aa' and thus [c in w[:i] + w[i+1:]] which in this case is equal to ['b' in 'aa'] will evaluate to [False], hence resulting in '('.
Effectively the lambda part is just a function that for each letter at a given position, checks if the same letter is present in a modified string with the letter removed from that position. It is then applied to an argument word.lower() which just insures that the caps are ignored (e.g., 'A' and 'a' are counted as the same letter).
This code replicates exactly what the lambda function does. By separating the logic into distinct statements it is easier to follow the logic. Remove the comments from the print statements to see the whole process in detail.
def simple_duplicate_encode(word):
output = ""
for i, c in enumerate(word):
# print(i,c)
i1 = word[:i]
i2 = word[i+1:]
# print(":{} = {}".format(i, word[:i]))
# print("{}: = {}".format(i+1, word[i+1:]))
is_duplicated = c in i1 + i2 # Check to see if the character c is in the rest of the string
# print("Is duplicated:{}".format(is_duplicated))
character = ('(',')')[is_duplicated] # If is_duplicated = True the value is 1, else 0
# print(character)
output += character
return output

Find characters inside strings from the elements of a list in python

I just started to use python 3. I want to find specific characters inside a string that is part of a list. Here is my code:
num = ["one","two","threex"]
for item in num:
if item.find("x"):
print("found")
So, I want to print "found" if the character "x" is inside of one of the elements of the list. But when I run the code, it prints 3 times instead of one.
Why is printing 3 times? Can someone help me?
find() returns -1 if the character is not found in the string. Anything that is not zero is equal to True. try if item.find("x") > -1.
You can use in again for strings:
num = ["one","two","threex"]
for item in num:
if "x" in item:
print("found")
Think in Strings as a list of chars like "ext" -> ['e', 'x', 't']
so "x" in "extreme" is True
find returns Index if found and -1 otherwise.
num = ["one","two","threex"]
for item in num:
if item.find("x"):
print item.find("x")
i hope that you got the solution from above post ,here you know the reason why
You need to break out of looping through the strings if 'x' is found as otherwise, it may be found in other strings. Also, when checking if 'x' is in the string, use in instead.
num = ["one","two","threex"]
for item in num:
if "x" in item:
print("found")
break
which outputs:
found
And if I modify the num list so that it has no x in any of the elements:
num = ["one","two","three"]
then there is no output when running the code again.
But why was it printing 3 times before?
Well simply, using item.find("x") will return an integer of the index of 'x' in the string. And the problem with evaluating this with an if-statement is that an integer always evaluates to True unless it is 0. This means that every string in the num list passed the test: if item.find("x") and so for each of the 3 strings, found was printed. In fact, the only time that found wouldn't be printed would be if the string began with an 'x'. In which case, the index of 'x' would be 0 and the if would evaluate to False.
Hope this clears up why your code wasn't working.
Oh, and some examples of testing the if:
>>> if 0:
... print("yes")
...
>>> if 1:
... print("yes")
...
yes
>>> if -1:
... print("yes")
...
yes

Resources