Pythonic idioms / Programming Puzzle
Anton Vredegoor
anton at vredegoor.doge.nl
Sat Jan 19 20:01:15 EST 2002
On 19 Jan 2002 13:51:51 GMT, ameoba <ahmebah at hotmail.com> wrote:
>Looking at these two fundamentally different solutions to the same problem
>got me thinking... Obviously, both of these solutions are correct and
>fully functional, but is one a more Pythonic way of solving the problem, or
>is there an even more Pythonic solution floating arround?
[Based also on parts of the code of the previous posters]
This is the way I would do it:
"""
indexed menuchoice based on a list of a list of possible items
"""
from operator import mul
class MenuChoice:
def __init__(self,menulist):
self.maxindex = reduce(mul,map(len, menulist)) - 1
self.menulist = menulist
def __getitem__(self, index):
res = []
counter = index
if index > self.maxindex:
raise IndexError, "No %ith menu avalable"
else:
for items in self.menulist:
nitems = len(items)
res.append(items[ counter % nitems])
counter /= nitems
res.reverse
return res
def test():
menudata = [["Small","Medium","Large"],
["Mountain Dew", "root beer", "orange juice"],
["\b, a"],
["hamburger", "cheeseburger", "double cheeseburger"],
["\b, and a"],
["small", "medium", "large"],
["fries."]]
menus = MenuChoice(menudata)
for menu in menus:
print " ".join(menu)
if __name__=='__main__':
test()
More information about the Python-list
mailing list