2017-04-25 85 views
0

大小为N的整数arr定义为{a,a,...。 。 。 , 一个 }。它必须将arr作为参数,按升序的顺序对其元素进行排序,然后将排序数组的每个元素打印为新的输出行。如果2个或更多的元素具有相同的频率,则这个元素的子集应该按照非递减顺序排序。自定义排序数组

Sample Input 0 53124 
Sample Output 0 1342 

我试图解决在Java和Python这个问题,因为我的学习锻炼,我得到了在Java中这方面的工作,但不知道我应该怎么处理它在Python。

public class CustomSort { 
    public static void main(String[] args) { 
     int[] arr = { 5, 3, 1, 2, 2, 2, 2, 2, 2, 2, 6, 6, 6, 6, 6, 5, 4 }; 
     customSort(arr); 
    } 

    static void customSort(int[] arr) { 
     Map<Integer, Integer> map = new HashMap<>(); 
     List<Integer> numbers = new ArrayList<>(); 

     for (int i : arr) { 
      if(map.containsKey(i)) { 
       map.put(i, map.get(i) + 1); 
      } else { 
       map.put(i, 1); 
      } 


      if (!numbers.contains(i)) { 
       numbers.add(i); 
      } 
     } 

     Collections.sort(numbers); 

     List<Integer> returning = new ArrayList<>(numbers); 
     int count = 1; 
     while(!returning.isEmpty()) { 
      returning = print(returning, map, count); 
      count++; 
     } 

    } 

    static List<Integer> print(List<Integer> numbers, Map<Integer, Integer> map, int howManyItens) { 
     List<Integer> returning = new ArrayList<>(); 

     for (Integer integer : numbers) { 
      if(map.get(integer) == howManyItens) { 
       for (int i = 1; i <= howManyItens; i++) { 
        System.out.println(integer); 
       } 
      } else { 
       returning.add(integer); 
      } 
     } 

     return returning; 
    } 
} 

我应该如何在Python中做到这一点?

def customSort(arr): 
    # what should I do here? 
+3

什么是翻译部分你havi有什么麻烦? –

+0

根据你提出这个问题的方式和你对现有答案的评论来看,你需要从一个基本的Python教程开始,而SO不适合做这个。 –

+0

*#我应该在这里做什么?*,可能写一些代码。在尝试提出更多问题之前,请阅读[我如何提出一个好问题?](http://stackoverflow.com/help/how-to-ask)。 –

回答

1

你可以这样做:

>>> li=[ 5, 3, 1, 2, 2, 2, 2, 2, 2, 2, 6, 6, 6, 6, 6, 5, 4 ] 
>>> sorted(li, key=lambda i: li.count(i)) 
[3, 1, 4, 5, 5, 6, 6, 6, 6, 6, 2, 2, 2, 2, 2, 2, 2] 

或者,你可以这样做:

def c_sort(li): 
    cnt={i:li.count(i) for i in set(li)} 
    return sorted(li, key=lambda e: cnt[e]) 

>>> c_sort(li) 
[3, 1, 4, 5, 5, 6, 6, 6, 6, 6, 2, 2, 2, 2, 2, 2, 2] 

如果您想对每个元素的值的辅助排序关键字,形成一个元组:

def c_sort(li): 
    cnt={i:li.count(i) for i in set(li)} 
    return sorted(li, key=lambda e: (cnt[e], e)) 

>>> c_sort(li) 
[1, 3, 4, 5, 5, 6, 6, 6, 6, 6, 2, 2, 2, 2, 2, 2, 2] 
+0

我可以在我的customSort函数中使用它,而不是在交互模式下运行它吗?我想运行.py文件。 – john

+1

是的,你可以在.py文件中使用它。祝你好运! – dawg

+0

我可以问 - 为什么要投票? – dawg