What i did wrong in my python function? - python

def make_str_from_row(board, row_index):
''' (list of list of str, int) -> str
Return the characters from the row of the board with index row_index
as a single string.
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
'''
for i in range(len(board)):
i = row_index
print(board[i])
This prints ['A', 'N', 'T', 'T']
How do I print it like this 'ANTT' instead?

Well, you got what you told to print!
board is a list of list of strs, so board[i] must be a list of strs, and when you write print(board[i]), you get a list!
You may need to write this:
print(''.join(board[i]))

You could simplify that a whole lot by using
>>> def make_str_from_row(board, row_index):
... print repr(''.join(board[row_index]))
...
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
The reason you get that output is because you print a list since the elements of board are lists. By using join, you get a string.
Also, I don't understand why you use a loop if are going to change the index you loop over.

I think this was what you were trying to do:
def make_str_from_row(board, row_index):
''' (list of list of str, int) -> str
Return the characters from the row of the board with index row_index
as a single string.
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
'''
for cell in board[row_index]:
print cell,

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))

Use global positions to mutate list, in list of lists

I need to keep my data in a list of lists, but want to edit elements in the lists based on their overall position.
For instance:
mylist = [['h','e','l','l','o'], ['w','o','r','l','d']]
I want to change position 5 as if it was all one list resulting in:
[['h','e','l','l','o'], ['change','o','r','l','d']]
This is for very large lists and lots of mutations so speed is essential!
Here is the solution of your's question
# initializing list
input_list = [['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']]
print("The initial list is : " + str(input_list))
length: int = 0
# define position(global index) where you want to update items in list
change_index = 5
## global starting index of sublist [0,5]
sub_list_start_index: list = list()
for sub_list in input_list:
sub_list_start_index.append(length)
length += len(sub_list)
# check if index we want to change is <= global list index and
if change_index <= length - 1 and change_index >= max(sub_list_start_index):
sub_list_index = int(change_index - max(sub_list_start_index))
input_list[input_list.index(sub_list)][sub_list_index] = 'change'
print("Updated list : " + str(input_list))
Output:
The initial list is : [['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']]
Updated list : [['h', 'e', 'l', 'l', 'o'], ['change', 'o', 'r', 'l', 'd']]

This code should reverse the list but only swaps first and last elements

class Solution:
def reverseString(self, s: List[str]) -> None:
if(len(s)<=1):
return
s[0],s[-1] = s[-1],s[0]
self.reverseString(s[1:-1])
this was a question on LeetCode. We have to reverse the list using recursion without using extra memory, i.e in-place.
I wrote this code but I am not sure why it is not working. For example, when s = ['h', 'e', 'l', 'l', 'o'], the output is ['o', 'e', 'l', 'l', 'h'] instead of ['o', 'l', 'l', 'e', 'h'] - it only swaps the first and last elements of the list.
The following works for me:
def reverse_inplace(char_list, step=1):
start, stop = step - 1, -step
if step == 1:
pass
elif len(char_list[start:stop]) <= 1:
return
char_list[start], char_list[stop] = char_list[stop], char_list[start]
reverse_inplace(char_list, step=step+1)
This passes the same list reference to each recursive call, and simply keeps track of how far along you are in the process with a step parameter.
reverse_inplace(list("hello")) outputs:
['o', 'l', 'l', 'e', 'h']
Kind of a fix for your concept:
def reverseString(s, n=0):
if(n==len(s)//2):
return
else:
s[n], s[-n-1]=s[-n-1], s[n]
reverseString(s, n+1)
x=list("new york")
reverseString(x)
print(''.join(x))
#outputs: kroy wen
x=list("hello")
reverseString(x)
print(''.join(x))
#outputs: olleh

Joining & printing characters into a string from a 2d array

Might be a simple fix but I've tried everything. I'm trying to join and print the values from my 2d array in a single string without each character being separated if not separated by an actual space. For example what my code does now "H E L L O W O R L D" instead of "HELLO WORLD". Can someone please help.
for a in range(int(numOfColumns)):
for b in range(numOfRows):
#''.join(Matric[b][a])
#print(Matrix[b][a]),
#print(Matrix[b][a]),
You can use a list comprejesions:
result = " ".join(["".join([i for i in row]) for row in Matrix])
Or just
result = " ".join(["".join(row) for row in Matrix])
as #Tomothy32 noted.
Here an expression
"".join(row)
which creates a string from a row, for example:
row = ['h', 'e', 'l', 'l', 'o']
"".join([row])
Out:
hello
Almost the same for the outer loop which iterates the row, but it joins the strings with a whitespaces:
result = " ".join(...)
Or you can do it step-by-step, but it's not so clear:
substrings = []
for row in Matrix:
substr = ""
for char in row:
substr += char
substrings.append(substr)
result = " ".join(substrings)
I don't know how to do that easily without comprehensions. Probably you should use it.
Edit
How it works:
Matrix = [
['H', 'e', 'l', 'l', 'o'], # it's a first row
['w', 'o', 'r', 'l', 'd'] # it's a second row
]
Python iterastes trough the outer level first, i.e.
[print(row) for row in Matrix]
will print something like that:
['H', 'e', 'l', 'l', 'o'],
['w', 'o', 'r', 'l', 'd']
each row is a list (in this case). So, we can iterate through it, using inner loop (list comprehension):
[[print(i, end='') for i in row]) for row in Matrix]
Out:
"hello"
"world"
(end='' just cahnges newline to the empty string). Now you can change print to the "".join method and get what you want.
How iterate columns? Well, it's not so easy, especially when lengths of the strings are different. If the length is equal, you could use dollowing comprehension (answered here):
[[row(i) for row in matrix] for i in range(max(len(r) for r in Matrix))]
Out:
[['h', 'w'],
['e', 'o'],
['l', 'r'],
['l', 'l'],
['o', 'd']]
But probably it's easier to generate you data already transposed. There are some tutorials about a comprehensions, you can read it, for example, this one. Comprehensions is a very useful tool.
Assuming below martix:
Matric = [['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']]
mat = ''
for x in Matric[0]:
mat = ''.join([mat,x])
mat += ' '
for y in Matric[1]:
mat = ''.join([mat, y])
print(mat)

