def get_req_norm(max, min, data, str, require_nor): if '-' in data: # 处理区间 index = data.index('-') # 返回'-'字符位置 mmin = division((int(data[:index]) - min), (max - min)) # normalization mmax = division((int(data[index + 1:]) - min), (max - min)) else: mmin = mmax = division((int(data) - min), (max - min)) require_nor[str] = [mmin, mmax] return
def gcd(a1, b1, printing=False): '''Returns the greatest common multiple''' # WLOG $a > b > 0$ a = max(abs(a1), abs(b1)) b = min(abs(a1), abs(b1)) # find the remainder upon division q, r = division(a, b) if r == 0: if printing: print(r'$\gcd({a}, {b}) = {b}$ since ${b}|{a}$'.format(**locals())) return b else: if printing: print(r'$\gcd({a}, {b}) = gcd({b}, {r})$ since ${a} = {b} * {q} + {r}$'.format(**locals())) return gcd(b, r, printing)
def getNormalization(max_list, min_list, line_de): # 非区间当做区间的特殊情况 for str in ['house_price', 'house_totalarea', 'house_room', 'house_hall']: nor_one[str] = division((int(line_de[str]) - min_list[str]), (max_list[str] - min_list[str])) return
a = raw_input("\nChoose your first number: ") ia = float(a) except ValueError: print "\nNegative/positve integers or decimals only." # Only options allowed continue else: break while True and c != "6": try: b = raw_input("\nChoose your second number: ") ib = float(b) except ValueError: print "\nNegative/positive integers or decimals only." # Only options allowed continue else: break if c == "1": # Calling on the proper function print add(ia, ib) elif c == "2": print minus(ia, ib) elif c == "3": print division(ia, ib) elif c == "4": print multiplication(ia, ib) elif c == "5": print exponentiation(ia, ib) elif c == "6": print squareRoot(ia)
print(first,) total = first + second first = second second = total third += 1 n = int(input().split()) fib_series(n) def isprime(n): for i in range(2,): if n%i==0: print(n,"not prime") break else: print(n,"is prime") break n=int(input()) isprime(n) #math.py from calc import * add(23,15) diff(45,12) multiply(3,4) sqroot(25) floor_div(9,2) division(5,4) fib_series(10) print("prime_check:", isprime(10))
def Simple_Game(sc, manage, level, absolute_win): walls_number = 1 blocks_number = (level + 1)**2 blocks_creation = [] blocks_coords = [] b_size = 3 def division(blocks_number, walls_number): if blocks_number >= 12: blocks_number = int(blocks_number / 2) walls_number *= 2 b_size = 1 return walls_number walls_number = division(blocks_number, walls_number) def blocks(blocks_number, walls_number): random_pos = [ sample(range(-10, 10), k=blocks_number) for H in range(walls_number) ] walls_pos = [11, -11] for i1 in range(walls_number): pos_y = walls_pos[i1] for j1 in range(blocks_number): pos_x = random_pos[i1][j1] pos_z = random_pos[-i1][-j1] blocks_coords.append([pos_x, pos_y, pos_z]) blocks_creation.append( box( pos=vector(pos_x, pos_y, pos_z), size=(b_size, 1., b_size), color=(random.random(), random.random(), random.random()), )) wall1 = box( pos=vector(-12, 0, 0), size=(1., 25., 25.), color=(0.8, 0, 1), ) wall2 = box( pos=vector(0, 0, -12), size=(25., 25., 1.), color=(0.8, 0, 1), ) wall3 = box( pos=vector(12, 0, 0), size=(1., 25., 25.), color=(0.8, 0, 1), ) wall4 = box( pos=vector(0, -12.5, 0), size=(25., 0., 25.), color=(0.8, 0, 1), ) wall5 = box( pos=vector(0, 12, 0), size=(25., 1., 25.), color=(0.8, 0, 1), ) velocity = 0.8 ball = sphere(pos=vector(0, 0, 0), velocity=vector(velocity + 0.15, -velocity - 0.2, velocity - 0.05), color=(0, 1, 1), radius=1) A = [] AA = [] ASAS = [] BL = [] spider = box( pos=vector(0, -7, 0), size=(5., 1., 5.), color=(0.5, 0.5, 0.5), ) blocks(blocks_number, walls_number) def stars(a, b, c): if b == 11: random_numbers_i = [random.uniform(8, 11) for ran in range(4)] elif b == -11: random_numbers_i = [random.uniform(-11, -8) for ran in range(4)] random_numbers_j = [random.uniform(-3, 3) for rand in range(4)] random_numbers_s = [random.uniform(-pi, 0) for randi in range(4)] for i in random_numbers_i: for j in random_numbers_j: for k in random_numbers_j: A.append( points(pos=[ vector(a + j - 0.25 - i / 20, i - 0.25, c + k - 0.25 - i / 20), vector(a + k + 0.25 + i / 20, i + 0.25, c + j + 0.25 + i / 20) ], radius=i, color=(random.random(), random.random(), random.random()), visible=0.5)) for ii in random_numbers_i: for jj in random_numbers_j: for kk in random_numbers_j: AA.append( points(pos=[ vector(a + jj - 0.25 - ii / 30, ii - 0.25, c + kk - 0.25 - ii / 30), vector(a + jj + 0.25 + ii / 30, ii + 0.25, c + kk + 0.25 + ii / 30) ], radius=ii, color=color.red)) for iii in random_numbers_i: for jjj in random_numbers_j: for kkk in random_numbers_j: ASAS.append( points(pos=[ vector(a + jjj - 0.3 - iii / 30, iii - 0.25, c + kkk - 0.3 - iii / 30), vector(a + jjj + 0.3 + iii / 30, iii + 0.25, c + kkk + 0.3 + iii / 30) ], radius=jjj, color=(random.random(), random.random(), random.random()), visible=0.5)) for I in random_numbers_i: for J in random_numbers_s: BL.append( sphere(pos=vector(a - I / 3 * cos(J), I, c - I / 3 * sin(J)), radius=0.2, color=color.orange)) def stars_disappear(): for t0 in A: t0.visible = 0 for t1 in AA: t1.visible = 0 for t2 in ASAS: t2.visible = 0 for t3 in BL: t3.visible = 0 def control(sc, spider): if manage == 'mouse': mouse_control(sc, spider) else: keyboard_control(sc, spider, dist) dt = 0.15 dist = 0.01 WIN = blocks_number while True: rate(50) dist *= 0.99 control(sc, spider) if ball.pos.x <= -10.8 or ball.pos.x >= 10.8: ball.velocity.x *= (-1) if ball.pos.y <= -11.8 or ball.pos.y >= 10.8: ball.velocity.y *= (-1) if ball.pos.z <= -10.8 or ball.pos.z >= 10.8: ball.velocity.z *= (-1) if ( ball.pos.y <= spider.pos.y + 1.2 and ball.pos.y > spider.pos.y or ball.pos.y >= spider.pos.y + 1.2 and ball.pos.y < spider.pos.y ) and ball.pos.x >= spider.pos.x - 3 and ball.pos.x <= spider.pos.x + 3 and ball.pos.z >= spider.pos.z - 3 and ball.pos.z >= spider.pos.z - 3: ball.velocity *= (-1) if ball.pos.y <= spider.pos.y + 1.2 and ball.pos.y >= spider.pos.y - 1.2: if (ball.pos.x > spider.pos.x and ball.pos.x <= spider.pos.x + 3.2 or ball.pos.x < spider.pos.x and ball.pos.x >= spider.pos.x + 3.2): ball.velocity.x *= (-1) if (ball.pos.z > spider.pos.z and ball.pos.z <= spider.pos.z + 3.2 or ball.pos.z < spider.pos.z and ball.pos.z >= spider.pos.z + 3.2): ball.velocity.z *= (-1) ball.pos += ball.velocity * dt count = -1 for u in range(len(blocks_coords)): count += 1 if ball.pos.y >= 8.8: if blocks_coords[count][ 0] - 2.2 <= ball.pos.x and blocks_coords[count][ 0] + 2.2 >= ball.pos.x: if blocks_coords[count][ 2] - 2.2 <= ball.pos.z and blocks_coords[count][ 2] + 2.2 >= ball.pos.z: b = 11 a = blocks_coords[count][0] c = blocks_coords[count][2] stars(a, b, c) ball.velocity.y *= (-1) try: del blocks_coords[u] blocks_creation[count].visible = False del blocks_creation[count] WIN -= 1 count -= 1 sleep(0.02) stars_disappear() except: pass elif level >= 3 and ball.pos.y <= -8.8: if blocks_coords[count][ 0] - 2.2 <= ball.pos.x and blocks_coords[count][ 0] + 2.2 >= ball.pos.x: if blocks_coords[count][ 2] - 2.2 <= ball.pos.z and blocks_coords[count][ 2] + 2.2 >= ball.pos.z: b = -11 a = blocks_coords[count][0] c = blocks_coords[count][2] stars(a, b, c) ball.velocity.y *= (-1) try: del blocks_coords[u] blocks_creation[count].visible = False del blocks_creation[count] WIN -= 1 count -= 1 sleep(0.02) stars_disappear() except: pass if WIN == 0: labelwin = label(pos=(0, 0, 0), text='YOU WIN', height=50, border=50, color=(0, 1, 1), opacity=0.5) sleep(2) labelwin.text = 'SCORE:' + str(level * 100) level += 1 spider.visible = 0 ball.visible = 0 sleep(1) labelwin.visible = 0 del spider del ball if level == 4: absolute_win = 1 labelwin.text = 'ABSOLUTE WINNER!' Menu() else: labelwin.text = 'LEVEL' + str(level) sleep(1) Simple_Game(sc, manage, level, 0)
def divide(self, a, b): self.result = division(a, b) return self.result
def interpol(xout, xin, yin): """ One-dimensional linear interpolation on first dimension. If xin and yin are 1D arrays, this function wraps to numpy.interp. If yin is an ND array and xin and xout are 1D, then yin is interpolated in its first dimension. Definition ---------- def interpol(xout, xin, yin): Input ----- xout 1D array of the x-coordinates of the interpolated values if yin is ND array. array-like of x-coordinates of the interpolated values if yin is 1D array. xin 1D array of the x-coordinates of the data points, must be increasing. yin ND array of the y-coordinates of the data points, 1st dim must have same length as xin. Output ------ The interpolated values with shape (np.size(xin),)+yin.shape[1:]. Examples -------- >>> import numpy as np >>> xin = np.arange(360, dtype=np.float) >>> yin = np.sin(xin) >>> xout = np.arange(10)*10. + 0.5 >>> soll = np.interp(xout, xin, yin) >>> yout = interpol(xout, xin, yin) >>> print(np.any(yout != soll)) False >>> sout = (3,1) >>> yin2 = np.transpose(np.tile(yin,sout)) >>> yout = interpol(xout, xin, yin2) >>> for i in range(3): ... if np.any(yout[:,i] != soll): ... print(True) >>> sout = (3,2,1) >>> yin3 = np.transpose(np.tile(yin,sout)) >>> yout = interpol(xout, xin, yin3) >>> for i in range(3): ... for j in range(2): ... if np.any(yout[:,j,i] != soll): ... print(True) License ------- This file is part of the JAMS Python package, distributed under the MIT License. The JAMS Python package originates from the former UFZ Python library, Department of Computational Hydrosystems, Helmholtz Centre for Environmental Research - UFZ, Leipzig, Germany. Copyright (c) 2012-2016 Matthias Cuntz - mc (at) macu (dot) de Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. History ------- Written, MC, Jun 2012 Modified, MC, Feb 2013 - ported to Python 3 MC, Apr 2014 - assert MC, Nov 2016 - const.tiny -> const.eps """ # # If yin 1D-array then call immediately np.interp without check # If no np.interp wanted uncomment next line # isone = False if np.ndim(yin) == 1: # If no np.interp wanted comment next line and uncomment the following two lines return np.interp(xout, xin, yin) # isone = True # yin = yin[:,np.newaxis] # # Check input assert np.ndim(xin) == 1, "x input values not 1D array" assert np.ndim(xout) <= 1, "x output values not scalar or 1D array" # # Subscripts eps = const.eps s = np.minimum(np.maximum(np.searchsorted(xin, xout)-1, 0), xin.size-2) # Subscript intervals # Distances ums1 = xout-xin[s] # distance from point before ums2 = xin[s+1]-xin[s] ums = division(ums1, ums2, 0.) ums = np.where((np.abs(ums1) < eps) | (np.abs(ums2) < eps), 0., ums) # for numerical stability # Blow to output shape sout = yin.shape[1:][::-1] + (1,) ums = np.transpose(np.tile(ums,sout)) # If no np.interp wanted comment next line and uncomment the following five lines return yin[s,...] + ums*(yin[s+1,...]-yin[s,...])
print(e) print("please try again!") else: break finally: print("cleaning up.") del x, y # In[128]: def division(x,y): if y == 0 : raise ZeroDivisionError('The zero is not allow') return x/y division(10,1) # In[195]: #方法,属性,迭代器 在python中 __xxx__ 由这些名字组成的集合所包含的方法称为魔法方法 #__metaclass__=type #构造方法 class Foobar: def __init__(self,value = 42): #构造方法 self.somevar = value f=Foobar('BC') f.somevar
def __rtruediv__(self, other): if simplify_null_element_division(other, self): return 0 else: return division(other, self)
MOD06_fp = 'MYD06_L2.A{:04d}{:03d}.{:02d}{:02d}.006.?????????????.hdf'.format( y, JD, granule_time.hour, granule_time.minute) MOD03_fn, MOD06_fn = [], [] for MOD06_flist in os.listdir(MOD06_path): if fnmatch.fnmatch(MOD06_flist, MOD06_fp): MOD06_fn = MOD06_flist for MOD03_flist in os.listdir(MOD03_path): if fnmatch.fnmatch(MOD03_flist, MOD03_fp): MOD03_fn = MOD03_flist if MOD03_fn and MOD06_fn: # if both MOD06 and MOD03 products are in the directory filenames0[i] = MOD06_fn + ' ' + MOD03_fn i = i + 1 granule_time += datetime.timedelta(minutes=5) ##### To split all the input files to different partitions for parallel computation filenames = filter(lambda x: len(x) > 0, filenames0) result = spark.sparkContext.parallelize( filenames, 288).map(lambda x: aggregate(x)).reduce(add) TOT_pix = np.sum(result[::2], axis=0) CLD_pix = np.sum(result[1::2], axis=0) ##### Written by Hua Song, using functions aggregate above print('derive the averaged Level-3 cloud fraction') total_cloud_fraction = division(CLD_pix, TOT_pix).reshape([nlat, nlon]) print('plot global map') plot_global_map(lat_bnd,lon_bnd,total_cloud_fraction, cmap= plt.get_cmap('jet'), \ vmin=0.0,vmax=1.0,title='cloud fraction', figure_name='MODIS_total_cloud_fraction_daily_mean_Spark') spark.stop()
def test_np_div(): two = np.array([2]) eight = np.array([8]) assert division(two,eight) == 0.25
def test_div(): assert division(2,8) == 0.25
from __future__ import division #DAY07_24DEC2016_Code015.py #NOTES ''' Using __future__ we can import the features of higher python versions without upgrading our python . ''' #QUES ''' ''' #SOLUTION def division(a, b): #Using __future__ I am using divsion as in Python 3.x print a / b #7/3 = 2.3333 print a // b #7/3 = 2 if __name__ == '__main__': a = int(raw_input()) b = int(raw_input()) result = division(a, b) print result
while numerator > 0 : prev_state = states.get(numerator,None) if prev_state!=None: start_repeat_index = prev_state non_repeating = answer[:start_repeat_index] repeating = answer[start_repeat_index:] return non_repeating + '[' + repeating + ']' states[numerator] = len(answer) v = numerator // denomerator answer+= str(v) numerator -= v*denomerator numerator *= 10 if numerator > 0: return answer + '...' return answer greatest = 0 greatestNumber = 1 for i in xrange(1,1000): number = division(1,i) start = number.find('[') end = number.find(']') answer = end-start if answer > greatest: greatest = answer greatestNumber = i print greatestNumber
buttonClear = Button(root, text='Clear', command=lambda: clear(trashcan)) buttonClear.grid(row=1, column=0) root.bind('c', clear) # Subtract Button buttonSubtract = Button(root, text='-', command=lambda: subtraction(trashcan)) buttonSubtract.grid(row=3, column=3) root.bind('-', subtraction) # Addition Button buttonAdd = Button(root, text='+', command=lambda: addition(trashcan)) buttonAdd.grid(row=4, column=3) root.bind('+', addition) # Divide Button buttonDivide = Button(root, text='÷', command=lambda: division(trashcan)) buttonDivide.grid(row=1, column=3) root.bind('/', division) # Multiply Button buttonMultiply = Button(root, text='x', command=lambda: multiplication(trashcan)) buttonMultiply.grid(row=2, column=3) root.bind('*', multiplication) # Power Button buttonPower = Button(root, text='^', command=power) buttonPower.grid(row=2, column=4) # Sqrt Button
for i in np.arange(latlon_index_unique.size): j = latlon_index_unique[i] TOT_pix[j] = TOT_pix[j] + np.sum( CM[np.where(latlon_index == j)] >= 0) CLD_pix[j] = CLD_pix[j] + np.sum( CM[np.where(latlon_index == j)] <= 1) CTP_pix[j] = CTP_pix[j] + np.sum( CTP[np.where(latlon_index == j)]) CTT_pix[j] = CTT_pix[j] + np.sum( CTT[np.where(latlon_index == j)]) CTH_pix[j] = CTH_pix[j] + np.sum( CTH[np.where(latlon_index == j)]) granule_time += datetime.timedelta(minutes=5) print('derive the averaged Level-3 cloud fraction') total_cloud_fraction = division(CLD_pix, TOT_pix).reshape([nlat, nlon]) mean['CTP'] = division(CTP_pix, CLD_pix).reshape([nlat, nlon]) mean['CTT'] = division(CTT_pix, CLD_pix).reshape([nlat, nlon]) mean['CTH'] = division(CTH_pix, CLD_pix).reshape([nlat, nlon]) save_hdf(out_name, total_cloud_fraction, mean, lat_bnd, lon_bnd) end = time.time() print('Total # of file couples read:%d' % (tot_F)) print('Total Cloud Fraction: %0.2f' % np.nansum(total_cloud_fraction)) print('Mean CTP: %0.2f hPa' % np.nanmean(mean['CTP'])) print('Mean CTT: %0.2f K' % np.nanmean(mean['CTT'])) print('Mean CTH: %0.2f m' % np.nanmean(mean['CTH'])) print('Time elapsed:%0.2f hours' % (end / 60 / 60 - start / 60 / 60)) # print('plot global map') # plot_global_map(lat_bnd,lon_bnd,total_cloud_fraction, cmap= plt.get_cmap('jet'), \ # vmin=0.0,vmax=1.0,title='cloud fraction', figure_name='MODIS_total_cloud_fraction_daily_mean_Python')