Python slicing with wrapping from negative to positive numbers - python

Say I have a string "abcde", and want to get "deab". How can I get "deab" using string slicing?
I've tried using string[-2:1], but this gives me an empty result ''.
The project I am working on makes splitting this up into [-2:] and [:2] difficult, hence the question. Thanks!

You can simulate wrapping by doubling the string:
(string * 2)[3:7]
This is not necessarily much less efficient than getting two slices the usual way: it only creates one temporary string instead of two, but obviously requires quite a bit more space.

You may want this,
s[-2:] + s[:2]

Related

How to shorten adding to byte array?

packed_source_stream_offsets = bytearray()
for x in source_stream_offset:
packed_source_stream_offsets += varint.encode(x)
Is there a way I can do this on fewer lines or make it more compact? I'm trying to make my code more compact, and I'm wondering if there's a shorter way of doing this.
It's always a bit difficult to answer when there is no reproducible code (e.g. not knowing what source_stream_offset is, or where varint comes from, but I think this should apply in general:
Instead of appending you can use an empty string or byte to join individual parts
You can map over the function rather than using an explicit value
That should yield something like:
bytearray(b''.join(map(varint.encode, source_stream_offset)))
Note: If you're not comfortable with the map syntax, you can also use a list comprehension like:
bytearray(b''.join([varint.encode(x) for x in source_stream_offset]))

Why can't a long integer be converted to an integer when inside a Python list?

I have seen many posts here, which gives ways of removing the trailing L from a list of python long integers.
The most proposed way is
print map(int,list)
However this seems not to work always.
Example---
A=[4198400644L, 3764083286L, 2895448686L, 1158179486, 2316359001L]
print map(int,A)
The above code gives the same result as the input.
I have noticed that the map method doesn't work whenever the number preceding L is large, and only when the numbers are in a list. e.g. Application of int() on 4198400644L does give the number without L, when out of the list.
Why is this occurring and more importantly, how to overcome this?
I think I really need to remove this L, because this is a small part of a program where I need to multiply some integer from this list A, with some integer from a list of non-long integers, and this L is disturbing.I could ofcourse convert the long integers into string,remove the L and convert them back to integer.But is there another way?
I am still using the now outdated Python 2.7.
Python has two different kinds of integers. The int type is used for those that fit into 32 bits, or -0x80000000 to 0x7fffffff. The long type is for anything outside that range, as all your examples are. The difference is marked with the L appended to the number, but only when you use repr(n) as is done automatically when the number is part of a list.
In Python 3 they realized that this difference was arbitrary and unnecessary. Any int can be as large as you want, and long is no longer a type. You won't see repr put the trailing L on any numbers no matter how large, and adding it yourself on a constant is a syntax error.

Fastest sorted string concatenation

What is the fastest and most efficient way to do this:
word = "dinosaur"
newWord = word[0] + ''.join(sorted(word[1:]))
output:
"dainorsu"
Thoughts:
Would something as converting the word to an array increase performance? I read somewhere that arrays have less overhead due to them being the same data type compared to a string.
Basically I want to sort everything after the first character in the string as fast as possible. If memory is saved that would also be a plus. The problem I am trying to solve needs to be within a certain time limit so I am trying to be as fast as possible. I dont know much about python efficiency under the hood so if you explain why this method is fast as well that would be AWESOME!
Here's how I'd approach it.
Create an array of size 26 (assuming that only lowercase letters are used). Then iterate through each character in the string. For the 1st letter of the alphabet, increment the 1st index of the array; for the 2nd, increment the 2nd. Once you've scanned the whole string (which is of complexity O(n)) you will be able to reconstruct it afterwards by repeating the 'a' array[0] times, 'b' array[1] times, and so on.
This approach would beat a fast sort algorithm like quicksort or partition sort, which have complexity O(nlogn).
EDIT: Finally you'd also want to reassemble the final string efficiently. The string concatenation provided by some languages using the + operator can be inefficient, so consider using an efficient string builder class.

What's the Ruby equivalent of Python's output[:-1]?

In Python, if I want to get the first n characters of a string minus the last character, I do:
output = 'stackoverflow'
print output[:-1]
What's the Ruby equivalent?
I don't want to get too nitpicky, but if you want to be more like Python's approach, rather than doing "StackOverflow"[0..-2] you can do "StackOverflow"[0...-1] for the same result.
In Ruby, a range with 3 dots excludes the right argument, where a range with two dots includes it. So, in the case of string slicing, the three dots is a bit more close to Python's syntax.
Your current Ruby doesn't do what you describe: it cuts off the last character, but it also reverses the string.
The closest equivalent to the Python snippet would be
output = 'stackoverflow'
puts output[0...-1]
You originally used .. instead of ... (which would work if you did output[0..-2]); the former being closed–closed the latter being closed–open. Slices—and most everything else—in Python are closed–open.
"stackoverflow"[0..-2] will return "stackoverflo"
If all you want to do is remove the last character of the string, you can use the 'chop' method as well:
puts output.chop
or
puts output.chop!
If you only want to remove the last character, you can also do
output.chop

Problem with list of strings in python

Why on Earth doesn't the interpreter raise SyntaxError everytime I do this:
my_abc = ['a',
'b',
'c'
'd',]
I just wanted to add 'c' to the list of strings, and forgot to append the comma. I would expect this to cause some kind of error, as it's cleary incorrect.
Instead, what I got:
>>> my_abc
['a', 'b', 'cd']
And this is never what I want.
Why is it automatically concatenated? I can hardly count how many times I got bitten by this behavior.
Is there anything I can do with it?
Just to clarify*: I don't actually mind auto-concatenation, my problem has to do ONLY with lists of strings, because they often do much more than just carry text, they're used to control flow, to pass field names and many other things.
Is called "Implicit String Concatenation" and a PEP that proposed its removal was rejected: http://www.python.org/dev/peps/pep-3126/
It's by design. It allows, for example, writing long string literals in several lines without using +.
As others said, it's by design.
Why is it so ? Mostly for historical reasons : C also does it.
In some cases it's handy because it reduce syntaxic noise and avoid adding unwanted spaces (inline SQL queries, complexes regexpes, etc).
What you can do about it ? Not much, but if it really happens often for you, try one of the following tricks.
indent your list with coma at the beginning of the line. It's weird, but if you do so the missing comas become obvious.
assign strings to variables and use variables list whenever you can (and it's often a good idea for other reasons, like avoiding duplicate strings).
split your list: for list of words you can put the whole list inside only one string and split it like below. For more than 5 elements it's also shorter.
'a b c d e'.split(' ').
Because two string literals side-by-side, delimited by whitespace, are concatenated. Since the strings are within a list, they are 'side-by-side'.
See: http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation
Because often people want to do something like this:
line = ("Here's a very long line, with no line breaks,"
" which should be displayed to the user (perhaps"
" as an error message or question box).")
It's easier to write this without having to manually concatenate strings. C, C++, and (I believe) Java and C# also have this behavior.

Categories

Resources