Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

CS 112 – Project 3 Loops, Lists The purpose of this assignment is to practice us

ID: 3834145 • Letter: C

Question

CS 112 – Project 3                                                                                                                                             Loops, Lists

The purpose of this assignment is to practice using loops and basic lists effectively.

Similar to previous projects, make sure to include your name, G#, Lecture/Lab sections, and any extra comments we ought to know.

If you have questions, feel free to use the Piazza discussion forums (and professor/TA office hours) to obtain assistance.

Remember, do not publicly post code for assignments on the forum! Ask a general question in public, or ask a private question (addressed to “instructors”) when you're asking about your particular code. Make sure to have a specific question; instead of "my code doesn't work, please help", we need something like "I'm having trouble when I add that particular line, what am I misunderstanding?". If you are unsure whether a question may be public or not, just mark it as private to be sure. We can change a post to public afterwards if it could have been public.

                       

Background

Loop statements allow us to run the same block of code repeatedly, with the chance to use different values for variables each time and to produce a cumulative effect. Lists and strings are sequences that can be inspected value-by-value (and modified at will). We define functions that perform calculations over sequences and numbers using loops.

Procedure

Create your python file with our normal naming convention: netID_Lab#_P3.py

Complete the function definitions described in the next few sections. Each will need one or more loops in their solutions. We’ve provided you with a few example calls, and more exhaustive tests are provided in the testing file included with this assignment:

o If you do not already have the file, download tester3p.py from Piazza o Invoke it as with prior assignments: demo$ python3 tester3p.py yourcode.py o You can test individual functions, or run in interactive mode; see previous assignment specifications for more details.

Turn in your file to the appropriate assignment on BlackBoard before the deadline/tokens window closes.

Restrictions

The purpose of this entire class is to teach you how to solve problems by writing code, not how to phone it in by calling pre-existing solutions. As a result, each project will have a "restrictions" section clarifying what is allowed to be used on it. You can ask for additional functionality to be allowed, but chances are slim that we will approve it. The general theme is: the interesting parts of the assignment must be completed by the student.

Allowed things:

Any arithmetic/comparison/boolean operators are all fine to use, such as +, -, *, /, %, and, or, >=, < etc.

Any control flow (selection statements, break/continue, for and while loops) can of course be used.

The following data types: int, float, string, bool, and list. No others.

The following built-in functions: len(), range(), int(), str(), float(). No others. o Note: standard I/O (input() and print()) are not needed since we are defining functions. You can use them for debugging purpose, but they should remove them before submission.

The following list operations: you can index and slice lists.

If you need to build up a list, you can start with the empty list and .append() values into it.

When creating lists and strings, the basic operators on them (such as +) are also allowed.

Any functions you define on your own in your program file may be used. Note: Not everything listed above are needed for the project.

Disallowed things:

Importing other modules isn't allowed.

No data types not listed in the "Allowed things" section above may be used.

No built-in functions (methods) not listed in the "Allowed things" section above may be used. o If you didn't define it, you may not call it for this project!

Missing your favorite function? Consider implementing it as a "helper function"

Additional requirements:

You must have at least one loop in each function.  

Any incoming list parameters must not be modified in your function.

Functions

sum_of_digits(n): Given a non-negative integer n, calculate and return the sum of all its digits.  

o Assume: n is a non-negative integer. o Return value: an integer. o Examples:

sum_of_digits(0) 0 # only digit is 0 sum_of_digits(204) 6 # 2+0+4 = 6

multiply_until_total_reached(original,total,n): Starting with a positive integer original, keep multiplying original by n and calculate the sum of all multiples generated including original until the sum is no longer smaller than total. Return the minimum number of multiplications needed to reach at value at or above the given total.  

Assume: All three arguments are integers: original and n are positive.

Return value: an integer. o Examples:

                                   multiply_until_total_reached (1,5,2)      2   

            # 1*2=2, (1+2)<5, 2*2=4, (1+2+4)>5, 2 multiplications needed multiply_until_total_reached (1,15,2) 3   

# 1*2=2, (1+2)<15, 2*2=4, (1+2+4)<15, 4*2=8, (1+2+4+8)=15, 3 multiplications multiply_until_total_reached (1,0,2) 0   # original 1>0, no multiplication

replicate(xs,n): Given a list of Python values xs and a non-negative integer n, construct and return a copy of xs but with each value replicated n times.  

Assume: xs is a list of zero or more Python values; n is a non-negative integer. o Return value: a list. Do NOT change the original list xs.

o

Examples:

replicate([1,2,2,3],2)

[1,1,2,2,2,2,3,3]

# replicate every value 2 times

replicate([1,2,2,3],0)

[]            

# replicate every value 0 times

     replicate([],2)   

[]            

# empty list stays empty

locate_second_divisor(xs,n): Check a list of positive integers xs to find the second number in xs that is a divisor of the non-negative integer n (i.e. it can divides n evenly). Return the location of that integer as a non-negative index. Return None if no such number can be found.

Assume: xs is a list of zero or more positive integers; n is a non-negative integer. o Return value: a non-negative integer or None.

Reminder: you cannot call .index(), see "Restrictions" section. o Examples:

locate_second_divisor([20,3,4,2],12) 2   # 4 (@index 2) is the 2nd divisor locate_second_divisor([20,3,5,9,3],12) 4 # the 2nd occurrence of 3 @ index 4 locate_second_divisor([20,3,5,8],12) None # only 1 divisor for 12

all_primes(xs): Given a list of integers xs, check and return True if all the numbers in xs are prime numbers; return False otherwise. Note: prime numbers must be positive.

Assume: xs is a non-empty list of integers.

o

Return value: a boolean.

o

Examples:

all_primes([5,2,11,37])

True

all_primes([5,2,4,37])

False

# 4 is not a prime

all_primes([5,2,-2,37])

False

# -2 is negative and cannot be a prime

count_2d(xss,v): Given a list of lists of values (a 2D list) xss and a value v, return a count of how many times v occurs in xss.

Assume: xss is a list of lists of values of any length; any member in xss could be empty. v can be any value (such as an integer, a string, etc.).

Return value: an integer.

Reminder: you cannot call .count(), see "Restrictions" section. o Examples:

count_2d([[2,3],[4,3,5]],3) 2 # two 3s, 1 in the 1st list, 1 in the 2nd count_2d([[2,2],[],[4,1,-5]],3)       0 # no 3s in any of the lists

                                   count_2d([],3)                     0     # empty list

         

Extra Credit

Implement the function below to get up to five additional points (via the five test cases)!

ranges_by_column(xss): Given a list of lists of integers (a 2D list) xss, find the range of each column (the min and max values). Return a list containing each min-max pair in order. In other words, the ith member of the return list is a two element list in the form: [min, max], where min and max are the highest and lowest value for the ith column of xss.

Assume: xss is a list of lists of integers; any member in xss could be empty or xss itself could be empty.

Return: a list of two-element lists o             Restriction: you cannot call max(), min() or any sorting facility. o        Examples:

ranges_by_column([[-1,1],[1,4],[2,3]]) [[-1,2],[1,4]]

# xss has 2 columns, the first contains -1, 1, and 2, the second contains 1, 4, and 3:

                                   #      -1 1

                                   #      1 4

                                   #      2 3

# therefore the return list contains the range [-1,2] and then the range [1,4]

ranges_by_column([[-1,1,3],[1],[2,5]]) [[-1,2],[1,5],[3,3]]

# Rows of different lengths, but there are three columns if you think of them as a table:

                                   #      -1 1      3

                                   #     1

                                   #      2 5

# So:

                                      # column 1: -1, 1, 2      min/max: [-1,2]

                                   #     column 2: 1, 5         min/max: [1,5]

                                   #     column 3: 3           min/max: [3,3]

                                   ranges_by_column([])                    []

# There are no ranges because there are no columns.

Grading Rubric

Code passes shared tests:     80 (zero points for hard-coding)

Well-documented/submitted:    10

Appropriate loop usage:       10

TOTAL:                       100 +5 extra credit for ranges_by_column()

Note 1: If your submission does not run (immediately crashes due to errors), it will receive at most 50%. No exceptions.   As stated on our syllabus, turning in running code is essential.

Note 2: You will not earn test case points if you hard-code the answers. Your program should work for all possible inputs, not just the provided test cases. If one test case calls sum_of_digits(204), and you write something like the following to pass that particular test case, you'd be hardcoding.

if n==204: #hard-coding example      return 6

  

Notice how it's not actually calculating, it's merely regurgitating a memorized answer. Doing this for all used test cases might make you feel like you've completed the program, but there are really unlimited numbers of test cases; hardcoded programs only work on the inputs that were hardcoded. You aren’t learning anything useful about loops, and the program isn't really that useful.

Reminders on Turning It In:

No work is accepted more than 48 hours after the initial deadline, regardless of token usage. Tokens are automatically applied whenever they are available, based on your last valid submission's time stamp.

You can turn in your code as many times as you want; we only grade the last submission that is <=48 hours late. If you are getting perilously close to the deadline, it may be worth it to turn in an "almost-done" version about 30 minutes before the clock strikes midnight. If you don't solve anything substantial at the last moment, you don't need to worry about turning in code that may or may not be runnable, or worry about being late by just an infuriatingly small number of seconds – you've already got a good version turned in that you knew worked at least for part of the program.

You can (and should) check your submitted files. If you re-visit BlackBoard and navigate to your submission, you can double-check that you actually submitted a file (it's possible to skip that crucial step and turn in a nofiles submission!), you can re-download that file, and then you can re-test that file to make sure you turned in the version you intended to turn in. It is your responsibility to turn in the correct file, on time, to the correct assignment.

Use a backup service. Do future you an enormous favor, and keep all of your code in an automatically synced location, such as a Dropbox or Google Drive folder. Each semester someone's computer is lost/drowned/dead, or their USB drive or hard drive fails. D

o

Examples:

replicate([1,2,2,3],2)

[1,1,2,2,2,2,3,3]

# replicate every value 2 times

replicate([1,2,2,3],0)

[]            

# replicate every value 0 times

     replicate([],2)   

[]            

# empty list stays empty

Explanation / Answer

Hi,

Please find below the python code-

def sum_of_digits(n):
s = 0
while n:
s += n % 10
n //= 10
return s
def multiply_until_total_reached(original,total,n):
count=0
while(original<total):
original=original+original*n
count+=1
return count
def replicate(xs,n):
return xs*n
def locate_second_divisor(xs,n):
pos=0
index=0
for x in xs:
index+=1
if n%x==0 :
pos+=1
if pos==2:
break
return index
  
print(sum_of_digits(234))
print(multiply_until_total_reached(1,5,2))
print(replicate([1,2,3,4,5],2))
print(locate_second_divisor([20,3,4,2],12))