How to merge 2d array into string in python - python

I have tried this solution but the problem I am facing is that when I want to convert
[[65, 'D', 'M', 'A', 'H'], [65, 'S', 'I', 'N']]
to string using the method above , what i get is
'65DMAH65SIN'
but what I want is
'65DMAH 65SIN'
i.e after every array ends, it gives me space. I am thinking of logics for this but not working.

I would use following comprehension for that task:
a = [[65, 'D', 'M', 'A', 'H'], [65, 'S', 'I', 'N']]
s = ' '.join(''.join(map(str,i)) for i in a)
print(s)
Output:
65DMAH 65SIN
For every sublist I map it, so every element of sublist become str, then I join elements of every sublist without separator (empty str), which then I join using space.

Your problem answer is:
def solution(List):
result = ''
for i in range(len(string)):
for j in string[i]:
result+=str(j)
result+=' '
return result

Related

How can I reference a string (e.g. 'A') to the index of a larger list (e.g. ['A', 'B', 'C', 'D', ...])?

I have been racking my brain and scouring the internet for some hours now, please help.
Effectively I am trying to create a self-contained function (in python) for producing a caesar cipher. I have a list - 'cache' - of all letters A-Z.
def caesarcipher(text, s):
global rawmessage #imports a string input - the 'raw message' which is to be encrypted.
result = ''
cache = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
Is it possible to analyze the string input (the 'rawmessage') and attribute each letter to its subsequent index position in the list 'cache'? e.g. if the input was 'AAA' then the console would recognise it as [0,0,0] in the list 'cache'. Or if the input was 'ABC' then the console would recognise it as [0,1,2] in the list 'cache'.
Thank you to anyone who makes the effort to help me out here.
Use a list comprehension:
positions = [cache.index(letter) for letter in rawmessage if letter in cache]
You can with a list comprehension. Also you can get the letter from string.
import string
print([string.ascii_uppercase.index(c) for c in "AAA"])
# [0, 0, 0]
print([string.ascii_uppercase.index(c) for c in "ABC"])
# [0, 1, 2]
result = []
for i in list(rawmessage):
result.append(cache.index(i))

Python rearrange list based on another list

I want to rearrange a list based on another list which have common elements between them.
my list = ['q','s','b','f','l','c','x','a']
base_list = ['z','a','b','c']
Above lists have common 'a','b' and 'c' as common elements.the expected outcome for is as below
my_result = ['a','b','c','q','s','f','l','x']
Thanks in Advance
Sky
my_list = ['q','s','b','f','l','c','x','a']
base_list = ['z','a','b','c']
res1=[x for x in base_list if x in my_list] # common elements
res2=[x for x in my_list if x not in res1] #
res3=res1+res2
Output :
['a', 'b', 'c', 'q', 's', 'f', 'l', 'x']
Create a custom key for sorted as shown in this document. Set the value arbitrarily high for the letters that don't appear in the base_list so they end up in the back. Since sorted is considered stable those that aren't in the base_list will remain untouched in terms of original order.
l = ['q','s','b','f','l','c','x','a']
base_list = ['z','a','b','c']
def custom_key(letter):
try:
return base_list.index(letter)
except ValueError:
return 1_000
sorted(l, key=custom_key)
['a', 'b', 'c', 'q', 's', 'f', 'l', 'x']
A (probably non optimal) way:
>>> sorted(my_list, key=lambda x: base_list.index(x) if x in base_list
else len(base_list)+1)
['a', 'b', 'c', 'q', 's', 'f', 'l', 'x']

Why can't I concatenate this list in order to switch characters?

