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
Related
How to write python code that let the computer know if the list is a right sequence and the position doesn't matter, it will return true, otherwise it return false.
below are some of my example, I really don't know how to start
b=[1,2,3,4,5] #return true
b=[1,2,2,1,3] # return false
b=[2,3,1,5,4] #return true
b=[2,4,6,4,3] # return false
sort function is O(nlogn), we can use for loop which is O(n):
def check_seq(in_list):
now_ele = set()
min_ele = max_ele = in_list[0]
for i in in_list:
if i in now_ele:
return False
min_ele = min(i, min_ele)
max_ele = max(i, max_ele)
now_ele.add(i)
if max_ele-min_ele+1 == len(in_list):
return True
return False
Create a set and one to compare with -- based on minimum and maximum:
isRightSequence = set(range(min(b), max(b)+1)) == set(b)
This question is quite simple and can be solved a few ways.
The conditional approach - if there is a number that is bigger than the length of the list, it automatically cannot be a sequence because there can only be numbers from 1-n where n is the size of the list. Also, you have to check if there are any duplicates in the list as this cannot be possible either. If none of these conditions occur, it should return true
Using dictionary - go through the entire list and add it as a key to a dictionary. Afterwards, simply loop through numbers 1-n where n is the length of the list and check if they are keys in the dictionary, if one of them isn't, return false. If all of them are, return true.
Both of these are quite simply approaches and you should be able to implement them yourselves. However, this is one implementation for both.
1.
def solve(list1):
seen = {}
for i in list1:
if i > len(list1):
return False
if i in seen:
return False
seen[i] = True
return False
def solve(list1):
seen = {}
for i in list1:
seen[i] = True
for i in range (1, len(list1)+1):
if i not in seen:
return False
return True
This solution needs O(n) runtime and O(n) space
def is_consecutive(l: list[int]):
if not l:
return False
low = min(l)
high = max(l)
# Bounds Check
if high - low != len(l) - 1:
return False
# Test all indices exist
test_vec = [False] * len(l) # O(n)
for i in range(len(l)):
test_vec[l[i] - low] = True
return all(test_vec)
assert is_consecutive(range(10))
assert is_consecutive([-1, 1,0])
assert not is_consecutive([1,1])
assert not is_consecutive([1,2,4,6,5])
I want to loop over each element and check if its type is int and if it lays within range of 12 <= i <= 20
if so return True
I use any to return if all elements are correct and isinstance to catch the type of each element.
The function gives me no output and no bug report so I don't know where the error is.
listoflist = [[14,13,13,14]]
def list_check(my_list):
if all(isinstance(i, int) and 12 <= i <= 20 for i in my_list):
print("true")
return True
Problem is that you use nested list. Also you do not get any output whatsoever because you are not calling the function.Following code prints True on console
my_list = [14,13,13,14]
def list_check(my_list):
if all(isinstance(i, int) and 12 <= i <= 20 for i in my_list):
print("true")
return True
list_check(my_list)
This is because you're looping through a one element list, so basically the for i in my_list only has one resulting item: [14,13,13,14]
You will need to select list[0] to iterate through the inner elements. There are also more elegant solutions than using for loops to apply such simple operations on lists, for instance map() and lambda:
listoflist = [[14,13,13,14]]
def list_check(mylist):
f = lambda x: isinstance(x, int) and 12 <= x <= 20
return all(map(f, mylist[0]))
list_check(listoflist)
Out[55]: True
lambda creates a "callable" function, and map applies this function to all elements of an iterable (e.g., list).
The problem in your case because you have list in list:
listoflist = [14,13,13,14]
def list_check(my_list):
if all(isinstance(i, int) and 12 <= i <= 20 for i in my_list):
print("true")
return True
print(list_check(listoflist))
Try this
def list_check(my_list_of_lists):
for my_list in my_list_of_lists:
if all([isinstance(i, int) and 12 <= i <= 20 for i in my_list]):
print("true")
return True
Its not clear that you want it always to use list of lists as you post in your example. Or if you want the output to be true if all the lists are true. This will output true as many times as there are lists that fulfill the condition.
I have an assignment where it ask to make a function where it goes through given sets of tuples to see if it has a cycle effect like in a game of dominos. For example given pairs [(2,3),(3,4),(4,5)], it would return True otherwise if the pairs were inputted like this [(2,3),(5,4)] it would return False. Essentially if the x value of the tuple pair after the first pair isn't the same as the y value of the first pair, it would return False.
Here's what I have so far but it only just checks the first pair of tuples to see if both the values match eachother.
def domino_cycle(tiles):
for (x,y) in tiles:
if y == x:
return True
else:
return False
domino_cycle()
Below
tiles1 = [(2,3),(3,4),(4,5)]
tiles2 = [(2,3),(3,24),(4,5)]
def is_domino_cycle(tiles):
for idx,tile in enumerate(tiles):
if idx > 0:
if tile[0] == tiles[idx-1][1]:
continue
else:
return False
return True
print(is_domino_cycle(tiles1))
print(is_domino_cycle(tiles2))
output
True
False
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"