Practice Question. Omar Khan / Atif Alvi. October 10, 2016

Similar documents
Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Addis Ababa University, Amist Kilo July 5, 2011 Algorithms and Programming for High Schoolers. Lab 2

Selection Statement ( if )

ANS:

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

Spring 2017 CS 1110/1111 Exam 2

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

Common Loop Algorithms 9/21/16 42

Test #2 October 8, 2015

CPSC 217 Midterm (Python 3 version)

Structure and Interpretation of Computer Programs

Basic Python Revision Notes With help from Nitish Mittal

3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >:

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Spring 2017 CS 1110/1111 Exam 1

Introduction to programming using Python

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Module 06. Topics: Iterative structure in Python Readings: ThinkP 7. CS116 Spring : Iteration

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

All written answers are limited to their question boxes. Make sure all answers are easily legible.

CSC A20H3 S 2011 Test 1 Duration 90 minutes Aids allowed: none. Student Number:

CS 1110: Introduction to Computing Using Python Loop Invariants

Midterm Exam 2A Principles of Computing Fall November 10, 2014

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Practical Questions CSCA48 Week 6

Midterm Exam 2B Answer key

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

List comprehensions (and other shortcuts) UW CSE 160 Spring 2015

The Big Python Guide

Python - Conditional Execution

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

More on Strings & Arrays

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

Lists, loops and decisions

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:

(Python) Chapter 3: Repetition

Short Answer Questions (40 points)

Functionally Modular. Self-Review Questions

CSC148 Fall 2017 Ramp Up Session Reference

There are three questions on this exam. You have 2 hours to complete it. Please indent your program so that it is easy for the grader to read.

Loops / Repetition Statements

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Issue with Implementing PrimeSieve() in Go

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

Programming Training

Types, lists & functions

Chapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements:

Fundamentals of Programming (Python) Getting Started with Programming

UTORid: Lecture Section: (circle one): L0101 (MWF10) L0201 (MWF11) Instructor: Jacqueline Smith Jen Campbell

Structure and Interpretation of Computer Programs

Title As It Is In the Proceedings Include Only If Paper Has a Subtitle. F. Author S. Another Freie Universität Berlin

Dynamic Programming. An Introduction to DP

Overview of List Syntax

CS 61A Control and Environments Spring 2018 Discussion 1: January 24, Control. If statements. Boolean Operators

Introduction to Mathematical and Scientific Programming TUTORIAL WEEK 2 (MATH 1MP3) Winter 2019

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19

Sequence Types FEB

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

Midterm I Practice Problems

Structure and Interpretation of Computer Programs

Python: common syntax

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

CS205: Scalable Software Systems

CS1110 Lab 6 (Mar 17-18, 2015)

Python for Finance. Control Flow, data structures and first application (part 2) Andras Niedermayer

Advanced Python. Executive Summary, Session 1

Statements 2. a operator= b a = a operator b

GWC Lesson 9 Partner Work and Comprehension

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

THE AUSTRALIAN NATIONAL UNIVERSITY Mid Semester Examination September COMP1730 / COMP6730 Programming for Scientists

mith College Computer Science Week 9 CSC111 - Fall 2018 Dominique Thiébaut

Flow Control: Branches and loops

CSCE 110: Programming I

Conditional Expressions and Decision Statements

CS-141 Final Exam Review December 8, 2017 Presented by the RIT Computer Science Community

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

RECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012

Scheme as implemented by Racket

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

COGS 119/219 MATLAB for Experimental Research. Fall 2016 Week 1 Built-in array functions, Data types.m files, begin Flow Control

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

Lecture #21: Search and Sets. Last modified: Wed Mar 9 15:44: CS61A: Lecture #21 1

Comp Exam 1 Overview.

PYTHON MOCK TEST PYTHON MOCK TEST III

York University AK/ITEC OBJECT-BASED PROGRAMMING. Midterm Test Sample. Examiner: S.Y. Chen Duration: One Hour and Fifteen Minutes

A453 Task 1: Analysis: Problem: Solution:

UNIT-II NUMBER THEORY

CSE 215: Foundations of Computer Science Recitation Exercises Set #4 Stony Brook University. Name: ID#: Section #: Score: / 4

Structure and Interpretation of Computer Programs

Spring 2017 CS 1110/1111 Exam 3

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Python for Non-programmers

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

CS-141 Final Exam Review May 16, 2015 Presented by the RIT Computer Science Community

Transcription:

Practice Question Omar Khan / Atif Alvi October 10, 2016 1

Chapter 1 Loops 1.1 While Loop Iterating through a string 1. Print the first 10 integers 1 i = 0 2 n = 10 3 while i<n: 4 print (i) 5 i = i + 1 6 print () 2. Print the first 10 integers in a row. : 1 i = 0 2 while i<n: 3 print (i, end =",") 4 i = i + 1 5 print () 3

3. Write code that prints the following pattern on the screen: * * * * * : 1 i = 1 2 while i<n: 3 j = 0 4 while j < i: 5 print (".", end =" ") 6 j = j + 1 7 print () 8 i = i + 1 9 print () 4. Write code that prints the following pattern on the screen: * : 1 i = 1 2 while i <=n: 3 j = 0 4 while j < i: 5 if j ==0 or j==i -1 or i==n: 4

6 print ("*", end =" ") 7 else : 8 print (" ", end =" ") 9 j = j + 1 10 print () 11 i = i + 1 12 print () 5. Write code to print the following pattern. You have to use nested while loops. * * * * : 1 i = 1 2 while i<n: 3 j = 0 4 while j < i %5: 5 print ("*", end =" ") 6 j = j + 1 7 print () 8 i = i + 1 9 print () 5

Chapter 2 Functions 1. Write a function isodd that return a True value if the input to it is an odd number and False value if the input number is even 1 def isodd (n): 2 return n %2==1 2. Write a function oddsinrange that takes two number l and u as input (you can assume that l u) and returns the number of odd number in the range l - u (l and u inclusive). Use the isodd function defined above. 1 def oddsinrange (l, u): 2 count = 0 3 while l < u: 4 if isodd (l): 5 count = count + 1 6 l = l + 1 7 return count 3. Write a function max4 that takes 4 numbers as input and returns the value of the largest. 1 def max4 (a, b, c, d): 2 maxval = a 3 if b > maxval : 4 maxval = b 5 if c > maxval : 6 maxval = c 7 if d > maxval : 8 maxval = d 9 return maxval 7

4. Write a function isprime that takes a positive integer as input and determines if the given number is a prime or not 1 def isprime (n): 2 if n <= 0 : 3 print (" Please use positive integers as input only ") 4 if n == 1 or n == 2: 5 return True 6 range = int (n /2) 7 i = 2 8 while i <= range : 9 if n %2==0: 10 return False 11 i = i + 2 12 return True 5. Write a function called dicen that takes a number n as input. The function when called should simulate the roll of a dice n times and return the ration of the times that the roll came up with the number 6 1 from random import randint 2 def dicen (n): 3 i = 0 4 count = 0 5 while i<n: 6 dice = randint (1,6) 7 if dice1 == 6: 8 count = count + 1 9 i = i + 1 10 return count / n 6. Write a function called dicesumratio that takes two positive integers n and total as input, simulates the roll of a pair of dice n times and returns the following ratio: 1 from random import randint 2 def dicesumratio (n, total ): 3 i = 0 4 count = 0 5 while i<n: 6 dice1 = randint (1,6) times that the sum of a roll is equal to total n 8

7 dice2 = randint (1,6) 8 if ( dice1 + dice2 ) == total : 9 count = count + 1 10 i = i + 1 11 return count / n Which sum do you expect to come up most often in a roll of a pair of dice? Can you write code that experimentally supports your answer? 7. Given the function below, show what values are printed for f(0), f(1), f(10). Describe the execution steps. 1 def f(a): 2 if a < 0: 3 return -1 4 n = a 5 while n > 0: 6 if n%2 == 0: 7 n = n //2 8 print (n) 9 elif n == 1: 10 print (n) 11 return 1 12 else : 13 n = 3 * n + 1 14 print (n) 15 return 0 a) For f(0) neither the condition for the if statement nor the condition for the while statement are true so the function just returns 0. b) For f(1) we enter the while loop and skip the condition with the if part and go into the body of the elif part. A value of 1 is printed and the function returns a value of 1 also. c) For f(10) the following evaluations take palce: i. n is even so n=n//2 is evaluated n becomes 5 and 5 is printed ii. In the next iteration of the while loop n is odd so n = 3 * n + 1 is evaluated n becomes 16. 16 gets printed iii. n is even so n=n//2 is evaluated n becomes 8 and 8 is printed iv. n is even so n=n//2 is evaluated n becomes 4 and 4 is printed v. n is now going to remain even until it becomes 1 at which point 1 gets printed and the function returns a value of 1. 9

The following thus gets printed: 5 16 8 4 2 1 10

Chapter 3 Strings 3.1 Iterative Questions Iterating through a string 1. Write a function called printstr that takes a string as an input parameter and prints out each element of the list on a separate line. 3 ways to do it are : 1 def printstr ( str ): 2 for c in str : 3 print (c) 1 def printstr ( str ): 2 for i in range ( len ( str )): 3 print ( str [i]) 1 def printstr ( str ): 2 i=0 3 while i<len ( str ): 4 print ( str [i]) 5 i = i + 1 Generating new strings from old 1. Write a function called punctuated that takes string s and a character c as input and prints a string that is the same as the input string s but with the character c between each adjacent letter 1 def punctuated (str, c): 2 for i in range ( len ( str ) -1): 11

3 print ( str [i], end =c) 4 print ( str [ -1]) Sample run 1 >>> punctuated ( Python, - ) 2 P-y-t-h-o-n 2. Write a function called rtnpunctuated that takes string str and a character c as input and returns a string that is the same as the input string str but with the character c between each adjacent letter 1 def punctuated (str, c): 2 rtnstr = 3 for i in range ( len ( str ) -1): 4 rtnstr = rtnstr + str [ i] + c 5 rtnstr = rtnstr + str [ i] 6 return rtnstr Sample run 1 >>> punctuated ( Python, - ) 2 P-y-t-h-o-n 3. Write a function called rtnsubstr that takes a string s and two integers starti and stopi as an input parameters and returns the substring represented by indices starti and stopi. 1 def rtnsubstr (s, starti, stopi ): 2 rtnstr = 3 for i in range ( starti, stopi +1) : 4 rtnstr = rtnstr + s[i] 5 return rtnstr Sample run 1 >>> rtnsubstr ( abracadabra, 3, 7) 2 acada 4. Write a function called prntfirstn that takes an integer n and a string as input and prints the first n characters of the string. If the string has fewer than n characters then print the message input list does not have enough elements. 12

1 def prntfirstn (n, str ): 2 if len ( str )<n: 3 print (" input string does not have enough elements ") 4 else : 5 for i in range (n): 6 print ( str [i]) 5. Write a function called prntlastn that takes an integer n and a str as input and prints the Last n members of the string. If the string has fewer than n elements then print the message input string does not have enough elements. 2 ways: 1 def prntlastn (n, str ): 2 if len ( str )<n: 3 print (" the input string does not have enough elements ") 4 else : 5 first = len ( str )-n 6 for i in range (first, len ( str )): 7 print ( str [i]) 1 def prntlastn (n, str ): 2 if len ( str )<n: 3 print (" the input string does not have enough elements ") 4 else : 5 first = len ( str )-n 6 for e in str [ first :]: 7 print (e) 6. Write a function prtrstr that prints the given string in reverse order. 1 def prtrlst ( str ): 2 i = len ( str ) -1 3 while i >=0: 4 print ( str [i], end = ) 5 i = i - 1 7. Write a function removechar that takes a string and a character as input and returns a string with all the instances of the character removed. 13

1 def removechar (istr, ic): 2 rstr = 3 for c in istr : 4 if c!= ic: 5 rstr = rstr + c 6 return rstr 8. Write a function replacechar that takes a string and two characters as input and returns a string with all the instances of the first character replaced by the second character. 1 def replacechar (istr, c1, c2): 2 rstr = 3 for c in istr : 4 if c== c1: 5 rstr = rstr + c2 6 else : 7 rstr = rstr + c 8 return rstr String Analysis 1. Write a function noofwords that takes a string and returns the number of words in that string. Words may be separated by multiple spaces! Do not use split. 1 def noofwords ( istr ): 2 readingaword = False 3 totalwords = 0 4 for c in istr : 5 if c == : 6 if readingaword : 7 readingaword = False 8 else : 9 if not readingaword : 10 readingaword = True 11 totalwords = totalwords + 1 12 return totalwords 14

Chapter 4 Lists 4.1 Iterative Questions Iterating through a list 1. Iterate through the members of a list. 3 ways: 1 lst = [1, a, " astring ", [1,2,3]] 2 for m in lst : 3 print (m) 1 lst = [1, a, " astring ", [1,2,3]] 2 for i in range ( len ( lst )): 3 print ( lst [i]) 1 lst = [1, a, " astring ", [1,2,3]] 2 i=0 3 while i<len ( lst ): 4 print ( lst [i]) 5 i=i+1 2. Write a function minmax That prints both the minimum and the max values contained in a list of number. 1 def minmax ( lst ): 2 min = lst [0] 3 max = lst [0] 4 for n in lst : 5 if n<min : 6 min = n 15

7 if n>max : 8 max = n 9 print (" Min : ", min ) 10 print (" Max : ", max ) 3. Write a function that takes a list of numbers and a number n as input and generates a new list consisting of all the number in the given list that are greater than n. 1 def greatern (lst, n): 2 rlst = [] 3 for i in lst : 4 if i>n: 5 rlst. append (i) 6 return rlst Mutating lists 1. Write a function squarelist that takes a list of numbers as input and applies the square function to each member of the list : 1 def squarelist ( lst ): 2 for i in range ( len ( lst )): 3 lst [i] = lst [i ]**2 Forming new lists 1. Write a function firstnsqs that takes a number n as input and return a list of the squares of the the first n integers. : 1 def firstnsqs (n): 2 rlst = [] 3 for i in range (1, n +1) : 4 rlst. append (i **2) 5 return rlst 2. Write a function strtolist that takes a string as input and returns a list of all the characters in the string. : 1 def strtolist ( str ): 2 rlst = [] 3 for s in str : 4 rlst. append (s) 5 return rlst 16