python consecutive elements to swap the list items [duplicate] - python

This question already has answers here:
What is the simplest way to swap each pair of adjoining chars in a string with Python?
(20 answers)
Closed 3 years ago.
here my input like:
['a','b','c','d','e','f']
output:
['b','a','d','c','f','e']
I tried to get consecutive list but i'm getting list in between empty string so please make to remove those empty list .
s = list(input().split())
def swap(c, i, j):
c[i], c[j] = c[j], c[i]
return ' '.join(c)
result = swap(s, 0, 1)
print(list(result))
current output:- ['b', ' ', 'a', ' ', 'c', ' ', 'd', ' ', 'e', ' ', 'f']
expected output:-['b', 'a', 'c', 'd', 'e','f']

You just need to return c as list, there is not need to convert to string and back again into a list:
s = ['a','b','c','d','e','f']
def swap(c, i, j):
c[i], c[j] = c[j], c[i]
return c
result = swap(s, 0, 1)
print(result)
Output:
['b', 'a', 'c', 'd', 'e', 'f']

a simple function to swap pairs that does not change the input:
def swap_pairs(list_to_swap):
s = list_to_swap[:] # create copy to not touch the original sequence
for i in range(0, len(s)-1, 2):
s[i], s[i+1] = s[i+1], s[i]
return s
s0 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
s1 = ['a', 'b', 'c', 'd', 'e', 'f']
print(swap_pairs(s0))
print(swap_pairs(s1))
# ['b', 'a', 'd', 'c', 'f', 'e', 'g']
# ['b', 'a', 'd', 'c', 'f', 'e']
### check if s0 and s1 are untouched:
print(s0)
print(s1)
# ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# ['a', 'b', 'c', 'd', 'e', 'f']
if you want to swap pairs 'in place', i.e. directly change the input, you could shorten the process to
def swap_pairs(s):
for i in range(0, len(s)-1, 2):
s[i], s[i+1] = s[i+1], s[i]
# return s
s1 = ['a', 'b', 'c', 'd', 'e', 'f']
swap_pairs(s1)
print(s1)
# ['b', 'a', 'd', 'c', 'f', 'e']
I think it's a matter of taste if a return statement should be added here. I'd consider it to be more clear not to return something since logically not needed. Anyway, be aware of variable scope.

this is the problem.. your joining on space. change it to the following.
def swap(c, i, j):
c[i], c[j] = c[j], c[i]
return ''.join(c)
for your output you could also do the following.
l = [x for x in [your output list] if x!= ' ']
or
l = [x for x in [your output list] if len(x.strip()) > 0]

Try returning only "C" and use recursion for swapping of all elements of list Then you will get expected Output. Check below code.
Output of below code: ['b','a','d','c','f','e']
s = ['a','b','c','d','e','f']
def swap(c, i, j):
if j<=len(c) and len(c)%2==0:
c[i], c[j] = c[j], c[i]
swap(c,i+2,j+2)
elif j<len(c):
c[i], c[j] = c[j], c[i]
swap(c,i+2,j+2)
return c
result = swap(s, 0, 1)
print(list(result))
and if you want Only output= ['b','a','c','d','e','f'] then no need of recursion just return c. Check below code:
s = ['a','b','c','d','e','f']
def swap(c, i, j):
c[i], c[j] = c[j], c[i]
return c
result = swap(s, 0, 1)
print(list(result))

Related

Combining values in an array in Python

I have an array like so: ['A', 'B', 'C', 'D', 'E'].
I've been trying to figure out how to make it like so: ['AB', 'CD', 'E']
I'm not sure where to start. Thanks in advance!
main.py
a = ['A', 'B', 'C', 'D', 'E']
b = [i + j for i, j in zip(a[:-1:2], a[1::2])]
if len(a) % 2 == 1:
b.append(a[-1])
print(b)
result
$ python main.py
['AB', 'CD', 'E']
>>> [''.join(a[i:i+2]) for i in range(0, len(a), 2)]
['AB', 'CD', 'E']
or (as I love iterators)
>>> it = iter(a)
>>> [s + next(it, '') for s in it]
['AB', 'CD', 'E']
I think that the easier way is to iterate through the array and concatenate the chars, it works if you have an array with even length, so you could add a check and append the last element in case of odd length.
array = ['A', 'B', 'C', 'D', 'E']
array2 = [f"{array[i]}{array[i+1]}" for i in range(0, len(array)-1, 2)]
if len(array)%2!=0:
array2.append(array[-1])
print(array2)
Try like this. This is very bare answer but should work.
my_array = ['A', 'B', 'C', 'D', 'E']
def combine_array(my_array):
mixed_array = []
start_new = True
for item in my_array:
if start_new:
mixed_array.append(item)
start_new = False
else:
mixed_array[-1] = mixed_array[-1] + item
start_new = True
return mixed_array
if __name__ == "__main__":
try:
print(combine_array(my_array))
except Exception as err:
print(err)
startArray = ['A', 'B', 'C', 'D', 'E']
currentIndex = 0
finishArray = ['']
for x in startArray:
if len(finishArray[currentIndex]) == 2:
currentIndex += 1
finishArray.insert(currentIndex,x)
else:
finishArray[currentIndex] += x
print(finishArray)

