Python. <Remove Element> in a list - python-2.7

Title:
172. Remove Element
Description:
Given an array and a value, remove all occurrences of that value in place and return the new length.
The order of elements can be changed, and the elements after the new length don't matter.
My Answer:
On LintCode
def removeElement(self, A, elem):
# write your code here
if A == []:
return A
if elem in A:
sortedA = sorted(A)
li = []
for i in xrange(len(sortedA)):
if sortedA[i] == elem:
li += [i]
newLength = sortedA[:min(li)] + sortedA[max(li)+1:]
return newLength
else:
return A
On my mac
A = [0,4,4,0,0,2,4,4]
elem = 4
def sss(A, elem):
if A == []:
return A
if elem in A:
print A
sortedA = sorted(A)
print sortedA
li = []
for i in xrange(len(sortedA)):
# print type(i)
if sortedA[i] == elem:
li += [i]
print li
newLength = sortedA[:min(li)] + sortedA[max(li)+1:]
print newLength
return newLength
else:
return A
print sss(A, elem)
This answer On my mac work's good, but On LintCode doesn't accept.

Why not use a list comprehension to filter out the unwanted elements?
class Solution:
def removeElement(self, A, elem):
A[:] = [item for item in A if item != elem]
return len(A)
The key here is the slice notation on the left hand side of the assignment. This makes it an "in place" operation, so the original list A is mutated, rather than a copy being made.
Example usage:
>>> l = [1, 2, 3, 4, 4, 5, 4, 10, 11, 4]
>>> len(l)
10
>>> Solution().removeElement(l, 4)
6
>>> l
[1, 2, 3, 5, 10, 11]
>>> len(l)
6

Although this is an old post, yet would like to add the different approaches I tried. Time Complexity is O(n) in all cases.
Method I: Override the elements if they are not val (Logical Approach)
def removeElement(self, nums: List[int], val: int) -> int:
i : int = 0 # This will be an index pointer & will provide the sixe at the end
for j in range(len(nums)):
if nums[j] != val: # if the values are not same
nums[i] = nums[j] # Override the value at location i
i+=1
return i
Method II: Override the val with last array element (Logical Approach)
def removeElement(self, nums: List[int], val: int) -> int:
i: int = 0
n: int = len(nums)
while(i<n):
if(nums[i] == val):
# Replace the element with last array element & reduce the array size by 1
nums[i] = nums[n-1]
n -=1
else:
i +=1
return n
Method III -- Improved form of Method 2 (Python way)
def removeElement(self, nums: List[int], val: int) -> int:
i : int = 0
n : int = len(nums)
while i< n :
print(i, nums, n)
if val in nums[:n]:
i = nums.index(val,0,n)
nums[i] = nums[n-1]
n -=1
else:
break
return n
Method IV -- Python way
def removeElement(self, nums: List[int], val: int) -> int:
nums[:] = [x for x in nums if x !=val]
return len(nums)
All of them have an average runtime of around 36ms and memory utilization around 13.8MB.

Related

List of natural numbers = > returns booleans

Write a function that receives a list of natural numbers as a parameter and returns a list of Booleans. If a number in the list is even, then we will add True to the final list; for odd numbers we add False.
My attempt:
def my_int_list(list):
new_list= []
for num in list:
if num % 2 == 0:
num = True
new_list.append(num)
elif num % 2 != 0:
num = False
new_list.append(num)
my_list=[2,5,8]
print(my_int_list(my_list))
You shouldn't call a variable list as it is a python built-in function, also you forgot to write return.
def my_int_list(listt):
new_list= []
for num in listt:
if num % 2: # If there is 1 in reminder (more Pythonic)
num = False
new_list.append(num)
else: # No need to Check reminder is 0?, because if reminder not 1 it always 0 (when divider is 2)
num = True
new_list.append(num)
return new_list
my_list=[2,5,8]
print(my_int_list(my_list))
here in condition
if num % 2:
return true, only when a reminder is any number other than 0,
In our case, there is only two option 0 or 1.
The simplest solution I can think of is by using map. map(fun, iter) is a function that returns a map object (an iterator) of the results after applying the given function to each item of it.
For example, using:
def my_int_list(lst):
return list(map(even, lst))
def even(n):
return n % 2 == 0
Allows you to return your int list as a boolean one:
print(my_int_list([1,2,3,4,5,6])) # -> [False, True, False, True, False, True]
Alternatively, this will do also
def my_int_list(my_list):
new_list = []
for num in my_list:
if num % 2 == 0:
new_list.append(True)
elif num % 2 != 0:
new_list.append(False)
print(new_list)
my_list = [2, 5, 8]
my_int_list(my_list)

