Access a variable in a list of lists in Python - python

How can I access the strings of 'X'
list = [['X','Y','Z'], ['X','Z','Y']]
For example I want to define a function to return True if list[1] of both list is equal to 'X'

You can use all to see if all ith elements in each sublist are the same:
def is_equal(l, i):
first = l[0][i]
return all(sub[i] == first for sub in l)
You might want to catch an IndexError in case i is outside the bounds of and sublist:
def is_equal(l, i):
try:
first = l[0][i]
return all(sub[i] == first for sub in l)
except IndexError:
return False
If you want to explicitly pass a value to check:
def is_equal(l, i, x):
try:
return all(sub[i] == x for sub in l)
except IndexError:
return False

def check_list(list):
for a in list:
if a == "X"
return True
return False
def check_list_list(list):
try:
return check_list(list[1])
except IndexError:
return False

Related

How do you call a function within its function among 4 inner classes

class Algorithms:
class SearchAlgorithms:
class RecursiveBinarySearch:
def RecursiveBinarySearchAlgo(List, Target):
'''
Return true value if it exists and a false if it doesn't
'''
# If the length of the List is equal to 0 : return False
if len(List) == 0:
return False
# Else if the list is not empty
else:
Midpoint = (len(List))//2
# IF the Midpoint value within the list is equal to Target value: return true
if List[Midpoint] == Target:
return True
else:
if List[Midpoint] < Target:
return Algorithms.SearchAlgorithm.RecursiveBinarySearch.RecursiveBinarySearchAlgo(List[Midpoint + 1:], Target)
else:
return Algorithms.SearchAlgorithm.RecursiveBinarySearch.RecursiveBinarySearchAlgo(List[:Midpoint], Target)
def Verify(Result):
print("Target found: ", Result)
Numbers = [1,2,3,4,5,6,7,8]
# Test Cases 1
Result = RecursiveBinarySearchAlgo(Numbers, 12)
Verify(Result)
# Test Case 2
Result = RecursiveBinarySearchAlgo(Numbers, 5)
Verify(Result)
I am getting a name error that the class is not defined name 'Algorithms' is not defined.
I tried entering init function with each class with self. But I am still getting the same error
the program should result in:
Target found : True
target found: False
I don't know why within inner class we cannot call method directly, but as #juanpa.arrivillaga suggested moving to one level up and using an instance of inner class works in addition to self keyword on methods:
class Algorithms:
class SearchAlgorithms:
class RecursiveBinarySearch:
def RecursiveBinarySearchAlgo(self, List, Target):
'''
Return true value if it exists and a false if it doesn't
'''
# If the length of the List is equal to 0 : return False
if len(List) == 0:
return False
# Else if the list is not empty
else:
Midpoint = (len(List))//2
# IF the Midpoint value within the list is equal to Target value: return true
if List[Midpoint] == Target:
return True
else:
if List[Midpoint] < Target:
return self.RecursiveBinarySearchAlgo(List[Midpoint + 1:], Target)
else:
return self.RecursiveBinarySearchAlgo(List[:Midpoint], Target)
def Verify(self, Result):
print("Target found: ", Result)
rbs = RecursiveBinarySearch()
Numbers = [1,2,3,4,5,6,7,8]
# Test Cases 1
Result = rbs.RecursiveBinarySearchAlgo(Numbers, 12)
rbs.Verify(Result)
# Test Case 2
Result = rbs.RecursiveBinarySearchAlgo(Numbers, 5)
rbs.Verify(Result)
If you don't want to create an instance in that case you can use #classmethod annotation as well:
class Algorithms:
class SearchAlgorithms:
class RecursiveBinarySearch:
#classmethod
def RecursiveBinarySearchAlgo(cls, List, Target):
'''
Return true value if it exists and a false if it doesn't
'''
# If the length of the List is equal to 0 : return False
if len(List) == 0:
return False
# Else if the list is not empty
else:
Midpoint = (len(List))//2
# IF the Midpoint value within the list is equal to Target value: return true
if List[Midpoint] == Target:
return True
else:
if List[Midpoint] < Target:
return cls.RecursiveBinarySearchAlgo(List[Midpoint + 1:], Target)
else:
return cls.RecursiveBinarySearchAlgo(List[:Midpoint], Target)
def Verify(Result):
print("Target found: ", Result)
Numbers = [1,2,3,4,5,6,7,8]
# Test Cases 1
Result = RecursiveBinarySearch.RecursiveBinarySearchAlgo(Numbers, 12)
RecursiveBinarySearch.Verify(Result)
# Test Case 2
Result = RecursiveBinarySearch.RecursiveBinarySearchAlgo(Numbers, 5)
RecursiveBinarySearch.Verify(Result)

