外包 | “Recursive“ Assignments

本文探讨了如何使用递归实现Collatz猜想的计数函数,以及如何通过递归检查文件中的目标字符。问题B涉及检查文档中是否存在特定字母,而问题C则要求遍历文件夹结构查找目标文件。通过解决这些问题,读者将加深对递归在搜索和验证任务中的应用理解。
摘要由CSDN通过智能技术生成

外包 | “Recursive Assignments”

相关文件下载

相关文件下载
 

Problem A

Problem A. (10 points) Collatz Sequence Length
The Collatz conjecture (https://en.wikipedia.org/wiki/Collatz_conjecture) is an unproven mathematical rule that says the following:
Take any positive integer n. If n is even, divide it by 2 to get n / 2 (use integer division so that you don’t end up with floating point numbers). If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process indefinitely, and eventually you will reach 1.

Write a recursive function called collatz that takes in a single positive integer argument n and returns a count of how many elements are in the collatz sequence from n to 1, inclusive. For example, suppose your initial number was 5. Then the collatz sequence would be the following:
The initial number is 5.
5 is odd, so the next number is 5*3 + 1 = 16
16 is even, so the next number is 16//2 = 8
8 is even, so the next number is 8//2 = 4
4 is even, so the next number is 4//2 = 2
2 is even, so the next number is 2//2 = 1

We have reached 1, so the sequence is complete, and the function would return 6
(since there were 6 elements in the sequence: 5, 16, 8, 4, 2, 1)
Hints:

  • You may assume that your function will only be called with positive integers.
  • This function returns an int, so both your base case and your recursive case(s) need to return an int

Constraints:

  • The collatz function must be implemented using recursion. Do not use any loop constructs (while or for).
def collatz(n):
    '''
    Purpose: solve The Collatz conjecture
    Parameter(s): an positive integer
    Return Value: Collatz sequence length
    '''

    if n == 1:
        return 1
    else:
        if n % 2 == 0:
            return collatz(n/2) + 1
        else:
            return collatz(n*3+1) + 1


"""
Examples:
>>> collatz(5)
6
>>> collatz(1)
1
>>> collatz(123)
47
"""

 

Problem B

Problem B. (10 points) Checking for Decoys
You are a detective trying to stop a powerful criminal organization from stealing some of the world’s treasures and monuments. How your enemies are capable of stealing entire buildings and even larger objects is not fully understood, but you have acquired documents containing information about their next potential targets.

First, though, you have learned that some of the documents are decoys. If every line in the file contains at least one of the letters ‘A’, ‘C’, ‘M’, or ‘E’, then the document represents a current target for the organization - otherwise it’s a decoy and should be ignored.

Write a recursive function called is_target(lines), which takes in a list of strings lines representing each line of a document, and returns the boolean True if that file is a target (that is, if every string in the list contains at least one of ‘A’, ‘C’, ‘M’, or ‘E’), or False if it’s a decoy.
Only the uppercase version of ‘A’, ‘C’, ‘M’, or ‘E’ count for this.

Hints:

  • You don’t have to do any File I/O for this problem, that’s handled in Part C.
  • You only need to use recursion to go through the list - you’re free to use the in keyword to check whether or not the letters in question are present in each string.

Constraints:

  • The is_target function must be implemented using recursion. Do not use any loop constructs (while or for).
def is_target(lines):
    '''
    Purpose: check if 'A' or 'C' or 'M' or 'E' in every lines
    Parameter(s): list of several lines
    Return Value: True of False
    '''
    if len(lines) == 0:
        return True
    line = lines.pop(0)
    for s in line:
        if s in ['A', 'C', 'M', 'E']:
            return is_target(lines)
    return False


"""
Examples:
>>> is_target(['One line\n', 'Two lines\n', 'Three lines\n'])
False
>>> is_target(['herE is a line\n', 'Another linE, starting with A\n', 'One More line'])
True
>>> is_target([])
True
>>> is_target(['More examples\n', 'Here there Are two problem lines\n', 'Not this onE\n', 'This one does not count\n', 'excellent'])
False
"""

 

Problem C

Problem C. (10 points) Searching All Files
Continuing from the previous question, you must now search through all of the documents and generate a list of the ones that represent targets of the evil organization. The problem is that the documents are not all in one directory: they’re in a nested directory structure, and could be in the top-level directory, or in subdirectories of that directory, or in subdirectories of those subdirectories, and so on.

Try out the function on some of the sample directories that were in the hw10.zip folder, to ensure that you understand what it currently does. If you’re not sure, ask a TA to explain it to you.

Then, alter the all_targets function above so that rather than printing the paths to all of the files in the nested directory, it returns a list of the paths to all of the files that are targets (but not the ones that are decoys, as defined in problem B). The order of the list does not matter.

Hints:

  • This problem uses both loops AND recursion: the loop is used to iterate through the files within each directory, while the recursive call is used to go deeper into one of the subdirectories.
  • You will need to open each file and read its contents to determine whether it’s a target.
  • Use .readlines() to get a list of strings representing the lines in each file, to pass into your is_target function.
  • You will need to write documentation for all_targets, even though we provide you with some of the code.

Constraints:

  • You must call your is_target function somewhere in all_targets.
  • Don’t import any modules other than os, and don’t use any os module methods other than those already used in the given function.
import os


def is_target(lines):
    '''
        Purpose: check if 'A' or 'C' or 'M' or 'E' in every lines
        Parameter(s): list of several lines
        Return Value: True of False
    '''
    if len(lines) == 0:
        return True
    line = lines.pop(0)
    for s in line:
        if s in ['A', 'C', 'M', 'E']:
            return is_target(lines)
    return False


def all_targets(path):
    '''
    Purpose: apply function 'is_target' in each file
    Parameter(s): file path
    Return Value: list of decoy-files
    '''
    targetList = []
    for file in os.listdir(path):
        if os.path.isfile(path+'/'+file):       # This is a file, print out the path
            f = open(path+'/'+file)
            lines = f.readlines()
            f.close()
            if is_target(lines):
                targetList.append(path+'/'+file)
        else:                                   # Go into a subdirectory
            targetList += all_targets(path+'/'+file)
    return targetList


"""
>>> all_targets('docs1')
['docs1/things.txt']

>>> all_targets('docs2')
['docs2/Africa/pyramids.txt', 
'docs2/antarctica.txt', 
'docs2/South_America/amazon.txt']

>>> all_targets('docs3')
['docs3/Asia/India/taj_mahal.txt', 
'docs3/Australia/sydney_opera_house.txt', 
'docs3/North_America/Canada/Alberta/west_edmonton_mall.txt', 
'docs3/North_America/Mexico/chichen_itza.txt', 
'docs3/North_America/United_States/Minnesota/Minneapolis/keller_hall.txt']
"""

 

Quiz

Q4 Write a Program 10 Points
Write a recursive function dot(left,right),which takes in two lists of integers left and right,which
you can assume have the same length.The function should return the dot product of those two
lists-that is,it should multiply each element in the left list with the one at the corresponding
index in the right list,and return the sum of all those products.

Constraints:
You are permitted to use a helper function,but at least one of your functions must use
recursion,and you are not permitted to use any loops(while/for).

def dot(left, right):
    if len(left) == 0:
        return 0
    a = left.pop(0)
    b = right.pop(0)
    return dot(left,  right) + a * b
"""
>>dot([0,4,21,[1,5,3])
26
>>>dot([],[])
0
>>> dot([2,5,2,1,10],[3,-12,6,-1,0])
-43
"""

Q3 Loop to Recursion Conversion 10 Points
Rewrite the mystery function below using recursion rather than a loop.You can either fill in your
code in the box below,or upload a file.You may assume that the user will always input integers.

You are permitted to use a helper function,but at least one of your functions must use
recursion,and you are not permitted to use any loops (while/for).

def mystery(n):
 out = []
 while len(out) < n:
   new_val = int(input(“Enter a number:”)
   if new_val > 0:
     out.append(new_val)
 return out

def mystery(n):
    if n == 0:
        return []
    new_val = int(input("Enter a number: "))
    n = n - 1
    return [new_val] + mystery(n)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值