this python program guess a random number, how to calculate the average numberguesses? - pp-python-parallel

import random
i went to add another function to calculate the number guesses
def guess(x):
randomNumb = random.randint(1, x)
guess = 0
while guess != randomNumb :
guess = int(input(f'entre number between 1 and {x} : '))
print(guess)
if guess < randomNumb :
print('guess is low')
elif guess > randomNumb :
print('guess is high')
print(f'guess is right {randomNumb}')
guess(100)

Related

SSP Algorithm minimal subset of length k

Suppose S is a set with t elements modulo n. There are indeed, 2^t subsets of any length. Illustrate a PARI/GP program which finds the smallest subset U (in terms of length) of distinct elements such that the sum of all elements in U is 0 modulo n. It is easy to write a program which searches via brute force, but brute force is infeasible as t and n get larger, so would appreciate help writing a program which doesn't use brute force to solve this instance of the subset sum problem.
Dynamic Approach:
def isSubsetSum(st, n, sm) :
# The value of subset[i][j] will be
# true if there is a subset of
# set[0..j-1] with sum equal to i
subset=[[True] * (sm+1)] * (n+1)
# If sum is 0, then answer is true
for i in range(0, n+1) :
subset[i][0] = True
# If sum is not 0 and set is empty,
# then answer is false
for i in range(1, sm + 1) :
subset[0][i] = False
# Fill the subset table in botton
# up manner
for i in range(1, n+1) :
for j in range(1, sm+1) :
if(j < st[i-1]) :
subset[i][j] = subset[i-1][j]
if (j >= st[i-1]) :
subset[i][j] = subset[i-1][j] or subset[i - 1][j-st[i-1]]
"""uncomment this code to print table
for i in range(0,n+1) :
for j in range(0,sm+1) :
print(subset[i][j],end="")
print(" ")"""
return subset[n][sm];
I got this code from here I don't know weather it seems to work.
function getSummingItems(a,t){
return a.reduce((h,n) => Object.keys(h)
.reduceRight((m,k) => +k+n <= t ? (m[+k+n] = m[+k+n] ? m[+k+n].concat(m[k].map(sa => sa.concat(n)))
: m[k].map(sa => sa.concat(n)),m)
: m, h), {0:[[]]})[t];
}
var arr = Array(20).fill().map((_,i) => i+1), // [1,2,..,20]
tgt = 42,
res = [];
console.time("test");
res = getSummingItems(arr,tgt);
console.timeEnd("test");
console.log("found",res.length,"subsequences summing to",tgt);
console.log(JSON.stringify(res));

Functional version of a typical nested while loop

I hope this question may please functional programming lovers. Could I ask for a way to translate the following fragment of code to a pure functional implementation in Scala with good balance between readability and execution speed?
Description: for each elements in a sequence, produce a sub-sequence contains the elements that comes after the current elements (including itself) with a distance smaller than a given threshold. Once the threshold is crossed, it is not necessary to process the remaining elements
def getGroupsOfElements(input : Seq[Element]) : Seq[Seq[Element]] = {
val maxDistance = 10 // put any number you may
var outerSequence = Seq.empty[Seq[Element]]
for (index <- 0 until input.length) {
var anotherIndex = index + 1
var distance = input(index) - input(anotherIndex) // let assume a separate function for computing the distance
var innerSequence = Seq(input(index))
while (distance < maxDistance && anotherIndex < (input.length - 1)) {
innerSequence = innerSequence ++ Seq(input(anotherIndex))
anotherIndex = anotherIndex + 1
distance = input(index) - input(anotherIndex)
}
outerSequence = outerSequence ++ Seq(innerSequence)
}
outerSequence
}
You know, this would be a ton easier if you added a description of what you're trying to accomplish along with the code.
Anyway, here's something that might get close to what you want.
def getGroupsOfElements(input: Seq[Element]): Seq[Seq[Element]] =
input.tails.map(x => x.takeWhile(y => distance(x.head,y) < maxDistance)).toSeq

Creating a for-loop that stores values in a new variable