__getitem__ a 2d array

I am getting a weird error when trying to make the getitem method.
My code is:
def __getitem__(self, item):
if (self.shape[0] == 1):
return self.values[item]
else:
x, y = item
return self.twoDim[x][y]
I can't see where my mistake is, when I try
assert my_array[1][0] == 4
I get this error under:
x, y = item
TypeError: cannot unpack non-iterable int object
Any idea what the problem is?
Thank for any tips
Doing array[0][1] is first passing 0 into the __getitem__ function, and then whatever the function returns, it passes [1] into that function. With your implementation, you cannot do this. You must input a tuple of values in the first __getitem__ function:
class Array:
def __init__(self):
self.shape = (2, 2)
self.values = None
self.twoDim = [[1, 2], [3, 4]]
def __getitem__(self, item):
print(f"{item=}")
if (self.shape[0] == 1):
return self.values[item]
else:
x, y = item
return self.twoDim[x][y]
array = Array()
try:
print(array[1][0]) # item=1
except TypeError:
pass
print("------")
print(array[1, 1] == 4) # item=(1, 1)
# True

class function to remove value from array list object

I am trying to write a class function that removes the first occurence of e (int number) from my array list and for it to return True but if no occurence then return false without adjustment to my array list.
def removeVal(self, e):
A = self.inArray
for x in A:
i+=1
if x == e:
A.remove(i)
self.inArray = A
return True
return False
list = [1,2,2,3,4,5]
list.removeVal(2)
print(list)
class ArrayList:
def __init__(self):
self.inArray = []
self.count = 0
def get(self, i):
return self.inArray[i]
def set(self, i, e):
self.inArray[i] = e
def length(self):
return self.count
def isIn(A, k): # similar to this
# for i in range(len(A)):
# if A[i] == k:
# return True
# return False
You can simply check if e is in the list. list.remove(x) removes the first occurence of x in the list.
You can switch out 'yourlist' with the list you are using.
def removeVal(self, e):
if e in yourlist:
yourlist.remove(e)
return True
return False

How to "Auto Generate" String in Sequence from "0-9 A-Z"

I am trying to auto generate string from 0-9 and A-z.
00001-99999
A0001-A9999
B0001-B9999
Z9999-AA999
AB001-ZZ999
AAA01-.....
And in sequence
just make a recursive call to a function.
list=[]
for i in range(10):
list.append(str(i))
for i in range(26):
list.append(chr(ord('a')+i))
def all(pre,n):
li=[]
if n==1:
for x in list:
for p in pre:
li.append(x+p)
return li
else:
for x in list:
for p in pre:
li.append(x+p)
return all(li,n-1)
print(all([''],2))
Recursor may take a lot of time for large numbers, so you can also make your own number system to increment.
class NumSys:
def __init__(self):
self.val=[0,0,0,0,0]
def next(self):
self.val[4]+=1
for i in range(5):
if self.val[4-i]>35:
if i==4:
return None
else:
self.val[4-i-1]+=1
self.val[4-i]-=35
def __str__(self):
stri=''
for i in range(5):
x=self.val[i]
if x<10:
stri+=str(x)
else:
stri+=chr(ord('a')+x-10)
return stri
n=NumSys()
for i in range(100):
print (str(n))
n.next()

