>>> a=10
>>> print(str(a)[a==10])
0
>>> print(str(a)[a=='10'])
1
>>> print(str(a)[a=='11'])
1
How is the above result of 0 and 1 obtained?
Let's put the print statement aside for a second.
Inside the square brackets, the expression being evaluated results in a boolean.
a==10 is True because a is an int equal to 10 and a=='10' is False because a is not a str with value '10'.
Each of those booleans is implicitly converted to an int because the square brackets are indexing the string. So, True becomes index 1 and False becomes index 0.
The string is indexed. '1' is at index 0 of '10', and '0' at index 1. Notice that what is returned is a string and not an integer, and this is because the result of the whole expression, e.g. str(a)[a==10], is a string in all your examples.
All of this is happening without print() being considered. print() just prints the representation to the screen. 0 the integer and '0' the string look the exact same on the screen. Try using type() to understand this.
This is simply because of indexing in strings
let me explain
when you perform str(a), you are typecasting a into a string and consequentially the 10 to '10' whereby '10' is a string with 2 characters ('1' and '0')
Now if you have a string with 2 characters, the character in the zeroth index is the first one('1') , while in the first index is the second character('0')
i.e
animal = 'cat'
print(animal[0])
>>'c'
print(animal[1])
>>'a'
print(animal[2])
>>'t'
moving on, now inside the square brackets you have boolean statements for which when the value is True the output is 1, when the value is False the output is 0
therefore 10==10 is true which is 1,thus str(a)[a==10] is str(a)[1] which is 0 (the 1st index but 2nd character of '10')
10=='10' is false which is 0
thus str(a)[a=='10'] is str(a)[0] which is 1 (the 0th index but 1st character of '10')
10=='11' is false which is 0
thus same as 2nd case
str(a)[a=='11'] is str(a)[0] which is 1 (the 0th index but 1st character of '10')
a = 10, a is a integer value 10
In print()
10 == 10 is false so it Will print 2nd position of str(a)
which is 0
10 == '10' is true so it Will print 1st position of str(a)
which is 1
Example:
a = 12
print(str(a)[4 == 4]) # output 2
Related
I am given a string and I have to determine whether it can be rearranged into a palindrome.
For example: "aabb" is true.
We can rearrange "aabb" to make "abba", which is a palindrome.
I have come up with the code below but it fails in some cases. Where is the problem and how to fix this?
def palindromeRearranging(inputString):
a = sorted(inputString)[::2]
b = sorted(inputString)[1::2]
return b == a[:len(b)]
def palindromeRearranging(inputString):
return sum(map(lambda x: inputString.count(x) % 2, set(inputString))) <= 1
this code counts occurrence for every character in string. in palindromes there is one character with odd occurrence if length of string is odd, if length of string is even then no character has odd occurance.
see here
def palindromeRearranging(inputString):
elements = {c:inputString.count(c) for c in set(inputString)}
even = [e % 2 == 0 for e in elements.values()]
return all(even) or (len(inputString) % 2 == 1 and even.count(False) == 1)
It counts each character number of appearances, and checks whether all elements appear an even number of times or if the length of the input string is odd, checks whether only one character appears an odd number of times.
Python3
def palindromeArrange (string):
string = list(string)
for i in range (len(string)):
"""if the string has even element count"""
if len(string) % 2 == 0 and len(string)/2 == len (set (string)):
return True
"""if the string has odd element count"""
if len(string) - ((len(string)-1)/2) == len (set (string)):
return True
return False
One liner using list comprehension in Python3
return len([x for x in set(inputString) if inputString.count(x) % 2 != 0]) <= 1
Basically counts those characters that have counts that aren't divisible by 2.
For even strings it would be zero, and for odd strings, it would be one.
The solution I can think of right away has time complexity is O(n). The assumption is, palindrome can not be made if there is more than one character with the odd count.
def solution(inputString):
string = list(inputString)
n = len(string)
s_set= set(string)
from collections import Counter
dic = Counter(string)
k =0 #counter for odd characters
for char in s_set:
if dic.get(char)%2!=0:
k+=1
if k>1:
return False
else:
return True
m = input()
bin_m = bin(M)[2:][::-1]
print(bin_m)
I was going through a code which requires me to convert decimal number to binary and they used:
bin_m = bin(M)[2:][::-1]
this to convert m to binary.
Somebody, please help me with this
what does [2:][::-1] mean
"""this is string slicing. It cuts a portion of string which you have provided it. For this you need to know string indexing.
suppose you are having a string "Python". Then each character of this string is having its index number. The index number starts from 0 from left to right, and -1 from reversed side
Character --> index number when you read the string from right to left --> index number when you read the string from right to left(reversed side)
P --> 0 --> -6
y --> 1 --> -5
t --> 2 --> -4
h --> 3 --> -3
o --> 4 --> -2
n --> 5 --> -1
Using these index numbers you can also access the characters from your string. For example:
{1} If you want print "P" from Python then"""
string = "Python"
print(string[0])
"""Result is P
Similarly you can access all the characters from your string
print(string[1], string[2])...
You can also use negative indexes like -1, -2..."""
print(string[-1])
# Result will be n
"""Now by using these indexes you can do string slicing
Syntax : variable_name[start_argument : stop_argument : step_argument]
start argument --> from where string slicing will start(index number)
stop argument --> till where the slicing will stop(index number) + 1
Now how to do string slicing
Suppose that you are having a string "Hello World" then you can perform slicing on this string"""
new_var = "Hello World"
print(new_var[0 : 5])
"""Now it will give me output Hello because it will slice the string from index 1 to index 4 because the value gets decreased by 1 in stop argument in stop argument
You can also give step argument"""
print(new_var[1 : 8 : 2])
"""At first our variable will get sliced that is "ello Wo"(between index 1 to 7) now our program will skip a word and then pick next word due to step argument
So our output will be "el W" rest all characters are skipped due to step argument
Note : By default the value of start argument is 0, stop argument is length of string and step argument is 1 so if you write var_name[::] then your full string will get printed
If we do not give to start argument then its value will be set to 0 and our string will be printed from beginning to character whose index number is stop argument -> 1"""
new_var[:9]
"""Result is Hello Wor
012345678
If we don't give the stop argument then by default the value will be set to length of string and our string will be sliced from start argument till the end"""
new_var[4:]
"""Result is o World
45678910
Here is also a trick to reverse your string"""
new_var[::-1]
"""Result is dlroW olleH
This happens because we have neither given the start argument nor the stop argument so our whole string is sliced. If we give negative value then our characters will be skipped from right to left i.e. reversed also the step argument value is 1(negative) so no character is skipped
I hope this helps you!!"""
I have a string, and when I want to get the value at i index it panics, but when I slice out of the same string keeping lower index value as length then it doesn't panic. Wanted to know how 1 and 2 differs?
func main() {
str := "a"
fmt.Println(str[1]) // 1 this panics
fmt.Println(str[1:]) // 2 this doesn't
}
TLDR; In an index expression the index must be less than the length, and in a slice expression the length is a valid index.
In an index expression the index must be in range, else it panics. The index is in range if 0 <= i < length. Quoting from the spec:
In the index expression a[x]...
If a is not a map:
the index x is in range if 0 <= x < len(a), otherwise it is out of range
And:
For a of string type:
if x is out of range at run time, a run-time panic occurs
Your str string variable stores a string value which has a single byte: 'a'. Indexing starts at zero, so that single byte has index 0. Its length is 1, so there is no element at index 1.
In a slice expression:
a[low : high]
For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range.
In a slice expression the length is a valid index. So in your case indexing str like str[1:] will result in an empty string: "":
In a slice expression a[low : high]...
The result has indices starting at 0 and length equal to high - low.
A missing low index defaults to zero; a missing high index defaults to the length of the sliced operand.
So str[1:] is the same as str[1:len(str)] which is str[1:1]. The result string will have a length of high - low = 1 - 1 = 0: the empty string.
question is :
Compare two strings A and B, determine whether A contains all of the characters in B.
The characters in string A and B are all Upper Case letters.
and I saw the solution is:
def compareStrings(self, A, B):
if len(B) == 0:
return True
if len(A) == 0:
return False
trackTable = [0 for _ in range(26)]
for i in A:
trackTable[ord(i) - 65] += 1
for i in B:
if trackTable[ord(i) - 65] == 0:
return False
else:
trackTable[ord(i) -65] -= 1
return True
I do not understand :
1) why give 26 '0' in the list at beginning ?
2) what does trackTable[ord(i) - 65] += 1 do ?
what is ord(i)?
Thanks !
Min
This is an interesting solution for sure (it's pretty convoluted). It creates a 26-element array to count the occurences of each letter in A, then makes sure that the count for each of those letters in B is greater than or equal to the count in A.
To directly answer your questions:
1) why give 26 '0' in the list at beginning ?
We are starting with a list of 26 0's, one for each letter A-Z. We will increment this in the first for loop.
2) what does trackTable[ord(i) - 65] += 1 do ?
This does the counting. Assuming the input is just capital letters A-Z, then ord('A')=65 and ord('Z')=90. We subtract 65 to make this range from 0-25.
3) what is ord(i)?
I would recommend searching online for this. https://www.programiz.com/python-programming/methods/built-in/ord
"The ord() method returns an integer representing Unicode code point for the given Unicode character."
I'm trying to generate code to return the number of substrings within an input that are in sequential alphabetical order.
i.e. Input: 'abccbaabccba'
Output: 2
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def cake(x):
for i in range(len(x)):
for j in range (len(x)+1):
s = x[i:j+1]
l = 0
if s in alphabet:
l += 1
return l
print (cake('abccbaabccba'))
So far my code will only return 1. Based on tests I've done on it, it seems it just returns a 1 if there are letters in the input. Does anyone see where I'm going wrong?
You are getting the output 1 every time because your code resets the count to l = 0 on every pass through the loop.
If you fix this, you will get the answer 96, because you are including a lot of redundant checks on empty strings ('' in alphabet returns True).
If you fix that, you will get 17, because your test string contains substrings of length 1 and 2, as well as 3+, that are also substrings of the alphabet. So, your code needs to take into account the minimum substring length you would like to consider—which I assume is 3:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def cake(x, minLength=3):
l = 0
for i in range(len(x)):
for j in range(i+minLength, len(x)): # carefully specify both the start and end values of the loop that determines where your substring will end
s = x[i:j]
if s in alphabet:
print(repr(s))
l += 1
return l
print (cake('abccbaabccba'))