String vs list membership check

So i'm wondering why this:
'alpha' in 'alphanumeric'
is True, but
list('alpha') in list('alphanumeric')
is False.
Why does x in s succeed when x is a substring of s, but x in l doesn't when x is a sublist of l?
When you use list function with any iterable, a new list object will be created with all the elements from the iterable as individual elements in the list.
In your case, strings are valid Python iterables, so
>>> list('alpha')
['a', 'l', 'p', 'h', 'a']
>>> list('alphanumeric')
['a', 'l', 'p', 'h', 'a', 'n', 'u', 'm', 'e', 'r', 'i', 'c']
So, you are effectively checking if one list is a sublist of another list.
In Python only Strings have the in operator to check if one string is part of another string. For all other collections, you can only use individual members. Quoting the documentation,
The operators in and not in test for collection membership. x in s evaluates to true if x is a member of the collection s, and false otherwise. x not in s returns the negation of x in s. The collection membership test has traditionally been bound to sequences; an object is a member of a collection if the collection is a sequence and contains an element equal to that object. However, it make sense for many other object types to support membership tests without being a sequence. In particular, dictionaries (for keys) and sets support membership testing.
For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.
For the Unicode and string types, x in y is true if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Note, x and y need not be the same type; consequently, u'ab' in 'abc' will return True. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.
For the second one you are asking if
['a', 'l', 'p', 'h', 'a'] in ['a', 'l', 'p', 'h', 'a', 'n', 'u', 'm', 'e', 'r', 'i', 'c']
and there is no sub-list in the second list only characters.
['a', 'l', 'p', 'h', 'a'] in [['a', 'l', 'p', 'h', 'a'], ['b', 'e', 't', 'a']]
would be true
lists determine membership if an item is equal to one of the list members.
strs determine whether string a is in string b if a substring of b is equal to a.
I suppose you are looking for the fact that string and list has different implementations of __contains__ magic method.
https://docs.python.org/2/reference/datamodel.html#object.contains
This is why 'alpha' in 'alphanumeric' is True, but
list('alpha') in list('alphanumeric') is False
maybe you should try issubset method.
>>> set('alpha').issubset(set('alphanumeric'))
True
although set('alpha') returns set(['a', 'p', 'l', 'h']), and set('alphanumeric'), set(['a', 'c', 'e', 'i', 'h', 'm', 'l', 'n', 'p', 'r', 'u']).
set method makes a list ignoring repetetive elements.

Categories