user3495872
user3495872

Reputation: 111

Sorted values in increasing order and adjacent values

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()

Upvotes: 0

Views: 270

Answers (2)

merlin2011
merlin2011

Reputation: 75579

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

Upvotes: 1

Amazingred
Amazingred

Reputation: 1007

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"

Upvotes: 0

Related Questions