Help me write better Code

sssdevelop sssdevelop at gmail.com
Thu Jul 10 10:39:55 EDT 2014


Mark - thank you so much. You have suggested be new best tool/module. 
It's going to help me many places. Was not aware of such powerful tool. 

thank you,



On Wednesday, July 9, 2014 9:14:01 PM UTC+5:30, Mark Lawrence wrote:
> On 09/07/2014 15:27, sssdevelop wrote:
> 
> > Hello,
> 
> >
> 
> > I have working code - but looking for better/improved code. Better coding practices, better algorithm :)
> 
> >
> 
> > Problem: Given sequence of increasing integers, print blocks of consecutive integers.
> 
> >
> 
> > Example:
> 
> >
> 
> > Input: [10, 11, 12, 15]
> 
> > Output: [10, 11, 12]
> 
> >
> 
> > Input: [51, 53, 55, 67, 68, 91, 92, 93, 94, 99]
> 
> > Outout: [67, 68], [91, 92, 93, 94]
> 
> >
> 
> > My code looks as below:
> 
> > -----------------------------
> 
> > #!/usr/bin/python
> 
> > a = [51, 53, 55, 67, 68, 91, 92, 93, 94, 99]
> 
> > #a = []
> 
> > #a = [10]
> 
> > #a = [10, 11, 12, 15]
> 
> > print "Input: "
> 
> > print  a
> 
> >
> 
> > prev = 0
> 
> > blocks = []
> 
> > tmp = []
> 
> > last = 0
> 
> > for element in a:
> 
> >     if prev == 0:
> 
> >        prev = element
> 
> >        next
> 
> >     if element == prev + 1:
> 
> >         if tmp:
> 
> >             pass
> 
> >         else:
> 
> >             tmp.append(prev)
> 
> >         tmp.append(element)
> 
> >     else:
> 
> >         if tmp:
> 
> >            blocks.append(tmp)
> 
> >         tmp = []
> 
> >
> 
> >     prev = element
> 
> >
> 
> > if tmp:
> 
> >      blocks.append(tmp)
> 
> >
> 
> > if blocks:
> 
> >      #print "I have repeated elements and those are:"
> 
> >      for b in blocks:
> 
> >          print b
> 
> >
> 
> > -----------------------
> 
> >
> 
> > thank you in advance!
> 
> >
> 
> 
> 
> Adopted from here https://docs.python.org/3.0/library/itertools.html
> 
> 
> 
> data = [51, 53, 55, 67, 68, 91, 92, 93, 94, 99]
> 
> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
> 
>      group = list(map(operator.itemgetter(1), g))
> 
>      if len(group) > 1:
> 
>          print(group)
> 
> 
> 
>  >>>
> 
> [67, 68]
> 
> [91, 92, 93, 94]
> 
>  >>>
> 
> 
> 
> -- 
> 
> My fellow Pythonistas, ask not what our language can do for you, ask 
> 
> what you can do for our language.
> 
> 
> 
> Mark Lawrence
> 
> 
> 
> ---
> 
> This email is free from viruses and malware because avast! Antivirus protection is active.
> 
> http://www.avast.com




More information about the Python-list mailing list