I'm quite new to Matlab so excuse me for the basic question.
I need to make a for-loop that repeats it's self 384 times.
So :
for i=1:384
I now need the for loop to check if 2 certain variables have the value 1 through 10, and then let them store this in a new variable with that value.
So:
if x==1
somevariable = 1
elseif x== 2
saomevariable = 2
..
..
..
elseif y = 1
someothervariable = 1
etc etc.
Is there a way to write this more efficient?
Thank you!
The first think you can do is:
if(x >= 1 && x <= 10)
somevariable=x;
end
if(y >= 1 && y <= 10)
someohtervariable=y;
end
If you could post more information about "x" and "y", perhaps your script can be further "improved".
Hope this helps.

How to sort fancytree nodes with folders at the top

I've reviewed the docs and examples for fancytree for hours soaking up all of fancytree's goodness like a sponge but I can't seem to figure how to sort my fancytree object with folders first by using the API calls. I've initially got around the problem by arranging my initial JSON data so that it's already sorted with folders at the top (a requirement of the project) but now I need to add a new folder to the tree and I need to re-sort the object making sure the newly added folder appears at the top of the tree with the others.
I notice there is a curious option for sortChildren() that allows for a defining a custom compare function but I'm having trouble wrapping my head around how to use it.
Any ideas would be much appreciated!
Snippet below on how I am doing things currently (I am populating the new child with data from some form elements):
//add the new foldername to the tree and re-order
var rootNode = jQuery("#document_objects").fancytree("getRootNode");
var childNode = rootNode.addChildren({
title: jQuery('#newfoldername').val(),
tooltip: jQuery('#description').val(),
folder: true
});
rootNode.sortChildren(null, true);
Thanks in advance!
sortChildren(cmp, deep) allows to pass a compare function:
http://www.wwwendt.de/tech/fancytree/doc/jsdoc/FancytreeNode.html#sortChildren
The default implementation (if you pass null or nothing for the cmp argument) is
function(a, b) {
var x = a.title.toLowerCase(),
y = b.title.toLowerCase();
return x === y ? 0 : x > y ? 1 : -1;
};
but you could add some prefix to force a different order, e.g.:
function(a, b) {
var x = (a.isFolder() ? "0" : "1") + a.title.toLowerCase(),
y = (b.isFolder() ? "0" : "1") + b.title.toLowerCase();
return x === y ? 0 : x > y ? 1 : -1;
};
Try below code:
var cmp= function(a, b) {
var x = (a.data.isFolder ? "0" : "1") + a.data.title.toLowerCase(),
y = (b.data.isFolder ? "0" : "1") + b.data.title.toLowerCase();
return x === y ? 0 : x > y ? 1 : -1;
};
node.sortChildren(cmp, true);

Matlab function calling basic

I'm new to Matlab and now learning the basic grammar.
I've written the file GetBin.m:
function res = GetBin(num_bin, bin, val)
if val >= bin(num_bin - 1)
res = num_bin;
else
for i = (num_bin - 1) : 1
if val < bin(i)
res = i;
end
end
end
and I call it with:
num_bin = 5;
bin = [48.4,96.8,145.2,193.6]; % bin stands for the intermediate borders, so there are 5 bins
fea_val = GetBin(num_bin,bin,fea(1,1)) % fea is a pre-defined 280x4096 matrix
It returns error:
Error in GetBin (line 2)
if val >= bin(num_bin - 1)
Output argument "res" (and maybe others) not assigned during call to
"/Users/mac/Documents/MATLAB/GetBin.m>GetBin".
Could anybody tell me what's wrong here? Thanks.
You need to ensure that every possible path through your code assigns a value to res.
In your case, it looks like that's not the case, because you have a loop:
for i = (num_bins-1) : 1
...
end
That loop will never iterate (so it will never assign a value to res). You need to explicitly specify that it's a decrementing loop:
for i = (num_bins-1) : -1 : 1
...
end
For more info, see the documentation on the colon operator.
for i = (num_bin - 1) : -1 : 1