Created
November 6, 2012 08:00
-
-
Save Andati/4023344 to your computer and use it in GitHub Desktop.
Solution to beads problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Beads problem. Written by Andati Rodgers on 6th Nov, 2012 | |
| Used aspects of dynamic programming | |
| """ | |
| def length(s): #determine possible max length of b's followed by r's given a string | |
| s2 =s | |
| b=r=pr=mx=index=i=j=0 | |
| same = True | |
| for k in range(0,len(s)-1): | |
| if s2[k] != s2[k+1]: | |
| same = False | |
| break | |
| if same == True: | |
| return len(s2),0 | |
| while j<len(s2)*2: | |
| if i==len(s2): | |
| i=0 | |
| if s2[i] == 'b': | |
| if s2[i-1]=='r': | |
| if mx < b+r: | |
| mx = b+r; index = i-r | |
| b=0; pr=r; r=0 | |
| b+=1 | |
| elif s2[i] == 'r': | |
| if s2[i-1]=='b': | |
| if mx < b+pr: | |
| mx = b+pr; index = i-b | |
| r+=1 | |
| i+=1; j+=1 | |
| if index<0: | |
| index = len(s2)+index | |
| return mx,index | |
| def dynamic(s,i): # dynamically look for all possible combinations of letter 'w' - if assigned r or b | |
| if i>=len(s): | |
| global mx,index | |
| num2,index2 = length(s) | |
| if num2 > mx: | |
| mx = num2; index = index2 | |
| return | |
| ss = list(s) | |
| if ss[i]=='w': | |
| ss[i]='r' | |
| dynamic("".join(ss),i+1) | |
| ss[i]='b' | |
| dynamic("".join(ss),i+1) | |
| else: | |
| dynamic("".join(ss),i+1) | |
| if __name__=="__main__": | |
| #ss = "wwwbbrwrbrbrrbrbrwrwwrbwrwrrb" | |
| ss = "bbb" | |
| mx = index= 0 | |
| dynamic(ss,0) | |
| print "Length",mx, "Index", index |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment