Why won't my function execute - python-2.7

I'm relatively new to python and the only other experience I've had is C++. Whenever I define a function in Python, I can't seem to execute it.
This my current code for my assignment, if possible I just want to know why my code won't execute
def birthexp(birthyear):
product = birthyear**birthyear
length = len(str(product))
onesCount = str(product).count("1")
threeCount = str(product).count("3")
fiveCount = str(product).count("5")
sevenCount = str(product).count("7")
nineCount = str(product).count("9")
sumCount = onesCount+threeCount+fiveCount+sevenCount+nineCount
oneRation = onesCount/float(length)*100
threeRatio = threeCount/float(length)*100
fiveRatio = fiveCount/float(length)*100
sevenRatio = sevenCount/float(length)*100
nineRatio = nineCount/float(length)*100
totalRatio = sumCount/float(length)*100
print(str(product) + ": product after multiplying the birth year to itself.")
print(str(onesCount) + ": number of ones found at a rate of " +str(oneRation)+ "percent.")
print(str(threeCount) + ": number of threes found at a rate of " +str(threeRatio)+ "percent")
print(str(fiveCount) + ": number of fives found at a rate of " +str(fiveRatio)+ "percent")
print(str(sevenCount) + ": number of sevens found at a rate of " +str(sevenRatio)+ "percent")
print(str(nineCount) + ": number of nine found at a rate of " +str(nineRatio)+ "percent")
print(str(sumCount) + ": total odd numbers found at a rate of " +str(totalRatio)+ "percent")
birthyear(1990)

You have a typo in this line totalRatio = sumCount/floar(length)*100. You need float instead of floar.
Secondly, you have loads of missing parenthesis in almost all lines with the print function.
If you want the function to return value, you should use return instead of print's:
return (str(product)
+ ": product after multiplying the birth year to itself.\n"
+ str(onesCount)
+ ": number of ones found at a rate of " + str(oneRation) + "percent.\n"
+ str(threeCount)
+ ": number of threes found at a rate of " + str(threeRatio) + "percent\n"
+ str(fiveCount)
+ ": number of fives found at a rate of " + str(fiveRatio) + "percent\n"
+ str(sevenCount)
+ ": number of sevens found at a rate of " + str(sevenRatio) + "percent\n"
+ str(nineCount)
+ ": number of nine found at a rate of " + str(nineRatio) + "percent\n"
+ str(sumCount)
+ ": total odd numbers found at a rate of " + str(totalRatio) + "percent\n")

Related

AWS adaptor with Spring Cloud function - payload body is removed

