Use Python 3.8:
Problem Description
Many recipes tend to be rather small, producing the fewest number of servings that are really possible with the included ingredients. Sometimes one will want to be able to scale those recipes upwards for serving larger groups.
This program's task is to determine how much of each ingredient in a recipe will be required for a target party size. The first inputs to the program will be the recipe itself.
Here is an example recipe that comes from the story "Chitty Chitty Bang Bang", written by Ian Fleming, who is much better known for introducing the world to James Bond:
This is a recipe scaler for serving large crowds! Enter one ingredient per line, with a numeric value first. Indicate the end of input with an empty line. 4 tbsp cocoa 1/4 pound butter 2 tsp corn syrup 1 can evaporated milk 1 tsp water Here is the recipe that has been recorded 4 tbsp cocoa 1/4 pound butter 2 tsp corn syrup 1 can evaporated milk 1 tsp water
How many does this recipe serve? 16 How many people must be served? 25 Multiplying the recipe by 2 8 tbsp cocoa 2/4 pound butter 4 tsp corn syrup 2 can evaporated milk 2 tsp water Serves 32
NOTE: The recipe rounds upwards, since it is usually not practical to obtain fractional cans or fractional eggs, etc.
Your program must obtain a complete recipe (not necessarily this one), echo it with good formatting, and then scale it up as shown above.
Program Hints:
Attractive user-friendly output is rather straightforward, with the help of Python's string formatting features. User-friendly input is a little trickier, but the split function from Unit 2 can be very helpful:
First hint:
The name of an ingredient might be more than one word. This will place all of the extra words into a single string variable 'item':
quant, unit, item = line.split(' ',2) # pull off at most 2 words from the front
Second hint:
Sometimes the measure will be fractional. We can recognize that if the number contains a slash.
if '/' in quant:
numer, denom = quant.split('/') # get the parts of the fraction
The rest is left up to the student -- since this is a string operation and this fraction represents a number.
Second Part:
No doubt the output seems to be a little strange to ask for 2/4 pounds of butter. One might think it would be better to ask for 1/2.
Modify the program so that all fractions are reduced to their lowest terms. There is a function in the Python math module named gcd that can help with this. (You can email course personnel if you need help accessing the math features.)
Also, express all improper fractions (where the numerator exceeds the denominator) as mixed fractions. Scaling this recipe by a factor of 10 would ask for 2 1/2 pounds of butter.
And of course, the resulting output should still be easy to read.
Other Guidelines:
Clarity of code is still important here -- and clear code is less likely to have bugs.
In particular, there should be very good and clear decisions in the code.
And there will be a penalty for usage of break or continue statements.
Planning out the design of the solution before diving into code will help!
The simplest solutions would use a list, but without any
indexing on that list
(or use of range() to get those indexes). Let Python
help you fill and traverse the recipe.
Storing the entire recipe in a single list before splitting things up often produces much simpler programs than trying to store everything into multiple separate lists!
IMPORTANT NOTE: As above, the recipe is provided as input to the program -- it is not part of the program itself. The program may not assume it knows what the ingredients are, or how many there are, or which ingredients have fractions and which ones do not. It must work for any number of valid input lines.
TASKS:
Recipe Data Structure: Effectively uses list (either parallel lists or lists of structures)
Input Recipe: Clearly reads input until blank line encountered
Serving Inputs: Correctly inputs two values: how many recipe serves, and how many will be served
Computing the Scale: math.ciel; if/else to round up; or anything else equivalent
Parsing the ingredients: Correctly parses ingredients (using given 'tricks') May be done at any point in the program
Scaling the recipe: Multiplies whole numbers and numerators by chosen scaling factor
Reduced fraction: Reduces using gcd; denominator 1 reported as whole numbers
Output presentation: Uses string formatting to present output recipe
Compilation: Program runs fully without change (with valid inputs of 3+ words separated with single spaces)
Correctness: Program behaves as expected (accounting for known errors above)
Program can handle "1 egg" as an ingredient (with only once space)
Only Python 3.8 will be allowed.
In: Computer Science
C++
1. Modify the code from your HW2 as follows:
Your triangle functions will now return a string object. This string will contain the identification of the triangle as one of the following (with a potential prefix of the word âRight â):
Not a triangle
Scalene triangle
Isosceles triangle
Equilateral triangle
2. All output to cout will be moved from the triangle functions to the main function.
3. The triangle functions are still responsible for rearranging the values such that c is at least as large as the other two sides.
4. Please run your program with all of your test cases from HW2. The results should be identical to that from HW2. You must supply a listing of your program and sample output
CODE right now
#include <cstdlib> //for exit, atoi, atof
#include <iostream> //for cout and cerr
#include <iomanip> //for i/o manipulation
#include <cstring> //for strcmp
#include <cmath> //for fabs
using namespace std;
//triangle function
void triangle(int a, int b, int c)
{
if (a + b <= c || a + c <= b || b + c <= a) //conditions for an invalid triangle
cout << a << " " << b << " " << c << " "
<< "Not a triangle";
else //if above returned false, then it is a valid triangle
{
int temp;
cout << a << " " << b << " " << c << " "; //print the side values
//logic to find out the largest value and store it to c.
if (a > b && a > c)
{
temp = a;
a = c;
c = temp;
}
else if (b > a && b > c)
{
temp = b;
b = c;
c = temp;
}
if (a == b && b == c) //condition for equilateral triangle
{
cout << "Equilateral triangle";
return;
}
else if (a * a == b * b + c * c ||
b * b == c * c + a * a ||
c * c == a * a + b * b) //condition for right triangle i.e. pythagoras theorem
cout << "Right ";
if (a == b || b == c || a == c) //condition for Isosceles triangle
cout << "Isosceles triangle";
else //if both the above ifs failed, then it is a scalene triangle
cout << "Scalene triangle";
}
}
//overloaded triangle function
void triangle(double a, double b, double c)
{
//equality threshold value for absolute difference procedure
const double EPSILON = 0.001;
if (a + b <= c || a + c <= b || b + c <= a) //conditions for an invalid triangle
cout << fixed << setprecision(5)
<< a << " " << b << " " << c << " "
<< "Not a triangle";
else //if above returned false, then it is a valid triangle
{
double temp;
cout << fixed << setprecision(5)
<< a << " " << b << " " << c << " "; //print the side values
//logic to find out the largest value and store it to c.
if (a > b && a > c)
{
temp = a;
a = c;
c = temp;
}
else if (b > a && b > c)
{
temp = b;
b = c;
c = temp;
}
if (fabs(a - b) < EPSILON &&
fabs(b - c) < EPSILON) //condition for equilateral triangle
{
cout << "Equilateral triangle";
return;
}
else if (fabs((a * a) - (b * b + c * c)) < EPSILON ||
fabs((b * b) - (c * c + a * a)) < EPSILON ||
fabs((c * c) - (a * a + b * b)) < EPSILON) //condition for right triangle i.e. pythagoras theorem
cout << "Right ";
if (fabs(a - b) < EPSILON ||
fabs(b - c) < EPSILON ||
fabs(a - c) < EPSILON) //condition for Isosceles triangle
cout << "Isosceles triangle";
else //if both the above ifs failed, then it is a scalene triangle
cout << "Scalene triangle";
}
}
//main function
int main(int argc, char **argv)
{
if (argc == 3 || argc > 5) //check argc for argument count
{
cerr << "Incorrect number of arguments. " << endl;
exit(1);
}
else if (argc == 1) //if no command arguments found then do the following
{
int a, b, c; //declare three int
cin >> a >> b >> c; //read the values
if (a <= 0 || b <= 0 || c <= 0) //if values are negative then exit
{
cerr << "Data must be a positive integer. " << endl;
exit(1);
}
triangle(a, b, c); //call the function if inputs are valid
}
else //if command arguments were found and valid
{
if (strcmp(argv[1], "-i") == 0)
{
int a, b, c, temp; //declare required variables
if (argc == 5)
{
//convert char to int using atoi()
a = atoi(argv[2]);
b = atoi(argv[3]);
c = atoi(argv[4]);
}
else
{
cin >> a >> b >> c; // read the values
}
if (a <= 0 || b <= 0 || c <= 0) //if values are negative then exit
{
cerr << "Data must be a positive integer. " << endl;
exit(1);
}
//call the function
triangle(a, b, c);
}
else if (strcmp(argv[1], "-d") == 0)
{
double a, b, c, temp; //declare required variables
if (argc == 5)
{
//convert char to int using atoi()
a = atof(argv[2]);
b = atof(argv[3]);
c = atof(argv[4]);
}
else
{
cin >> a >> b >> c; // read the values
}
if (a <= 0 || b <= 0 || c <= 0) //if values are negative then exit
{
cerr << "Data must be a positive double. " << endl;
exit(1);
}
//call the overloaded function
triangle(a, b, c);
}
}
cout << endl;
return 0;
}In: Computer Science
Use Python 3.8:
Problem Description
Many recipes tend to be rather small, producing the fewest number of servings that are really possible with the included ingredients. Sometimes one will want to be able to scale those recipes upwards for serving larger groups.
This program's task is to determine how much of each ingredient in a recipe will be required for a target party size. The first inputs to the program will be the recipe itself.
Here is an example recipe that comes from the story "Chitty Chitty Bang Bang", written by Ian Fleming, who is much better known for introducing the world to James Bond:
This is a recipe scaler for serving large crowds! Enter one ingredient per line, with a numeric value first. Indicate the end of input with an empty line. 4 tbsp cocoa 1/4 pound butter 2 tsp corn syrup 1 can evaporated milk 1 tsp water Here is the recipe that has been recorded 4 tbsp cocoa 1/4 pound butter 2 tsp corn syrup 1 can evaporated milk 1 tsp water How many does this recipe serve? 16 How many people must be served? 25 Multiplying the recipe by 2 8 tbsp cocoa 2/4 pound butter 4 tsp corn syrup 2 can evaporated milk 2 tsp water Serves 32
NOTE: The recipe rounds upwards, since it is usually not practical to obtain fractional cans or fractional eggs, etc.
Your program must obtain a complete recipe (not necessarily this one), echo it with good formatting, and then scale it up as shown above.
Program Hints:
Attractive user-friendly output is rather straightforward, with the help of Python's string formatting features. User-friendly input is a little trickier, but the split function from Unit 2 can be very helpful:
First hint:
The name of an ingredient might be more than one word. This will place all of the extra words into a single string variable 'item':
quant, unit, item = line.split(' ',2) # pull off at most 2 words from the front
Second hint:
Sometimes the measure will be fractional. We can recognize that if the number contains a slash.
if '/' in quant:
numer, denom = quant.split('/') # get the parts of the fraction
The rest is left up to the student -- since this is a string operation and this fraction represents a number.
Second Part:
No doubt the output seems to be a little strange to ask for 2/4 pounds of butter. One might think it would be better to ask for 1/2.
Modify the program so that all fractions are reduced to their lowest terms. There is a function in the Python math module named gcd that can help with this. (You can email course personnel if you need help accessing the math features.)
Also, express all improper fractions (where the numerator exceeds the denominator) as mixed fractions. Scaling this recipe by a factor of 10 would ask for 2 1/2 pounds of butter.
And of course, the resulting output should still be easy to read.
Other Guidelines:
Clarity of code is still important here -- and clear code is less likely to have bugs.
In particular, there should be very good and clear decisions in the code.
And there will be a penalty for usage of break or continue statements.
Planning out the design of the solution before diving into code will help!
The simplest solutions would use a list, but without any
indexing on that list
(or use of range() to get those indexes). Let Python
help you fill and traverse the recipe.
Storing the entire recipe in a single list before splitting things up often produces much simpler programs than trying to store everything into multiple separate lists!
IMPORTANT NOTE: As above, the recipe is provided as input to the program -- it is not part of the program itself. The program may not assume it knows what the ingredients are, or how many there are, or which ingredients have fractions and which ones do not. It must work for any number of valid input lines.
TASKS:
Recipe Data Structure: Effectively uses list (either parallel lists or lists of structures)
Input Recipe: Clearly reads input until blank line encountered
Serving Inputs: Correctly inputs two values: how many recipe serves, and how many will be served
Computing the Scale: math.ciel; if/else to round up; or anything else equivalent
Parsing the ingredients: Correctly parses ingredients (using given 'tricks') May be done at any point in the program
Scaling the recipe: Multiplies whole numbers and numerators by chosen scaling factor
Reduced fraction: Reduces using gcd; denominator 1 reported as whole numbers
Output presentation: Uses string formatting to present output recipe
Compilation: Program runs fully without change (with valid inputs of 3+ words separated with single spaces)
Correctness: Program behaves as expected (accounting for known errors above)
Program can handle "1 egg" as an ingredient (with only once space)
Only Python 3.8 will be allowed.
In: Computer Science
The Objectives are to:
Discussion:
The best way to learn Python (or any programming language) is to write & run Python programs. In this lab you will enter two programs, and run them to produce the output. Then deliberately insert syntax errors to see what kinds of error messages you get. Finally, you will be given a "specification" of a simple problem to solve. From this specification create a program, and run it against a set of specified test values. Properly document the last program so another person can read it and determine its purpose.
Specifications:
1. Using IDLE IDE to create a source code file named welcome.py, enter the following Python code, translate it and run it.
def main():
print("Welcome to the wonderful world of Python programming!")
main()
After a successful run, capture its output and close its workspace.
2. Perform the same steps described in part 1 for the following program:
def main():
integer1 = int(input("Enter first integer")) # prompt and enter the first integer
integer2 = int(input("Enter second integer")) # prompt and enter the second integer
sum = integer1 + integer2 # generate and assign the sum
print("The sum of", integer1, "and", integer2,
"is", sum) # print sum
difference = integer1 â integer2 # assignment of difference
print("The difference of", integer1, "minus",
integer2, "is", difference) # print difference
main()
3. "Comment-out" the second line of the second program so it looks like this:
# integer1 = int(input("Enter first integer")) # prompt for and input first integer
Try to run the modified program and record (and hand in) the error message(s).
4. Remove the comment symbol from the previous part (i.e., restore your program to
its previous working condition) and then comment-out the sum assignment statement like this:
# sum = integer1 + integer2 # assignment of sum
Run the modified program and capture the error message(s) you see.
5. Restore your working program again and then comment-out the code line,
# difference = integer1 â integer2 # assignment of difference
Once again run the modified program and capture the error message(s) you see. Explain why the error message you got when commenting out the sum statement differs than when commenting out the difference statement.
6. Problem: Design, Develop, Integrate, and Test (DDI&T) a Python program that converts a Fahrenheit temperature into its Celsius temperature equivalent.
The formula for converting Fahrenheit to Celsius is,
Celsius = 5.0/9.0*(Fahrenheit â 32.0)
Your program should prompt the user for a Fahrenheit temperature, convert it to Celsius and then output both values in the following format:
Fahrenheit Temperature = <Fahrenheit value>
Celsius Temperature = <Celsius value>
Fully test your program with the following set of Fahrenheit temperatures:
75.5, 32.0, -459.4, -40.0, 0.0, 100.0, and 212.0
Note that the temperature values are both input and output with one decimal of precision after the decimal point.
Documentation Guidelines:
Use good programming style (e.g., indentation for readability) and document each of your program parts with the following items (the items shown between the '<' and '>' angle brackets are only placeholders. You should replace the placeholders and the comments between them with your specific information). Your cover sheet should have some of the same information, but what follows should be at the top of each program's sheet of source code. Some lines of code should have an explanation of what is to be accomplished, this will allow someone supporting your code years later to comprehend your purpose. Be brief and to the point. Start your design by writing comment lines of pseudocode. Once that is complete, begin adding executable lines. Finally run and test your program.
#===================================================================
# CS119T â Unit 1-Submission Node â IDEs and Debugging
# Filename: Unit 1 Submission Node: my-unit1-submission-node.doc
# Author: <Your name>
# Purpose: Demonstrate basic Python programming in the IDLE
# development environment
# by following steps 1 through 6 above.
#===================================================================
Deliverable(s):
Your deliverable should be a Word document with screenshots showing the code you have created, and discuss the issues that you had for this project related to AWS and/or Python IDE and how you solved them for all of the programs listed above as well as the inputs and outputs from running them. For parts 3, 4 and 5 where you deliberately "seeded" errors into your code, capture and turn in the error messages you encountered when attempting to translate and run these errant programs. Include a cover sheet with the hardcopy of your labs when you turn them in to the instructor.
In: Computer Science
Beacon Signals Company maintains and repairs warning lights, such as those found on radio towers and lighthouses. Beacon Signals Company prepared the following end-of-period spreadsheet at December 31, 2019, the end of the fiscal year: Beacon Signals Company End-of-Period Spreadsheet For the Year Ended December 31, 2019 Unadjusted Trial Balance Adjustments Adjusted Trial Balance Account Title Dr. Cr. Dr. Cr. Dr. Cr. Cash 13,000.00 13,000.00 Accounts Receivable 40,500.00 (a) 12,500.00 53,000.00 Prepaid Insurance 4,200.00 (b) 3,000.00 1,200.00 Supplies 3,000.00 (c) 2,250.00 750.00 Land 98,000.00 98,000.00 Building 500,000.00 500,000.00 Accumulated Depreciation-Building 255,300.00 (d) 9,000.00 264,300.00 Equipment 121,900.00 121,900.00 Accumulated Depreciation-Equipment 100,100.00 (e) 4,500.00 104,600.00 Accounts Payable 15,700.00 15,700.00 Salaries and Wages Payable (f) 4,900.00 4,900.00 Unearned Rent 2,100.00 (g) 1,300.00 800.00 Sarah Colin, Capital 238,100.00 238,100.00 Sarah Colin, Drawing 10,000.00 10,000.00 Fees Earned 388,700.00 (a) 12,500.00 401,200.00 Rent Revenue (g) 1,300.00 1,300.00 Salaries and Wages Expense 163,100.00 (f) 4,900.00 168,000.00 Advertising Expense 21,700.00 21,700.00 Utilities Expense 11,400.00 11,400.00 Depreciation Expense-Building (d) 9,000.00 9,000.00 Repairs Expense 8,850.00 8,850.00 Depreciation Expense-Equipment (e) 4,500.00 4,500.00 Insurance Expense (b) 3,000.00 3,000.00 Supplies Expense (c) 2,250.00 2,250.00 Miscellaneous Expense 4,350.00 4,350.00 1,000,000.00 1,000,000.00 37,450.00 37,450.00 1,030,900.00 1,030,900.00 Required: 1. Prepare an income statement for the year ended December 31. If a net loss has been incurred, enter that amount as a negative number using a minus sign. Be sure to complete the statement heading. Use the list of Labels and Amount Descriptions for the correct wording of text items other than account names. You will not need to enter colons (:) on the income statement. 2. Prepare a statement of ownerâs equity for the year ended December 31. No additional investments were made during the year. For those boxes in which you must enter subtracted or negative numbers use a minus sign. Be sure to complete the statement heading. Use the list of Labels and Amount Descriptions for the correct wording of text items. 3. Prepare a balance sheet as of December 31. Fixed assets must be entered in order according to account number. Be sure to complete the statement heading. Use the list of Labels and Amount Descriptions for the correct wording of text items other than account names. You will not need to enter colons (:) or the word "Less" on the balance sheet; they will automatically insert where necessary. 4. Based upon the end-of-period spreadsheet, journalize the closing entries. Explanations should be omitted. If you are unsure of account titles, see the chart of accounts. 5. Prepare a post-closing trial balance. CHART OF ACCOUNTS Beacon Signals Company General Ledger ASSETS 11 Cash 12 Accounts Receivable 13 Prepaid Insurance 14 Supplies 15 Land 16 Building 17 Accumulated Depreciation-Building 18 Equipment 19 Accumulated Depreciation-Equipment LIABILITIES 21 Accounts Payable 22 Salaries and Wages Payable 23 Unearned Rent EQUITY 31 Sarah Colin, Capital 32 Sarah Colin, Drawing REVENUE 41 Fees Earned 42 Rent Revenue EXPENSES 51 Salaries and Wages Expense 52 Advertising Expense 53 Utilities Expense 54 Depreciation Expense-Building 55 Repairs Expense 56 Depreciation Expense-Equipment 57 Insurance Expense 58 Supplies Expense 59 Miscellaneous Expense Labels Current assets Current liabilities December 31, 2019 Expenses For the Year Ended December 31, 2019 Property, plant, and equipment Revenues Amount Descriptions Decrease in ownerâs equity Increase in ownerâs equity Net income Net loss Sarah Colin, capital, January 1, 2019 Sarah Colin, capital, December 31, 2019 Total assets Total current assets Total expenses Total liabilities Total liabilities and ownerâs equity Total property, plant, and equipment Total revenues Withdrawals 1. Prepare an income statement for the year ended December 31. If a net loss has been incurred, enter that amount as a negative number using a minus sign. Be sure to complete the statement heading. Use the list of Labels and Amount Descriptions for the correct wording of text items other than account names. You will not need to enter colons (:) on the income statement. Beacon Signals Company Income Statement For the Year Ended December 31, 2019 Text entry invalid 1 Revenue: 2 Fees earned 3 Rent revenue 4 Expense 5 (Label) 6 7 8 9 10 11 12 13 14 15 16
In: Accounting
write pseudocode for the following problems using if
while conditions
A student buys various books at the start of the
semester from a bookshop. Write pseudocode for a program which
takes the total amount spent on books and the total number of books
as input and outputs the average cost per book.
Write pseudocode for a program which takes a year as
input (e.g. 2014) and determines whether or not it is a leap year.
A leap year is a multiple of 4, and if it is a multiple of 100, it
must also be a multiple of 400.
Write pseudocode for a program which takes 3 integer
values, a b c, as input and prints their sum. However, if one of
the values is the same as another of the values, it does not count
towards the sum.
When squirrels get together for a party, they like to
have nuts. A squirrel party is successful when the number of nuts
is between 40 and 60, inclusive. Unless it is the weekend, in which
case there is no upper bound on the number of nus. Write pseudocode
of a program which inputs the number of nuts consumed at a party,
and prints âTrueâ if the party with the given values is successful,
or âFalseâ otherwise.
Write pseudo code that will perform the
following.
Read in 5 separate numbers.
Calculate the average of the five numbers.
Find the smallest (minimum) and largest (maximum) of
the five entered numbers.
Write out the results found from steps b and c with a
message describing what they are.
Write pseudo code that reads in three numbers and
writes them all in sorted order.
You are driving a little too fast, and a police
officer stops you. Write pseudocode to compute the result, encoded
as an integer value: 0=no ticket, 1=small ticket, 2=big ticket. If
speed is 60 or less, the result is 0. If speed is between 61 and 80
inclusive, the result is 1. If speed is 81 or more, the result is
2. Unless it is your birthday -- on that day, your speed can be 5
higher in all cases.
Write pseudocode for a program that prints the numbers
from 1 to 100. But for multiples of three print âFizzâ instead of
the number and for the multiples of five print âBuzzâ. For numbers
which are multiples of both three and five print
âFizzBuzzâ.
Iterations
Write a loop to print this fencepostpattern. Such
fencepost loops can be created by placing one post (i.e. |) outside
your loop, and then alternating between wires (i.e. ==) and posts
inside the loop.
|==|==|==|==|
Write pseudocode for a program that takes an integer
and uses a fencepost loop to print the factors of that number,
separated by the word "and". For example, for the number 24, it
should print the following output.
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
Write pseudocode for a program which repeatedly reads
integers from the user, stopping only when the user enters -1, and
returns the largest value input.
write a program that calculates the sum of numbers
entered by a user one at a time. The program terminates when user
enters -1.
Write pseudcode for a program that calculates the area
of simple shapes. The Shape given as input can be circle, square,
or right triangle.
Extend the previous program such that the users can
calculate the area (of the 3 specified shapes) as many times as
they want.
Write PC that takes in a +ve number N and prints the
square of size N composed of '*'.
Write PC that takes in a +ve number N and determines
if it is a prime or not.
Q4. can be calculated from the infinite series
given below:
=4- 43+ 45- 47+ 49- 411+
Write a pseudo code that prints the value of after the first 100 terms, 200 terms and 300 terms. Write one pseudo code that prints all three values. Donât write 3 different codes.
Write a program that takes in a +ve integer and prints
its break up in terms of units, tens, hundreds etc. The number is
not longer than 4 digits.
Input 2000 Output: 0 units, 0
tens, 0 hundreds, 2 thousands
Input 173 Output:
3 units, 7 tens, 1 hundreds
Write a program to output the individual digits of a
number from right to left with spaces added in between each digit.
For example if the number is 9867 then your program should output:
7 6 8 9
Repeat the above so that the digits are printed
from left to right. For example for 9867 the output should be 9 8 6
7. The maximum number you have to cater for is 105. The leading
zeros should NOT be printed so if the number is 105 the output
should be 1 0 5 and NOT 0 0 0 1 0 5.
Write a program that inputs numbers from the user till
the user inputs a negative number. The program should then print
the second maximum of all numbers and second minimum of all numbers
that were input. The last negative number should not count towards
the minimum. For example if the input is: 10 7 42 2 2 0 56 6
-1
The output should be: second maximum is 10 and second minimum is
2
In: Computer Science
THONNY: This project focusses on dealing with strings of text. The starting point for this is a variable, âtextâ, that contains a random collection of words. The aim of this assignment is to iterate over the words and find the length of the longest word.
text = ("Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Aliquam rhoncus facilisis consequat. "
"Nam ultricies quis dolor vitae placerat. Integer in ante sit amet
eros egestas porttitor. Phasellus "
"semper lectus dapibus volutpat consequat. Duis gravida sit amet
ipsum eget maximus. Mauris condimentum "
"sem porta, aliquet mi ut, fringilla erat. Nunc maximus, magna ac
volutpat mattis, tellus mi dignissim "
"dolor, vel rutrum nulla risus quis quam. Vestibulum ante ipsum
primis in faucibus orci luctus et ultrices "
"posuere cubilia Curae; Integer ut urna nunc. Morbi id iaculis
augue. "
"Proin malesuada scelerisque massa et tristique. Sed blandit nisi
nunc, nec euismod nulla dignissim eu. "
"Pellentesque consequat mauris eu augue blandit, quis consectetur
urna convallis. Phasellus eget molestie "
"libero, ac hendrerit eros. Quisque ut tellus sed metus finibus
dictum. Nullam rhoncus, purus ac finibus "
"placerat, sapien sapien maximus nunc, a tempor lorem mauris eu
eros. Integer gravida est eget lacinia "
"aliquam. Phasellus sem urna, varius ac quam a, fringilla vehicula
neque. Duis faucibus purus arcu, ac "
"vehicula mauris lacinia quis. Nunc vel dolor non ex luctus
efficitur quis in leo. Sed vehicula lectus sit "
"amet ante commodo luctus. Etiam ac ullamcorper turpis, ac ornare
urna. "
"Nulla sit amet posuere eros, eget viverra dolor. Suspendisse
potenti. Mauris scelerisque mauris id lectus "
"auctor ultrices. Vivamus sodales malesuada erat, in ornare felis
auctor id. Curabitur at quam pellentesque, "
"pharetra sem a, pulvinar magna. Integer nisl mi, rhoncus eget urna
eget, posuere accumsan risus. In nisi est, "
"condimentum vel ornare sit amet, semper ut nunc. Nam risus leo,
maximus eu aliquet non, fringilla id ligula. In "
"metus ipsum, gravida in lectus eget, aliquam egestas ipsum. Fusce
placerat cursus mi ultrices luctus. Maecenas eu "
"ipsum diam. Nullam nec augue a diam rhoncus lobortis at id sapien.
Ut in erat laoreet, porta nunc quis, luctus "
"justo. Pellentesque dictum sit amet mauris et sodales. Morbi
fermentum sem hendrerit, hendrerit ex eu, laoreet sem. "
"Nam at tristique quam. Aliquam erat volutpat. Quisque rhoncus
augue a luctus hendrerit. Pellentesque at eros "
"ut nulla volutpat ullamcorper. Curabitur varius nisl hendrerit est
rhoncus suscipit. Duis gravida erat sit "
"amet nunc maximus laoreet. Cras dictum quam eu pellentesque
commodo. Phasellus non mauris non dolor tincidunt "
"ultrices et in eros. Aenean quis enim mollis, aliquet lorem a,
commodo leo. Phasellus elementum quis quam "
"eget condimentum. Nam convallis, enim id faucibus ornare, augue
erat rhoncus eros, at vehicula lacus mi sit amet "
"leo. Mauris libero mi, commodo blandit consectetur et, bibendum id
magna. In hac habitasse platea dictumst. "
"Sed in diam ut neque pretium gravida. "
"Nullam venenatis elit nec quam lobortis, nec rutrum justo
ullamcorper. Pellentesque eleifend lacus elit, "
"nec gravida purus lacinia in. Cras imperdiet, dui in elementum
feugiat, est mauris dignissim quam, in facilisis "
"purus lorem vel velit. Suspendisse potenti. Duis a venenatis enim.
Vestibulum vitae neque odio. Ut eget ex at "
"libero vehicula faucibus. "
"Integer placerat lobortis sem, a ullamcorper nunc pharetra quis.
Integer id consequat mauris, ac rhoncus "
"purus. Nunc sit amet sodales ante, eget rutrum odio. Nullam
elementum pretium velit et facilisis. Duis "
"porttitor quam a pharetra ullamcorper. Donec sollicitudin blandit
sem, ut rhoncus leo feugiat in. Morbi quis "
"dui a massa sagittis mattis. Curabitur malesuada, eros nec
pharetra fermentum, diam nulla euismod nulla, "
"rutrum hendrerit mi nisi feugiat est. Vivamus diam est, iaculis et
orci non, fringilla hendrerit nulla. Etiam "
"consectetur eros libero, a ultrices magna blandit quis. Proin eu
augue vel ante convallis viverra et sodales "
"magna. Nullam ullamcorper arcu at justo lobortis, at malesuada
risus gravida. Curabitur sapien est, tristique "
"in varius eget, consequat a leo. ")
In: Computer Science
Following a rather lengthy but stringent interview process, you have been selected as the project manager for the âWeb-Enhanced Communications Systemsâ Project. You have previous project management and systems analysis experience within the company with some experience in web technology. You wasted no time and started to put the project team together. You knew you would have to develop a survey to solicit input from all the relevant stakeholders with regards to the new system and make sure it meets the intended purpose for which this project is undertaken. BMHS has enlisted the service of Mark McGrath, a reputable web consultant for his advice and expertise. Mark has agreed to come in 2 hours a week for the first 3 months and then as and when required as the project progresses. The project team is required to work closely with him to tap the most out of this engagement â after all, he charges $200 an hour! Recall from running case 1 that this initiative is to develop a Web-based application to improve development and delivery of products and services. BMHS Board of Directors is very enthusiastic about this project and has approved a $2 million budget for this project. It is estimated that this system would save the company about $1.5 million each year for four years after implementation. It will also have the potential to significantly improve customer service and expand BMHS customer base. The system is estimated to take one year to complete with an estimated ballpark figure of $2 million to develop and an additional 10 percent of development costs ($200,000) each year to maintain over the next 4 years. Through the convergence of Web technology, wireless networks, and portable client devices, the system will be able to leverage Internet connectivity to support communications services and boost its âweb presenceâ for people, places and things. In addition, BMHS directorsâ strategic vision is to be the leader in health research and development as well as in the forefront in providing community health services. In particular, it is envisaged that this web-enhanced health communication system would: ⢠Allow customers and suppliers to provide suggestions, enter orders, view the status and history of orders, ⢠Allow customers and suppliers to use electronic commerce capabilities to purchase and sell their products. ⢠Allow Web-based communication between employees, customers, and suppliers in order to improve development and delivery of health care products and services.Provide a platform for health and scientific research where the medical community could collaborate and foster research and innovation. Support delivery of health care services to indigenous communities in remote places throughout Australia. (By allowing medical specialists to interact with Aboriginal health workers or remote local health care providers using web-supported videoconferencing and related technologies.) After consultation with experts and users, you have drafted out the following attributes and points to consider. You are planning to discuss these with your team in your next meeting: ďˇ The Web-Enhanced Communications Systems will be launched in the BMHS standard business theme built in the Drupal content management system (CMS) and work across mobile, tablets, and other devices. ďˇ Ensure adherence to BMHS policies and standards for the web, including accessibility, brand policy, and security. ďˇ The system will use the BMHS Bios System for shared bios which means information entered once will appear in multiple places; ďˇ Thoughts have to be put into site organisation, website strategy, and content advisement to make the website user-friendly and meet audience needs and organisational goals ďˇ Ease of use for users of the system and consistency in user experience across the different interface, making it easier for audience to find information without the need to learn how to navigate each page/site ďˇ Ease of use for non-technical content contributorsâthe content management system (CMS) should use a WYSIWYG editing tool, similar to Microsoft Word. As such, knowledge of HTML and other web programming skills is not required to update the sites. This helps ensure that the site will be maintained after its initial launch by administrative support and other job functions typically tasked with making updates to unit websites. ďˇ Ensure that website hosting and technical infrastructure does not violate the Australian privacy act as well as the HIPAA as BMHS has dealings with their US counterparts. (HIPAA = Health Insurance Portability and Accountability is United States legislation that provides data privacy and security provisions for safeguarding medical information.) ďˇ The site for the system will use responsive design, meaning they The site for the system will use responsive design, meaning they will adapt to new technology and screen sizes and thus works seamlessly on mobile and other devices. ďˇ Training and support for content contributors as well as staff using the system. It would probably be ideal to have online manuals and interactive online tutorials for remote users.
***Develop a requirements traceability matrix for the âWeb-Enhanced Communications Systemsâ Project. You should include at least eight requirements, identifying whether it is functional or non-functional requirements.
In: Computer Science
The function 'make_enzyme_threads' has a memory bug. Fix this by simply re-ordering the lines in this function. It is simple fix but may take a while for you to find it. As a hint, you may want to pay attention to the addresses of the pointers that are passed to the individual enzymes
#include "enzyme.h"
int please_quit;
int use_yield;
int workperformed;
// The code executed by each enzyme.
void *run_enzyme(void *data) {
/* This function should :
1. Cast the void* pointer to thread_info_t* (defined in
enzyme.h)*/
thread_info_t *inp;
inp = (thread_info_t *)(data);
/*2. Initialize the swapcount to zero*/
int swapcount = 0;
/*3. Set the cancel type to PTHREAD_CANCEL_ASYNCHRONOUS (see pthread_setcanceltype)*/
void *cancel_type = PTHREAD_CANCEL_ASYNCHRONOUS;
/*4. If the first letter of the string is a C then call
pthread_cancel on this thread.
(see also, pthread_self)
Note, depeneding on your platform (and specifically for macOS) you
have
to replace the call to pthread_cancel with
pthread_exit(PTHREAD_CANCELED) in order to make the cancel
test
pass.*/
if (s[0]) == 'C')
pthread_cancel(pthread_self());
/*5. Create a while loop that only exits when please_quit is
nonzero
6. Within this loop: if the first character of the string has an
ascii
value greater than the second (info->string[0] >
info->string[1]) then
- Set workperformed = 1
- Increment swapcount for this thread
- Swap the two characters around
7. If "use_yield" is nonzero then call pthread_yield at the end of
the loop.
8. Return a pointer to the updated structure.
*/
while (please_quit == 0) {
if (s[0] >s[1]) {
workperformed = 1;
threadswapcount++;
char c;
c = s[0];
s[0] = s[1];
s[1] = c;
}
if (use_yield != 0)
pthread_yield(pthread_self());
}
while(0) {
pthread_yield();
};
return NULL;
}
// Make threads to sort string.
// Returns the number of threads created.
// There is a memory bug in this function.
int make_enzyme_threads(pthread_t * enzymes, char *string, void
*(*fp)(void *)) {
int i, rv, len;
thread_info_t *info;
len = strlen(string);
info = (thread_info_t *)malloc(sizeof(thread_info_t));
for (i = 0; i < len - 1; i++) {
info->string = string + i;
rv = pthread_create(enzymes + i, NULL, fp, info);
if (rv) {
fprintf(stderr,"Could not create thread %d : %s\n", i,
strerror(rv));
exit(1);
}
}
return len - 1;
}
// Join all threads at the end.
// Returns the total number of swaps.
int join_on_enzymes(pthread_t *threads, int n) {
int i;
int totalswapcount = 0;
//initialize the cancelled count
int cancelcount = 0; // just to make the code
compile
// you will need to edit the code below
for (i = 0; i<n; i++) {
void *status;
int rv = pthread_join(threads[i],
&status);
/*if join status is non zero, then
cant join the threads
Thus the condition is to check
whether rv estimated
Above has a non zero value*/
if (rv != 0)
{
fprintf(stderr, "Can't join thread %d:%s.\n", i,
strerror(rv));
continue;
}
//if status is
PTHREAD_CANCELED
if ((void*)status ==
PTHREAD_CANCELED)
{
//increment the
cancelled count
cancelcount++;
continue;
}
else if (status == NULL)
{
printf("Thread
%d did not return anything\n", i);
}
else
{
printf("Thread
%d exited normally: ", i);// Don't change this line
//need to cast the status with
thread_info_t
//and then get the swap count as thread swap
count
int
threadswapcount = (thread_info_t *)status->swapcount;
// Hint - you
will need to cast something.
printf("%d
swaps.\n", threadswapcount); // Don't change this line
totalswapcount
+= threadswapcount;// Don't change this line
}
}
return totalswapcount;
}
/* Wait until the string is in order. Note, we need the
workperformed flag just
* in case a thread is in the middle of swapping characters so that
the string
* temporarily is in order because the swap is not complete.
*/
void wait_till_done(char *string, int n) {
int i;
while (1) {
pthread_yield();
workperformed = 0;
for (i = 0; i < n; i++)
if (string[i] > string[i + 1]) {
workperformed = 1;
}
if (workperformed == 0) {
break;
}
}
}
void * sleeper_func(void *p) {
sleep( (int) p);
// Actually this may return before p seconds because of
signals.
// See man sleep for more information
printf("sleeper func woke up - exiting the program\n");
exit(1);
}
int smp2_main(int argc, char **argv) {
pthread_t enzymes[MAX];
int n, totalswap;
char string[MAX];
if (argc <= 1) {
fprintf(stderr,"Usage: %s <word>\n",argv[0]);
exit(1);
}
// Why is this necessary? Why cant we give argv[1] directly to
the thread
// functions?
strncpy(string,argv[1],MAX);
please_quit = 0;
use_yield = 1;
printf("Creating threads...\n");
n = make_enzyme_threads(enzymes, string, run_enzyme);
printf("Done creating %d threads.\n",n);
pthread_t sleeperid;
pthread_create(&sleeperid, NULL, sleeper_func, (void*)5);
wait_till_done(string, n);
please_quit = 1;
printf("Joining threads...\n");
totalswap = join_on_enzymes(enzymes, n);
printf("Total: %d swaps\n", totalswap);
printf("Sorted string: %s\n", string);
exit(0);
}
In: Computer Science
Question 1:
Some people are more susceptible to hypnosis than others. People who are highly suggestible have a vivid imagination and fantasy life. This has led researchers to hypothesize that the ability to recall dreams will also be affected by hypnotic susceptibility (HS). Dr. Flowers wanted to test this hypothesis. Using the Stanford Scale of Hypnotic Susceptibility, she assigned participants to low, medium, and high susceptibility groups. Dr. Flowers asked all participants to keep a dream diary. At the end of 1 month, the diaries were collected and Dr. Flowers counted the number of dreams each person had recalled.
What is the alternative research hypothesis for this study?
What is the null research hypothesis for this study?
What is the first word in the alternative statistical hypothesis for any experiment with three levels of a single IV?
What is the null statistical hypothesis for the study of dream recall among groups with different levels of hypnotic susceptibility?
ÎźlowHS = ÎźmedHS = ÎźhighHSÎźlowHS = ÎźmedHS = ÎźhighHS
ÎźlowHS â ÎźmedHS â ÎźhighHSÎźlowHS â ÎźmedHS â ÎźhighHS
In SPSS, analyze the data in the table using a one-way ANOVA.
|
Low HS |
Medium HS |
High HS |
|
4 |
14 |
22 |
|
9 |
12 |
26 |
|
6 |
3 |
13 |
|
8 |
26 |
20 |
|
14 |
15 |
27 |
|
16 |
19 |
19 |
|
8 |
17 |
16 |
|
10 |
5 |
14 |
Use the results in the output box labeled Descriptives to complete the following chart, which you will then use to answer the following 6 questions.
|
Low HS |
Med HS |
High HS |
|
|
Mean |
|||
|
SD |
What is the mean of the low HS group? (2 decimal places)
What is the mean of the medium HS group? (2 decimal places)
What is the mean of the high HS group? (2 decimal places)
What is the SD of the low HS group? (2 decimal places)
What is the SD of the medium HS group? (2 decimal places)
What is the SD of the high HS group? (2 decimal places)
Using the results in the output box labeled ANOVA, answer the next two questions.
What is the F ratio reported in the source table? (2 decimal places)
What is the p value reported in the source table? (located in the column labeled Sig)(3 decimal places)
In SPSS, conduct a post hoc test using Tukey's HSD to determine which groups differ significantly.
Complete the chart below to help you answer the following 6 questions.
|
Low vs. Med. |
Low vs. High |
Med. vs. High |
|
|
Mean difference (absolute value) |
|||
|
p value |
What is the absolute value of the mean difference between the low and the mediumhypnotic susceptibility conditions? (2 decimal places)
What is the absolute value of the mean difference between the low and the high hypnotic susceptibility conditions? (2 decimal places)
What is the absolute value of the mean difference between the medium and the high hypnotic susceptibility conditions? (2 decimal places)
What is the p value for the comparison between the low and the medium hypnotic susceptibility conditions? (3 decimal places)
What is the p value for the comparison between the low and the high hypnotic susceptibility conditions? (3 decimal places)
What is the p value for the comparison between the medium and the high hypnotic susceptibility conditions? (3 decimal places)
What are the F-obtained values?
What are the between-groups MS? (3 decimal places)
What are the within-groups MS? (3 decimal places)
What are the significance levels?
Which component of the F ratio is affected by the distance between the mean?
|
MSbetween (the numerator) |
|
|
MSwithin (the denominator) |
Which component of the F ratio is affected by the amount of variability within the group?
|
MSbetween (the numerator) |
|
|
MSwithin (the denominator) |
Which component of the F ratio is affected by the amount of variability within the group?
|
MSbetween (the numerator) |
|
|
MSwithin (the denominator) |
Write a complete APA-style conclusion.
This is a template you will use to report the results of Experiment 1 of this study in the same format in which you would write the Results section of an APA-style lab report or journal article:
Based on a one-way ANOVA conducted in SPSS (Version 25), hypnotic susceptibility (HS) does /does not have an effect on the number of dreams recalled, F(#,##) = ###, p= ###. Tukeyâs post hoc tests revealed that fewer / the same number of / more dreams are recalled in the high HS condition (M= ###) than / as in the low HS condition (M= ###), p= ###. There is a / no significant difference between the number of dreams recalled in the low HS condition and the medium HS condition (M= ###), p= ###. There is also a / no significant difference between the number of dreams recalled in the medium HS condition and the high HS condition, p= ###. Therefore, the results confirm that high HS is associated with fewer / the same number of / more dreams being recalled when compared to those with low HS.
In: Math