2015-03-03 131 views
0

我有一個學校的工作,需要找到平均和最小和最大,但我不知道如何找到最小和最大,老師說我們不能使用python中建立最小最大值,也沒有排序。我已經得到了平均水平,只需要做最小和最大,這是我的代碼。如何在Python中找到最小值和最大值?

import random 
import math 
n = 0 
with open("numbers2.txt", 'w') as f: 
for x in range(random.randrange(10,20)): 
    numbers = random.randint(1,50) #random value between 1 to 50 
    f.write(str(numbers) + "\n") 
    print(numbers) 

f = open("numbers2.txt", 'r') 
fr = f.read() 
fs = fr.split() 
length = len(fs) 
sum = 0 
for line in fs: 
    line = line.strip() 
    number = int(line) 
    sum += number  
print("The average is :" , sum/length) 
+1

提示:你需要將一個變量與數字進行比較。 '如果變量<數字:' – Iftah 2015-03-03 02:19:02

+0

虐待嘗試這樣做。 – yahoo911emil 2015-03-03 02:24:22

回答

4

將以下行添加到您的代碼中。

fs = fr.split() 
print(min(int(i) for i in fs)) 
print(max(int(i) for i in fs)) 

更新:

min_num = int(fs[0])    # Fetches the first item from the list and convert the type to `int` and then it assigns the int value to `min_num` variable. 
max_num = int(fs[0])    # Fetches the first item from the list and convert the type to `int` and then it assigns the int value to `max_num` variable. 
for number in fs[1:]:    # iterate over all the items in the list from second element. 
    if int(number) > max_num:  # it converts the datatype of each element to int and then it check with the `max_num` variable. 
     max_num = int(number)  # If the number is greater than max_num then it assign the number back to the max_num 
    if int(number) < min_num: 
     min_num = int(number) 
print(max_num) 
print(min_num) 

如果存在一個空行其間那麼上面將無法正常工作。你需要把代碼放到try塊中去。

try: 
    min_num = int(fs[0]) 
    max_num = int(fs[0]) 
    for number in fs[1:]: 

     if int(number) > max_num: 
      max_num = int(number) 

     if int(number) < min_num: 
      min_num = int(number) 
except ValueError: 
    pass    

print(max_num) 
print(min_num) 
+0

@Aavall但是這個答案仍然有好處,作爲替代或黃金標準來比較他們的結果。 – Marcin 2015-03-03 02:22:32

+0

是的,我的老師不允許我使用內置的 – yahoo911emil 2015-03-03 02:23:25

+0

@ yahoo911emil檢查我的更新。 – 2015-03-03 02:48:54

1

也許你可以通過搜索到號碼列表找到最大和最小:

numbers=[1,2,6,5,3,6] 

max_num=numbers[0] 
min_num=numbers[0] 
for number in numbers: 
    if number > max_num: 
     max_num = number 
    if number < min_num: 
     min_num = number 

print max_num 
print min_num 
+0

我試過這樣做,但沒有使用我使用的數字,它似乎並沒有工作,我的意思是它的作品,但它打印出不同的結果 – yahoo911emil 2015-03-03 02:35:55

+0

檢查中間結果。您的分割功能是否按照您期望的方式工作? – 2015-03-03 02:49:00

+0

您需要將字符串的數據類型轉換爲int。看到我的答案。 – 2015-03-03 02:49:43

0

如果你學會如何思考這些類型的問題,這都屬於應該到位。

  • 如果您沒有號碼,最小/最大值是多少?
  • 如果您有一個號碼, 最小/最大值是多少?
  • 如果您有n個號碼,其中n大於 1,最小值和最大值是多少?
相關問題