I can't figure out this sequence - 11110000111000110010

Jake McBride

NOTE: This is for a homework assignment, but the portion I have a question on is ok to ask help for.

I have to script out a sequence 11110000111000110010 (i am using python) without using switches or if statements and only a maximum of 5 for and whiles.

I already have my script laid out to iterate, I just can't figure out the algorithm as recursive or explicit let alone whether the element's are 1's 2's or 4's =/

As much as we have learned so far there is no equation or algorithm to use to figure OUT the algorithm for sequence. Just a set of instructions for defining one once we figure it out. Does anyone see a pattern here I am missing?

EDIT: What I am looking for is the algorithm to determine the sequence. IE the sequence 1,3,6,10,15 would come out to be a[n]=(a[n-1]+n) where n is the index of the sequence. This would be a recursive sequence because it relies on a previous element's value or index. In this case a[n-1] refers to the previous index's value. Another sequence would be 2, 4, 6, 8 would come out to be a[n] = (n*2) which is an explicit sequence because you only require the current index or value.

EDIT: Figured it out thanks to all the helpful people that replied.... I can't believe I didn't see it =/

Aditya

There are many possible solutions to this problem. Here's a reusable solution that simply decrements from 4 to 1 and adds the expected number of 1's and 0's.

Loops used : 1

def sequence(n):
    string = ""
    for i in range(n):
        string+='1'*(n-i)
        string+='0'*(n-i)
    return string

print sequence(4)

There's another single-line elegant and more pythonic way to do this:

print ''.join(['1'*x+'0'*x for x in range(4,0,-1)]) 

Loops used : 1, Lines of code : 1

;)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related