Understanding this python code - python-2.7

This code was on an exam and it asked what it's output was going to be.
I got it wrong unfortunately and put it was all 1's.
I'm a little confused with what this program is doing specifically with the if/else statement.
I'm a C programmer, so if possible could someone please translate the if/else statement into C code so I can understand what is going on. Thank you!
EDIT: to clarify, I'm not sure what the condition means "if x in d"
def somefunction(L):
d = {}
for x in L:
if x in d:
d[x] = d[x] + 1
else:
d[x] = 1
return d
L = [6, 10, -2, 2, 6, 4, -2, 6]
print somefunction(L)
output: {10: 1, 2: 1, 4: 1, -2: 2, 6: 3}

in in Python performs a containment check. It looks at the right-hand operand to see if it contains the left-hand operand.
>>> 2 in [1, 2, 4]
True
>>> 3 in [1, 2, 4]
False

I'd encourage you NOT to translate everything into C. Python is considerably different and trying to keep things in a C frame of mind will make things harder to understand.
One thing that is great is that Python is interpreted, so you can type "python" and then enter commands to see what they do. You can exam all the variables as things are manipulated. For example, you can do:
L = [6, 10, -2, 2, 6, 4, -2, 6]
for x in L:
print x
To see what the "in" does. Likewise for the rest of the code. Also, there are great online tutorials on Python, Google "Dive into Python", for example.

See Basically in this code what you are doing is you are making a count of no of times the element is repeated in the list..you are using dictionary as a means to take the count..
First of all in the if-else block you are checking whether the element is present or not..if its present then you are incrementing the count using the element as key..else you are creating a new key,key being the element and default value being 1...
Thus you iterate all over the list and check the count of each element in the list..
d[i]=j
#i is key,j is value.
And at last you print your findings by printing the dictionary..!!

Related

How can be found all occurrences redefined operator calling in c++ code?

Recently I've got not obvious (for me) result with opencv cv::Mat. Using
cv::Mat a=cv::Mat::ones(2,2,CV_8UC3) + 1;
std::cout << a;
I've got
[ 2, 0, 0, 2, 0, 0;
2, 0, 0, 2, 0, 0]
instead of expected
[ 2, 2, 2, 2, 2, 2;
2, 2, 2, 2, 2, 2]
Of course, it is due to conversion from 1 to cv::Scalar(1,0,0), but I didn't expected that behaviour.
Now for quite big code project it is necessary to check all other occurrences of operator + or operator - which take cv::Mat as right argument. Is there any tool that can find those operator usages? It seems to me, that CLion, VSCode and Visual Studio don't have such feature. At least, I am failed to find that.
I am thinking about analysis of object file listings, where these operators callings should appear in decorated manner and can be searched through, but it seems too low level and bulky having in mind number of operator overloads (including templated): https://github.com/opencv/opencv/blob/d9a444ca1a97740f9d092816a0ad0a523482911f/modules/core/include/opencv2/core/mat.hpp#L3606
Another idea is to redefine (probably temporarily in Mat.hpp) + operators (and others), that add trivial value to cv::Mat, with custom #warning message in it's body.
What else could be done?

How to recode missing values within a range in Stata

I asked a similar question earlier. I'm attempting to fill in missing values such that observations 0-458 are e 0, 445-832 are 1, and 832-850 are 0.
The following code allowed me to replace missing values in observations 1-160 with 1, with the rest of the observations set to 0.
replace myvar = cond(_n <= 160, 1, 0) if missing(myvar)
How can I interpret this command for what my current purpose?
There is no observation 0. I assume you meant observation 1. Your rules are ambiguous otherwise as you give two rules for 445-458 and two rules for 832.
I will give code for a minimal data example.
clear
set obs 6
gen myvar = .
Assume you want myvar in observations 1/2 to be 0, 3/4 to be 1, 5/6 to be 0.
Method 1
replace myvar = inrange(_n, 3, 4) if missing(myvar)
Method 2
replace myvar = cond(_n <= 2, 0, cond(_n <= 4, 1, 0))
Method 3
replace myvar = 0 if missing(myvar) in 1/2
replace myvar = 1 if missing(myvar) in 3/4
replace myvar = 0 if missing(myvar) in 5/6
In general, however, replacing in terms of observation numbers is not best technique. It is utterly dependent on sort order. Also, if there are criteria in terms of other variables, they are preferable as making more and better sense in records of reproducible research, to yourself in the future and to colleagues, reviewers and yet others too.

