Reverse only if all characters are unique
Which one-line Python expression reverses a string s only when all of its characters are unique, without using slicing [::-1] or reversed(), for example producing 'cba' from s='abc' but leaving s='abca' unchanged?
- ''.join(s[i] for i in range(len(s)-1, -1, -1)) if len(s) == len(set(s)) else s
- ''.join(reversed(s)) if len(s) == len(set(s)) else s
- s[::-1] if len(set(s)) == len(s) else s
- ''.join(s[i] for i in range(len(s))) if len(set(s)) == len(s) else s
- s if len(set(s)) == len(s) else ''.join(s[i] for i in range(len(s)-1, -1, -1))
Second-largest in one pass without sorting
Given a list nums and sentinels largest = second = float('-inf'), which in-loop update logic correctly computes a distinct second-largest value in a single pass without using sort or sorted, even when nums contains duplicates (e.g., nums=[5, 1, 5, 3])?
- if x u003E largest: second, largest = largest, x; elif x u003C largest and x u003E second: second = x
- if x u003E= largest: second, largest = largest, x; elif x u003E second: second = x
- if x u003E largest: largest, second = x, second; elif x u003E second: second = x
- if x u003E largest: second = x; largest = x
- if x u003E largest and x u003E second: second = x; largest = x
Flatten a shallow nested list without recursion in one line
Which one-line Python expression flattens a list like lst = [1, [2, 3], [4, 5], 6] into [1, 2, 3, 4, 5, 6] without using recursion or additional imports?
- [y for x in lst for y in (x if isinstance(x, list) else [x])]
- [item for sub in lst for item in sub]
- list(sum(lst))
- list(chain.from_iterable(lst))
- flatten(lst)
Understanding reverse indices with range
For a string s of length 4, what sequence of indices does range(len(s)-1, -1, -1) generate, which is commonly used to traverse s in reverse without slicing?
- [3, 2, 1, 0]
- [4, 3, 2, 1]
- [3, 2, 1]
- [0, 1, 2, 3]
- [-1, -2, -3, -4]
Applying reverse-if-unique to a non-unique string
When evaluating the expression ''.join(s[i] for i in range(len(s)-1, -1, -1)) if len(s) == len(set(s)) else s on s = 'abca', what string is returned?
- abca
- acba
- aabc
- a c b a