Splitting a python list into smaller lists at spaces

I have a list which consists of alphabets and spaces:
s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j'];
I need to split it into smaller individual lists:
s=[['a','b'],['b','c'],['d','e','f','g','h'],['i','j']]
I am new to python.
The entire code:
#To get the longest alphabetical substring from a given string
s = input("Enter any string: ")
alpha_string = []
for i in range(len(s)-1): #if length is 5: 0,1,2,3
if(s[i] <= s[i+1]):
if i == len(s)-2:
alpha_string.append(s[i])
alpha_string.append(s[i+1])
else:
alpha_string.append(s[i])
if(s[i] > s[i+1] and s[i-1] <= s[i]):
alpha_string.append(s[i])
alpha_string.append(" ")
if(s[i] > s[i+1] and s[i-1] > s[i]):
alpha_string.append(" ")
print(alpha_string)
#Getting the position of each space in the list
position = []
for j in range(len(alpha_string)):
if alpha_string[j] == " ":
position.append([j])
print(position)
#Using the position of each space to create slices into the list
start = 0
final_string = []
for k in range(len(position)):
final_string.append(alpha_string[start:position[k]])
temp = position[k]
start = temp
print(final_string)`
Try a list comprehension as follows
print([list(i) for i in ''.join(s).split(' ') if i != ''])
[['a', 'b'], ['b', 'c'], ['d', 'e', 'f', 'g', 'h'], ['i', 'j']]
Here generator will be perfect :
s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j'];
def generator_approach(list_):
list_s=[]
for i in list_:
if i==' ':
if list_s:
yield list_s
list_s=[]
else:
list_s.append(i)
yield list_s
closure=generator_approach(s)
print(list(closure))
output:
[['a', 'b'], ['b', 'c'], ['d', 'e', 'f', 'g', 'h'], ['i', 'j']]
Or simply in one line, result = [list(item) for item in ''.join(s).split()]
This is one functional way.
s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j']
res = list(map(list, ''.join(s).split()))
# [['a', 'b'], ['b', 'c'], ['d', 'e', 'f', 'g', 'h'], ['i', 'j']]
from itertools import groupby
s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j']
t = [list(g) for k, g in groupby(s, str.isspace) if not k]
print(t)
OUTPUT
[['a', 'b'], ['b', 'c'], ['d', 'e', 'f', 'g', 'h'], ['i', 'j']]
This doesn't require the strings to be single letter like many of the join() and split() solutions:
>>> from itertools import groupby
>>>
>>> s = ['abc','bcd',' ',' ','bcd','cde',' ','def','efg','fgh','ghi','hij',' ','ijk','jkl']
>>>
>>> [list(g) for k, g in groupby(s, str.isspace) if not k]
[['abc', 'bcd'], ['bcd', 'cde'], ['def', 'efg', 'fgh', 'ghi', 'hij'], ['ijk', 'jkl']]
>>>
I can never pass up an opportunity to (ab)use groupby()

How can I reverse a section of a list using a loop in Python?

I'm in need of a little help reversing a section of a list in Python using a loop.
I have a list: mylist = ['a', 'b', 'c', 'd', 'e', 'f']
Also have an index number, this number will tell where to start the reversing. For example, if the reverse-index number is 3, it needs to be something like this: ['d', 'c', 'b', 'a', 'e', 'f']
What I currently have:
def list_section_reverse(list1, reverse_index):
print("In function reverse()")
n_list = []
for item in range( len(list1) ):
n_list.append( (list1[(reverse_index - 1) - item]) )
item += 1
return n_list
mylist = ['a', 'b', 'c', 'd', 'e', 'f']
print( list_section_reverse(mylist, 3) )
Which returns ['c', 'b', 'a', 'f', 'e', 'd']
How can I alter my code, so that it prints out ['d', 'c', 'b', 'a', 'e', 'f']?
You can simply use:
def list_section_reverse(list1, reverse_index):
return list(reversed(list1[:reverse_index+1])) + list1[reverse_index+1:]
Edit: The problem with your existing solution is that you keep reversing after reverse_index. If you have to use a loop, try this:
def list_section_reverse(list1, reverse_index):
print("In function reverse()")
n_list = list1[:]
for i in range(reverse_index + 1):
n_list[i] = list1[-i-reverse_index]
return n_list
mylist = ['a', 'b', 'c', 'd', 'e', 'f']
print(list_section_reverse(mylist, 3))
The pythonic solution:
list1[reverse_index::-1] + list1[reverse_index+1:]
Now, that's not using loops like you asked. Well, not explicitly... Instead we can break down the above into its constituent for loops.
def list_section_reverse(list1, reverse_index):
if reverse_index < 0 or reversed_index >= len(list1):
raise ValueError("reverse index out of range")
reversed_part = []
for i in range(reverse_index, -1, -1): # like for i in [n, n-1, ..., 1, 0]
reversed_part.append(list1[i]
normal_part = []
for i in range(reverse_index + 1, len(list1)):
normal_part.append(list1[i])
return reversed_part + normal_part
Is it allowed to make a copy of the list?
def list_section_reverse(list1, reverse_index):
print("In function reverse()")
n_list = [ element for element in list1 ]
for item in range( reverse_index + 1 ):
n_list[ item ] = list1[ reverse_index - item ]
item += 1
return n_list
mylist = ['a', 'b', 'c', 'd', 'e', 'f']
print(list_section_reverse(mylist, 3))
Outs:
In function reverse()
['d', 'c', 'b', 'a', 'e', 'f']
You can modify the list inplace using a slice.
mylist[:4] = mylist[:4][::-1]
You can try this. This makes use of no slicing, and can use either a while loop or for loop.
def reversed_list(my_list, index):
result = []
list_copy = my_list.copy()
i = 0
while i < index+1:
result.append(my_list[i])
list_copy.remove(my_list[i])
i+=1
result.reverse()
return result + list_copy
Or with a for loop
def reversed_list(my_list, index):
result = []
list_copy = my_list.copy()
for i in range(len(my_list)):
if i < index + 1:
result.append(my_list[i])
list_copy.remove(my_list[i])
result.reverse()
return result + list_copy

Weird list assignment

I'm trying to write program that will find all palindromes in a word. For example word "radar" has got 2 palindromes radar and ada. We skip single letters, so r, a, d, etc. aren't palindromes.
import copy
def ILEP(word):
lista = list(word)
counter = 0
pali = []
def isPalindrome(listaWord):
backup = copy.deepcopy(listaWord)
backup.reverse()
a = ''.join(backup)
b = ''.join(listaWord)
if(a == b):
return True
else:
return False
for i in range(len(lista)):
current = [lista[i]]
for j in range(i+1, len(lista)):
current.append(lista[j])
if(isPalindrome(current)):
print(current)
pali.append(current)
counter+=1
print(pali)
return counter
print(ILEP("radar"))
The program is finding all palindromes correctly, but it assings them wrong to the list pali. Console:
['r', 'a', 'd', 'a', 'r']
['a', 'd', 'a']
[['r', 'a', 'd', 'a', 'r'], ['a', 'd', 'a', 'r']]
2
As U can see it prints palindromes ['r', 'a', 'd', 'a', 'r'] and ['a', 'd', 'a'], but the list pali has got wrong value [['r', 'a', 'd', 'a', 'r'], ['a', 'd', 'a', 'r']]
You are changing your list current after appending to pali. You have to make a copy:
def is_palindrome(word):
return word[::-1] == word
def ILEP(word):
pali = []
for i, ch in enumerate(word):
current = [ch]
for ch in word[i+1:]:
current.append(ch)
if is_palindrome(current):
print(current)
pali.append(current[:])
print(pali)
return len(pali)
print(ILEP("radar"))

Complicated array join in Python

I'm having an array like this:
pairs = [['a', 'b', 'c', 'd'], ['g', 'h', 'j', 'k', 'l', 'm']]
I'd like to join them and create a new array so that on the output I'd have something like this:
['a_b', 'b_c', 'c_d']
['g_h', 'h_j', 'j_k', 'k_l', 'l_m']
I'm struggling with an algorithm and can't come up with something. How can I do that?
[['{}_{}'.format(*x) for x in zip(p, p[1:])] for p in pairs]
the for p in pairs part iterate each of your input lists.
zip(p, p[1:]) returns pairs of each item with the next item
'{}_{}'.format(*x) gets the string you requested
joinedIt = []
for i in range(0, len(pairs)):
for j in range(0, len(pairs[i])-1):
joinedIt[i].append(pairs[i][j] + pairs[i][j+1])
>>> pairs = [['a', 'b', 'c', 'd'], ['g', 'h', 'j', 'k', 'l', 'm']]
>>> [[s[i] + '_' + s[i+1] for i in range(len(s)-1)] for s in pairs]
[['a_b', 'b_c', 'c_d'], ['g_h', 'h_j', 'j_k', 'k_l', 'l_m']]
You could do that by using for loops with ranges
def parse(list):
new_list = []
for i in range(len(list) - 1):
new_list.append(list[i] + "_" + list[i+1])
return new_list
zipped = (zip(x,x[1:]) for x in pairs)
[["{}_{}".format(ele[0], ele[1]) for ele in x ]for x in zipped]

Categories