user2560609
user2560609

Reputation: 79

Python Function returns wrong value

periodsList = [] 
su = '0:'
Su = []
sun = []
SUN = ''

I'm formating timetables by converting

extendedPeriods = ['0: 1200 - 1500',
    '0: 1800 - 2330',
    '2: 1200 - 1500',
    '2: 1800 - 2330',
    '3: 1200 - 1500',
    '3: 1800 - 2330',
    '4: 1200 - 1500',
    '4: 1800 - 2330',
    '5: 1200 - 1500',
    '5: 1800 - 2330',
    '6: 1200 - 1500',
    '6: 1800 - 2330']

into '1200 - 1500/1800 - 2330'

Then I tried to write a function to apply my "converter" also to the other days..

def formatPeriods(id, store1, store2, periodsDay): 
  for line in extendedPeriods:
    if id in line:    
      store1.append(line)

  for item in store1:
    store2.append(item.replace(id, '', 1).strip())

  periodsDay = '/'.join([str(x) for x in store2])  
  return periodsDay     

But the function returns 12 misformatted strings...

'1200 - 1500', '1200 - 1500/1200 - 1500/1800 - 2330',

Upvotes: 1

Views: 805

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

You can use collections.OrderedDict here, if order doesn't matter then use collections.defaultdict

>>> from collections import OrderedDict
>>> dic = OrderedDict()
for item in extendedPeriods:
    k,v = item.split(': ')
    dic.setdefault(k,[]).append(v)
...     
>>> for k,v in dic.iteritems():
...     print "/".join(v)
...     
1200 - 1500/1800 - 2330
1200 - 1500/1800 - 2330
1200 - 1500/1800 - 2330
1200 - 1500/1800 - 2330
1200 - 1500/1800 - 2330
1200 - 1500/1800 - 2330

To access a particular day you can use:

>>> print "/".join(dic['0'])   #sunday
1200 - 1500/1800 - 2330
>>> print "/".join(dic['2'])   #tuesday
1200 - 1500/1800 - 2330

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174614

This is your general logic:

from collections import defaultdict

d = defaultdict(list)

for i in extended_periods:
    bits = i.split(':')
    d[i[0].strip()].append(i[1].strip())

for i,v in d.iteritems():
   print i,'/'.join(v)

The output is:

0 1200 - 1500/1800 - 2330
3 1200 - 1500/1800 - 2330
2 1200 - 1500/1800 - 2330
5 1200 - 1500/1800 - 2330
4 1200 - 1500/1800 - 2330
6 1200 - 1500/1800 - 2330

To make it function for a day, simply select d[0] (for Sunday, for example):

def schedule_per_day(day):

    d = defaultdict(list)

    for i in extended_periods:
        bits = i.split(':')
        d[i[0].strip()].append(i[1].strip())

    return '/'.join(d[day]) if d.get(day) else None

Upvotes: 1

Related Questions