I'm having this problem and have been up for hours trying to work it out, does anyone know what might be going wrong?
When I write
plant = 'blackberry'
temp = list(plant)
def switch(xs):
return [xs[1]] + xs[0] + [xs[2:-1]]
and then call it in
switch(temp)
I get the error 'TypeError: can only concatenate list (not "str") to list'
I'm wondering why? I'm trying to do a switch of the first two letters of blackberry where the input isn't modified to memory, so that if I was to call
temp
afterwards, then it would still be 'blackberry' rather than the switched version - does anyone know how to get rid of this error?
I'd be very grateful for any clarification on this
Look at what each item you are returning actually is:
print([xs[1]]) # ['l']
print(xs[0]) # 'b'
print([xs[2:-1]]) # [['a', 'c', 'k', 'b', 'e', 'r', 'r']]
return [xs[1]] + xs[0] + [xs[2:-1]]
# ['l'] + 'b' + [['a', 'c', 'k', 'b', 'e', 'r', 'r']]
You cannot add different elements like this. You need to make sure they are all the same type, i.e.:
return [xs[1]] + [xs[0]] + xs[2:-1]
# ['l'] + ['b'] + ['a', 'c', 'k', 'b', 'e', 'r', 'r']
xs[1] is "l"
[xs[1]] is ["l"]
xs[0] is "b"
xs[2:-1] is ['a', 'c', 'k', 'b', 'e', 'r', 'r']
[xs[2:-1]] is [['a', 'c', 'k', 'b', 'e', 'r', 'r']]
As you can see:
[xs[2:-1]] is a list
[xs[1]] is a list
xs[0] is a string
In python, string and list cannot be concatenated. That means, one cannot add a string with a list.
In general you can use type() function to see the type of a variable. For example:
print(type(xs[0])) results in this output: <class 'list'>
The xs[2:-1] is an array whereas xs[1], xs[0] are just characters which work as strings so there is conflict in concatenation
Further list concatenation to strings is done via join methods
String = "<anyString>".join(listarr)
The following solution will work for your case
plant = 'blackberry'
temp = list(plant)
def switch(xs):
print("".join([xs[1], xs[0], "".join(xs[2:])]))
return "".join([xs[1], xs[0], "".join(xs[2:])])
switch(temp)

Convert a Python list of lists to a single string

I have list of lists consisting of chars and integers like this:
list = [[65], [119, 'e', 's', 'i'], [111, 'd', 'l'], [111, 'l', 'w'], [108, 'd', 'v', 'e', 'i'], [105, 'n'], [97, 'n'], ['111', 'k', 'a']]
I want to convert this into a single string like this:
"65 119esi 111dl 111lw 108dvei 105n 97n 111ka"
I have tried this:
new_list = [' '.join(x for x in list)]
but it is giving me this error:
TypeError: sequence item 0: expected str instance, list found
So what am i supposed to do, I'm new to coding!
That error you get is because .join() expects strings to join together, but you are passing it a list instead (one of the subarrays).
A one liner would be:
" ".join(["".join([str(item) for item in sublist]) for sublist in your_list])
Note that this only works for one level of nested arrays. If you had more or indefinite, probably its better to write your own function that does the job.
To make it a bit easier to see what is happening you could use:
final_string = ""
for elem in list:
final_string = final_string + " "
for el in elem:
final_string = final_string +str(el)
You have ints in your sublists aswell, that need converting before joining. You can do the following, using map to do the string conversion of the tokens and str.join to piece them together:
lst = [[65], [119, 'e', ... ] # do NOT call a variable "list"
new_lst = " ".join("".join(map(str, sub)) for sub in lst)
# '65 119esi 111dl 111lw 108dvei 105n 97n 111ka'

Is passing an array slice to a function in Python an O(1) or O(N) operation?

I have a function that takes an input string of characters and reverses them according to the white space breaks.
For example:
input: arr = [ 'p', 'e', 'r', 'f', 'e', 'c', 't', ' ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'r', 'a', 'c', 't', 'i', 'c', 'e' ]
output: [ 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'e', 'r', 'f', 'e', 'c', 't' ]
To reverse the 'words', I use the following function
def reverse_word(arr):
i = 0
j = len(arr) - 1
while i < j:
arr[j], arr[i] = arr[i], arr[j]
i += 1
j -= 1
return arr
def reverse_words(arr):
arr.reverse()
p1 = 0
for i, v in enumerate(arr):
if v == ' ':
if arr[p1] != ' ':
arr[p1:i] = reverse_word(arr[p1:i])
p1 = i + 1
arr[p1:] = reverse_word(arr[p1:])
return arr
My question is: Is the call to reverse an O(1) or O(N) space operation? I assumed O(N) but someone else said it was O(1). I assumed O(N) because in the worst case, with one word, the entire array will need to be copied to the stackcall. Space is not "constant" because the space size allocated to the call is dependent on the input length.
To answer your question first: Yes the reverse function you defined is an O(1) space operation(even though it's wrong and will never end). The reason is, when you pass in a list to the function in python, it does not copy the whole list, it passes it's reference(or the pointer, if you are familiar with C concepts). So no matter how long your array is, the space usage is constant.
However, your question alone may be meaningful, but in this program, it does not matter. We all know for an algorithm, the big-O for space and time is determined by the largest part of the algorithm. You actually other operations in your code that has O(N) space operation. For example, reversed() function generates a whole new list.
BTW, it's not the best practice to define a function that has the same name with other methods you may use(in this case, reverse).

Categories