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!!"""
Related
INPUT: srt1(binary string)
Valid String: Any string in which any two consecutive elements are not same.
e.g.: 1010101, 0101010
Operations allowed:
Swap any two character of str1
or
Replace any 1 with 0, or 0 with 1
OUTPUT: Minimum number of operations to transform str1 into valid string
TEST CASES
T1:
str1= "11111"
valid str= "10101"
two elements replaced 1->0
Output: 2
T2:
str1="01101"
valid str="10101"
element 0 and 1 are swapped 1 operation
Output: 1
Can anyone help me with the algorithm or how to approach the code?
>>> 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
Given a string I need to remove the smallest character and return the sum of indices of removed charecter.
Suppose the string is 'abcab' I need to remove first a at index 1.
We are left with 'bcab'. Now remove again a which is smallest in remaining string and is at index 3
We are left with 'bcb'.
In the same way remove b at index 1,then remove again b from 'cb' at index 2 and finally remove c
Total of all indices is 1+3+1+2+1=8
Question is simple but we need to do it in O(n). for that I need to remove kth element in O(1). In python del list[index] has time complexity O(n).
How can I delete in constant time using python
Edit
This is the exact question
You are given a string S of size N. Assume that count is equal to 0.
Your task is the remove all the N elements of string S by performing the following operation N times
• In a single operation, select an alphabetically smallest character in S, for example, Remove from S and add its index to count. If multiple characters such as c exist, then select that has the smallest index.
Print the value of count.
Note Consider 1-based indexing
Solve the problem for T test cases
Input format
The first line of the input contains an integer T denoting the number of test cases • The first line of each test case contains an integer N denoting the size of string S
• The second line of each test case contains a string S
Output format
For each test case print a single line containing one integer denoting the value of count
1<T, N < 10^5
• S contains only lowercase English alphabets
Sum of N over all test cases does not exceed 10
Sample input 1
5
abcab
Sample Output1
8
Explanation
The operations occur in the following order
Current string S= abcab', The alphabetically smallest character of s is 'a As there are 2 occurrences of a, we choose the first occurrence. Its Index 1 will be added to the count and a will be removed. Therefore, S becomes bcab
a will.be removed from 5 (bcab) and 3 will.be added to count
The first occurrence of b will be removed from (bcb) and 1 will be added to count.
b will be removed from s (cb) and 2 will be added to count
c will be removed from 5 (c) and 1 will be added to count
If you follow your procedure of repeatedly removing the first occurrence of the smallest character, then each character's index -- when you remove it -- is the number of preceding larger characters in the original string plus one.
So what you really need to do is find, for each character, the number of preceding larger characters, and then add up all those counts.
There are only 26 characters, so you can do this as you go with 26 counters.
Please link to the original problem statement, or copy/paste exactly what it says, without trying to explain it. As is, what you're asking for is impossible.
Forget deleting: if what you're asking for was possible, sorting would be worse-case O(n) (remove the minimum remaining n times, at O(1) cost for each), but it's well known that comparison-based sorting cannot do better than worst case O(n log n).
One bet: the original problem statement doesn't require that you delete anything - but instead that you return the result as if you had deleted.
With one pass over the input
Putting together various ideas, the final index of a character is one more than the number of larger characters seen before it. So it's possible to do this in one left-to-right pass over the input, using O(1) storage and O(n) time, while deleting nothing:
def crunch(s):
neq = [0] * 26
result = 0
orda = ord('a')
for ch in map(ord, s):
ch -= orda
result += sum(neq[i] for i in range(ch + 1, 26)) + 1
neq[ch] += 1
return result
For your original:
>>> crunch('abcab')
8
But it's also possible to process arbitary iterables one character at a time:
>>> from itertools import repeat, chain
>>> crunch(chain(repeat('y', 1000000), 'xz'))
2000002
x is originally at (1-based) index 1000001, which accounts for half the result. Then each of a million 'y's is conceptually deleted, each at index 1. Finally 'z' is at index 1, for a grand total of 2000002.
Looks like you're only interested in the resulting sum of indices and don't need to simulate this algorithm step by step.
In which case you could compute the result in the following way:
For each letter from a to z:
Have a counter of already removed letters set to 0
Iterate over the string and if you encounter the current letter add current_index - already_removed_counter to the result.
2a. If you encounter current or earlier (smaller) letter increase the counter as it already has been removed
The time complexity is 26 * O{n} which is O{n}.
Since there are only 26 distinct chatacters in the string, we can take each character separately and linearly traverse the string to find all its occurences. Keep a counter of how many chacters were found. Each time an occurence of a given character is found display its index decreased by the counter. Before switching to a new character, remove all the occurences of the previous one - this can be done in linear time.
res = 0
for c in 'a' .. 'z'
cnt = 0
for idx = 1 .. len(s)
if s[idx] = c
print idx - cnt
res += idx - cnt
cnt++
removeAll(s, c)
return res
where
removeAll(s,c):
i = 1
cnt = 0
n = len(s)
while (i < n)
if s[i + cnt] = c
cnt++
n--
else
s[i] = s[i + cnt]
i++
len(s) = n
It prints the elements of the sum to better illustrate what's going on.
Edit:
An updated version based on Igor's answer, that does not require actually removing elements. The complexity is the same i.e. O(n).
res = 0
for c in 'a' .. 'z'
cnt = 0
for idx = 1 .. len(s)
if s[idx] <= c
if s[idx] = c
print idx - cnt
res += idx - cnt
cnt++
return res
Define a function called repeat_middle which receives as parameter one string (with at least one character), and it should return a new string which will have the middle character/s in the string repeated as many times as the length of the input (original) string.
Notice that if the original string has an odd number of characters there is only one middle character. If, on the other hand, if the original string has an even number of characters then there will be two middle characters, and both have to be repeated (see the example).
Additionally, if there is only one middle character, then the string should be surrounded by 1 exclamation sign in each extreme . If , on the other hand, the original string has two middle characters then the returned string should have two exclamation signs at each extreme.
As an example, the following code fragment:
print (repeat_middle("abMNcd"))
should produce the output:
!!MNMNMNMNMNMN!!
Try the following:
def repeat_middle(string):
l = len(string)
if l % 2 == 0:
return "!!{}!!".format(string[int(l / 2 - .5) : int(l / 2 + 1.5)] * l)
else:
return "{}".format(string[int(l / 2)] * l)
odd = "ham"
even = "spam"
print("Original odd length string: {}".format(odd))
print("Returned string: {}".format(repeat_middle(odd)))
print("")
print("Original even length string: {}".format(even))
print("Returned string: {}".format(repeat_middle(even)))
Where the sample output is:
Original even length string: spam
Returned string: !!papapapa!!
Original odd length string: ham
Returned string: aaa
You will find that print(repeat_middle("abMNcd")) does indeed output !!MNMNMNMNMNMN!!.
I want to get each character of each variable to mix like "ababaaaa" if there is no more character left,
`s= "aaaaaa"
t= "bb"
def func():
string =""
for i in range(3):
string=string+s[i]+t[i]
print(string)
func()`
# combine the following strings, starting with string a, interleave
# character for character, and fill the rest of the string with the content
# of the longest string, using "list slicing" method
a = "aaaaaa"
b = "bb"
# create a list of empty strings `['']` with a length
# equal to the maximum length of the longest string
# `(len(a)|len(b))*2` times two
result_list = [''] * ((len(a) | len(b)) * 2)
# fill every second element `[::2]` with the elements of
# string a, to the maximum lenght of the lenght
# of string a times two `[:(len(a)*2):]`, starting at position 0 `[0::]`
result_list[0:(len(a)*2):2] = a
# fill every second element with the elements of
# string b, to the maximum lenght of the lenght
# of string b times two, starting at position 1
result_list[1:(len(b)*2):2] = b
# join the elements of the string list toghether
# to get a string as result
result_string = ''.join(e for e in result_list)
print(result_string)