0

Python questions

Write a Python function histogram(l) that takes as input a list of integers with repetitions and returns a list of pairs as follows: for each number n that appears in l, there should be exactly one pair (n,r) in the list returned by the function, where r is is the number of repetitions of n in l. the final list should be sorted in ascending order by r, the number of repetitions. For numbers that occur with the same number of repetitions, arrange the pairs in ascending order of the value of the number.

2nd Mar 2018, 5:46 AM
Leela Karthik Uttarkar
Leela Karthik Uttarkar - avatar
3 Answers
+ 1
def histogram(l): b=[] x=[] f=[] for i in range(len(l)): a=() if l[i] not in x: c=l.count(l[i]) f.append(c) f.sort() a=a+(l[i],c) b.append(a) x.append(l[i]) del a else: continue b=sorted(b,key=lambda f: (f[1],f[0])) return b
3rd Mar 2018, 4:56 PM
Aashutosh Singh
Aashutosh Singh  - avatar
0
For instance: >>> histogram([13,12,11,13,14,13,7,7,13,14,12]) [(11, 1), (7, 2), (12, 2), (14, 2), (13, 4)] >>> histogram([7,12,11,13,7,11,13,14,12]) [(14, 1), (7, 2), (11, 2), (12, 2), (13, 2)] can any one write code for thiss
2nd Mar 2018, 5:46 AM
Leela Karthik Uttarkar
Leela Karthik Uttarkar - avatar
0
any doubt in my code feel free to ask.. n if my code needs any improvements than plz do tell def histogram(l): count = 0 x=[] k=[] for i in range(len(l)): index=i count=0 for j in range(index,len(l)): if l[index] == l[j] and l[index] not in k : count =count + 1 k = k + [l[index]] if (count != 0): x = x + [(l[index], count)] x.sort() x=sorted(x,key=lambda x:x[1]) return x #print(histogram([13,12,11,13,14,13,7,7,13,14,12]))
10th Mar 2018, 7:18 AM
Gaurav
Gaurav - avatar