Can’t post image, so: a[i]={(-1)^(i+1)*sin(x)*ln(x)}/{i^2*(i+1)!}
The task:
Need to find a1,a2,…,an.
n is natural and it’s given.
That’s the way I tried to do this:
import math
a=[]
k=0
p=0
def factorial(n):
f=1
for i in range(1,n+1):
f=f*i
return f
def narys(n):
x=input('input x: ') #x isn't given by task rules, so i think that is error else.
float(x)
k=(math.pow(-1,n+1)*math.sin(x)*math.log10(n*x))/(n*n*factorial(n+1))
a.append=k
n=int(input('input n: '))
narys(n)
for i in a:
print(a[p])
p=p+1
Уведомления
- Начало
- » Python для новичков
- » Не могу исправить ошибку (Легкая программа)
#1 Сен. 26, 2016 16:04:48
Не могу исправить ошибку (Легкая программа)
import math a=float(input("Введіть число a: ")) x=float(input("Введіть число х: ")) y=(2/a*x)*(math.pow((math.tan),2/3))*(a*x/2)-(math.pow((math.tan),3))*(a*x/2) print("Відповідь: ", format(y,'.2f')) input()
выдаёт ошибку: TypeError: a float is required
Помогите!
Прикреплённый файлы: 0.png (1,2 KБ)
Офлайн
- Пожаловаться
#2 Сен. 26, 2016 16:27:06
Не могу исправить ошибку (Легкая программа)
Return the tangent of x radians.
Другими словами
(math.pow((math.tan),2/3))
— ошибка! Нужно указать тангенс чего
Влодение рускай арфаграфией — это как владение кунг-фу: настаящие мастира не преминяют ево бес ниабхадимости
Офлайн
- Пожаловаться
#4 Сен. 26, 2016 20:18:09
Не могу исправить ошибку (Легкая программа)
A=Mas_dab1
C=Mas_dab2
Max=0.0 # отношение Ai/Ci
Max=A/C
Помогите, пожалуйста, не знаю как написать, что элементы массива С не могут быть равными 0.
Офлайн
- Пожаловаться
#5 Сен. 27, 2016 08:19:15
Не могу исправить ошибку (Легкая программа)
Щас вот не понял…
Влодение рускай арфаграфией — это как владение кунг-фу: настаящие мастира не преминяют ево бес ниабхадимости
Офлайн
- Пожаловаться
#6 Сен. 27, 2016 08:28:41
Не могу исправить ошибку (Легкая программа)
Anna_Keld
A=Mas_dab1C=Mas_dab2Max=0.0 # отношение Ai/CiMax=A/CПомогите, пожалуйста, не знаю как написать, что элементы массива С не могут быть равными 0.
C = [1,2,3,0] assert 0 not in C, "Houston, we've got a problem"
Офлайн
- Пожаловаться
#7 Сен. 28, 2016 17:24:44
Не могу исправить ошибку (Легкая программа)
Подскажите, пожалуйста, по проблеме.
from datetime import datetime past = input('') now = datetime.now() print(past) print(datetime.now()) age = datetime.now() - datetime(past) print(age) print(age.days/365)
1980, 1, 1
1980, 1, 1
2016-09-28 17:22:06.219872
—————————————————————————
TypeError Traceback (most recent call last)
<ipython-input-8-eeea22692c41> in <module>()
4 print(past)
5 print(datetime.now())
—-> 6 age = datetime.now() — datetime(past)
7 print(age)
8 print(age.days/365)
TypeError: an integer is required (got type str)
Пробовал так
age = datetime.now() - str(datetime(past)) age = str(datetime.now() - datetime(past))
Отредактировано gyddik (Сен. 28, 2016 17:26:46)
Офлайн
- Пожаловаться
#8 Сен. 29, 2016 02:23:23
Не могу исправить ошибку (Легкая программа)
gyddik
datetime в вашем коде не принимает строку, которую вы ввели с клавиатуры, для этого смотрите в строну datetime.strftime
_________________________________________________________________________________
полезный блог о python john16blog.blogspot.com
Офлайн
- Пожаловаться
#9 Сен. 29, 2016 11:50:56
Не могу исправить ошибку (Легкая программа)
JOHN_16
gyddikdatetime в вашем коде не принимает строку, которую вы ввели с клавиатуры, для этого смотрите в строну datetime.strftime
Спасибо, но все равно не догоняю.
from datetime import datetime a = input() b = datetime.strptime(a, '%Y%m%d') c = datetime.now() now = c.strftime('%Y, %m, %d') past = b.strftime('%Y, %m, %d') print(past) print(now) age = datetime(now) - datetime(past) print(age) print(age.days/365)
555599
5555, 09, 09
2016, 09, 29
—————————————————————————
TypeError Traceback (most recent call last)
<ipython-input-31-69f67edee1e1> in <module>()
7 print(past)
8 print(now)
—-> 9 age = datetime(now) — datetime(past)
10 print(age)
11 print(age.days/365)
TypeError: an integer is required (got type str)
Офлайн
- Пожаловаться
#10 Сен. 29, 2016 17:27:49
Не могу исправить ошибку (Легкая программа)
Разобрался
Вот, что получилось:
from datetime import datetime, date, time a = input() born = datetime.strptime(a, "%Y, %m, %d") now = datetime.now() age = born - now print(age) print(age.days/365)
Офлайн
- Пожаловаться
- Начало
- » Python для новичков
- » Не могу исправить ошибку (Легкая программа)
What is the problem?
By assigning to inputs to Value_1
, separated by a comma, you are defining a tuple. As a short example for this:
In [1]: tup = 42, 23
In [2]: type(tup)
Out[2]: tuple
However, the math.sqrt
function requires a float value as input, not a tuple.
How to solve this
You can use tuple unpacking to keep the structure of your original post intact:
import math
# read in x and y value of the first point and store them in a tuple
point_1 = float(input("What is the x value of point 1? ")), float(input("What is the y value of point 1? "))
# read in x and y value of the second point and store them in a tuple
point_2 = float(input("What is the x value of point 2? ")), float(input("What is the y value of point 2? "))
# This is where the tuple unpacking happens.
# After this you have the x and y values
# of the points in their respective variables.
p1_x, p1_y = point_1
p2_x, p2_y = point_2
# At this point you can use point_1 when you need both x and y value of
# of the first point. If you need only the x or y value you can use the
# unpacked coordinates saved in p1_x and p1_y respectively.
x_diff = abs(p1_x - p2_x)
y_diff = abs(p1_y - p2_y)
distance = math.sqrt(math.pow(x_diff, 2) + math.pow(y_diff, 2))
print("Distance of {} and {} is {}".format(point_1, point_2, distance))
As you can see above it can be helpful to save the information for the point as a tuple first and then use the unpacked coordinates at at a different point.
I hope this sheds some light on what happened.
TypeError: a float is required
Newbie here. I’m following a (Python, Flask, MySQL) tutorial and am getting a «TypeError: a float is required» error when running some example code.
Tutorial: https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/Python3_Flask.html#zz-6.2
Code: http://pastebin.com/1jwCE8Y8
Error:
Traceback (most recent call last): File "sqlalchemy_app2.py", line 82, in <module> print(instance) # Invoke __repr__() File "sqlalchemy_app2.py", line 40, in __repr__ self.id, self.category, self.name, self.price) TypeError: a float is required
Here’s what I’ve tried:
One:
[line 27] Changing price = Column(Numeric(precision=5,scale=2))
to price = Column(Float(precision=5,scale=2))
NameError: name ‘Float’ is not defined
Two:
[line 39] Changing return "<Cafe(%d, %s, %s, %5.2f)>" % (
to return "<Cafe(%d, %s, %s, %d)>" % (
TypeError: %d format: a number is required, not NoneType
Three:
[line 39] Changing return "<Cafe(%d, %s, %s, %5.2f)>" % (
to return "<Cafe(%d, %s, %s, %f)>" % (
TypeError: a float is required
How do I update my code so that I no longer get the «TypeError: a float is required» error? I’m using Python3. Thanks in advance.
Edit to include I’m using SQLAlchemy
catboost version: 0.16.4
Operating System: Windows 10 64-bits
CPU: Intel Core i7 8th Gen
Python 2.7
Problem:
When I try to fit a simple CatBoostClassifier on my DataFrame containing categorical variables, I get the very cryptic error below.
Here is what I did to try to troubleshoot down the issue:
- tested a clean notebook on a tutorial (https://github.com/catboost/tutorials/blob/master/python_tutorial.ipynb) —> OK
- fit CatBoostClassifier only on my non-categorical variables —> OK
- try to encode with a LabelEncoder my categorical variables and then fit CatBoostClassifier —> OK
- try to use any single categorical variable without encoding like in the titanic tutorial above —> KO
I can’t understand what’s happening here and have no idea on how to debug this further. If anyone has any idea, please let me know, I can provide more info.
Here is the code failing (it’s not a minimal example, I’m not sure how I can reproduce this):
import catboost
model = catboost.CatBoostClassifier(custom_loss=['Accuracy'], random_seed=0, eval_metric='AUC', logging_level='Silent')
model.fit(X_train.loc[:, ['categoricalvariable']], y_train_enc,
cat_features=[0],
plot=True
)
And the error traceback:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-100-7e62575dc820> in <module>()
----> 5 plot=True
6 )
C:UsersAIAnaconda2libsite-packagescatboostcore.pyc in fit(self, X, y, cat_features, sample_weight, baseline, use_best_model, eval_set, verbose, logging_level, plot, column_description, verbose_eval, metric_period, silent, early_stopping_rounds, save_snapshot, snapshot_file, snapshot_interval, init_model)
3455 self._fit(X, y, cat_features, None, sample_weight, None, None, None, None, baseline, use_best_model,
3456 eval_set, verbose, logging_level, plot, column_description, verbose_eval, metric_period,
-> 3457 silent, early_stopping_rounds, save_snapshot, snapshot_file, snapshot_interval, init_model)
3458 return self
3459
C:UsersAIAnaconda2libsite-packagescatboostcore.pyc in _fit(self, X, y, cat_features, pairs, sample_weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, use_best_model, eval_set, verbose, logging_level, plot, column_description, verbose_eval, metric_period, silent, early_stopping_rounds, save_snapshot, snapshot_file, snapshot_interval, init_model)
1386 use_best_model, eval_set, verbose, logging_level, plot,
1387 column_description, verbose_eval, metric_period, silent, early_stopping_rounds,
-> 1388 save_snapshot, snapshot_file, snapshot_interval, init_model
1389 )
1390 params = train_params["params"]
C:UsersAIAnaconda2libsite-packagescatboostcore.pyc in _prepare_train_params(self, X, y, cat_features, pairs, sample_weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, use_best_model, eval_set, verbose, logging_level, plot, column_description, verbose_eval, metric_period, silent, early_stopping_rounds, save_snapshot, snapshot_file, snapshot_interval, init_model)
1281 del params['cat_features']
1282
-> 1283 train_pool = _build_train_pool(X, y, cat_features, pairs, sample_weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, column_description)
1284 if train_pool.is_empty_:
1285 raise CatBoostError("X is empty.")
C:UsersAIAnaconda2libsite-packagescatboostcore.pyc in _build_train_pool(X, y, cat_features, pairs, sample_weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, column_description)
697 raise CatBoostError("y has not initialized in fit(): X is not catboost.Pool object, y must be not None in fit().")
698 train_pool = Pool(X, y, cat_features=cat_features, pairs=pairs, weight=sample_weight, group_id=group_id,
--> 699 group_weight=group_weight, subgroup_id=subgroup_id, pairs_weight=pairs_weight, baseline=baseline)
700 return train_pool
701
C:UsersAIAnaconda2libsite-packagescatboostcore.pyc in __init__(self, data, label, cat_features, column_description, pairs, delimiter, has_header, weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, feature_names, thread_count)
326 )
327
--> 328 self._init(data, label, cat_features, pairs, weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, feature_names)
329 super(Pool, self).__init__()
330
C:UsersAIAnaconda2libsite-packagescatboostcore.pyc in _init(self, data, label, cat_features, pairs, weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, feature_names)
678 baseline = np.reshape(baseline, (samples_count, -1))
679 self._check_baseline_shape(baseline, samples_count)
--> 680 self._init_pool(data, label, cat_features, pairs, weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, feature_names)
681
682
_catboost.pyx in _catboost._PoolBase._init_pool()
_catboost.pyx in _catboost._PoolBase._init_pool()
_catboost.pyx in _catboost._PoolBase._init_features_order_layout_pool()
_catboost.pyx in _catboost._set_features_order_data_pd_data_frame()
_catboost.pyx in _catboost.get_cat_factor_bytes_representation()
_catboost.pyx in _catboost.get_id_object_bytes_string_representation()
TypeError: a float is required