I am trying to solve leetcode problem 6 and encountered something that I can't understand. The problem is asking me to use a zigzag pattern to rearrange a string column by column and output it row by row. In my function I used two different ways to create my initial list that stores the output. However, one of them works and the other doesn't. Can someone help me understand why this is happening? Here are the methods I used to initilize the list down below. Since there are multiple rows to output and I want to keep track of which row contains what letter, I thought I could create a list includes muliple sublists.The first method worked just fine, however, the second one could not distinguish which sublist contains which letter and appened the entire string after iterations.
zigzag = [[] for x in range(n)]
zigzag = [[]]*n
for crct in l:
zigzag[row].append(crct)
Here's the output for the first method: [['P', 'I', 'N'], ['A', 'L', 'S', 'I', 'G'], ['Y', 'A', 'H', 'R'], ['P', 'I']]
And the output for the second: [['P', 'A', 'Y', 'P', 'A', 'L', 'I', 'S', 'H', 'I', 'R', 'I', 'N', 'G'], ['P', 'A', 'Y', 'P', 'A', 'L', 'I', 'S', 'H', 'I', 'R', 'I', 'N', 'G'], ['P', 'A', 'Y', 'P', 'A', 'L', 'I', 'S', 'H', 'I', 'R', 'I', 'N', 'G'], ['P', 'A', 'Y', 'P', 'A', 'L', 'I', 'S', 'H', 'I', 'R', 'I', 'N', 'G']]
When you are doing, zigzag = [[] for x in range(n)], python created n different instances of list. So when you are performing append operation it works as expected.
But in case of zigzag = [[]]*n, python created only one instance and after that you are asking python to create n copies of that and which is the reason every index of the outer list contains the exact same elements as they are pointing to the same reference.
For more clarification, check the output of the below code snippet.
zigzag = [[]]*5
print([id(i) for i in zigzag])
Output: [4606230920, 4606230920, 4606230920, 4606230920, 4606230920] # Same address
zigzag = [[] for x in range(5)]
print([id(i) for i in zigzag])
Output: [4606232136, 4606183048, 4606167304, 4606231240, 4606230792] # Different addresses
Related
I have a dictionary of key-value pairs. My value is a nested list. I am trying to make a new nested list out of the old one by combining all the elements with same index together.
I have tried making a new list of the old one,so that it doesn't change my original dictionary. I tired using a loop and indexing my values but it doesn't give me what i need
dict_mutated = []
for key,value,i in dict_ni.items():
dict_mutated['lst_{}'.format(i)] = [item[i] for item in value]
I get an error "ValueError: too many values to unpack (expected 2)"
My input looks like
{lst_0_0 :[['a', 'b', 'c'],['d' ,'e' ,'f'],['g' ,'h' ,'i']],
lst_0_1 :[['a1', 'b1', 'c1'],['d1' ,'e1' ,'f1'],['g1' ,'h1' ,'i1']]}
I expect to get
{lst_0_0: [['a' 'd' 'g'], ['b' 'e' 'h'], ['c' 'f' 'i']],
lst_0_1: [['a1' 'd1' 'g1'], ['b1' 'e1' 'h1'], ['c1' 'f1' 'i1']]
}
Use zip
Ex:
data = {"lst_0_0" :[['a', 'b', 'c'],['d' ,'e' ,'f'],['g' ,'h' ,'i']],
"lst_0_1" :[['a1', 'b1', 'c1'],['d1' ,'e1' ,'f1'],['g1' ,'h1' ,'i1']]}
result = {}
for k, v in data.items():
result[k] = [list(i) for i in zip(*v)]
print(result)
Or a dict comprehension.
result = {k: [list(i) for i in zip(*v)] for k, v in data.items()}
Output:
{'lst_0_0': [['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']],
'lst_0_1': [['a1', 'd1', 'g1'], ['b1', 'e1', 'h1'], ['c1', 'f1', 'i1']]}
i'm trying to use a member defined in a struct to compute another member of the same struct. In particular I have:
DATI= struct( 'L_x', 1e7,...
'L_y', 2*pi*1e6,...
'H', 200,...
'W', 0.3e-7,...
'R', 0.6e-3,...
'c_beta', 0,...
'c_gamma', W*pi/(R*L_y),...
'c_alpha', [H*c_beta/R;0]);
In this way I cannot use members like 'W' or 'R', how can I solve this?
You must first define the structure as you're doing, then use its values. The fields of a structure can be accessed with a dot (.).
To define the c_gamma and c_alpha fields you can use:
DATI= struct( 'L_x', 1e7,...
'L_y', 2*pi*1e6,...
'H', 200,...
'W', 0.3e-7,...
'R', 0.6e-3,...
'c_beta', 0);
DATI.c_gamma = DATI.W*pi/(DATI.R*DATI.L_y);
DATI.c_alpha = [DATI.H*DATI.c_beta/DATI.R;0];
or using strings for variable field names:
DATI= struct( 'L_x', 1e7,...
'L_y', 2*pi*1e6,...
'H', 200,...
'W', 0.3e-7,...
'R', 0.6e-3,...
'c_beta', 0);
DATI.c_gamma = DATI.('W')*pi/(DATI.('R')*DATI.('L_y'));
DATI.c_alpha = [DATI.('H')*DATI.('c_beta')/DATI.('R');0];
You cannot, on the other hand, do this operation with a single command, like this:
DATI= struct( 'L_x', 1e7,...
'L_y', 2*pi*1e6,...
'H', 200,...
'W', 0.3e-7,...
'R', 0.6e-3,...
'c_beta', 0,...
'c_gamma', DATI.W*pi/(DATI.R*DATI.L_y),...
'c_alpha', [DATI.H*DATI.c_beta/DATI.R;0]);
because in the latter case the fields have not been created yet.
I have made a class definition...
class Element():
def __init__(self, word_list, type):
self.type = type
self.list = word_list
And on another Python file (practice_page_1) a function definition...
from class_element import Element
test_list = []
def test(word_list):
num = 0
for letter in word_list:
if letter == 'd':
global test_list
test_list = word_list[:num + 1]
test_list = Element(test_list, 'letters')
return True
num += 1
And then on another Python file the operation of the function...
from practice_page_1 import test
from practice_page_1 import test_list
my_list = ['a', 'b', 'c', 'd', 'a', 'a', 'e', 'f', 'a', 'g']
test(my_list)
print(test_list)
When it prints test_list it prints an empty list [] while I was expecting it to print a class object. However if I move the exact same lines of operation back to practice_page_1, it does print test_list as a class object. Why is this?
When you use from ... import ..., the imported object is put in the current namespace. It is a reference to the object itself, not the module variable. If you want to get the most recent changes, use this:
import practice_page_1
my_list = ['a', 'b', 'c', 'd', 'a', 'a', 'e', 'f', 'a', 'g']
practice_page_1.test(my_list)
print(practice_page_1.test_list)
That works because you are now accessing the variable called test in the module namespace instead of the current one (which used to be the same object as that in the module namespace). You probably want to do import ... as ... when you have a module with that long a name, but there you go.
I have an array of cells, for example,
cells = {'a', 'b', 'c', d', 'e'};
which is inside a for loop of 1 to 5.
I want to create a variable from a to e depending on the loop index, as 1 to a, 2 to b...
When I try (i is the for index),
eval(cells{i}) = values; it gives me the error,
Undefined function or method 'eval' for input arguments of type 'a'
Here the answer:
eval(sprintf([cells{i} '=values;']))
And you can remove the ; if you want to see the display in command window.
In answer to your comment :
cells = {'a', 'b', 'c', 'd', 'e'};
values = 4;
i = 1;
eval(sprintf([cells{i} '=values;']))
This works perfectly fine on my computer, and i get no warning or error messages.
when calling eval, all arguments must be strings, so convert your cell elements to strings first.
eval([ cellstr(cells{i}) ' = values;']))
I have a matrix with population data and a vector that makes reference to each type of data example, age, country, gender, height, ethnicity.
I need to in a part of the code, use those strings as char 1x1. I thougnt in making some relation as
variables = {'age', 'a';
'gender', 'b';
'country', 'c';
'height', 'd';
'ethnicity', 'e'};
I would like something that any time I use the leters, 'a', 'b', 'c', 'd' or 'e', the code understands that I want to use 'age', 'gender', 'country', 'height' or 'ehtnicity', respectively.
how could I do this?
thanks!
You have two options:
A more common method is to use a structure:
codes.a = 'age';
codes.b = 'gender';
...
So anytime you need a code, just get the value of the equivalent structure member:
character_you_typed = 'a';
getfield(codes, character_you_typed)
or (based on #Amro 's comment below):
codes.(character_you_typed)
This method does not restrict you to one-character keys. Another method is to use the recently added Map container with a 'char' key:
codes = containers.Map('KeyType', 'char');
codes('a') = 'age';
codes('b') = 'gender';
...
Then:
character_you_typed = 'a';
codes(character_you_typed)
The second method looks much better, but unfortunately you are restricted to a single character for the keys.