Free

Final exam - Assignment Example

Comments (0) Cite this document
Summary
Since python relies on indentation in order to recognize program structure, a clear way to identify indentation is required. 4 spaces per indentation, it maintains consistency and…
Download full paperFile format: .doc, available for editing
GRAB THE BEST PAPER96.2% of users find it useful
Final exam
Read TextPreview

Extract of sample "Final exam"

CS 120 Final Exam - Part ____________________ Fall Take-home - individual work only Carefully define the following Python terms:
a. variable - This is a reserved memory location that is used to store values, these values that can be changed at a later time
b. function - A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
c. list-  It is a data type used to store a collection of different pieces of information as a sequence under a single variable name.
d. file - file is a place on disk where a group of related data is stored
2. For each of the candidate Python variable names listed below, state whether each is valid or invalid. If invalid, state the reason why.
a. 3rdBase- Base three uses digits 0, 1, 2. Otherwise if other digits will be used other than the stated ones, then the base will be regarded as invalid.
b. total$cost- valid
c. Top_Gun- valid
d. Range- valid
3. a. What is the main difference between definite iteration and indefinite iteration?
- Definite iteration is an iteration which has repeated sequence operations for a fixed number of repetitions in a cycle while indefinite iteration has no calculated cycle prior of execution.
b. What Python keyword is used most often for definite iteration?
- for
4. List two of the most effective ways to make your Python source code easier to read.
a. write one statement per line.
b. Put spaces around assignments and comparisons and avoid mixing tabs and spaces.
5. How does the output of print ("2 + 3", 4) differ from print(2 + 3, 4) in a Python print statement?
"2 + 3" is a string variable and hence will output it as a string while in the second case, 2+3, ‘4’ will print integer 5 four times.
6. If X = 15, what is the resulting value of Y in the following Python statements?
a. Y = (X % 8) // 3
Y=3
b. Y = (X - 5)**2 - 3*X
Y= - 5
c. Y = (X - 6.0) / 2.0
Y=4.5
d. Y = (X - 10)*(X - 20) / 5
Y= -5
7. Describe all errors in each of the following Python code fragments:
a. Q = "123"
Q = Q * 4
Q = Q + 56
Q is a string as declared in Q= “123”. Therefore Q= Q*4 and Q= Q+ 56 will lead to syntax error since the action required for the second and third case is an integer operation.
b. Y = {1, 2, "buckle", "my"}
append("shoe")
Y.sort
The term “shoe” has not been declared initially hence the sorting can’t be done.
c. sum = 0.0
for n in range(1,5)
sum = sum + 1.0/(5-n)
The sum has been declared to be 0.0 as a constant.
8. When adding a new value to a Python list, what is the difference between using insert versus append?
- The append method adds a single item to the end of the list, while insert is used to add an object or element in a list.
9. Since comments are ignored by the Python compiler, why bother to put comments in your code?
-Python has its own commenting syntax and incorrect commenting syntax leads to code that throws errors and won’t compile. Comments help you remember the purpose of a function.
10. Describe two motivations for defining functions in programs.
a. Easier to maintain – while using functions changes can easily be made to a specific
module rather than the whole module, this also reduces memory requirement.
b. Software Reusability - Use existing modules as building blocks to create new programs.
11. Write one or more Python statements to perform the following computations separately. Assume that all necessary variables or objects have already been defined and given an initial value..
a. Check if an integer N is divisible by 5 and is less than 100.
n = 0
s = 0
while (n < 100):
x = n/5
if isinstance(x, (int, long)):
print Multiple of 5!
s = s + n
if False:
y = n/5
if isinstance(y, (int, long)):
s = s + n
print Number:
print n
print Sum:
print s
n = n + 1
b. Check if a string S contains any digits.
import string
def containsNumber(line):
res = False
try:
for val in line.split():
if (float(val.strip(string.punctuation))):
res = True
break
except ValueError, e:
pass
return res
c. Calculate a random floating point number X between 2.5 and 7.5 (inclusive).
import random
for i in xrange(5):
print %04.3f % random.uniform(2.5, 7.5)
d. Open a file called Prices.txt for reading. The file contains one numeric data value per line.
12. a. What is the purpose of a sentinel in data entry?
The purpose of a sentinel is to signify the end of the input session.
b. Give an example.
print("Welcome to this accumulating program")
SENTINEL = -555
total = 0
entry = int(input("Enter a number (Enter -555 to quit): ")
while entry != SENTINEL:
total += entry
entry = int(input("Enter another number (Enter -555to quit): ")
print ("The total of the numbers entered: ", total)
The goal of the loop is to execute the loop until that one particular sentinel value is executed.
13. Given the initial strings: S1 = "Dark", S2 = "Chocolate!". Evaluate the following expressions.
a. S1.upper() + " " + S2[:]
Prints Dark and then space then Chocolate!
b. S1[2] + S2[6:9]
Add string one to string 2 from the sixth to 9th cycle.
d. S2.rfind("o") + len(S1)
Returns a pointer to the first occurrence of string s2 in string s1
14. What is the best choice for the number of spaces to indent in Python? Justify your answer.
The best choice is 4 spaces per indentation level. Since python relies on indentation in order to recognize program structure, a clear way to identify indentation is required. 4 spaces per indentation, it maintains consistency and helps a user to have a clear flow of code.15. In Python, how do you terminate a while loop?
Use a break statement
16. What is reason for red comments when you try to run your Python code in IDLE?
These are runtime errors. Runtime errors occur as your program executes. Since Python is an interpreted language, these errors will not occur until the flow of control in your program reaches the line with the problem.
17. Which section in the textbook is the hardest to read, or makes the least sense?
The section on loops.
18. The hailstone sequence is generated by starting with a positive integer X and repeatedly applying the following calculations on X until reaching 1:
if X is even: X = X/2
if X is odd: X = 3X + 1
Write a Python function hailstone(X) in which the return value is the number of iterations to reach 1 (i.e. the first index in the sequence to equal 1, with X at index 0). For example, if X is 10, the sequence is 10,5,16,8,4,2,1. The return value would be 6.
(defun hailstone (len)
(loop for x = len
then (if (evenp x)
(/ x 2)
(+ 1 (* 3 x)))
collect x until (= x 1)))
 
;; Must be tail recursive
(defun max-hailstone-start (limit mx curr)
(declare (xargs :mode :program))
(if (zp limit)
(mv mx curr)
(let ((new-mx (len (hailstone limit))))
(if (> new-mx mx)
(max-hailstone-start (1- limit) new-mx limit)
(max-hailstone-start (1- limit) mx curr))))) Read More
Cite this document
  • APA
  • MLA
  • CHICAGO
(“Final exam Assignment Example | Topics and Well Written Essays - 500 words - 2”, n.d.)
Final exam Assignment Example | Topics and Well Written Essays - 500 words - 2. Retrieved from https://studentshare.org/information-technology/1671575-final-exam
(Final Exam Assignment Example | Topics and Well Written Essays - 500 Words - 2)
Final Exam Assignment Example | Topics and Well Written Essays - 500 Words - 2. https://studentshare.org/information-technology/1671575-final-exam.
“Final Exam Assignment Example | Topics and Well Written Essays - 500 Words - 2”, n.d. https://studentshare.org/information-technology/1671575-final-exam.
  • Cited: 0 times
Comments (0)
Click to create a comment or rate a document

CHECK THESE SAMPLES OF Final exam

Final exam

...? Final Exam Final Exam Question Some organizations have a strategic management processin place while many don’t. Suppose you are working as a consultant, how would you convince an organization that a strategic management system will help them improve public services? According to Lamb (1984), strategic management is a continuous process that controls and evaluates the business undertaken by the organization, evaluates the potential of its competitors of the organization, and it specifies goals and strategies for the organization in order to enable it to face the threats posed by the competitors, and then re-evaluates the efficiency and effectiveness of the strategy on a...
4 Pages(1000 words)Assignment

Final exam

... Questions Compare and contrast the effectiveness of survey and ethnography research as a strategy of data collection. If you have to perform one or another what would be the most appropriate sampling technique you would follow? Why? Research is a source of answers to various questions that we ask in our everyday lives. It is a significant source of information if it is executed well. It is a process in which measurements are taken of organizations or individuals, and the resulting data is subjected to analysis and interpretation. Usually, research aims to provide an accurate answer to the posed research question by using the various research methods. According to Green and Dixon (1), the foundation of research is evidence... Questions...
6 Pages(1500 words)Essay

Final Exam

... Questions and Answers The benefits of knowing more than one language are quite many but the most important one is the ability to interact with different people from different cultures. Application of this advantage is found in international jobs where some employees employ bilingual or multilingual individuals. Knowledge of another language apart from the mother tongue usually confers competitive advantage on an individual when applying for a job. This is because the world has become globalized and the business world deals with clients from all over the globe hence necessitating the need for more than one language knowledge. In this regards, one is assured of job security because of knowing another language. Knowledge of another... Questions ...
4 Pages(1000 words)Assignment

Final Exam

... submitted History and Political Science Introduction Jose Ortega y Gasset wrote a famous book, The Revolt of the Masses,which represents his most fundamental deliberations concerning European integration. The work tries to characterize the consequences of Revolt regarding political unification of Europe. This paper highlights on numerous issues surrounding the work of Ortega. This book served many people in different nations, however, its effects was greatly felt for European supranational unity. To some extent, Ortega’s work is controversial in Spain and many other nations. In Spain, it highlighted on the controversy over the alleged elitism of Revolt and the French did not welcome Ortega’s reasoning or philosophical views... submitted...
4 Pages(1000 words)Essay

Final exam

...in navigating the essay. For instance, in the fourth paragraph, I wrote: “After discussing Witty’s article, the paper explores Calhoun’s text…” (5). Through these transitions, I prepared readers on what they will expect next, by connecting every paragraph to the thesis and the past paragraph. Moreover, within each paragraph, I made use of the right conjunctions to ensure the smooth flow of my ideas. To illustrate, I used the words “moreover” and “also” to connect these claims that support each main point. These transitions sentences helped me organize my ideas and ensured consistency in presenting and arguing my thesis. The final strength of the essay is its clear description of the photo’s meaning and implications to...
3 Pages(750 words)Essay

Final Exam

... The Green Move Company: Legal and Ethical Issues A1. The new product being produced at Green Move is a hazard to theusers of the product (Sheerow 15). The Zero Pedal accelerates dangerously once exposed to high temperatures for four consecutive hours. The fact that the person you are replacing was fired after he told his bosses about the defect shows that your revealing this defect could cost me my job. On the other hand however, exposing my customers to such a risk is illegal because if one of them dies during cycling, then they shall sue the company. This is not to mention the fact that human life is more precious than the zero pedals. The board has proved to be rather rigid when dealing with this matter. Whichever way I look... The Green...
10 Pages(2500 words)Essay

Final Exam

...1. Supporters contend the Sabanes-Oxley Act of 2002 was necessary and has played a useful role in restoring public confidence in the nation’s capital markets by, among other things, strengthening corporate accounting controls. Opponents claim it has reduced America’s international competitive edge against foreign financial service providers, saying SOX has introduced an overly complex regulatory environment into U.S. financial markets (Gale, n.p.). It does not seem fair that senior executives take individual responsibility for the accuracy and completeness of corporate financial reports. Although the act adds responsibility for the chief executives it benefit’s the public shareholders and protects them from unethical business... Supporters...
7 Pages(1750 words)Essay

Final exam

... fit with new recruits” (Fisher, 2007). Employment Interviews The selection committee would call the candidates for the interviews, who would pass the written tests. The interviews would help the company determine confidence of the candidates along with their verbal and nonverbal communication skills. Issuance of Appointment Letters This would be the last stage of the employee selection process. The selection committee would analyze all aspects of every candidate’s performance and would send the summary of each candidate’s performance to the higher authorities along with the recommendation letters. Finally, the HR department would send appointment letters to the selected employees. Training Issue - Priority No. 5 Training is one...
5 Pages(1250 words)Essay

Final Exam

... Final Exam What is your moral responsibility, if any, as a citizen of an affluent nation toward alleviating severe poverty in the world? In extreme poverty, individuals from affluent nations have the ability to save people in situations that are life threatening due to absolute poverty. By donating fifteen cents, they can help a child in extreme poverty get oral rehydration salts that could save its life while a twenty-five cent donation could purchase antibiotics for respiratory infections. Individuals from affluent nations have the lifestyle that gives them the capacity to give much more than these fifteen or twenty five dollars. Just as, one is obligated morally to save a child from drowning, the capacity to help people... war...
2 Pages(500 words)Essay

Final Exam

...Final Exam: Essay Questions Question Norton Long focused on public administration particularly the administrative power. Long argued that power is a very essential element in administration and this power is the force behind administration’s existence. In his work, Power and Administration, Long posits that administrative institutions including public agencies and bureaus are involved in a battle for political survival (Stillman 2010, p.97). For instance, the bureaucrats struggle for limited power resources from interest groups and others to sustain their organizations. Long argues further that the attainment, maintenance, increase and decrease of power are very important aspects that people cannot neglect. According to Long... Exam: Essay...
4 Pages(1000 words)Essay
sponsored ads
We use cookies to create the best experience for you. Keep on browsing if you are OK with that, or find out how to manage cookies.

Let us find you another Assignment on topic Final exam for FREE!

Contact Us