Mathematica solution?

I am new with Mathematica and I have one more task to figure out, but I can't find the answer. I have two lists of numbers ("b","u"):
b = {8.734059001373602`, 8.330508824111284`, 5.620669156438947`,
1.4722145583571766`, 1.797504620275392`, 7.045821078656974`,
2.1437334927375247`, 2.295629405840401`, 9.749038328921163`,
5.9928406294151095`, 5.710839663259195`, 7.6983109942364365`,
1.02781847368645`, 4.909108426318685`, 2.5860897177525572`,
9.56334726886076`, 5.661774934433563`, 3.4927397824800384`,
0.4570000499566351`, 6.240122061193738`, 8.371962670138991`,
4.593105388706549`, 7.653068139076581`, 2.2715973346475877`,
7.6234743784167875`, 0.9177107503732636`, 3.182296027902268`,
6.196168580445633`, 0.1486794884986935`, 1.2920960388213274`,
7.478757220079665`, 9.610332785387424`, 0.05088141346751485`,
3.940557901075696`, 5.21881311050797`, 7.489624788199514`,
8.773397599406234`, 3.397275198258715`, 1.4847171141876618`,
0.06574278834161795`, 0.620801320529969`, 2.075457888143216`,
5.244608900551409`, 4.54384757203616`, 7.114276285060143`,
2.8878711430358344`, 5.70657733453041`, 8.759173986432632`,
1.9392596667256967`, 7.419234634325729`, 8.258205508179927`,
1.185315253730261`, 3.907753644335596`, 7.168561412289151`,
9.919881985898002`, 3.169835543867407`, 8.352858871046699`,
7.959492335118693`, 7.772764587074317`, 7.091413185764939`,
1.433673058797801`};
and
u={5.1929, 3.95756, 5.55276, 3.97068, 5.67986, 4.57951, 4.12308,
2.52284, 6.58678, 4.32735, 7.08465, 4.65308, 3.82025, 5.01325,
1.17007, 6.43412, 4.67273, 3.7701, 4.10398, 2.90585, 3.75596,
5.12365, 4.78612, 7.20375, 3.19926, 8.10662};
This is the LinePlot of "b" and "u";
I need to compare first 5 numbers from "b" to 1st number in "u" and always leave the maximum (replace "b"<"u" with "u"). Then I need to shift by 2 numbers and compare 3rd, 4th, 5th, 6th and 7th "b" with 2nd "u" and so on (shift always => 2 steps). But the overlapping numbers need to be "remembered" and compared in the next step, so that always the maximum is picked (e.g. 3rd, 4th and 5th "b" has to be > than 1st and 2nd "u").
Possibly the easiest way would be to cover the maximums showed in the image throughout the whole function, but I am new to this software and I don't have the experience to do that. Still It would be awesome if someone would figure out how to do this with a function that would do what I have described above.
I believe this does what you want:
With[{n = Length # u},
Array[b[[#]] ~Max~ Take[u, ⌊{#-2, #+1}/2⌋ ~Clip~ {1, n}] &, 2 n + 3]
]
{8.73406, 8.33051, 5.62067, 5.1929, 5.55276, 7.04582, 5.55276, 5.55276, 9.74904,--
Or if the length of u and v are appropriately matched:
With[{n = Length # u},
MapIndexed[# ~Max~ Take[u, ⌊(#2[[1]] + {-2, 1})/2⌋ ~Clip~ {1, n}] &, b]
]
These are quite a lot faster than Mark's solution. With the following data:
u = RandomReal[{1, 1000}, 1500];
b = RandomReal[{1, 1000}, 3004];
Mark's code takes 2.8 seconds, while mine take 0.014 and 0.015 seconds.
Please ask your future questions on the dedicated Mathematica StackExchange site:
I think that there's a small problem with your data, u doesn't have as many elements as Partition[b,5,2]. Leaving that to one side, the best I could do was:
Max /# Transpose[
Table[Map[If[# > 0, Max[#, u[[i]]], 0] &,
RotateRight[PadRight[Partition[b, 5, 2][[i]], Length[b]],
2 (i - 1)]], {i, 1, Length[u]}]]
which starts producing the same numbers as in your comment.
As ever, pick this apart from the innermost expression and work outwards.

Mathematica - Functions with Lists

I got this error in Mathematica today:
Set::shape: "Lists {0,0,0,0,0,0,0,0,0,0} and {0,0,0,0,0,0,0,0,0,0,{1}} are not the same shape" >>
And after 3 of those :
General::stop : Further output of Set::shape will be suppressed during this calculation. >>
I am confused as to why I cannot append a "1" to my list of zeros. Is this because I cannot edit the list that is passed into the function? If so, how could I edit that list and somehow return or print it?
Here is my full code:
notFunctioningFunction[list_] := (For[i = 1, i < 10, i++, list = Append[list, {1}]];
Print[list])
list = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
notFunctioningFunction[list]
The reason why I am appending a "{1}" is because in my function, I am solving an equation, and getting the value of the variable which outputs {1}. Here is my code for that :
varName / . Solve[ function1 == function2 ]
Obviously I am a beginner with Mathematica so please be patient :)
Thanks,
Bucco
Append needs to take one list and one element. Like so:
Append[{1,2,3,4},5]
If you have two lists, you can use Join. Like so:
Join[{1,2,3,4},{5}]
Both of these will yield the same result: {1,2,3,4,5}.
Dear Mathematica beginner.
First, when you use something like
{a,b} = {c,d,e};
in Mathematica, between two lists, the program has a difficulty because this is a construct used to assign values to variables, and it requires (among other things) the two lists to be equal.
If what you want is just to add a "1" to an existing and named list, one at a time, the best construct is:
AppendTo[list, 1];
(this construct will modify the variable 'list')
or
list = Join[list, {1}];
Second: about the error messages, they are printed 3 times by default in an evaluation, then muted so that a long list of identical error messages does not clutter your display.
Third, if what you need is adding 10 1s to a list, there is no need to construct that in a loop. You can do that in one pass:
list = Join[list, Table[1, {10}]]
or, more cryptic for beginners
list = Join[list, Array[1&, 10]]

How to feed a list valued variable in the Outer command in mathematica

Consider the following piece of mathematica code:
a := {1, 2, 3};
f[n_, a_] := Sum[a[[j]], {j, 1, n}];
Outer[f, {3}, (a)]
The intention is to simply to evaluate f[3,a]. But I get the following error messages:
During evaluation of In[16]:= Part::partd: Part specification 1[[1]] is longer
than depth of object. >>
During evaluation of In[16]:= Part::partd: Part specification 1[[2]] is longer
than depth of object. >>
During evaluation of In[16]:= Part::partd: Part specification 1[[3]] is longer
than depth of object. >>
During evaluation of In[16]:= General::stop: Further output of Part::partd will
be suppressed during this calculation. >>
Out[16]= {{1[[1]] + 1[[2]] + 1[[3]], 2[[1]] + 2[[2]] + 2[[3]],
3[[1]] + 3[[2]] + 3[[3]]}}
So apparently Outer takes the list variable input a apart and treat its components separately.
My question is, how can I bundle the components in a together in the Outer environment? Many thanks!
You can do this:
Outer[f, {3}, {a}, 1, 1]
(* {{6}} *)
Depending on the real problem you are solving, there may be more superior ways (w.r.t. Outer), using Map or similar.