Home > OS >  How to break a while loop, when duplicate occurs
How to break a while loop, when duplicate occurs

Time:06-29

I want to write a programm in Python/Sage that takes an input 'n' and does the following:

  • if n%2==0 -> n/2 and then adds the result to a list
  • if n%2!=0 -> 3*n 1

The program should stop once a duplicate occurs. Then I want to print out the full list the duplicate.

e.g. for input '2' it should be [2,1,4,2], for '3' [3,10,5,16,8,4,2,1,4]

This was the basis I had made so far:

def f(n):
    my_list=[]  
    while n not in my_list:
        if n%2==0:
            n=n/2
        else:
            n=3*n 1
        my_list.append(n)
    return print(n,'already occured in sequence.'),my_list.append(n),print(my_list)

This however always stops at the first element.

I tried converting the list to a set and then comparing the length, but that did not work out:

def f(n):
    my_list = [n]
    my_set = set(my_list)
    has_duplicate = len(my_list) != len(my_set)
    while n in my_list:
        if n%2==0:
            n=n/2
        else:
            n=3*n 1
        my_list.append(n)
    return has_duplicate, list

I basically am looking for a way to have the while loop run infinitely, but once a duplicate occurs it should return/break.

Any tips would be greatly appreciated.

CodePudding user response:

Your first example is almost there, but the line my_list.append(n) should be at the start of the while loop instead of at the end:

def f(n):
    my_list = []  
    while n not in my_list:
        my_list.append(n)
        if n % 2 == 0:
            n = n / 2
        else:
            n = n * 3   1
    print(n, "has already occurred")
    print(my_list)
    print(n)

CodePudding user response:

Is this what you're looking for?

def f(n):
    my_list=[]  
    while n not in my_list:
        my_list.append(n)
        if n%2==0:
            n=n/2
        else:
            n=3*n 1
    my_list.append(n)
    print(n,'already occured in sequence.')
    return my_list
  • Related