How to check if I can 'make' a specific number from a set of numbers?

Let's say we have a list:
list = [10,10,20,20,20,50,100,200,200]
and a specific number we want to make using numbers from the list:
x = 110
What is the easiest and the fastest way to check if we can 'make' the number we want?
Adding is the only operation allowed !!!
So possible solution to our example could be [10+100] or [20+20+20+50] etc. I don't really need to know all the possible combinations, if we find at least one - return true, if none - return false.
This may not be the fastest process, but I do have a solution.
flag = False
def f(L, x):
global flag
if L == [ ]:
return
if sum(L) == x:
flag = True
return
for i in range(len(L)):
if not flag:
B = L[:i] + L[i+1:]
f(B, x)
L = eval(input('Enter the elements: '))
x = int(input('Enter the required sum: '))
f(L, x)
print(flag)
How about this?
def f(L, x, p):
# x is the target sum. Only consider smaller numbers
L1 = list(filter(lambda val: val <= x, L))
# There's nothing left to try. This path has no answer.
if (len(L1) == 0):
return []
# The next value to try is the largest, at the right-hand side of the list
tryNext = L1[len(L1)-1]
# Jackpot?
if (tryNext == x):
retVal = p[:]
retVal.append(x)
return retVal
# See if we can get to victory using the largest item on the list
# Get the sublist to pass to f (all but the last item)
newL = L1[:len(L1)-1]
newP = p[:]
newP.append(tryNext)
newX = x - tryNext
result = f(newL, newX, newP)
return result
def myResult(L, x):
# Make sure the list is sorted
L.sort()
result = f(L, x, [])
if (len(result) > 0):
print("Got a result: ",result)
else:
print("No answer found")
return len(result) > 0
L0 = [5,5,10,10,20,20,20,50,100,200,200]
x = 110
print(myResult(L0, x))
You are right! Here, with numpy to try it out.
from numpy.random import seed
from numpy.random import randint
def f(L0, x0, L, x, p):
# x is the target sum. Only consider smaller numbers
L1 = list(filter(lambda val: val <= x, L))
# There's nothing left to try. This path has no answer.
if (len(L1) == 0):
if (len(p) == 0):
return []
# Find the next largest number to start with from the original list
L2 = list(filter(lambda val: val < p[0], L0))
if (len(L2) == 0):
return []
return f(L2, x0, L2, x0, [])
# The next value to try is the largest, at the right-hand side of the list
tryNext = L1[len(L1)-1]
# Jackpot?
if (tryNext == x):
retVal = p[:]
retVal.append(x)
return retVal
# See if we can get to victory using the largest item on the list
# Get the sublist to pass to f (all but the last item)
newL = L1[:len(L1)-1]
newP = p[:]
newP.append(tryNext)
newX = x - tryNext
result = f(L0, x0, newL, newX, newP)
return result
def myResult(L, x):
# Make sure the list is sorted
L.sort()
result = f(L, x, L, x, [])
if (len(result) > 0):
print("Got a result: ",result)
else:
print("No answer found")
return len(result) > 0
seed()
values = randint(0, 50000, 10000)
x = randint(1,100000)
print(myResult(values, x))

Print each items of List N times

I'm new to Scala/Functional Programming and want to understand if my below solution fits into the functional programming world. If someone can suggest me a better approach, I will be obliged.
Problem Statement: Print each item of a list, n times
Solution:
import scala.collection.mutable.ListBuffer
object ListReplication extends App {
def printNTimes(items: List[Int], n: Int): ListBuffer[Int] = {
var outputList = new ListBuffer[Int]
def storeNTime(item: Int): Unit = {
for (_ <- 1 to n) outputList += item
}
for (item <- items) storeNTime(item)
outputList
}
val result = printNTimes(items = List(1,2,4), n = 3)
println(result)
}
It is always better to work with immutable types. So I'll change the return type into List[Int]. You can just do:
def printNTimes(items: List[Int], n: Int): List[Int] = {
items.flatMap(i => Vector.fill(n)(i))
}
or:
def printNTimes(items: List[Int], n: Int): List[Int] = {
items.flatMap(Vector.fill(n)(_))
}
Then running:
println(printNTimes(List(1,2,4), 3))
will output:
List(1, 1, 1, 2, 2, 2, 4, 4, 4)