I am building a AWS lambda function using Spring cloud, aws adapter and spring native.
The lambda is fronted by a APIGateway HTTP API V2.0.
<java.version>11</java.version>
<spring-cloud.version>2021.0.2</spring-cloud.version>
<spring-native.version>0.11.4</spring-native.version>
<aws-lambda-events.version>3.9.0</aws-lambda-events.version>
<wrapper.version>1.0.27.RELEASE</wrapper.version>here
When I hit the API with the cloud function pointing to echo function, I get a response with the body of the request removed!
I setup below test to debug the issue. Found that the below highlighted code from
org.springframework.cloud.function.adapter.aws.AWSLambdaUtils
is causing the issue. I see that the highlighted line is removed in the 4X branch. Request to kindly guide how to incorporate that fix into my project while staying on the release version of the dependencies.
public static void main(String[] args) {
String message = "{\r\n"
+ " \"version\": \"2.0\",\r\n"
+ " \"routeKey\": \"POST /updatePet\",\r\n"
+ " \"rawPath\": \"/updatePet\",\r\n"
+ " \"rawQueryString\": \"\",\r\n"
+ " \"headers\": {\r\n"
+ " \"accept\": \"*/*\",\r\n"
+ " \"accept-encoding\": \"gzip, deflate, br\",\r\n"
+ " \"content-length\": \"77\",\r\n"
+ " \"content-type\": \"application/json\",\r\n"
+ " \"host\": \"XXXXXX.execute-api.ap-south-1.amazonaws.com\",\r\n"
+ " \"postman-token\": \"2004009f-2661-46ea-9a31-2d6be0bb9281\",\r\n"
+ " \"user-agent\": \"PostmanRuntime/7.29.0\",\r\n"
+ " \"x-amzn-trace-id\": \"Root=1-62823410-XXXXXXXXXXXXX\",\r\n"
+ " \"x-forwarded-for\": \"111.11.111.111, 111.111.111.111\",\r\n"
+ " \"x-forwarded-port\": \"443\",\r\n"
+ " \"x-forwarded-proto\": \"https\"\r\n"
+ " },\r\n"
+ " \"requestContext\": {\r\n"
+ " \"accountId\": \"123456733\",\r\n"
+ " \"apiId\": \"xxxxx\",\r\n"
+ " \"domainName\": \"xxxxxx.execute-api.ap-south-1.amazonaws.com\",\r\n"
+ " \"domainPrefix\": \"vaoo36b2l5\",\r\n"
+ " \"http\": {\r\n"
+ " \"method\": \"POST\",\r\n"
+ " \"path\": \"/updatePet\",\r\n"
+ " \"protocol\": \"HTTP/1.1\",\r\n"
+ " \"sourceIp\": \"1.1.1.1\",\r\n"
+ " \"userAgent\": \"PostmanRuntime/7.29.0\"\r\n"
+ " },\r\n"
+ " \"requestId\": \"SN0SoioabccwEJuQ=\",\r\n"
+ " \"routeKey\": \"POST /updatePet\",\r\n"
+ " \"stage\": \"$default\",\r\n"
+ " \"time\": \"16/May/2022:11:22:56 +0000\",\r\n"
+ " \"timeEpoch\": 1652700176657\r\n"
+ " },\r\n"
+ " \"body\": \"{\\r\\n\\\"id\\\":1,\\r\\n\\\"name\\\":\\\"toto\\\",\\r\\n\\\"type\\\":\\\"dog\\\",\\r\\n\\\"owner\\\":{\\\"name\\\":\\\"test\\\",\\\"age\\\":8}\\r\\n}\",\r\n"
+ " \"isBase64Encoded\": false\r\n"
+ "}";
Message<byte[]> msg = AWSLambdaUtils.generateMessage(message.getBytes(StandardCharsets.UTF_8), headers(), String.class, mapper());
var payload = new String(msg.getPayload(),StandardCharsets.UTF_8);
System.out.println("payload is"+payload);
}

Time duration Calculator with c++ Problems

