First of all, thank you for reading it. I am new to Python and learning something new every day.
I wrote a function where inputs are 4 variables and output are 4 variables.
My problem is variables are getting defined somewhere else and it's calling the script. Now, what if the user only defines 3 variables in that case I automatically want a 4th variable to get assigned zero value. I also included another code that I am trying to use for the same purpose.
volsum = vol1 + vol2 + vol3 + vol4
if vol1n == missing:
vol1n = 0
else:
vol1n=vol1/volsum
if vol2n == missing:
vol2n = 0
else:
vol2n=vol2/volsum
if vol3n = missing:
vol3n = 0
else:
vol3n=vol3/volsum
if vol4n == missing:
vol4n = 0
else:
vol4n=vol4/volsum
or maybe using a function
def vol(vol1,vol2,vol3,vol4):
volsum = vol1 + vol2
vol1n=vol1/volsum
vol2n=vol2/volsum
vol3n=vol3/volsum
vol4n=vol4/volsum
return vol1n, vol2n,vol3n,vol4n
Try Assigning Values when you Define the Fucntion:
def vol(vol1 = 0,vol2 = 0,vol3 = 0,vol4 = 0):
volsum = vol1 + vol2
vol1n = vol1 / volsum
vol2n = vol2 / volsum
vol3n = vol3 / volsum
vol4n = vol4 / volsum
return vol1n, vol2n,vol3n,vol4n
Now suppose you want to skip vol2:
variable_assigned = vol(vol1 = 5,vol3 = 2,vol4 = 5)
If you require a One-Line (I love creating one):
#defining vol()
def vol(*kwargs): return [i/sum(kwargs) for i in kwargs]
# using vol()
#example
vol (1,2,3)
#returns
[0.16666666666666666, 0.3333333333333333, 0.5]
# so to assign variables,
#if you give 3 values,
vol1n, vol2n, vol3n = vol(1,2,3)
# if 4,
vol1n, vol2n, vol3n, vol4n = vol(1,2,3,5)
A little Fun (Not recommended):
Lets say your vol1 =1, vol2 = 5 vol3 = 3 ...voln = 10
So let:
vol = [ 1, 5, 3, ... n values, 10]
Now if you run the following code:
for j in range(len(vol)): exec(f'vol{j+1}n = [i/sum(vol) for i in vol][j]')
This code will automatically create your vol1n, vol2n, ... volnn variables automatically.
Rather than a 0, could it be forgotten? Personally, I don't like typing things out when they don't need to be. Try the *args feature out.
def vol_func(*args):
volumesum = sum(args)
vals = []
for i in range(len(args)):
vals.append(args[i] / volumesum)
return vals
volsumlst = vol_func(2.3, 4)
You can check if a variable is defined or not using 'locals' function. Alternatively if variables are defined globally, then you should use 'globals' function.
if 'vol1n' not in locals():
vol1n = 0
else:
vol1n=vol1/volsum
if 'vol2n' not in locals():
vol2n = 0
else:
vol2n=vol2/volsum
if 'vol3n' not in locals():
vol3n = 0
else:
vol3n=vol3/volsum
if 'vol4n' not in locals():
vol4n = 0
else:
vol4n=vol4/volsum
Related
I have the following code:
class MyFirstClass:
def myDef(self):
global x, y
x = 'some_str'
y = 0
class MySecondClass:
def myOtherDef(self):
for i in range(10):
y += 1
if y % 2 == 0:
y = 0
x = 'new_str'
However, y += 1 errors with local variable 'y' defined in an enclosing scope on line 4 referenced before assignment
How can I re-assign variable y in the new class?
There are 2 issues with this. The first is that you need to define x and y as members of MyFirstClass, not as globals in a method. You won't be able to access them that way. The second is that you need an instance of MyFirstClass in MySecondClass:
class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass()
def myOtherDef(self):
for i in range(10):
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print(self.myFirstClass.x)
mySecondClass = MySecondClass()
mySecondClass.myOtherDef()
Output:
new_str
new_str
new_str
new_str
new_str
The program I am trying to create involves writing a method called monster_fight(monster1,monster2) to have the two monsters "Fight". However I am having one issue retrieving the damage value stored in each of the monster object dictionaries named 'self.attacks'.
I am trying to retrieve a value from dictionary 'monster1.attacks' to reduce the hp of the monster2 object. However with the current code I have in place, the program does not recognize the value of the keys when I call the dictionary. Can anybody show what I am doing wrong?
Thanks!
class Monster():
def __init__(self, name, max_hp = 20, hp=20):
self.name = name
self.type = type
self.current_hp = max_hp
self.attacks = {'wait': 0}
self.possible_attacks = {'sneak_attack': 1,
'slash': 2,
'ice_storm': 3,
'fire_storm': 3,
'whirlwind': 3,
'earthquake': 2,
'double_hit': 4,
'wait': 0}
self.exp = 0
def add_attack(self, attack_name):
if attack_name in self.possible_attacks:
self.attacks[attack_name] = self.possible_attacks.get(attack_name)
return True
else:
return False
if attack_name in self.attacks:
return False
def remove_attack(self, attack_name):
if attack_name in self.attacks:
self.attacks.pop(attack_name)
if len(self.attacks) == 0:
self.attacks['wait'] = 0
return True
else:
return False
def win_fight(self):
self.exp += 5
self.current_hp = self.max_hp
def lose_fight(self):
self.exp += 1
self.current_hp = self.max_hp
def monster_fight(monster1,monster2):
round1 = 0
moves1 = []
moves2 = []
list1 = []
list2 = []
for i in monster1.attacks:
values = ''
values = monster1.attacks.get(i)
list1.append(values)
for i in range(0,len(monster2.attacks)):
values = monster2.attacks.get(i)
list2.append(values)
while monster1.current_hp > 0 or monster2.current_hp > 0:
round1 += 1
monster1_attack = int(monster1.attacks[list1[(round1-1)%len(list1)]])
monster2.current_hp -= monster1_attack
moves1.append(list1[(round1-1)%len(list1)])
monster2_attack= monster2.attacks[list2[(round1-1)%len(list2)]]
monster1.current_hp -= monster2_attack
moves2.append(list2[(round1-1)%len(list2)])
if monster1.current_hp <= 0:
monster1.lose_fight()
monster2.win_fight()
return round1, monster2.name, moves2
elif monster1.current_hp <= 0:
monster2.lose_fight()
monster1.win_fight()
return round1,monster1.name, moves1
else:
return -1,"None","None"
a = Monster("a", 9)
b = Monster("b", 9)
a.add_attack("ice_storm")
b.add_attack("ice_storm")
b.remove_attack("wait")
a.remove_attack("wait")
round1, winner, moves = monster_fight(a, b)
print(round1)
print(winner.name)
print(moves)
monster1_attack = int(monster1.attacks[list1[(round1-1)%len(list1)]])
KeyError: 3
Well, let's see. You're calling:
monster1_attack = int(monster1.attacks[list1[(round1-1)%len(list1)]])
monster1 is a Monster object, created from:
a = Monster("a", 9)
a.add_attack("ice_storm")
a.remove_attack("wait")
So monster1.attacks looks like:
{
'ice_storm': 3,
}
You're trying to access that dictionary using key dervied from list1[(round1-1)%len(list1)].
list1 is set here:
for i in monster1.attacks:
values = ''
values = monster1.attacks.get(i)
list1.append(values)
After the above code runs, list1 is a list that looks like:
[3]
(Because you ask for monster1.attacks.get(i), which will return the value associated with key i.)
So when you ask for list1[(round1-1)%len(list1)], you get the value 3, which means you're asking for monster1.attacks[3].
There is no key named 3 in monster1.attacks. As we saw earlier, the only key is ice_storm which has the value 3. It looks like you're trying to figure out the damage that monster1's attack will do. That is actually what you have in list1, so in theory you could just write:
monster1_attack = list1[(round1-1)%len(list1)]
monster2.current_hp -= monster1_attack
I think your logic here may be a bit convoluted. You should probably think carefully about exactly what you're trying to accomplish and try to simplify your code with that goal in mind. Using the Python debugger to see the value of your variables prior to the error -- or using print statements to accomplish the same thing -- can help diagnose this sort of problem.
Consider a right-angle triangle, which has the properties
Hypotenuse (side)
Adjacent (side)
Opposite (side)
Area
Given any 2 of these properties, it is always possible to calculate the value of the other 2. My question relates to what the most efficient/elegant way of doing this is.
At present, the only way of doing this that I can think of is to use (4C2)*2 = 12 case statements, each relating to a possible combination of inputsa that may be provided.
For example, using python you might have something like
class RightAngleTriangle():
def __init__(this, propertyType1, propertyValue1, propertyType2, propertyValue2):
this.adjacent = 0
this.opposite = 0
this.hypotenuse = 0
this.area = 0
if (propertyType1 == "adjacent" and propertyType2 == "opposite"):
this.adjacent = propertyValue1
this.opposite = propertyValue2
this.hypotenuse = (propertyValue1**2 + propertyValue2**2)**0.5
this.area = (propertyValue1 * propertyValue2)/2
elif (propertyType1 == "opposite" and propertyType2 == "adjacent"):
this.adjacent = propertyValue2
this.opposite = propertyValue1
this.hypotenuse = (propertyValue1**2 + propertyValue2**2)**0.5
this.area = (propertyValue1 * propertyValue2)/2
elif (propertyType1 == "adjacent" and propertyType2 == "hypotenuse"):
this.adjacent = propertyValue1
this.hypotenuse = propertyValue2
this.opposite = (propertyValue2**2 + propertyValue1**2)**0.5
this.area = (this.opposite * this.adjacent)/2
...and so on...
You could then create your triangle object, and print its four properties, using code (in this case python) like the below.
t1 = RightAngleTriangle("adjacent", 10, "opposite", 12)
print(t1.adjacent)
print(t1.opposite)
print(t1.hypotenuse)
print(t1.area)
This is hideous. Is there a more eligant solution to this problem?
Yes, at least two - one using args and one using key word args. So:
class RightAngleTriangle():
def __init__(self, *args):
self.adjacent = 0
self.opposite = 0
self.hypotenuse = 0
self.area = 0
for property_type, property_value in zip(args[::2], args[1::2]):
setattr(self, property_type, property_value)
if not self.adjacent:
# calculate
elif not self.opposite:
# calculate
elif not self.hypotenuse:
# calculate
self.area = (this.opposite * this.adjacent) / 2
This would work with your current input, but let's agree - it's still not very elegant solution. So, let's use kwargs:
class RightAngleTriangle():
def __init__(self, adjacent=0, opposite=0, hypotenuse=0):
self.adjacent = adjacent
self.opposite = opposite
self.hypotenuse = hypotenuse
self.area = 0
if not self.adjacent:
# calculate
elif not self.opposite:
# calculate
elif not self.hypotenuse:
# calculate
self.area = (this.opposite * this.adjacent) / 2
And now you can simply call this code as:
t1 = RightAngleTriangle(adjacent=10, opposite=12)
This question already has answers here:
Overloaded functions in Python
(6 answers)
Closed 5 years ago.
Im to trying run a Python script in Spyder IDE (Python 3.6) and as I progress Im starting to refactor it to more of OOP (Object Oriented) and hopefully a mature package.
I have a class titled (Epoch), see below:
class Epoch:
def __init__(self):
self.Epoch_Counter = 0
self.Timings = []
self.Timings_millisec_ticks = []
self.Duration_milli_secs = 0
self.Raw = []
self.Stimulia = []
self.Majority_stimulia = "NA"
self.epoch = datetime.datetime.utcfromtimestamp(0)
#median, positive area, negative area, geometric,max,ratio positive vs negative
self._median = 0
self._mean = 0
self._positive_area = 0
self._negative_area = 0
self._geometric_area = 0
self._max = 0
self._min = 0
self._max_amplitude = 0
self._integral = 0
self._variance= 0
self._positive_to_negative_ratio = 0
self._skew = 0
self._kurtosis = 0
self.Components = []
#mean
def mean(self,value):
self._mean = value
def mean(self):
return self._mean
#median
def median(self,value):
self._median = value
def median(self):
return self._median
#positive_area
def positive_area(self,value):
self._positive_area = value
def positive_area(self):
return self._positive_area
#negative_area
def negative_area(self,value):
self._negative_area = value
def negative_area(self):
return self._negative_area
#geometric_area
def geometric_area(self,value):
self._geometric_area = value
def geometric_area(self):
return self._geometric_area
def integral(self,value):
self.integral = value
def integral(self):
return self.integral
def max_amplitude(self,value):
self._max_amplitude = value
def max_amplitude(self):
return self._max_amplitude
def max_(self,value):
self._max = value
def max_(self):
return self._max
#min
def min_(self,value):
self.min = value
def min_(self):
return self._min
def positive_to_negative_ratio(self,value):
self.positive_to_negative_ratio = value
def positive_to_negative_ratio(self,value):
return self._positive_to_negative_ratio
#Timings_millisec_ticks
def timings_millisec_ticks(self):
return self.Timings_millisec_ticks
def timings_millisec_ticks_append(self,value):
self.Timings_millisec_ticks.append(value)
#start_time
def timings(self):
return self.Timings
def timings_append(self,value):
self.Timings.append(value)
#end_time
def end_time(self):
return self.Timings[len(self.Timings)-1]
#start_time
def start_time(self):
return self.Timings[0]
#duration
def duration_milli_secs(self):
return self.Duration_milli_secs
def duration_milli_secs(self):
return self.unix_time_millis(self.str_to_datetime_(self.end_time())) - self.unix_time_millis(self.str_to_datetime_(self.start_time()))
#raw
def raw(self):
return self.Raw
def raw_append(self,value):
self.Raw.append(value)
#components
def components(self):
return self.Components
def components_append(self,value):
self.Components.append(value)
#stimulia
def stimulia_append(self,value):
self.Stimulia.append(value)
def stimulia(self):
return self.Stimulia
#variance
def variance(self):
return self.variance
def variance(self,value):
self.variance = value
#skew
def skew(self,value):
self._skew = value
def skew(self):
return self._skew
def unix_time_millis(self,dt):
return (dt - self.epoch).total_seconds() * 1000.0
""" covert datetime of this format 2017-10-13 19:22:50:525 to datetime object"""
def str_to_datetime_(self,datetime_str):
return datetime.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S:%f')
def _print(self):
return str(self.Epoch_Counter)+","+str(len(self.Timings))+","+str(self.duration_milli_secs())+","+str(len(self.Raw))+","+str(len(self.Stimulia))+","+str(self.majority_stimulia)
I have script that has function, that calculates summary statistics and attempts to set the value of the statistics in the Epoch object (mean,median,etc...), see below:
def get_epoch_summary_stats(eeg_record_epochs_):
import numpy as np
import scipy.stats as stats
import pylab as pl
##stimulia
stimulia_raw_median = []
stimulia_raw_mean = []
stimulia_raw_positive_area = []
stimulia_raw_negative_area = []
stimulia_raw_geometric_area = []
stimulia_raw_max = []
stimulia_raw_min = []
stimulia_raw_positive_to_negative = []
stimulia_variance = []
stimulia_max_amplitude = []
stimulia_integral = []
stimulia_raw_kurtosis = []
stimulia_raw_skew = []
##no stimulia
no_stimulia_raw_median = []
no_stimulia_raw_mean = []
no_stimulia_raw_positive_area = []
no_stimulia_raw_negative_area = []
no_stimulia_raw_geometric_area = []
no_stimulia_raw_max = []
no_stimulia_raw_min = []
no_stimulia_raw_positive_to_negative = []
no_stimulia_variance = []
no_stimulia_max_amplitude = []
no_stimulia_integral = []
no_stimulia_raw_kurtosis = []
no_stimulia_raw_skew = []
no_stimulia_class_count = 0
stimulia_class_count = 0
epoch_durations = []
stimulia_raws = []
no_stimulia_raws = []
for item in eeg_record_epochs:
epoch_durations.append(item.duration_milli_secs())
epoch_durations_sorted = sorted(epoch_durations)
mean_duration = np.mean(epoch_durations_sorted)
std_duration = np.std(epoch_durations_sorted)
print("Input data:",path)
print("Epoch duration(millisecs) - mean_duration:",mean_duration)
print("Epoch duration(millisecs) - std_duration:",std_duration)
#remove epoch that are more than 1 standard deviation away from the mean in epoch size
counter = 0
for item in eeg_record_epochs_:
##DURATION SELECTION RULE
if (item.duration_milli_secs() > (mean_duration + std_duration) or item.duration_milli_secs() < (mean_duration - std_duration)):
del eeg_record_epochs[counter]
##print("epoch duration_milli_secs - REMOVED:",item.duration_milli_secs())
else:
##print("epoch duration_milli_secs:",item.duration_milli_secs())
#median, positive area, negative area, geometric area, max , ratio positive vs negative, ratio negative vs positive
raw_float_array = np.array(item.raw()).astype(np.float)
#median
item.median(np.median(raw_float_array))
#mean
item.mean(np.mean(raw_float_array))
##print("raw median: ",item.median)
positive_area = 0
negative_area = 0
#positive area
for value in raw_float_array:
if value > 0:
positive_area = positive_area + value
item.positive_area(positive_area)
##print("raw positive_area:", item.positive_area)
#negative area
for value in raw_float_array:
if value < 0 :
negative_area = negative_area + abs(value)
item.negative_area(negative_area)
##print("raw negative_area:", item.negative_area)
#geometric area
abs_raw_float_array = np.abs(raw_float_array)
item.geometric_area(sum(abs_raw_float_array))
##print("raw geometric_area:", item.geometric_area)
#max_
item.max(max(raw_float_array))
##print("raw max_:",item.max_)
#min
item.min(min(raw_float_array))
item.max_amplitude(max(max(raw_float_array),abs(min(raw_float_array))))
item.integral(item.positive_area - abs(item.negative_area))
##print("raw min_:",item.min_)
#min
#positive_to_negative_ratio
try:
item.positive_to_negative_ratio=abs(item.positive_area/item.negative_area)
except ZeroDivision as err:
continue
#variance
item.variance(np.var(raw_float_array))
#skew
item.skew(stats.skew(raw_float_array))
#kurtosis
item.kurtosis(stats.kurtosis(raw_float_array))
##print("raw positive_to_negative:",item.positive_to_negative_ratio)
item.majority_stimulia()
##default NO_STIMULIA
stimulia_class = "NO_STIMULIA"
if item.majority_stimulia().upper() == "ON":
stimulia_class = "ON"
print(stimulia_class)
item.plot()
for raw_value in item.raw():
stimulia_raws.append(int(raw_value))
stimulia_raw_median.append(item.median)
stimulia_raw_mean.append(item.mean)
stimulia_raw_positive_area.append(item.positive_area)
stimulia_raw_negative_area.append(item.negative_area)
stimulia_raw_geometric_area.append(item.geometric_area)
stimulia_raw_max.append(item.max_)
stimulia_raw_min.append(item.min_)
stimulia_raw_mean.append(item.mean)
stimulia_raw_skew.append(item.skew)
stimulia_raw_kurtosis.append(item.kurtosis)
stimulia_max_amplitude.append(item.max_amplitude)
stimulia_integral.append(item.integral)
##append only if the number is not inf or nan but just a number
if is_not_inf_or_is_nan(item.positive_to_negative_ratio) != 1:
stimulia_raw_positive_to_negative.append(item.positive_to_negative_ratio)
##print("item.positive_to_negative_ratio:",item.positive_to_negative_ratio)
stimulia_variance.append(item.variance)
stimulia_class_count= stimulia_class_count + 1
#P3 component stats +/- estimated peek for P3
else:
no_stimulia_class_count = no_stimulia_class_count + 1
print(stimulia_class)
item.plot()
for raw_value in item.raw():
no_stimulia_raws.append(int(raw_value))
no_stimulia_raw_median.append(item.median)
no_stimulia_raw_mean.append(item.mean)
no_stimulia_raw_positive_area.append(item.positive_area)
no_stimulia_raw_negative_area.append(item.negative_area)
no_stimulia_raw_geometric_area.append(item.geometric_area)
no_stimulia_raw_max.append(item.max_)
no_stimulia_raw_min.append(item.min_)
no_stimulia_raw_mean.append(item.mean)
no_stimulia_raw_skew.append(item.skew)
no_stimulia_raw_kurtosis.append(item.kurtosis)
no_stimulia_max_amplitude.append(item.max_amplitude)
no_stimulia_integral.append(item.integral)
##append only if the number is not inf or nan but just a number
if is_not_inf_or_is_nan(item.positive_to_negative_ratio) != 1:
no_stimulia_raw_positive_to_negative.append(item.positive_to_negative_ratio)
##print("item.positive_to_negative_ratio:",item.positive_to_negative_ratio)
no_stimulia_variance.append(item.variance)
##print("majority stimulia:",item.Majority_stimulia)
counter = counter + 1
##component_extraction(item,"ON",300,200,800)
print("ON summary stats-")
mean_plot = float(sum(stimulia_raw_mean)/counter)
std_plot = float(math.sqrt(sum(stimulia_variance)/counter))
fit = stats.norm.pdf(sorted(stimulia_raws), mean_plot, std_plot) #this is a fitting indeed
pl.plot(sorted(stimulia_raws),fit,'-o')
pl.hist(sorted(stimulia_raws),normed=True) #use this to draw histogram of your data
pl.show()
print("stimulia_class_count:",stimulia_class_count)
print("average stimulia_raw_mean:",sum(stimulia_raw_mean)/counter)
print("average stimulia_raw_median:",sum(stimulia_raw_median)/counter)
print("average stimulia_raw_positive_area:",sum(stimulia_raw_positive_area)/counter)
print("average stimulia_raw_negative_area:",sum(stimulia_raw_negative_area)/counter)
print("average stimulia_raw_geometric_are:",sum(stimulia_raw_geometric_area)/counter)
print("average stimulia_raw_max:",sum(stimulia_raw_max)/counter)
print("average stimulia_raw_min:",sum(stimulia_raw_min)/counter)
print("average stimulia_max_amplitude:",sum(stimulia_max_amplitude)/counter)
print("average stimulia_integral:",sum(stimulia_integral)/counter)
print("average stimulia_variance:",sum(stimulia_variance)/counter)
print("average stimulia_std:",math.sqrt(sum(stimulia_variance)/counter))
print("average stimulia_skew:",sum(stimulia_raw_skew)/counter)
print("average stimulia_kurtosis:",sum(stimulia_raw_kurtosis)/counter)
print("average stimulia_raw_positive_to_negative:",sum(stimulia_raw_positive_to_negative)/counter)
print("NO_STIMULIA summary stats-")
mean_plot = float(sum(no_stimulia_raw_mean)/counter)
std_plot = float(math.sqrt(sum(no_stimulia_variance)/counter))
fit = stats.norm.pdf(sorted(no_stimulia_raws), mean_plot, std_plot) #this is a fitting indeed
pl.plot(sorted(no_stimulia_raws),fit,'-o')
pl.hist(sorted(no_stimulia_raws),normed=True) #use this to draw histogram of your data
pl.show()
print("no_stimulia_class_count:",no_stimulia_class_count)
print("average no_stimulia_raw_mean:",sum(no_stimulia_raw_mean)/counter)
print("average no_stimulia_raw_median:",sum(no_stimulia_raw_median)/counter)
print("average no_stimulia_raw_positive_area:",sum(no_stimulia_raw_positive_area)/counter)
print("average no_stimulia_raw_negative_area:",sum(no_stimulia_raw_negative_area)/counter)
print("average no_stimulia_raw_geometric_are:",sum(no_stimulia_raw_geometric_area)/counter)
print("average no_stimulia__raw_max:",sum(no_stimulia_raw_max)/counter)
print("average no_stimulia_raw_min:",sum(no_stimulia_raw_min)/counter)
print("average no_stimulia_max_amplitude:",sum(no_stimulia_max_amplitude)/counter)
print("average no_stimulia_integral:",sum(no_stimulia_integral)/counter)
print("average no_stimulia_variance:",sum(no_stimulia_variance)/counter)
print("average no_stimulia_std:",math.sqrt(sum(no_stimulia_variance)/counter))
print("average no_stimulia_skew:",sum(no_stimulia_raw_skew)/counter)
print("average no_stimulia_kurtosis:",sum(no_stimulia_raw_kurtosis)/counter)
print("average no_stimulia_raw_positive_to_negative:",sum(no_stimulia_raw_positive_to_negative)/counter)
When running the script, I get an error:
File "", line 1, in
get_epoch_summary_stats(eeg_record_epochs)
File "", line 425, in get_epoch_summary_stats
item.median(np.median(raw_float_array))
TypeError: median() takes 1 positional argument but 2 were given
How can I fix the Epoch class or my call to item.median() in order to set Epoch's median attribute without getting this error.
Thanks a million!
There is no method overloading in python. If you define median function twice, the second definition will be used. Therefore in your code, the second definition is used, i.e.,
def median(self):
return self._median
So it only takes one positional argument (self).
It seems what you want to define is a getter and a setter. In python, you can do it by adding functional decorators. For example:
#property
def median(self):
return self._median
#median.setter
def median(self, value):
self._median = value
The first one is a getter for median, and the second one is a setter. When you invoke print(self.median), the first function will be called, while if you execute self.median = 5, the second function will be called.
You can read this article for more information about getter and setters in python: http://stackabuse.com/python-properties/
You are defining median two times:
#median
def median(self,value):
self._median = value
def median(self):
return self._median
The second definition is used, which does not accept a second argument named value.
Adding to the other answer as he was correct. Try to focus on changing your functions to getters and setters. Should help out in the long run.
I'm getting a getting a TypeError for unbound method (at the bottom). I'm teaching myself Python so this may be some simple mistake. The issue is with outFormat(), which didn't give me problems when I test it by itself but is not working within the class. Here's the class:
class gf2poly:
#binary arithemtic on polynomials
def __init__(self,expr):
self.expr = expr
def id(self):
return [self.expr[i]%2 for i in range(len(self.expr))]
def listToInt(self):
result = gf2poly.id(self)
return int(''.join(map(str,result)))
def prepBinary(a,b):
a = gf2poly.listToInt(a); b = gf2poly.listToInt(b)
bina = int(str(a),2); binb = int(str(b),2)
a = min(bina,binb); b = max(bina,binb);
return a,b
def outFormat(raw):
raw = str(raw); g = []
[g.append(i) for i,c in enumerate(raw) if c == '1']
processed = "x**"+' + x**'.join(map(str, g[::-1]))
#print "processed ",processed
return processed
def divide(a,b): #a,b are lists like (1,0,1,0,0,1,....)
a,b = gf2poly.prepBinary(a,b)
bitsa = "{0:b}".format(a); bitsb = "{0:b}".format(b)
difflen = len(str(bitsb)) - len(str(bitsa))
c = a<<difflen; q=0
while difflen >= 0 and b != 0:
q+=1<<difflen; b = b^c
lendif = abs(len(str(bin(b))) - len(str(bin(c))))
c = c>>lendif; difflen -= lendif
r = "{0:b}".format(b); q = "{0:b}".format(q)
#print "r,q ",type(r),type(q)
return r,q #returns r remainder and q quotient in gf2 division
def remainder(a,b): #separate function for clarity when calling
r = gf2poly.divide(a,b)[0]; r = int(str(r),2)
return "{0:b}".format(r)
def quotient(a,b): #separate function for clarity when calling
q = gf2poly.divide(a,b)[1]; q = int(str(q),2)
return "{0:b}".format(q)
This is how I'm calling it:
testp = gf2poly.quotient(f4,f2)
testr = gf2poly.remainder(f4,f2)
print "quotient: ",testp
print "remainder: ",testr
print "***********************************"
print "types ",type(testp),type(testr),testp,testr
testp = str(testp)
print "outFormat testp: ",gf2poly.outFormat(testp)
#print "outFormat testr: ",gf2poly.outFormat(testr)
This is the error:
TypeError: unbound method outFormat() must be called with gf2poly instance as first argument (got str instance instead)
Where you have this:
def outFormat(raw):
You probably want either this:
def outFormat(self, raw):
Or this:
#staticmethod
def outFormat(raw):
The former if you eventually need access to self in outFormat(), or the latter if you do not (as currently is the case in the posted code).