I've been messing around with this code for much longer than necessary. I'm changing to change the value of a dictionary entry depending on a person's choice.
while points <= 10:
print "You have " + str(points) + " points left.\n"
stats = {
"Strength": 0,
"Dexterity": 0,
"Constitution": 0,
"Intelligence": 0,
"Wisdom": 0,
"Charisma": 0
}
for i in sorted(stats):
print i + ": \t" + str(stats[i])
statInc = raw_input("\nWhere do you want to put your points? ").capitalize()
if statInc in stats:
points -= 1
stats[statInc] += 1
I started off with the stats[statInc] as a if/elif that specifies the strings by name. I can't get the values to change, but the point number will decrease accordingly. I know this because I originally had points set to 10.
I've never had this problem before with my other codes that revolved around dictionaries and their values. But I've tried tackling this from every angle and I feel like an idiot.
Nothing is changing because you are setting stats to {"Strength": 0,"Dexterity": 0,"Constitution": 0,"Intelligence": 0,"Wisdom": 0,"Charisma": 0} within your while loop. Every time it loops around, it will recreate stats, making it appear like it never changed.
The way to fix this would be to put the stats = {"Strength": 0,"Dexterity": 0,"Constitution": 0,"Intelligence": 0,"Wisdom": 0,"Charisma": 0} line before you enter your while loop.
You're re-instantiating your dictionary every time the loop evaluates. Move your initial stats declaration out of your loop (before it) so those values aren't reset continuously.
Note that you'll also want to test for while points > 0 instead of points <= 10 since you're starting at 10 and decrementing rather than starting at 0 and incrementing. You could also just test your max points value against sum(stats.values()) to be sure you're getting the current sum rather than using a counter variable, though in this case it doesn't really matter.
Related
I have some C++ code that picks a random item from a list. I need it to weight that randomness so that an item at place "n" has a chance equal to x/n where "x" is the chance that item one in the list will be selected. My current code is like this:
srand(time(NULL));
string a[≈9000] = {"String#1", "String#2", . . ., "String #≈9000"};
int value = rand() % ≈9000;
cout << a[value]
Note that the number notated as "≈9000" is a precise integer obscured for confidentiality. Variable names may be changed.
How can I weight it? I've come up with an equivalent formula
List B[≈9000] = "Item 'n' of 'a' times ≈9000 ÷ n"
Though you might notice that that isn't accurate CPP notation. Do y'all have any ideas how I can implement this?
This is not possible.
You need somehow to allow a variation on your conditions to have a proper distribution.
I'm trying to code a script where a counter increment of 1 every time one condition is false, otherwise it's equal to 0.
The condition is a boolean output of the function CROSS().
I've tried:
1° version
var countSma50 = 0
countSma50_=countSma50
iff(cross(open, sma(close, 50)), countSma50=0, countSma50=countSma50_+1)
but when I plot countSma50 I obtain a line adding 1 from the first bar of the chart up to the last, countSma50 never return to 0.
or
2°Version
if cross(close,sma(close, 50))==true
countSma50+=1
else
countSma50=0
but the compiler return to me " Syntax error at input 'countSma50'."
The two script give me errors or wrong counter value..
The goal is to create a counter increasing of 1 at every bar, resetting itself every time the close crosses under/above the single moving average (sma).
Anyone can help me?
The second version was almost there, note that variables declared in the local scope are not visible from the global context of the script, declare the variable in the global scope first and re-assign later, the script below reset the value to 0 if there is a cross() trigger, otherwise will keep counting every bar:
//#version=4
study("My script")
var int countSma50 = 0
if cross(close,sma(close, 50))
countSma50 := 0
else
countSma50 += 1
plot(countSma50)
Goal: perform rolling window calculations on panel data in Stata with variables PanelVar, TimeVar, and Var1, where the window can change within a loop over different window sizes.
Problem: no access to SSC for the packages that would take care of this (like rangestat)
I know that
by PanelVar: gen Var1_1 = Var1[_n]
produces a copy of Var1 in Var1_1. So I thought it would make sense to try
by PanelVar: gen Var1SumLag = sum(Var1[(_n-3)/_n])
to produce a rolling window calculation for _n-3 to _n for the whole variable. But it fails to produce the results I want, it just produces zeros.
You could use sum(Var1) - sum(Var1[_n-3]), but I also want to be able to make the rolling window left justified (summing future observations) as well as right justified (summing past observations).
Essentially I would like to replicate Python's ".rolling().agg()" functionality.
In Stata _n is the index of the current observation. The expression (_n - 3) / _n yields -2 when _n is 1 and increases slowly with _n but is always less than 1. As a subscript applied to extract values from observations of a variable it always yields missing values given an extra rule that Stata rounds down expressions so supplied. Hence it reduces to -2, -1 or 0: in each case it yields missing values when given as a subscript. Experiment will show you that given any numeric variable say numvar references to numvar[-2] or numvar[-1] or numvar[0] all yield missing values. Otherwise put, you seem to be hoping that the / yields a set of subscripts that return a sequence you can sum over, but that is a long way from what Stata will do in that context: the / is just interpreted as division. (The running sum of missings is always returned as 0, which is an expression of missings being ignored in that calculation: just as 2 + 3 + . + 4 is returned as 9 so also . + . + . + . is returned as 0.)
A fairly general way to do what you want is to use time series operators, and this is strongly preferable to subscripts as (1) doing the right thing with gaps (2) automatically working for panels too. Thus after a tsset or xtset
L0.numvar + L1.numvar + L2.numvar + L3.numvar
yields the sum of the current value and the three previous and
L0.numvar + F1.numvar + F2.numvar + F3.numvar
yields the sum of the current value and the three next. If any of these terms is missing, the sum will be too; a work-around for that is to return say
cond(missing(L3.numvar), 0, L3.numvar)
More general code will require some kind of loop.
Given a desire to loop over lags (negative) and leads (positive) some code might look like this, given a range of subscripts as local macros i <= j
* example i and j
local i = -3
local j = 0
gen double wanted = 0
forval k = `i'/`j' {
if `k' < 0 {
local k1 = -(`k')
replace wanted = wanted + L`k1'.numvar
}
else replace wanted = wanted + F`k'.numvar
}
Alternatively, use Mata.
EDIT There's a simpler method, to use tssmooth ma to get moving averages and then multiply up by the number of terms.
tssmooth ma wanted1=numvar, w(3 1)
tssmooth ma wanted2=numvar, w(0 1 3)
replace wanted1 = 4 * wanted1
replace wanted2 = 4 * wanted2
Note that in contrast to the method above tssmooth ma uses whatever is available at the beginning and end of each panel. So, the first moving average, the average of the first value and the three previous, is returned as just the first value at the beginning of each panel (when the three previous values are unknown).
I am having trouble in solving the following flowchart question. Could you please help me as soon as possible ?
Links are given below:-
Problem 3 and Problem 4:
http://placement.freshersworld.com/placement-papers/ThoughtWorks/Placement-Paper-Whole-Testpaper-29732
Problem 3:
Let's understand the instructions first.
Instruction 3 is a bit ambiguous whether it's referring to the box number or the number in the box. This becomes more straightforward when you read the rest of the instructions all referring to making changes to instruction 2. So we can conclude it means the first box number which is also the first number mentioned in the instruction's text rather than the number in the box.
Instruction 4 is a bit confusing due to its seemingly superfluous usage of the word "whose". If instruction 4 is interpreted to mean look at the number in box 6 and go to that instruction number, if you try to work out the rest of the problem, we have an infinite loop. But if we interpret it to mean:
boxes[boxes[6]] then we don't have an infinite loop.
Let's write some code, the following is JavaScript which you can execute in your JavaScript console, in chrome that is ctrl+shift+j:
var instruction2Variables=[null,1,10];
var boxes=[null,8,6,5,7,4,2,2,11,8,-2,2,1];
var instructions=[];
instructions[1]=function()
{
boxes[11]=boxes[11]+3;
};
instructions[2]=function()
{
instruction2Variables[2]=instruction2Variables[1];
};
instructions[3]=function()
{
return instruction2Variables[1]%2==1;
}
instructions[4]=function()
{
return boxes[boxes[6]];
}
instructions[5]=function()
{
instruction2Variables[1]+=2;
}
instructions[6]=function()
{
boxes[11]=boxes[5]+boxes[11];
}
instructions[7]=function()
{
instruction2Variables[1]+=boxes[12];
instruction2Variables[2]-=boxes[12];
}
instructions[8]=function()
{
return instruction2Variables[2]<boxes[1];
}
instructions[9]=function()
{
return 2;
}
var loops=0;
for(var i=1;i<10;i++)
{
loops++;
if(loops>1000){console.log('breaking an endless loop...');break;}
console.log('Instruction '+i);
var result=instructions[i]();
if(i==3)
{
if(!result){i=6;continue;}
}else if(i==4){
console.log('Going to instruction '+result);
i=result;continue;
}else if(i==8){
if(result){i=10;break;}
}
}
boxes.shift();//get rid of our leading null value
console.log(boxes);//[8, 6, 5, 7, 4, 2, 2, 11, 8, -2, 5, 1]
Problem 4:
First we need to realize the yes/no for instruction 3 is actually pointing the wrong way. There is no question in instruction 1, so the "no" result for instruction 3 is supposed to point upwards meaning to repeat instruction 1 again if "yes".
Instruction 2 seems to reference boxes beyond our 12 boxes at first glance, but it really means we're increasing where we're storing our result of what will always be zero.
Solving this is rather easy. Our first loop we will be storing a 0 in box 2. Our second loop we will be storing a 0 in box 4. Our third loop we will be storing a 0 in box 6. After this, we must stop the looping at exactly this point as-to not corrupt our data. Our answer at first glace seems to be 6, but we're changing our box data in instruction 1 and changing instruction 1 in instruction 2. So after we execute instruction 1 for a third time, we will have boxes 2,4, and 6 set to 0. Then we will run instruction 2 for a third time, thus increasing the box reference to box 8. Finally we want to break our loop, so we need box 3 to store a value of 8.
In my c++ class, we got assigned pairs. Normally I can come up with an effective algorithm quite easily, this time I cannot figure out how to do this to save my life.
What I am looking for is someone to explain an algorithm (or just give me tips on what would work) in order to get this done. I'm still at the planning stage and want to get this code done on my own in order to learn. I just need a little help to get there.
We have to create histograms based on a 4 or 5 integer input. It is supposed to look something like this:
Calling histo(5, 4, 6, 2) should produce output that appears like:
*
* *
* * *
* * *
* * * *
* * * *
-------
A B C D
The formatting to this is just killing me. What makes it worse is that we cannot use any type of arrays or "advanced" sorting systems using other libraries.
At first I thought I could arrange the values from highest to lowest order. But then I realized I did not know how to do this without using the sort function and I was not sure how to go on from there.
Kudos for anyone who could help me get started on this assignment. :)
Try something along the lines of this:
Determine the largest number in the histogram
Using a loop like this to construct the histogram:
for(int i = largest; i >= 1; i--)
Inside the body of the loop, do steps 3 to 5 inclusive
If i <= value_of_column_a then print a *, otherwise print a space
Repeat step 3 for each column (or write a loop...)
Print a newline character
Print the horizontal line using -
Print the column labels
Maybe i'm mistaken on your q, but if you know how many items are in each column, it should be pretty easy to print them like your example:
Step 1: Find the Max of the numbers, store in variable, assign to column.
Step 2: Print spaces until you get to column with the max. Print star. Print remaining stars / spaces. Add a \n character.
Step 3: Find next max. Print stars in columns where the max is >= the max, otherwise print a space. Add newline. at end.
Step 4: Repeat step 3 (until stop condition below)
when you've printed the # of stars equal to the largest max, you've printed all of them.
Step 5: add the -------- line, and a \n
Step 6: add row headers and a \n
If I understood the problem correctly I think the problem can be solved like this:
a= <array of the numbers entered>
T=<number of numbers entered> = length(a) //This variable is used to
//determine if we have finished
//and it will change its value
Alph={A,B,C,D,E,F,G,..., Z} //A constant array containing the alphabet
//We will use it to print the bottom row
for (i=1 to T) {print Alph[i]+" "}; //Prints the letters (plus space),
//one for each number entered
for (i=1 to T) {print "--"}; //Prints the two dashes per letter above
//the letters, one for each
while (T!=0) do {
for (i=1 to N) do {
if (a[i]>0) {print "*"; a[i]--;} else {print " "; T--;};
};
if (T!=0) {T=N};
}
What this does is, for each non-zero entered number, it will print a * and then decrease the number entered. When one of the numbers becomes zero it stops putting *s for its column. When all numbers have become zero (notice that this will occur when the value of T comes out of the for as zero. This is what the variable T is for) then it stops.
I think the problem wasn't really about histograms. Notice it also doesn't require sorting or even knowing the