I'm currently taking a c++ college course, and I'm running into a problem that makes me feel like an idiot. We're making a time duration calculator that calculates the time after and before a certain duration, and the assignment tries to instruct us how to avoid negatives. I'm not sure what I'm doing wrong, but no matter what I do, it won't work. This is his instruction: "Also, when negative operands are used, the remainder operator is not defined the same way that the mathematical modulus operation (Euclidian Division) is defined. For those reasons, it is easier to just make sure we don't end up with negative remainders. This is easily done by adding a day (or two or three) to before when calculating the difference. Go ahead and do that."
and this is my code (all of which has followed his instructions till now)
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int run()
{
int timeHours;
int timeMinutes;
int durationHours;
int durationMinutes;
char discard; // won't keep this character
cout << "Enter current time: " << endl;
cin >> timeHours >> discard >> timeMinutes;
cout << "Enter duration: " << endl;
cin >> durationHours >> discard >> durationMinutes;
// processing section - compute the results
int timeInMin = (timeHours * 60) + timeMinutes;
int durationInMin = (durationHours * 60) + durationMinutes;
int after = timeInMin + durationInMin;
int before = timeInMin - durationInMin;
int afterHours = after / 60%12;
int afterMinutes = after % 60;
int beforeHours = (before / 60);
int beforeMinutes = (before % 60);
// output section: test data inside brackets[]
cout << setfill('0'); // only needed once
cout << endl;
cout << durationHours << ":" << setw(2) << durationMinutes << " hours after, and before, " <<
timeHours << ":" << setw(2) << timeMinutes << " is [" << afterHours << ":" << setw(2) <<
afterMinutes << ", " << beforeHours << ":" << setw(2) << beforeMinutes << "]" << endl;
return 0;
}
for example, if I plug in 2:30 as the time and 13:27 as the duration, expected [3:57, 1:03] but found [3:57, -10:-57]
I've tried adding both 24 and 1440 (number of minutes in a day) to before as well as the calculations that use the int before, but no luck. I've tried reaching out to my class a few days ago, but no one has responded.
Edit: he also says to do this in order to get rid of midnight times that look like 0:32 by doing this: Add 11 to after-hours. Find the remainder of dividing by 12. Add 1 to the result. Does he mean something like:
int afterHours = (((after / 60%12) + 11) / 12) + 1
the %12 was so that the hours wouldn't go over 12 and turn into military time
Instead of this:
// processing section - compute the results
int timeInMin = (timeHours * 60) + timeMinutes;
int durationInMin = (durationHours * 60) + durationMinutes;
int after = timeInMin + durationInMin;
int before = timeInMin - durationInMin;
int afterHours = after / 60%12;
int afterMinutes = after % 60;
int beforeHours = (before / 60);
int beforeMinutes = (before % 60);
This:
int timeInMin = (timeHours * 60) + timeMinutes;
int durationInMin = (durationHours * 60) + durationMinutes;
int after = timeInMin + durationInMin;
int before = (timeInMin % 720) + 720 - durationInMin; // 720 is 12 hours in minutes
int afterHours = (after / 60) % 12;
int afterMinutes = (after - (afterHours * 60)) % 60;
afterHours = afterHours + 12 * (afterHours == 0);
int beforeHours = (before / 60) % 12;
int beforeMinutes = (before - (beforeHours * 60)) % 60;
beforeHours = beforeHours + 12 * (beforeHours == 0);
The trick is to get an integer into the range [1,12] using only +, - and %.
Let's start with the negative numbers:
t = 8;
d = 11;
b = t-d; // -3
So we add 12:
b = t-d + 12; // 9
Ah, but what if the interval is bigger?
d = 100;
b = t-d + 12; // -80
This is why your teacher talked about adding "a day or two or three". But how to know how many? No need, we have modulo:
d = 100;
d = d%12; // 4
b = t-d + 12; // 16
Now we're positive, but we're getting numbers greater than 12. No problem, we use modulo again:
d = 100;
d = d%12; // 4
b = (t-d + 12)%12; // 4
a = (t+d)%12; // 0
Ah, now we're getting [0,11], but we want [1,12]. So we use the trick (x-1)%m +1:
d = 100;
d = d%12; // 4
b = (t-d + 12 - 1)%12 + 1; // 4
a = (t+d - 1)%12 + 1; // 12
There we have it. We still have to deal with minutes (the same way) and with a smart Alec user who enters negative numbers, but it should be clear how to do that and this post is getting long.

Newbie error with "expression must have integral or enum type"

