我很难让我的帮助函数运行程序。这是我目前在我的计划中所拥有的:
# create_grades - A function that will create and return a list of
# 'amount' randomly selected between 0 and 100. 0 and 100 are included.
def create_grades(amount):
import random
grade_list = []
for i in range (amount):
number = random.randint (0, 100)
grade_list.append (number)
return grade_list
# print_rows - A function that prints all of grade_list displaying 4 space
# separated values in each row. Last row may have fewer than 4 values in it.
def print_rows(grade_list):
count = 0
for i in range (len(grade_list)):
print(grade_list[i], end = " ")
if (grade_list[i] % 2 == 0):
count += 1
# add_grade - A function that gets user input from 0 to 100, and counts how
# many times the grade occurs in 'grade_list'. Result is printed out.
def add_grade(grade_list):
grade = int(input("\nEnter a grade between 0 and 100: "))
print (grade, "occurs", number, "times.")
# count_grades - A function that calculates and returns amount of 2-digit grades
# in grade_list. grade_list is assumed to have at least one value.
def count_grades(grade_list):
count = 0
if (grade_list > 9 and grade_list <= 100):
count +=1
# Main function - Test all of the helper functions
def test_grades():
grade_list = create_grades (11)
print_rows (grade_list)
add_grade (grade_list)
print_rows (grade_list)
print ("Amount of 2-digit values =", count_grades (grade_list))
该程序在这里和那里都缺少了部分因为我似乎无法通过剩余的辅助函数来解决我的问题。我正在努力获取print_rows,add_grade和count_grades来产生这种结果:
test_grades()
47 7 43 90
7 39 97 41
36 100 64
Enter a grade between 0 and 100: 7
7 occurs 3 times
47 7 43 90
7 39 97 41
36 100 64
Amount of 2-digit values = 8
答案 0 :(得分:0)
我将假设您正在使用Python 2.7,因为这是您标记的内容。如果您将其分解为多个部分以使每个部分单独工作,则此任务更容易实现。
如果count等于3(python索引从0开始),则可以修改 print_rows
以在新行上打印。在python 2.x中的同一行上打印是通过在print语句的末尾添加一个逗号:
def print_rows(grade_list):
count = 0
for i in grade_list:
if count == 3:
print i
count = 0
else:
print i,
count += 1
在add_grade
中,您需要确定grade
中grade_list
出现的时间grade_list.count(grade)
。这可以使用def add_grade(grade_list):
grade = int(input("\nEnter a grade between 0 and 100: "))
print grade, "occurs", list(grade_list).count(grade), "time(s)."
count_grade
在len()
中,您需要过滤掉您不想要的列表中的结果,然后使用内置函数def count_grades(grade_list):
two_digit_grades = grade_list[(grade_list > 9) & (grade_list <= 100)]
return len(two_digit_grades)
计算列表的长度:
create_grades
另外,使用numpy
简化def create_grades(amount):
import numpy as np
return np.random.randint(0, 100, amount)
:
def test_grades():
grade_list = create_grades(11)
print_rows(grade_list)
add_grade(grade_list)
print "Amount of 2-digit values =", count_grades(grade_list)
test_grades()
调用这些功能
25 88 93 16
27 53 62 46
28 6 85
Enter a grade between 0 and 100: 88
88 occurs 1 time(s).
Amount of 2-digit values = 10
给出:
{{1}}