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.
Related
In this problem, I take two strings from the user, the first string being s and the second string being t. If t is the reverse of s, I print "YES" else I print "NO".
Here is my code which gives me expected outputs:
s = input()
t = input()
if t == s[::-1]:
print("YES")
else:
print("NO")
But I found another approach that I am curious to understand, but the slicing part is making me confused. Here the code goes:
print("YNEOS"[input()!=input()[::-1]::2])
Trying to find a good explanation, so StackOverflow is what came to my mind before anything else.
Let's first extract the parts of that expression that concern the input/output and the string reversal. We then get this solution:
s = input()
t = input()
trev = t[::-1]
result = "YNEOS"[s != trev::2]
print(result)
The focus of the question is on the expression "YNEOS"[s != trev::2]
Now we get to the "trick" that is performed here. The expression s != trev can be either False or True. This boolean value becomes the first part in the slicing. You'd expect to have the start index of the slice at this position. But the boolean value will also work, as booleans are a subclass of integers, and False is 0 and True is 1. So the above expression evaluates to either:
"YNEOS"[0::2]
or
"YNEOS"[1::2]
The 2 serves as the step, and so "YNEOS"[0::2] will take the characters at indices 0, 2 and 4 ("YES"), while "YNEOS"[1::2] takes the characters at indices 1 and 3 ("NO").
I hope this clarifies it.
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"))
The code below prints out the numbers which are duplicated in A.
From my understanding, the for loop goes through each element in the list and turns it into a negative number, though i can not figure out why it does not turn the numbers it prints (which are at at position 0,4,5) negative.
A = [1,2,3,1,3,6,6]
def printRepeating(arr, size):
print("The repeating elements are: ")
for i,x in enumerate(arr):
if arr[abs(arr[i])] >= 0:
arr[abs(arr[i])] = -arr[abs(arr[i])]
print(arr)
else:
print (abs(arr[i]), end = " ")
printRepeating(A,len(A))
The algorithm assumes:
all the elements of the array start as positive numbers, and
all the elements of the array are less than the length of the array.
In your example, since the length of the array is 7, all the elements in the array must be between 1 and 6.
What the algorithm does is change array[k] to negative to indicate that k has been seen. For example, since 1 is the first number seen, array[1] is changed to a negative number. The next time 1 is seen, array[1] is already negative, so 1 must be a duplicate.
If you just want to print the repeated values in the list then why not try this:
A = [1, 2, 3, 1, 3, 6, 6]
def get_repeated_elements(lst):
return list(set((i for i in lst if lst.count(i) > 1)))
print(get_repeated_elements(A))
This function converts the passed array into a generator of duplicated values
and then converts this into a set to filter out duplicates in the generator and then converts this into a list for returning to the caller. This is a far shorter function than the one given.
The algorithm assumes that all entries are strictly positive and smaller than the length of the list. Then, what it does is essentially using the sign of the i-th element to store if it already saw number i. In your example:
A=[1,2,3,1,3,6,6] Take 1
A[1] is positive, i.e. we have not seen it. Make it negative to mark it
A=[1,-2,3,1,3,6,6] Take -2 (stands for 2)
A[2] is positive, i.e. we have not seen it. Make it negative to mark it
A=[1,-2,-3,1,3,6,6] Take -3
A[3] is positive, i.e. we have not seen it. Make it negative to mark it
A=[1,-2,-3,-1,3,6,6] Take -1
A[1] is negative, i.e. we have already seen it. Report it.
A=[1,-2,-3,-1,3,6,6] Take 3
A[3] is negative, i.e. we have already seen it. Report it.
...
The below code can be used to find repeated elements in the list and also unique elements in the list.
from collections import Counter
A = [1,2,3,1,3,6,6]
B = Counter(A)
The below line prints repeated elements.
[k for k, v in B.items() if v > 1]
Output : [1, 3, 6]
The below line prints unique elements.
[k for k, v in B.items() if v == 1]
Output : [2]
write a python program to Arrange the string in every possible
correct alphabetical sequence of three characters
for example :
INPUT : "ahdgbice"
OUTPUT: {'abc', 'bcd', 'ghi', 'cde'}
Can anyone Suggest me a Optimised Method to do that I have tried and Was Successful in generating the output but I am not satisfied with my code so Anyone please suggest me a proper optimised way to solve this problem.
This is probably a decent result:
>>> import itertools as it
>>> in_s="ahdgbice"
>>> in_test=''.join([chr(e) for e in range(ord(min(in_s)),ord(max(in_s))+1)])
>>> {s for s in map(lambda e: ''.join(e), (it.combinations(sorted(in_s),3))) if s in in_test}
{'abc', 'ghi', 'bcd', 'cde'}
How it works:
Generate a string that goes abc..khi in this case to test if the substring are in alphabetical order: in_test=''.join([chr(e) for e in range(ord(min(in_s)),ord(max(in_s))+1)])
Generate every combination of 3 letter substrings from a sorted in_s with map(lambda e: ''.join(e), (it.combinations(sorted(in_s),3)))
Test if the substring is sorted by testing if it is a substring of abcd..[max letter of in_s]
Solution: It's not optimised solution but it fulfil the requirement
# for using array import numpy lib
import numpy as np
#input string
str_1="ahdgbice"
#breaking the string into characters by puting it into a list.
list_1=list(str_1)
# for sorting we copy that list value in an array
arr_1=np.array(list_1)
arr_2=np.sort(arr_1)
# some temp variables
previous=0
str_2=""
list_2=list()
#logic and loops starts here : looping outer loop from 0 to length of sorted array
for outer in range(0,len(arr_2)):
#looping inner loop from outer index value to length of sorted array
for inner in range(outer,len(arr_2)):
value=arr_2[inner]
#ord() return an ascii value of characters
if(previous is 0):
previous=ord(value)
#difference between two consecutive sequence is always 1 or -1
# e.g ascii of a= 97, b=98 ,So a-b=-1 or b-a=1 and used abs() to return absolute value
if(abs(previous-ord(value)) is 1):
str_2=str_2+value # appending character with previous str_2 values
previous=ord(value) # storing current character's ascii value to previous
else:
str_2=value # assigning character value to str_2
previous=ord(value) # storing current character's ascii value to previous
# for making a string of three characters
if(len(str_2) == 3):
list_2.append(str_2)
# Logic and loops ends here
# put into the set to remove duplicate values
set_1=set(list_2)
#printing final output
print(set_1)
Output:
{'abc', 'bcd', 'ghi', 'cde'}
I would use the itertool module's permutations function to get a list of all three-element permutations of your input, and then for each result see if it is identical to a sorted version of itself.
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