Skip to content

Instantly share code, notes, and snippets.

@derekmhewitt
Created August 19, 2016 16:39
Show Gist options
  • Save derekmhewitt/47b5dff3bc5debc1566cc607f0adb4c2 to your computer and use it in GitHub Desktop.
Save derekmhewitt/47b5dff3bc5debc1566cc607f0adb4c2 to your computer and use it in GitHub Desktop.
Python 401 Weekly Challenge #2
sample_string = "I am a very long string with some extra words that are silly."
def smart_substr(string, terminate="..."):
if len(string) < 30:
return string
else:
list_of_words = sample_string.split()
output = ""
while len(output) < 30:
if (len(list_of_words[0]) + len(output)) < 30:
output.join(list_of_words[:1]) # this is not working
list_of_words.pop(0)
print(len(output))
print("joined word")
else:
output.join(terminate)
print("I'm in a loop")
break
return output
# got help from:
# http://stackoverflow.com/questions/6905636/python-conditional-list-joins
# https://docs.python.org/2/library/string.html#string.join
# http://stackoverflow.com/questions/4426663/how-do-i-remove-the-first-item-from-a-python-list
@cewing
Copy link

cewing commented Aug 23, 2016

a few things that could be improved here. First, remember that join is called on the string you want to use to join the list of strings you pass as the argument. So " ".join([[output] + list_of_words[0]) would work where your line 12 does not. Second, remember that you can iterate directly through a list of words, so rather than having to use the list.pop(0) method to shorten the list, you can just grab your words one at a time and use them directly. Your approach here is sound, but your execution is problematic. It's mostly due to familiarity with your tools. This will improve (and it has improved already).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment