Re-Exam 1 Practice Problems

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

M The University Of Michigan Andrew M. Morgan EECS Lecture 01 Savitch Ch. 2 C++ Basics Flow Of Control.
Introduction to C Programming
Lecture 6 Strings and more I/O COMP1681 / SE15 Introduction to Programming.
Chapter 7: Arrays In this chapter, you will learn about
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Monday, Jan 20, 2002Kate Gregory with material from Deitel and Deitel Week 3 Questions from Last Week Hand in Lab 1 Arrays Pointers Strings Lab 2.
CMPT 120 Control Structures in Python
1 Review Quisioner Kendala: Kurang paham materi. Praktikum Pengaruh teman.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Complexity Analysis (Part II)
Standard Algorithms Find the highest number. ! Your name and today’s date ! Find the maximum Dim numbers(20) As Integer.
Computer Programming w/ Eng. Applications
CS110 Programming Language I
Analysis of Algorithms
 2000 Prentice Hall, Inc. All rights reserved Fundamentals of Strings and Characters String declarations –Declare as a character array or a variable.
1 Various Methods of Populating Arrays Randomly generated integers.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 8 - Characters and Strings Outline 8.1Introduction.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
CS 1400 Chapter 5, section 2. Loops! while (rel-expression)while (rel-expression) {statements statement } if the relational-expression is true, execute.
Working with the data type: char  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming.
1 Key Concepts:  Data types in C.  What is a variable?  Variable Declaration  Variable Initialization  Printf()  Scanf()  Working with numbers in.
1 Introduction to Computers and Programming Class 3 Introduction to C Professor Avi Rosenfeld.
ISAT 252 Introduction to Arrays. Should have read 2 Chapter 8 –pp , and pp
CS 127 Writing Simple Programs.  Stages involved  Analyze the problem  Understand as much as possible what is trying to be solved  Determine Specifications.
C programming for Engineers Lcc compiler – a free C compiler available on the web. Some instructions.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
C Programming n General Information on C n Data Types n Arithmetic Operators n Relational Operators n if, if-else, for, while by Kulapan Waranyuwat.
CS 108 Computing Fundamentals Notes for Thursday, February 19, 2015.
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
Advanced Computer Science Lesson 4: Reviewing Loops and Arrays Reading User Input.
Count and add list of numbers From user input and from file.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
***** SWTJC STEM ***** Chapter 7 cg 68 What Are Arrays? An array is a simple but powerful way to organize and store large amounts of data and information.
CS140: Intro to CS An Overview of Programming in C by Erin Chambers.
Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed.
1 Programming 2 Overview of Programming 1. Write the equations in C++ notation : a) R =   a + b  24  2 a  b) W = a 12 + b 2 – 2abcos(y) 2a.
Homework #2: Functions and Arrays By J. H. Wang Mar. 20, 2012.
How to design and code functions Chapter 4 (ctd).
Validation final steps Stopping gaps being entered in an input.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
Arrays. The array data structure Array is a collection of elements, that have the same data type Integers (int) Floating point numbers (float, double)
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
Data Types and Conversions, Input from the Keyboard CS303E: Elements of Computers and Programming.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
Data Types and Conversions, Input from the Keyboard If you can't write it down in English, you can't code it. -- Peter Halpern If you lie to the computer,
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Python: Experiencing IDLE, writing simple programs
Chapter 8 - Characters and Strings
Computational Thinking
Computational Thinking
CS 1430: Programming in C++ Turn in your Quiz1-2 No time to cover HiC.
Introduction to C Topics Compilation Using the gcc Compiler
Class Examples.
Coding Concepts (Data- Types)
Arrays.
Building Java Programs
functions: argument, return value
Introduction to C Topics Compilation Using the gcc Compiler
String Processing 1 MIS 3406 Department of MIS Fox School of Business
Other types of variables
Question 1a) What is printed by the following Java program? int s;
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Data Types and Maths Programming Guides.
Presentation transcript:

Re-Exam 1 Practice Problems SOLUTIONS

1. The Konditorei coffee shop sells coffee at $10 1. The Konditorei coffee shop sells coffee at $10.50 a pound plus the cost of shipping. Each order ships at $0.86 per pound + $1.50 fixed cost for overhead. Write a program that inputs the number of pounds in an order and prints the total cost of the order, including shipping. n = float(input("Enter the number of pounds: ")) coffee_cost = 10.5*n shipping_cost = 1.50 + 0.86*n total = coffee_cost + shipping_cost print("Total cost, including shipping: ",total)

2. Write a program to compute the sum and average of a series of numbers values entered by the user. The program should first ask the user how many numbers there are. Then it should input the numbers one after another, then print their sum and average value. Your program should use a for loop. n = int(input("Enter a the number of values: ")) sum = 0 for i in range(n): sum += eval(input("Next number: ")) print("sum = ",sum,"; average = ",sum/n,sep='')

3. An acronym is a word formed by taking the first letters of the words in a phrase and making a word from them using all capital letters. For example, RAM is an acronym for "random access memory". Note that all the letters of the acronym are capital letters even in the words are lower-case. Write a program that allows the user to enter a phrase and prints the acronym for that phrase. phrase = input("Enter a phrase: ") words = phrase.split() acronym = "" for w in words: acronym = acronym + w[0].upper() print("Acronym for your phrase: ",acronym)

4. Numerologists claim to be able to determine a person's character traits based on the "numeric value" of a name. The value of a name is determined by summing up the values of the letters of the name where 'a' is 1, 'b' = 2, …,'z' = 26. Upper- and lower-case letters are treated as equal. For example, "Tindell" would have value 20+9+14+4+5+12+12 = 76, which happens to be a very auspicious number. Write a program that prints the numeric value of a name entered by the user. Solution I: name = input("Enter your last name: ") numval = 0 for ch in name: if ch.isalpha(): numval += ord(ch.lower())-ord('a')+1 print("The numerical value of your name is",numval)

4. Numerologists claim to be able to determine a person's character traits based on the "numeric value" of a name. The value of a name is determined by summing up the values of the letters of the name where 'a' is 1, 'b' = 2, …,'z' = 26. Upper- and lower-case letters are treated as equal. For example, "Tindell" would have value 20+9+14+4+5+12+12 = 76, which happens to be a very auspicious number. Write a program that prints the numeric value of a name entered by the user. Solution II: letters = " abcdefghijklmnopqrstuvwxyz" name = input("Enter your last name: ") numval = 0 for ch in name: if ch.isalpha(): numval += letters.index(ch.lower()) print("The numerical value of your name is",numval)

5. Write a program that counts and prints the number of words in a sentence entered by the user.. sentence = input("Enter a sentence: ") word_count = len(sentence.split()) print("Your sentence contains",word_count,"words") 6. Write a program that computes and prints the average length of the words in a sentence entered by the user. word_list = sentence.split() word_count = len(word_list) total_len = sum([len(w) for w in word_list]) print("The average word length is",total_len/word_count)

7. A common utility on Unix/Linux systems is a small program called wc 7. A common utility on Unix/Linux systems is a small program called wc. This program analyzes a file to determine the number of lines, words and characters contained therein. Write your own program to input a filename and print the three numbers produced by wc. Your program should define a function with parameter a file name that returns the line count, word count and character count for the file. def wc(fname): with open(fname,'r') as f: S = f.read() chars = len(S) words = len(S.split()) lines = len(S.splitlines()) return lines,words,chars fnom = input("Enter a file name: ") l,w,c = wc(fnom) print(l,"lines,",w,"words",c,"characters")

8. Write and test a function to meet this specification. SquareEach(nums) nums is a list of numbers. Modifies the list by squaring each entry def SquareEach(nums): for i in range(len(nums)): nums[i] = nums[i]*nums[i] # Test L = [1,2,3,4,5] print(L) SquareEach(L)

9. Write and test a function to meet this specification. sumList(nums) nums is a list of numbers. Returns the sum of the numbers in nums. def sumList(nums): sum = 0 for item in nums: sum += item return sum # Test L = [1,2,3,4,5] sum = sumList(L) print(sum9)

10. Write and test a function to meet this specification. toNumbers(strList) strList is a list of strings of digit characters. Modifies each entry of the list by converting it to an integer. def toNumbers(strList): for i in range(len(strList)): strList[i] = int(strList[i]) # Test L = ['1','2','3','4','5'] toNumbers(L) print(L)

11. Write and test a function innerProd(x,y) that returns the inner product of same-length lists x and y. The inner product of [x1, x2,…, xn] and [y1, y2,…, yn] is x1y1 + x2y2 + … + xnyn def innerProd(x,y): sum = 0 for i in range(len(x)): sum += x[i]*y[i] return sum # Test a = [1,2,3,4,5] b = [5,4,3,2,1] print(innerProd(a,b))

12. Most companies pay time and a half for any hours worked above 40 in a given week. Write a program to input the number of hours worked and the hourly rate, then prints the total wages for the week. hrs = eval(input("Enter hours worked this week: ")) rate = eval(input("Enter the hourly rate: ")) if hrs <= 40: pay = hrs*rate else: pay = 40*rate + 1.5*rate*(hrs-40) print("Total wages for the week:",pay)

13. The speeding ticket fine policy in Podunksville is $50 plus $5 for each mph over the limit plus a penalty of $200 for any speed over 90 mph. Write a program that inputs a speed limit and a clocked speed and either prints a message indicating the speed was legal or prints the amount of fine. limit = eval(input("Enter speed limit: ")) actual = eval(input("Enter clocked speed: ")) if actual <= limit: print("Speed OK, no fine") else: fine = 50+5*(actual-limit) if actual > 90: fine += 200 print("Amount of fine:",fine)

14. A formula for computing the date of Easter in the years 1982-2048, inclusive, is as follows. Let a = year % 19, b = year%4, c = year%7, d = (19*a + 24)%30, and e = (2*b+4*c+6*d+5)%7. The date of Easter is (d+e) days after March 22 (which could be in April). Write a program that inputs a year, verifies that it is in the proper range, and then prints the date of Easter that year. year = eval(input("Enter a year between 1982 and 2048: ")) if year < 1982 or year > 2048: print("Illegal date") else: a,b,c = year%19,year%4,year%7 d = (19*a+24)%30 e = (2*b+4*c+6*d+5)%7 days_after = d+e days = 22+days_after print("In year ",year,", Easter falls on",sep = "",end = " ") if days <= 31: print("March " +str(days)) print("April " + str(days-31))

15. Preceding Easter formula works for range 1900-2099 with the exception that it is a week later than the actual date for years 1954, 1981, 2049, and 2076. Modify your program to accept dates between 1900 and 2099. year = eval(input("Enter a year between 1900 and 2099: ")) if year < 1900 or year > 2099: print("Illegal date") else: a,b,c = year%19,year%4,year%7 d = (19*a+24)%30 e = (2*b+4*c+6*d+5)%7 days_after = d+e days = 22+days_after if year in [1954, 1981, 2049, 2076]: days -= 7 print("In year ",year,", Easter falls on",sep = "",end = " ") if days <= 31: print("March " +str(days)) print("April " + str(days-31))

16. Write a program that inputs a date in the form month/day/year (all integers) and prints a message indicating whether the date is valid. For example, 5/24/1962 is valid but 9/31/2000 is not (September has only 30 days). def is_leap_year(year): if year%4 != 0 or (year%100 == 0 and year%400 != 0): return False else: return True days_in_month=[0,31,28,31,30,31,30,31,31,30,31,30,31] datestr = input("Enter a date (month/day/year): ") m,d,y = (int(k) for k in datestr.split('/')) if is_leap_year(y): days_in_month[2] = 29 if m < 1 or m > 12: print("Invalid date") elif d > days_in_month[m]: print("Valid date")

17. You are to write a Python program that uses a while loop to determine how long it takes to double an initial investment with a fixed annual percentage rate. def years_to_double(start_amt,rate): years = 0 amt = start_amt while(amt < 2*start_amt): amt = (1+rate)*amt years += 1 return years a = float(input("Enter initial investment: ")) r = float(input("Enter the yearly interest rate: ")) d = years_to_double(a,r) print("Years to double your investment:",d)

18. A prefix atom of a list L of strings is a string A in L such that, for any string W in L, if W is a prefix of A, then W is equal to A. First write a function is_prefix_atom(L,A) that returns True if and only if A is a prefix atom of L. Then write a function prefix_atoms(L) that returns a list of the distinct prefix atoms of L sorted by increasing length. Next write a function prefix_dictionary(L) that returns a dictionary whose keys are the prefix atoms of L; and the value in the dictionary for prefix atom A is a list of the distinct strings in L having A as a prefix. Complete your program by prompting the user for a string and printing, for each prefix atom of the word list of S, the atom, A , the character : and then the list of words of S having A as a prefix. Each atom and list should be on a separate line.

18. A prefix atom of a list L of strings is a string A in L such that, for any string W in L, if W is a prefix of A, then W is equal to A. First write a function is_prefix_atom(L,A) that returns True if and only if A is a prefix atom of L. Then write a function prefix_atoms(L) that returns a list of the distinct prefix atoms of L sorted by increasing length. def is_prefix_atom(w,L): if w not in L: return False for u in L: if u != w and w.startswith(u): return True

18. A prefix atom of a list L of strings is a string A in L such that, for any string W in L, if W is a prefix of A, then W is equal to A. Next write a function prefix_dictionary(L) that returns a dictionary whose keys are the prefix atoms of L; and the value in the dictionary for prefix atom A is a list of the distinct strings in L having A as a prefix. def prefix_dictionary(L): D = {} X = {w for w in L if is_prefix_atom(w,L)} for w in X: D[w] = {u for u in L if u.startswith(w)} return D

18. A prefix atom of a list L of strings is a string A in L such that, for any string W in L, if W is a prefix of A, then W is equal to A. Complete your program by prompting the user for a string and printing, for each prefix atom of the word list of S, the atom, A , the character : and then the list of words of S having A as a prefix. Each atom and list should be on a separate line. S = input("Enter a string: ") L = S.split() D = prefix_dictionary(L) for A in D: print(A,':',','.join(D[A]))