Use List comprehension instead of loop in python - python-2.7

def interval(a,b,n):
dx = float(b-a)/(n+1)
cnt = 1
points = [a]
xj = a
while cnt <= n+1:
xj += dx
points.append(xj)
cnt+=1
return points

Replace your function as given below :-
def interval(a,b,n):
dx = float(b-a)/(n+1)
points = [a]
xj = a
points.extend([xj + (i * dx) for i in xrange(1, n+2)])
return points

Related

hello, given a list L, I want to split the list into sublists with sum of elements 10 when possible and when not to sublists with sum < 10

for example having L=[7,8,3,2,5,4,1,5,5,8,8], a possible split is [7,3], [8,2], [5,5] [5,4,1] and [8], [8] since there is no possibilities to have sublists of sum 10 anymore
def divide_list(lst):
sublists = []
current_sublist = []
current_sum = 0
def add_to_sublist(num):
nonlocal current_sublist, current_sum
current_sublist.append(num)
current_sum += num
if current_sum >= 10:
sublists.append(current_sublist)
current_sublist = []
current_sum = 0
for num in lst:
if current_sum + num <= 10:
add_to_sublist(num)
else:
remaining_sum = 10 - current_sum
add_to_sublist(remaining_sum)
divide_list([num] + lst[lst.index(num)+1:])
break
if current_sublist:
sublists.append(current_sublist)
remaining = lst[lst.index(sublists[-1][-1])+1:] if sublists else lst
while remaining:
current_sublist = [remaining.pop(0)]
current_sum = current_sublist[0]
while current_sum < 10 and remaining:
num = remaining.pop(0)
current_sublist.append(num)
current_sum += num
sublists.append(current_sublist)
###
return sublists
lst = [6,4,5,5,7,3,9,1,8,2,7,4,5]
sublists = divide_list(lst)
print(sublists)
this is an example where after there is no longer a sublist with a sum of 10 i got [7, 4], [5]

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))

SML: why the return type is unit?

So I have wrote a function (I will describe it briefly to avoid confusion)
fun function1 (l, a1,a2, suma, b2, sumb, d) =
while(a1<a2 andalso k>d) do
let
val k = Real.fromInt(a2-a1)
val suma = suma - Real.fromInt(List.nth(l, a1))
val sumb = sumb - Real.fromInt(List.nth(l, b2))
val a1 = a1+1
val b2 = b2-1
in
if suma<0.0 andalso ( (~sumf)/(N*k) )>1.0 andalso k>d
then k
else if sumb<0.0 andalso ((~sumb)/(N*k))>1.0 andalso k>d
then k
else d
end;
The system says this:
val function1 = fn : int list * int * int * real * int * real * real -> unit
I don't get the return type. I want to return a real like d & k . Why it's unit??

increasing sum of the elements of a list

How to compute the sum of each element of a list multiplied by it's index position in OCaml? example: for [4;7;9] the result is 45 (4x1 + 7x2 + 9x3 = 45). the only authorized functions are List.hd, List.tl et List.length.
I can do it in the other direction with this code:
let rec sum l =
let n = (List.length l) + 1 in
if l = [] then 0 else
((List.hd l)*(n-1))+ (sum(List.tl l)) ;;
sum [4;7;9];;
- : int = 35 (4x3 + 7x2 + 9x1 = 35)
But the expected result is 45 (4x1 + 7x2 + 9x3 = 45).
thank you for your help.
Personally, I'd probably do something like this..
let rec new_sum l n =
match l with
| [] -> 0
| head::tail -> (head * n) + new_sum tail (n+1)
let sum l =
new_sum l 1;;
sum [4;7;9]
...if you don't like the guards for pattern matching, and prefer List.hd, List.tl, List.length then you could use...
let rec new_sum l n =
if (List.length l == 0) then 0
else ((List.hd l) * n) + new_sum (List.tl l) (n+1)
let sum l =
new_sum l 1;;
sum [4;7;9];

Implementing binary search but can't find an element

I have a code in sml of binary search , the thing is when I search 20, output shows there is no element in an array even though array has 20.
I can't figure out why is this happening.
open Array;
fun binsearch (A, x) =
let val n = length A;
val lo = ref 0 and hi = ref n;
val mid = ref ((!lo + !hi) div 2);
in
while ((!hi - !lo > 1) andalso (x <> sub (A, !mid))) do
(
if x < sub (A, !mid) then hi := !mid - 1
else lo := !mid + 1;
mid := (!lo + !hi) div 2
);
if x = sub (A, !mid) then SOME (!mid)
else NONE
end;
open Array;
val A = fromList [~24, ~24, ~12, ~12, 0, 0, 1, 20, 45, 123];
binsearch (A, 20);
binsearch (A, ~24);
binsearch (A, 123);
Code can't search number 20.
The reason for this error is an off-by-one mistake in (!hi - !lo > 1) which should be either (!hi - !lo > 0) or (!hi - !lo >= 1).
ML is, however, intended to be a functional language. A more functional approach (i.e. without references and while loops) might look like this:
fun binsearch arr x =
let
val l = Array.length arr
fun subsearch arr x lo hi =
if lo > hi then NONE
else
let
val mid = (lo + hi) div 2
val v = Array.sub (arr, mid)
in
if x < v then subsearch arr x lo (mid-1)
else if x > v then subsearch arr x (mid+1) hi
else SOME mid
end
in
subsearch arr x 0 (l-1)
end;