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"
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])
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)
I want to creates a function that returns True if a list contains two consecutive 3 and false if not.
when using this code it doesn't work:
def has_33(x):
for i in range(len(x)-1):
if x[i:i+2] == [3,3]:
return True
else:
return False
But with this it works:
def has_33(x):
for i in range(len(x)-1):
if x[i:i+2] == [3,3]:
return True
return False
For me it's the same thing can you explain to me why plz
In the top code you only check the first 2 indices. In the bottom code you're checking the whole array. Here's why:
In the top code you have an else condition, which means that on the first iteration either the if-condition is true (i.e. the first and the second element of the list are 3) or you will go into the else condition. In either case, you're hitting a return statement after checking just the first 2 elements.
In the bottom code, you only return if you find something, or once you've finished the whole loop
I've added some print statements to both your functions. You can run this code and see the output to help you understand what's happening:
def has_33_incorrect(x):
print("\nRunning the incorrect function")
for i in range(len(x)-1):
print("Checking indices {} and {}".format(i, i+1))
if x[i:i+2] == [3,3]:
print("indices contain 2 consecutive 3's. Returning true")
return True
else:
print("indices don't contain 2 consecutive 3's. Returning false")
return False
def has_33_correct(x):
print("\nRunning the correct function")
for i in range(len(x)-1):
print("Checking indices {} and {}".format(i, i+1))
if x[i:i+2] == [3,3]:
print("indices contain 2 consecutive 3's. Returning true")
return True
print("Did not find consecutive 3's. Returning false")
return False
list = [1, 2, 4, 5, 6, 3, 3, 2, 5]
has_33_incorrect(list)
has_33_correct(list)
One more solution with any python builtin:
def has_33(l):
return any(l[i+1] == l[i] == 3 for i in range(len(l) - 1))
This code works since if the if condition is false it doesn't return anything, yet in the first function you showed it returns false and exits the function. You shouldn't return anything until you find that its true somewhere, only after you've iterate over the entire list then and only then should you return False
def has_33(x):
for i in range(len(x)-1):
if x[i:i+2] == [3,3]:
return True
return False
You can iterate over the list directly.
def has_33(x):
current = None
for item in x:
if current == item == 3:
return True
current = item
return False
If you ever find both current and item are equal to 3, you can return True immediately. Otherwise, you will return False when the loop exits naturally.
If you loop through adjacent entries at the same time, you can compare:
def adjacent_threes(x):
for a, b, in zip(x[:-1], x[1:]):
if a == b == 3:
return True
return False
Try this ,it's simple:
def has_33(nums):
for i,num in enumerate(nums):
if nums[i]==3 and nums[i+1]==3:
return True
return False
python code as follows :
def has_33(nums):
my_list = []
y =len(nums)-1
for x in range(0,y) :
if nums[x] == 3 and nums[x+1] == 3:
my_list.append(1)
else :
my_list.append(0)
print(my_list)
if 1 in my_list:
return True
else :
return False
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 code checks whether or not a combination of numbers produces a vampire number but returns an incorrect True if x = 2947051 and y = 8469153.
def vampire_test(x, y):
vamp = (list(str(x) + str(y)))
prod = x*y
vamp_check = list(str(prod))
print vamp, vamp_check
if '-' in vamp and '-' not in vamp_check:
return False
else:
check = cmp(vamp.sort(),vamp_check.sort())
if check == 0 and len(vamp) == len(vamp_check):
return True
else:
return False
What's the issue and how can I improve the code I've already written?
There is a logic problem. This line:
check = cmp(vamp.sort(),vamp_check.sort())
Will do check = 0 every time, because the .sort() method of list sorts in place and returns None.