Skip to main content
 首页 » 编程设计

python之命令行输入、极端和 map 模式 python

2024年08月27日36qlqwjy

我正在为我的入门级 CS 类(class)做作业,但我不太确定如何解决此任务。在这里:

Create a program that takes command line input to obtain the data and process the data using a list. Here is how the program should behave:

ubuntu@ubuntu:~/cs150/loops$ python3 command.py 11 5 3 51 
the smallest number is 3 

To convert the arguments to integers, use the map pattern, as in:

strings = ArrayToList(sys.argv[1:]) 
numbers = ListMap(int,strings) 

The ListMap function is already defined for you in List.py, which you can download with:

wget troll.cs.ua.edu/cs150/book/List.py 

You will need to import the List and sys modules in your program:

import sys 
from List import * 

Finally, use the extreme pattern for lists to find and print the smallest integer once ListMap has converted the argument strings into ints.

这是我的:

import sys 
from List import * 
 
def main(): 
   strings = ArrayToList(sys.argv[1:]) 
   numbers = ListMap(int,strings) 
   smallest = numbers[0] 
   for i in range(0,len(numbers),1): 
      if (numbers[i] < smallest): 
        smallest = numbers[i] 
   print("The smallest number is: ", smallest) 
main() 

这是我从这段代码中收到的错误消息:

File "command.py", line 12, in <module> 
  main() 
File "command.py", line 9, in main 
  if (numbers[i] < smallest): 
TypeError: unorderable types: list() < int() 

抱歉,这篇文章太长了,我真的需要一些帮助,因为我是编码的新手,我想写得更透彻。不确定我哪里出错或我需要添加/更改什么,我们将不胜感激。提前致谢。

请您参考如下方法:

您的列表的内部表示实际上是一个列表列表,如下所示:['4', ['2', ['5', ['1', [ '0',无]]]]]。您应该使用 List.py 模块中的 head 和 tail 函数来获取列表的第一个元素:

while numbers: 
    num, numbers = head(numbers), tail(numbers) 
    if num < smallest: 
        smallest = num 

请注意,鉴于此列表的实现,递归实现可能更自然:

def get_smallest(lst): 
    h, t = head(lst), tail(lst) 
    return min(h, get_smallest(t)) if t else h 
smallest = get_smallest(numbers)