Skip to content

Instantly share code, notes, and snippets.

@zgrge
Last active September 5, 2016 07:43
Show Gist options
  • Save zgrge/31d850d28e0ca921ef211f15530d7d0d to your computer and use it in GitHub Desktop.
Save zgrge/31d850d28e0ca921ef211f15530d7d0d to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
#Alphabetical substrings problem 3 Problem Set 1 EDX 6.00.1x Introduction to Computer Science and Programming Using Python Python 3.5 August 2016
"""
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc
Note: This problem may be challenging. We encourage you to work smart. If you've spent more than a few hours on this problem, we suggest that you move on to a different part of the course. If you have time, come back to this problem after you've had a break and cleared your head.
"""
import string
import random
randstr = lambda x: ''.join(random.choice(string.ascii_lowercase) for _ in range(x))
def ugly(s):
#also wrong
pos = 0
l = []
ss = []
while pos <= (len(s)-1):
if pos == (len(s)-1):
if len(ss) == 0:
pass
elif s[pos] > ss[-1]:
ss.append(s[pos])
l.append(ss)
break
elif s[pos] <= s[pos+1]:
ss.append(s[pos])
pos += 1
else:
ss.append(s[pos])
pos +=1
l.append(ss)
ss = []
return l
def better(s):
res_list = []
res = []
for x,y in zip (s,s[1:]):
if res == []:
res.append(x)
if x<=y:
res.append(y)
else:
res_list.append(res)
res = []
res_list.append(res)
return res_list
def worse(s):
for x,y in zip(s,s[1:]):
if x<=y:
yield x
else:
yield x+';'
lworse = lambda s: ''.join(worse(s)).split(sep=';')
def mad(s):
res = s[0]
lres = ''
for char in s[1:]:
if char >= res[-1]:
res += char
else:
if len(res) > len(lres):
lres = res
res = char
return max(lres,res,key=len)
##
res = s[0]
lres = ''
for char in s[1:]:
if char >= res[-1]:
res += char
else:
if len(res) > len(lres):
lres = res
res = char
print('Longest substring in alphabetical order is: ', max(lres,res,key=len))
##
def good(s):
res = s[0]
lres = ''
counter=1
lcounter=0
for char in s[1:]:
if char >= res[-1]:
res += char
counter +=1
else:
if counter > lcounter:
lres = res
lcounter = counter
counter = 1
res = char
return max(lres,res,key=len)
oneliner = lambda s: max(''.join(x if x<=y else x+';' for x,y in zip(s,s[1:])).split(sep=';'),key=len)
s = randstr(9999)
ugly(s)
better(s)
worse(s)
print ('Longest substring in alphabetical order is: ', ''.join(max(lworse(s), key=len)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment