I want to create a function that checks if the given tab fits or not. My matrix should be a 3x3 with 3 tuples, each with 3 integers.
I want this interaction to happen:
>>> tab = ((1,0,0),(-1,1,0),(1,-1,-1))
>>> tabuleiro(tab)
True
>>> tab = ((1,0,0),(’O’,1,0),(1,-1,-1))
>>> tabuleiro(tab)
False
>>> tab = ((1,0,0),(-1,1,0),(1,-1))
>>> tabuleiro(tab)
False
All I have right now is:
def tabuleiro(tab):
return isinstance(tab, tuple) and len(tab) == 3 and \
all((isinstance( l, tuple) and len (l) == len(tab[0])) for l in tab) and len (tab[0]) == 3 and \
(....)
This is probably easier to read and reason about if you break it into one function for the group and another function for each member of the group. Then you could do something like:
def tab_is_valid(tab, valid_size=3):
''' is an individual member valid'''
return len(tab) == valid_size and all(isinstance(n, int) for n in tab)
def tabuleiro(tab):
''' is the whole structure valid '''
return all((
isinstance(tab, tuple),
len(tab) == 3,
all(tab_is_valid(t) for t in tab),
))
tabuleiro(((1,0,1),(-1,1,0),(1,-1,-1)))
# True
tabuleiro(((1,0,1.6),(-1,1,0),(1,-1,-1)))
# False
tabuleiro(((1,0),(-1,1,0),(1,-1,-1)))
#False
tabuleiro(((1,0, 1),(-1,1,0),(1,-1,-1), (1, 1, 1)))
# False
In python3.10 and above, you can use pattern matching:
def tabuleiro(tab):
match tab:
case (int(),int(),int()),(int(),int(),int()),(int(),int(),int()):
return True
case _:
return False
print(tabuleiro(((1,0,1),(-1,1,0),(1,-1,-1))))
# True
print(tabuleiro(((1,0,1.6),(-1,1,0),(1,-1,-1))))
# False
print(tabuleiro(((1,0),(-1,1,0),(1,-1,-1))))
#False
print(tabuleiro("string is not a tuple"))
# False
The line case _: does not change the value of variable _ (If I use another variable name, the value of this variable whould be the value of tab).
This line and the identation of last line return false are here not necessary, but I keep them for sake of readability.
Related
Create a global variable called myUniqueList. It should be an empty list to start.
Next, create a function that allows you to add things to that list. Anything that's passed to this function should get added to myUniqueList, unless its value already exists in myUniqueList. If the value doesn't exist already, it should be added and the function should return True. If the value does exist, it should not be added, and the function should return False;
extra is if we can make the remaining values to a list called my leftovers
myUniqueList = []
myLeftovers = []
def addUniqueElement(b):
if b not in myUniqueList:
print(myUniqueList.append(b))
return True
else:
myLeftovers.append(newElement)
return False
print(addUniqueElement())
Something to note is that your attempt was very good. It did everything right except for a few things:
You should print out the list if you want to see the final list
eg.
print(myUniqueList)
Next, the function requires an argument, in this case, I'll use "cool"
so now we have
addUniqueElement("cool")
print(myUniqueList)
In the end we get
myUniqueList = []
myLeftovers = []
def addUniqueElement(b):
if b not in myUniqueList:
print(myUniqueList.append(b))
else:
myLeftovers.append(newElement)
addUniqueElement("cool")
print(myUniqueList)
print(myLeftovers)
There's no point in printing when you call myUniqueList.append(b). It just updates the list, it doesn't return anything.
You need to pass an argument when you call the function.
newElement should be b.
def addUniqueElement(b):
if b not in myUniqueList:
myUniqueList.append(b)
return True
else:
myLeftovers.append(b)
return False
print(addUniqueElement(1)) # True
print(addUniqueElement(2)) # True
print(addUniqueElement(1)) # False
print(addUniqueElement(5)) # True
print(addUniqueElement(10))# True
print(addUniqueElement(5)) # False
print(myUniqueList) # [1, 2, 5, 10]
print(myLeftovers) # [1, 5]
here you can continuously add text (ex numbers ) and watch them being added to the one or to the other list
myUniqueList = []
myLeftovers = []
def addUniqueElement(text):
if text not in myUniqueList:
myUniqueList.append(text)
return True
else:
myLeftovers.append(text)
return False
while ( 1 ):
text = input("text: ")
addUniqueElement(text)
print("myUniqueList: ", myUniqueList)
print("myLeftovers: ", myLeftovers)
If I have a function that receives an argument and I want that argument to return True if I put a correct tab but return False if I put anything else, even if the result in one of the elements is one (like 1+1-1 or 1*1), how do I do it?
What can I do to return False if I put on the argument a tab with an element like 1*1 or 1-1. In this case "tab" can have elements equal to 1,-1 and 0 so 1-1 should return False. Here is the function:
#lets consider this for tab. as you can see tab is a tuple with 3 tuples, each with 3 elements
tab = ((1,-1,1),(0,-1,0),(-1,1,1))
tab2 = ((1,-1,1),(1-1,-1,0),(-1,1,1))
def eh_tabuleiro(tab):
if len(tab) != 3:
return False
else:
for row in tab:
if len(row) != 3:
return False
else:
for element in row:
if element not in (-1, 0, 1):
return False
return True
In this case if tab, eh_tabuleiro(tab) returns True (as it should) but eh_tabuleiro(tab2) also returns True and it should be False. What can I do?
Thanks in advance guys!
For a tuple of tuples I want to check that all the inner tuples have the same length.
I've tried comparing indexes but it doesn't work.
p = ((1,1,1),(1,0,1,1),(1,1,1))
def lab(x):
if type(x) != tuple:
return False
else:
z = len(x[0])
for y in x:
if len(y) < 3 and len(y[1:]) != z:
return False
else:
while x[0][0] != 1:
return False
while x[len(x)-1][-1] != 1:
return False
else:
return True
print(lab(p))
Basically, you can see the 2nd tuple has 4 elements and not 3 and i just wanted the function to return false and not True, since the 2nd tuple has a size different than the 1st and it should return false since that happaned.
Im trying to build a maze and its squared and like all squares all the parts have the same size so i need all the tuples to have the same length, the first digit of the 1st tuple has to be 1 and the last digit of the last tuple to be 1 too in order to build this maze.
Ps: I just need the length part the rest is taken care of, but if u have any ideas on how to improve this im all ears.
You can check this with a one-liner:
def lab(tups):
return len(set([len(tup) for tup in tups])) == 1
print(lab(((1,1,1),(1,0,1,1),(1,1,1)))) # False
print(lab(((1,1,1),(1,1,1),(1,1,1)))) # True
... Of course, you probably want to add error checks for empty tuples, etc
If you want to check that all the inner tuples/lists have the same length:
>>> f = lambda l: all([len(t) == len(l[0]) for t in l])
>>> f([(1,1,1),(1,1,1),(1,1,1)])
True
>>> f([(1,1,1),(1,0,1,1),(1,1,1)])
False
>>> f([])
True
This is a function in a greater a program that solves a sudoku puzzle. At this point, I would like the function to return false if there is more then 1 occurrence of a number unless the number is zero. What do am I missing to achieve this?
L is a list of numbers
l =[1,0,0,2,3,0,0,8,0]
def alldifferent1D(l):
for i in range(len(l)):
if l.count(l[i])>1 and l[i] != 0: #does this do it?
return False
return True
Assuming the list is length 9, you can ignore the inefficiency of using count here (Using a helper datastructure - Counter etc probably takes longer than running .count() a few times). You can write the expression to say they are all different more naturally as:
def alldifferent1D(L):
return all(L.count(x) <= 1 for x in L if x != 0)
This also saves calling count() for all the 0's
>>> from collections import counter
>>> def all_different(xs):
... return len(set(Counter(filter(None, xs)).values()) - set([1])) == 0
Tests:
>>> all_different([])
True
>>> all_different([0,0,0])
True
>>> all_different([0,0,1,2,3])
True
>>> all_different([1])
True
>>> all_different([1,2])
True
>>> all_different([0,2,0,1,2,3])
False
>>> all_different([2,2])
False
>>> all_different([1,2,3,2,2,3])
False
So we can break this down into two problems:
Getting rid of the zeros, since we don't care about them.
Checking if there are any duplicate numbers.
Striping the zeros is easy enough:
filter(lambda a: a != 0, x)
And we can check for differences in a set (which has only one of each element) and a list
if len(x) == len(set(x)):
return True
return False
Making these into functions we have:
def remove_zeros(x):
return filter(lambda a: a != 0, x)
def duplicates(x):
if len(x) == len(set(x)):
return True
return False
def alldifferent1D(x):
return duplicates(remove_zeros(x))
One way to avoid searching for every entry in every position is to:
flags = (len(l)+1)*[False];
for cell in l:
if cell>0:
if flags[cell]:
return False
flags[cell] = True
return True
The flags list has a True at index k if the value k has been seen before in the list.
I'm sure you could speed this up with list comprehension and an all() or any() test, but this worked well enough for me.
PS: The first intro didn't survive my edit, but this is from a Sudoku solver I wrote years ago. (Python 2.4 or 2.5 iirc)
In python, I am trying to check if a given list of values is currently sorted in increasing order and if there are adjacent duplicates in the list. If there are, the code should return True. I am not sure why this code does not work. Any ideas? Thanks in advance!!
def main():
values = [1, 4, 9, 16, 25]
print("Return true if list is currently sorted in increasing order: ", increasingorder(values))
print("Return true if list contains two adjacent duplicate elements: ", twoadjacentduplicates(values))
def increasingorder(values):
hlist = values
a = hlist.sort()
if a == hlist:
return True
else:
return False
def twoadjacentduplicates(values):
ilist = values
true = 0
for i in range(1, len(ilist)-1):
if ilist[i] == ilist[i - 1] or ilist[i] == ilist[i + 1] :
true = true + 1
if true == 0:
return False
if true > 0:
return True
main()
Your increasingorder function will almost certainly not work, because Python uses references, and the sort function modifies a list in-place and returns None. That means that after your call a = hlist.sort(), both hlist will be sorted and a will be None. so they will not compare equal.
You probably meant to do the following, which will return a sorted list instead.
a = sorted(hlist)
This function works:
def increasingorder(values):
hlist = values
a = sorted(hlist)
if a == hlist:
return True
else:
return False
You can of course simplify this down to a single line.
def increasingorder(values):
return sorted(values) == values
Your second function looks logically correct, but can be simplified down to the following.
def twoadjacentduplicates(values):
for i in range(0, len(values)-1):
if values[i] == values[i + 1] :
return True
return False
Try creating a True False function for each value check operation you want done taking the list as a parameter. then call each function like "if 1 and 2 print 3" format. That may make thinking through the flow a little easier.
Is this kind of what you were wanting?
def isincreasing(values):
if values==sorted(values):
return True
return False
def has2adjdup(values):
for x in range(len(values)-1):
if values[x]==values[x+1]:
return True
return False
if isincreasing(values) and has2adjdup(values):
print "True"