所以我正在學習python,想解決一個問題,將面積作為整數輸入并計算可以用它制作多少平方米。
例子
比如輸入12米的面積(輸入12),就可以做成1個3x3平方米(面積9米)。那將留下 3 米的面積,因此您可以將它們變成三個 1x1 平方米。
示例輸入和輸出。
input: function(12)
output: 9,1,1,1
input: function(22)
output: 16, 4, 1, 1
input: function(15324)
output: 15129,169,25,1
我嘗試了以下但我無法做到。
def area(num):
return num * num
number = float(input(" Please Enter any numeric Value : "))
area= square(number)
print(area)
我只嘗試回傳給定數字的平方數,但如何根據問題改進它?
uj5u.com熱心網友回復:
我認為您已接近解決方案。我實施了一個簡單但有效的解決方案。
import math
def square(n):
lis = []
rest = n
while n > 0:
rest = math.floor(math.sqrt(n))**2
lis.append(rest)
n-= rest
return(lis)
可以看到,這條線 math.floor(math.sqrt(n))^2 是計算小于 n 的最接近完美平方。然后,我將結果保存在一個串列中,并通過減去 n 減去其余部分來更新 n 值。用 while 回圈迭代這個程序,我得到一個包含您指定結果的最終串列。
square(12)
>>> [9, 1, 1, 1]
square(22)
>>> [16, 4, 1, 1]
square(15324)
>>> [15129, 169, 25, 1]
EDIT
提示命令執行該功能。
n = float(input(" Please Enter any numeric Value : "))
square(n)
總之,如果你想擁有一個帶提示的全功能。
import math
def square_prompt():
n = 1
while n>0:
n = float(input(" Please Enter any numeric Value : "))
if n:
print(square(n))
square_prompt()
注意。如果您插入一個小于 0 的數字,您將停止回圈(這意味著用戶沒有任何其他數字可以向程式詢問)。
uj5u.com熱心網友回復:
你可以用一個while回圈來做到這一點:
import numpy as np
def func(a):
lst = []
while a: # Repeat until a reaches 0
n = int(np.sqrt(a))**2 # Largest square number < a
a -= n # Reduce a by n
lst.append(n) # Append n to a list and repeat
return lst
print(func(12))
print(func(22))
print(func(15324))
輸出:
[9, 1, 1, 1]
[16, 4, 1, 1]
[15129, 169, 25, 1]
uj5u.com熱心網友回復:
from math import sqrt
def square(n):
lst = [] # Empty List
while True:
for a in range(1,int(n)):
if n-a > 0:
if round(sqrt(n-a)) == sqrt(n-a):
lst.append(str((round(n-a)))) # I am check that if round of square of a number is equal to square of number because sqrt gives square for every not but I need only perfect square. Square Of 3 is 1.732 but this is a perfect square not then round(1.732) returns 2 which is not equal to 1.732.
n = a
if n==4: # This line is because 4-Anything is not a perfect square therefore I need to add a custom if statement.
lst.append(str(4)) # Because 4 is a perfect square of therefore I add 4 to the list.
n = 0
break # exit While Loop
if n<=4: # Because if n is 3 then I need to add 1 to the list for n times.
break # exit While loop
for a in range(int(n)): # add 1 to n times in lst if n is less than 4.
lst.append('1')
return ' '.join(lst)
def area(num):
return num * num
number = float(input(" Please Enter any numeric Value : "))
area= square(number)
print(area)
輸出:
IN:22, OUT:16 4 1 1
這是我可以向你解釋的。
uj5u.com熱心網友回復:
您可以將此問題轉換為find the closest square number問題,因此您需要計算輸入區域的平方根并使用math庫來計算該值,得到最接近的平方數:
import math
area = float(input(" Please Enter any numeric Value : "))
sqrt = area**0.5
closest = math.floor(sqrt)**2
print(closest, area-closest)
輸出:
Please Enter any numeric Value : 12
9 3.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463755.html
上一篇:Vue3重復識別符號ref
