How to skip some condition when using python' for loop


  • 0
    L

    Hi, all.

    I am trying to use python to re-write my algorithm exercise and I found out that the python's for loop is really inconvenient to use.

    For example, for this question I used to write the following cpp solution
    class Solution

    class Solution{
    public:
    	vector<vector<int>> res;
    	vector<vector<int>> subsetsWithDup(vector<int> &s){
    		if (s.empty()){
    			return res;
    		}
    		sort(S.begin(), S.end());
    		res.push_back(vector<int>());
    		vector<int> v;
    		generate(0, v, s);
    		return res;
    	}
    	void generate(int start, vector<int>& v, vector<int>& s){
    		if (start == S.size()){
    			return;
    		}
    		for (int i = start; i < S.size(); i ++){
    			v.push_back(S[i]);
    			res.push_back(v);
    			generate(i+1, v, S);
    			v.pop_back();
    			while (i , S.size() -1 && S[i] == S[i+1]){
    				i ++;
    			}
    		}
    	}
    };
    

    I use the while loop to skip some case to avoid the duplication in my result. However I don't know how to implement it in python. Any help would be appreciated.

    Thanks,


  • 1
    B

    How about soemthing like this?

    for i in range(start, len(S)):
       if i > start and S[i] == S[i-1]:
             continue    
        # recurse...
    

    The idea is move the while loop in your c++ solution to the top and use contiue instead


  • 0
    L

    Great! Thank you!!!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.