Partition Array

2024/10/11 6:31:21

Given an array nums of integers and an int k, partition the array (i.e move the elements in nums) such that: All elements < k are moved to the left. All elements >= k are moved to the right Return the partitioning index, i.e the first index i nums[i] >= k.

class Solution:def partitionArray(self, nums, k):# write your code hereif nums == []:return 0left = 0i = 0while i <= len(nums):if nums[i] < k:i += 1left += 1else:r = nums[i]del nums[i]nums.append(r)i += 1return left

My idea is to going through the list one by one. The num[i] whose larger than k will be removed and append at the end of the num, the one whose smaller than k will be kept at the original place. Once the whole list has been going through, all the smaller num are at the front. left is a counter at this point for return. But I cannot fix the problem with nums[i]. After the each mods to the list, the counter i cannot point at the correct item in the list.

How can I write the code base on this idea???

Answer

You're looking for the index(k). This seems like a homework assignment so you may be limited to what built in functionality you can use. However, a pythonic approach to this is

def solution(nums, k):return sorted(nums).index(k)

You are doing several things I would recommend avoiding.

  1. Concurrent modification; you should not add or delete from a list while looping it.
  2. You can not loop up to i == len(nums) because list indexes start at 0.

Since you are really just looking for index(k) you need only keep track of numbers less than k and not concern yourself with re-organizing the list.

class Solution:def partitionArray(self,nums, k):# write your code hereif nums == []:return 0left = 0i = 0while i < len(nums):if nums[i] < k:left += 1i += 1return left
https://en.xdnf.cn/q/118353.html

Related Q&A

Tensorflow model accuracy

My model which I have trained on a set of 29K images for 36 classes and validated on 7K images. The model has a training accuracy of 94.59% and validation accuracy of 95.72% It has been created for OCR…

python email.message_from_string() parse problems

My setup uses fetchmail to pull emails from Gmail, which are processed by procmail and passes it to a python script.When I use email.message_from_string(), the resulting object is not parsed as an emai…

Python: Function returning highest value in list without max()? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 7…

Given edges, how can find routes that consists of two edges in a vectorised way?

I have an array of towns and their neighbours. I want to get a set all the pairs of towns that have at least one route that consists of exactly two different edges. Is there a vectorized way to do this…

Usefulness of one-line statements in Python [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…

Pack data into binary string in Python [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Parsing Complex Mathematical Functions in Python

Is there a way in Python to parse a mathematical expression in Python that describes a 3D graph? Using other math modules or not. I couldnt seem to find a way for it to handle two inputs.An example of…

How do I check if the user has entered a number? [duplicate]

This question already has answers here:How can I read inputs as numbers?(10 answers)Closed last year.I making a quiz program using Python 3. Im trying to implement checks so that if the user enters a …

high F1 score and low values in confusion matrix

consider I have 2 classes of data and I am using sklearn for classification, def cv_classif_wrapper(classifier, X, y, n_splits=5, random_state=42, verbose=0):cross validation wrappercv = StratifiedKFol…

Replace `\n` in html page with space in python LXML

I have an unclear xml and process it with python lxml module. I want replace all \n in content with space before any processing, how can I do this work for text of all elements.edit my xml example:<…