Recursively remove nested items in dictionary

Currently, I'm creating two lists and comparing them for duplicates.
Instead of that, I want to recursively remove nested items from the dictionary
The question I have is, how do I select a deeply nested item AND change the dictionary while performing this recursion?
Current function:
def _finditem(obj,key):
if key == 'haha' or key == 'haha1':
global a_list
global b_list
if isinstance(obj,dict):
_finditem(obj['children'],key)
else:
for x in obj:
if x['title'] == 'Bookmarks Menu':
_finditem(x['children'],'haha')
elif x['title'] == 'surf':
_finditem(x['children'],'haha1')
else:
try:
_finditem(x['children'],key)
except:
if key == 'haha':
a_list.append(x['title'])
elif key == 'haha1':
b_list.append(x['title'])
pass
Modifying a list while iterating over it:
I used a list slice and excluded items from the original based on a test function.
def discard_func(list_of_dicts):
list_of_dicts[:] = [x for x in list_of_dicts if test(x)]
return list_of_dicts
list[:] is list slice syntax for entire list
Explain Python's slice notation
Remove items from a list while iterating
Scope:
The list slice also solves that, since it modifies the original object.
However, I added returns to each function and assignments to each recursive function call anyway. So that the variable being assigned to, gets the returned value from the function, however deep it may go.
def _finditem(op_type, obj):
if isinstance(obj, dict):
obj['children'] = _finditem(op_type, obj['children'])
else:
for x in obj:
if x['title'] in subjects[op_type]:
x['children'] = operations[op_type](x['children'])
else:
try:
x['children'] = _finditem(op_type, x['children'])
except:
continue
return obj
entire file:
assign_var = {'compare' : None , 'discard' : [] , 'keep' : [] , 'pairs' : None}
subjects = {'keep' : ['Bookmarks Menu'] , 'discard' : ['surf'] , 'compare' : None , 'pairs' : [ {'keep' : ['Bookmarks Menu'] , 'discard' : ['surf']} , {'keep':'bla','discard':'etc'} ] }
def test(y):
if 'children' in y:
if y['title'] not in subjects['keep']:
discard_func(y['children'])
else:
pass
elif y['title'] in assign_var['keep']:
print 'Dupicate found'
return False
return True
def discard_func(loo):
loo[:] = [x for x in loo if test(x)]
return loo
def keep_func(x):
global assign_var
for y in x:
if 'children' in y:
if y['title'] not in subjects['discard']:
keep_func(y['children'])
else:
continue
else:
assign_var['keep'].append(y['title'])
return x
def _finditem(op_type, obj):
if isinstance(obj, dict):
obj['children'] = _finditem(op_type, obj['children'])
else:
for x in obj:
if x['title'] in subjects[op_type]:
x['children'] = operations[op_type](x['children'])
else:
try:
x['children'] = _finditem(op_type, x['children'])
except:
continue
return obj
operations = { 'keep' : keep_func , 'discard' : discard_func , 'pairs' : None , 'compare' : None }
def parent_function():
op_type = 'keep'
_finditem(op_type, book)
op_type = 'discard'
book_new = _finditem(op_type, book)
# for op_type in assign_var:
# try:
# _finditem(op_type = op_type, obj = book)
# except:
# pass
return book_new
if __name__ == '__main__':
print 'In __main__'
import json
loc = 'C:\\workspace\\temp\\'
with open(loc + 'bookmarks-2014-05-24.json', 'r') as nctn:
book = json.load(nctn)
book_new = parent_function()
with open(loc + 'bookmarks-2014-05-24_new.json', 'w') as nctn:
nctn.write(json.dumps(book_new))

Categories