Be gentle ... I'm 5 weeks into studying C++. I've dug and dug and cannot figure out why Visual Studio Express (and online compilers) are throwing errors about this.
Note that I've included all my declarations for the sake of clarity -- most are used in different section of code. The line that gets the errors is this one: newsharePrice = perchangeEnd * profitLoss << '\n';
The error I get is c2296, left operand has type double. I have no idea why it doesn't like this ... I multiply other doubles just fine.
double numberShares,
sharePrice,
profitLoss,
profitGain,
commissionPaid,
commissionCost,
sharesCost,
totalshareCost,
newtotalshareCost,
newcommissionCost,
newsharePrice;
double perChange;
double perchangeEnd;
const int minVALUE = 1;
const int maxVALUE = 100;
int seed = time(0);
srand (seed);
perChange = (rand() % (maxVALUE - minVALUE + 1)) + minVALUE;
cout << perChange << '\n';
perchangeEnd = perChange / 100;
int flip = rand() % 2 + 1;
if (flip == 1)
profitLoss = 1;
else
profitLoss = -1;
newsharePrice = perchangeEnd * profitLoss << '\n';
newsharePrice = newsharePrice + sharePrice;
cout << newsharePrice << '\n';
newtotalshareCost = numberShares * newsharePrice;
cout << "You've now paid " << newtotalshareCost << " for your shares." << '\n';
newcommissionCost = newtotalshareCost * commissionRate;
cout << "The new amount of commission for this is " << newcommissionCost << " ." << '/n';
Well, just read the problematic line:
newsharePrice = perchangeEnd * profitLoss << '\n';
// ▲▲▲▲▲▲▲▲
That << '\n' is not part of the multiplication; a copy-pasta fail from your cout lines?
In this context, the compiler has no choice but to assume you're trying to perform a bitwise left-shift operation, which cannot be performed on doubles; only on integers.
While the compilation error is now fixed, your domain error is still there (today is Friday, isn't it?). Why would share price fluctuation affect your commission in any way? You already hace your position. You also measure your number of shares with floating-point precision. While in some cases you might have uneven number of shares, this happens quite seldom. Are you really account for this or just incorrectly use double? Most systmes would count number of shares as integer. Also, you can have negative position, which after all calctulations will give negative commission! Brokers would not agree to that ;). The last, but not the least, in US commission is rarely expressed as percentage of transaction value. It is usually charged in a form of cents per share (or fixed transaction cost for most retail brokers).

'+' cannot add two pointers, but just printing an int and an explicit string?

I am trying to use an array to keep track of the totals of different types of items (up to 50 types). When I want to print the totals out, I get an error saying "'+' cannot add two pointers." I'm thinking the problem is with my totals array somehow, but I can't figure it out. Below is a sample of my code:
string printSolution()
{
int totals[50];
string printableSolution = "";
for (int k = 0; k < itemTypeCount; k++)
{
totals[k] = 0;
}
for (int i = 0; i < itemCount; i++)
{
totals[items[i].typeCode]++;
}
for (int a = 0; a < itemTypeCount; a++)
{
printableSolution.append("There are " + totals[a] + " of Item type " + (a + 1) + ". \n");
}
}
The string literals "Foo" are of const char*, i.e. pointer type.
To understand what happens with:
"There are " + totals[a] + " of Item type " + (a + 1) + ". \n"
Let's look at an expression:
"0123456789" + 5
This actually just offsets 5 bytes from the start, so becomes:
"56789"
So an expression:
"0123456789" + 5 + "foo"
becomes:
"56789" + "foo"
as pointers, and this is not defined.
What you really want is string concatenation; this can be achieved using std::string.
We can write:
std::string("56789") + "foo"
and this generates a std::string with value: "56789foo" as you desire.
But:
std::string("0123456789") + 5
is also not defined. You need to use:
std::string("0123456789") + std::to_string(5)
So, finally you want:
std::string("There are ") + std::to_string(totals[a]) + " of Item type " + std::to_string(a + 1) + ". \n"
Note now you do not need to explitly convert all the "" to std:string, as once you have one implicit type conversion will take care of the other operand in operator+. However, adding them would do no harm:
std::string("There are ") + std::to_string(totals[a]) + std::string(" of Item type ") + std::to_string(a + 1) + std::string(". \n")
The problem is here:
"There are " + totals[a] + " of Item type " + (a + 1) + ". \n"
It means char* + int + char* + int + char*. You need to print them out separately or change the int to a std::string.
Use C++-style formatting instead:
std::ostringstream oss;
oss << "There are " << totals[a] << " of Item type " << (a + 1) << ". \n";
printableSolution += oss.str();

Curious division result

How can this code...
vector<double> _pc;
vector<int> _documentClassIds;
[...]
someMemberFunction(vector<int> const & documentIds) {
cout << "_pc[0] = "<< _pc[0]<<endl;
cout << "_pc[1] = "<< _pc[1]<<endl;
cout << "documentIds.size() = " << documentIds.size()<<endl;
// Normalize
for (auto documentId : documentIds)
_pc[_documentClassIds[documentId]] =
_pc[_documentClassIds[documentId]] / documentIds.size();
cout << "_pc[0] = "<< _pc[0]<<endl;
cout << "_pc[1] = "<< _pc[1]<<endl;
}
produce this output?
_pc[0] = 3
_pc[1] = 3
documentIds.size() = 6
_pc[0] = 0.0138889
_pc[1] = 0.0138889
I'm not sure what you think the problem is.
You have six document IDs, so your for loop runs six times. Each time it runs, it divides one of your _pc array values by six.
Since 0.0138888... is 3 divided by 216 (6^3), the calculations seem correct.
It's obvious that the selection of which _pc array entry to divide is equally distibuted so that each gets divided three times, so each ends up as:
(((3 / 6) / 6) / 6) => 0.013888...