Scala: slice a list from the first non-zero element

Suppose I have a list filled with zeroes
val a = List(0,0,0,0,2,4,0,6,0,7)
I want to slice away the zeroes preceding the first non-zero element and also return the index where the 1st non-zero element is present.
Foe the above case I want an output:
output = List(2,4,0,6,0,7)
idx = 4
How do I do it?
First, you can use zipWithIndex to conveniently pair each element with its index. Then use dropWhile to return all of the preceding zero elements. From there, you'll have all of the remaining elements paired with their indices from the original List. You can unzip them. Since this may result in an empty list, the index you're looking for should be optional.
scala> val (remaining, indices) = a.zipWithIndex.dropWhile { case (a, i) => a == 0 }.unzip
remaining: List[Int] = List(2, 4, 0, 6, 0, 7) // <--- The list you want
indices: List[Int] = List(4, 5, 6, 7, 8, 9)
scala> val index = indices.headOption
index: Option[Int] = Some(4) // <--- the index of the first non-zero element
This is a use-case for span:
val a = List(0,0,0,0,2,4,0,6,0,7)
val (zeros, output) = a.span(_ == 0)
val idx = zeros.length
use dropWhile:
val output = a.dropWhile{ _ == 0 }
val idx = output.headOption
.map(_ => a.length - output.length)
.getOrElse(-1) // index starting from 0, -1 if not found
Sightly modified from #bottaio answer, but returning an Option[Int] instead of a plain Int for the index.
def firstNonZero(l: List[Int]): (Option[Int], List[Int]) = {
#annotation.tailrec
def go(remaining: List[Int], idx: Int): (Int, List[Int]) =
remaining match {
case Nil => idx -> Nil
case 0 :: xs => go(remaining = xs, idx + 1)
case xs => idx -> xs
}
l match {
case 0 :: xs =>
val (idx, list) = go(remaining = xs, idx = 1)
Some(idx) -> list
case list =>
None -> list
}
}
Just another solution using foldLeft:
val (i, l) =
a.foldLeft((None: Option[Int], List.empty: List[Int]))((b, n) => {
if (n == 0 && b._2.isEmpty) (b._1.orElse(Some(0)).map(_ + 1), List.empty)
else (b._1.orElse(Some(0)), b._2 :+ n)
})
i: Option[Int] = Some(4)
l: List[Int] = List(2, 4, 0, 6, 0, 7)
You can do it pretty clean with indexWhere:
val idx = a.indexWhere(_!=0)
val output = a.drop(idx)
Others have provided answers that requires multiple list traversals. You can write a recursive function to calculate that in a single pass:
def firstNonZero(l: List[Int]): (Int, List[Int]) = {
#tailrec
def go(l: List[Int], idx: Int): (Int, List[Int]) = l match {
case Nil => (idx, Nil)
case 0 :: xs => go(xs, idx + 1)
case xs => (idx, xs)
}
go(l, 0)
}
what is also equivalent to
val (leadingZeros, rest) = a.span(_ == 0)
val (index, output) = (leadingZeros.length, rest)

Multiply a list of ints using list comprehension

Is there a way to do this with list comprehension?
for i in range(0, len(x)):
if i == 0:
sum = x[i]
else:
sum = sum * x[i]
I've tried this:
[total for i in x if i == 0 total = x[i] else total = total * x[i]]
and this:
[total = x[i] if i == 0 else total = total * x[i] for i in x]
I saw that there is a way to do it with enumerate but I was wondering if there is a way to do it in one line just using list comprehension. I'm not trying to solve a problem, I'm just curious.
I think what you need is reduce, but not list comprehension.
from operator import mul
s = [1, 2, 3]
print reduce(mul, s, 1)
Or using list comprehension:
class Mul(object):
def __init__(self):
self.product = 1
def __call__(self, x):
self.product *= x
return self.product
s = [1, 2, 3, 4, 5]
m = Mul()
[m(x) for x in s]
I'm gonna prefix this with "you do not want to do this". No really. But if you did...
# whatever your input is
x = [1, 2, 3, 4, 5]
# set the initial total to 1, and wrap it in a list so we can modify it in an expression
total = [1]
# did I mention you shouldn't do this?
[total.__setitem__(0, xi * total.__getitem__(0)) for xi in x]
print total[0]
120