[Tutor] adding users to tweets on a list

Saad Javed sbjaved at gmail.com
Tue Aug 6 19:31:45 CEST 2013


> Ah, I see. Sorry, I misread your requirements. Something like this should
> work.
>
>     #!/usr/bin/env python
>
>     MAX_LENGTH = 140
>
>
>     class TweetTooLongError(Exception):
>         """
>         Raised when a user would be too long to add to the tweet, even
> alone.
>         """
>         pass
>
>
>     def generate_tweets(message, users):
>         """
>         Generate tweets based around a message, with users
>         appended to each tweet.
>
>         :param message: the base message
>         :param users: a group of users to append
>         :returns: tweets based around the message to the users
>         """
>
>         add = ""
>         longest_in_list = " @" + max(users, key=len)
>
>         if len(longest_in_list) + len(message) > MAX_LENGTH:
>             raise TweetTooLongError(
>                 "At least one user would make the tweet too long."
>             )
>
>         while users:
>             new_message = message
>             while len(new_message) + len(add) <= MAX_LENGTH:
>                 new_message += add
>                 if not users:
>                     break
>                 add = " @" + users.pop(0)
>             yield new_message
>
>
>     if __name__ == "__main__":
>         users = [
>             "saad", "asad", "sherry", "danny", "ali", "hasan", "adil",
>             "yousaf", "maria", "bilal", "owais",
>         ]
>         message = raw_input("Enter string: ")
>         print("\n".join(generate_tweets(message, users)))
>

Thank you for your response. This code has a bug.

If there is one user left in the user list, it doesn't print a tweet with
just that one user added. For example use this string: "These are my
friends living in the same city as i am. I have known them for years. They
are good people in general. They are:"...you will see that "owais" is still
in the list and is not added to a new tweet and printed.

Saad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130806/e8f155cd/attachment.html>


More information about the Tutor mailing list