def A(n: int, k: int): """ Функция возвращает кол-во размещений(с учетом последовательности) к элементов из n возможных n - всего элементов k - размер выборки из всех элементов """ return int(fl(n) / fl(n - k))
def get_crop(img, path): factor_ceil = random.uniform(0.4, 1) factor_floor = random.uniform(0, 0.4) l1, l2 = img.shape[0], img.shape[1] img_crop = img[fl(l1 * factor_floor):fl(l2 * factor_ceil), fl(l1 * factor_floor):fl(l2 * factor_ceil)] cv2.imwrite(path, img_crop)
def C(n: int, k: int): """ Функция возвращает кол-во сочетаний(без учета последовательности) к элементов из n возможных n - всего элементов k - размер выборки из всех элементов """ return int(fl(n) / (fl(k) * fl(n - k)))
def update_rating(request): if not request.user.is_authenticated: return JsonResponse({"msg": "authenticationerror"}) data = json.loads(request.body) productId = data['productId'] rating = float(data['rating']) try: product = Story.objects.get(id=productId) except: print("pid:", productId) return JsonResponse({"msg": "servererror"}) reviews = product.reviewer_set.all() rev_arr = [elem.reviewerguy for elem in reviews] rat_arr = [float(elem.rating) for elem in reviews] sum_rat = 0 count = 0 for x in rat_arr: if x != 6: sum_rat += x count += 1 if request.user.username not in rev_arr: product.reviewer_set.create(reviewerguy=request.user.username, rating=rating) sum_rat += float(rating) count += 1 else: review = Reviewer.objects.get(reviewerguy=request.user.username, reviewedstory=product) if review.rating != 6: sum_rat -= float(review.rating) else: count += 1 sum_rat += float(rating) review.rating = rating review.save() product.rating = round(sum_rat / count, 1) if product.rating - fl(product.rating) < 0.3: product.rating = fl(product.rating) elif product.rating - fl(product.rating) > 0.7: product.rating = fl(product.rating) + 1 else: product.rating = fl(product.rating) + 0.5 product.save() return JsonResponse({"msg": "done"})
def draw(self): for i in range(len(self.b)): print('\tRow ' + str(i) + ' ' * (int(fl((i - 2.5)**2) + 4)), end='') for c in self.b[i]: print(c, end=' ') print()
def func(n, cache): global b if (n == 0): return 0 if (cache[n] != -1): return cache[n] else: cache[n] = n + func(fl(n / 2), cache) return cache[n]
def poisson(n: int, m: int, p: float): """ Распределение Пуассона Функция возвращет вероятность k наступлени события с А в n независимых испытаниях когда веростность наступления А мала, а количество испытаний большое n - количество испытаний m - количество наступления события A из n испытаний p - вероятность настуления А в каждом из испытаний """ lambda_ = n * p return (lambda_**m / fl(m)) * exp(-lambda_)
def MyCorrelation(im, filter, mode): # filter height and width if mode not in ['full', 'same', 'valid']: return fh, fw = filter.shape # Create a copy of the image with a black border to perform correlation. ih, iw = im.shape ih = ih + 2 * (fh - 1) iw = iw + 2 * (fw - 1) im_cp = np.zeros((ih, iw)) im_cp[fh - 1:ih - fh + 1, fw - 1:iw - fw + 1] = im[:, :] # create a blank image to store the result dst = np.zeros((ih, iw)) # start and end point of correlation x_start = fl(fw / 2) x_end = iw - fl(fw / 2) y_start = fl(fh / 2) y_end = ih - fl(fh / 2) # iterate through each pixel proper distance away from border and perform correlation for x in range(x_start, x_end, 1): for y in range(y_start, y_end, 1): color = 0 for x_f in range(fw): for y_f in range(fh): x_delta = x_f - fl(fw / 2) y_delta = y_f - fl(fh / 2) color = color + filter[y_f, x_f] * im_cp[y + y_delta, x + x_delta] dst[y, x] = color # crop image according to the mode requirement if mode == 'full': return dst[y_start:y_end, x_start:x_end] elif mode == 'same': return dst[fh - 1:ih - fh + 1, fw - 1:iw - fw + 1] else: return dst[fh - 1 + fl(fh / 2):ih - fh - fl(fh / 2) + 1, fw - 1 + fl(fw / 2):iw - fw - fl(fw / 2) + 1]
def calc_Damage(attacker, defender, move): #todo: Include a check to determine if the move has a special damage formula, such as Seismic Toss or Dragon Rage L = attacker.Level #todo: Add support for variable base power P = move.Power #todo: Include checks on multipliers for stats if move.Damage == 'physical': A = attacker.Stats['Atk'] D = defender.Stats['Def'] else: A = attacker.Stats['SpA'] D = defender.Stats['SpD'] dmg = fl(fl(fl(2 * L / 5 + 2) * A * P / D) / 50) + 2 t = [i.lower().capitalize() for i in attacker.Type] if move.Type in t: dmg *= 1.5 dmg *= defender.DefType[move.Type] R = random.choice(range(16)) rand_mult = float(100 - R) / 100 dmg *= rand_mult return int(dmg)
def calc_Damage(attacker, defender, move): # todo: Include a check to determine if the move has a special damage formula, such as Seismic Toss or Dragon Rage L = attacker.Level # todo: Add support for variable base power P = move.Power # todo: Include checks on multipliers for stats if move.Damage == "physical": A = attacker.Stats["Atk"] D = defender.Stats["Def"] else: A = attacker.Stats["SpA"] D = defender.Stats["SpD"] dmg = fl(fl(fl(2 * L / 5 + 2) * A * P / D) / 50) + 2 t = [i.lower().capitalize() for i in attacker.Type] if move.Type in t: dmg *= 1.5 dmg *= defender.DefType[move.Type] R = random.choice(range(16)) rand_mult = float(100 - R) / 100 dmg *= rand_mult return int(dmg)
def binarysearch(arr, l, r, q): if r >= l: mid = int(fl((l + r) / 2)) print("left = ", l) print("right =", r) print("Current middle of array is :", mid) if arr[mid] == q: print(" i am here now and mid=", mid) return mid elif arr[mid] > q: return binarysearch(arr, 0, mid, q) else: return binarysearch(arr, mid, r, q) else: return -1
def payouts(self, player): payouts = { 'SIX!!!': 1500, 'LUCKY6': 250, 'CHERRY': 150, '3-BAR!': 100, '2-BAR!': 50, '1-BAR!': 20, 'MIX BAR': 3 } if self.horizontal_winning_value: payout_value = payouts[self.horizontal_winning_value] print("You have won {} tokens!".format(self.wager * payout_value)) player.add_tokens(self.wager * payout_value) elif self.diagonal_winning_value: payout_value = payouts[self.diagonal_winning_value] floor_payout = int(fl(self.wager * payout_value * 0.75)) print("You have won {} tokens!".format(floor_payout)) player.add_tokens(floor_payout) else: print("Won 0 tokens. Try again!")
def non_max_suppression(im, f_size): ih, iw = im.shape ih = ih + 2 * (f_size - 1) iw = iw + 2 * (f_size - 1) radius = fl(f_size / 2) im_cp = np.zeros((ih, iw)) im_cp[f_size - 1:ih - f_size + 1, f_size - 1:iw - f_size + 1] = im[:, :] x_start = radius x_end = iw - radius y_start = radius y_end = ih - radius # try a 3x3 window for suppression first for x in range(x_start, x_end, 1): for y in range(y_start, y_end, 1): if im_cp[y, x] < im_cp[y - radius:y + radius, x - radius:x + radius].max(): im_cp[y, x] = 0 # elif im_cp[y, x] != 0: # im_cp[y, x] = 1 return im_cp[f_size - 1: ih - f_size + 1, f_size - 1: iw - f_size + 1]
def send_marker(index): global ascii_value, curr_Epoch timestamp = int(time.time() * 100) if testMode: marker_list[timestamp] = index else: vec = [] if (ascii_value < 65): temp = ascii_value - 22 else: temp = ascii_value - 65 col = temp % 6 + 7 row = fl(temp / 6) + 1 curr_marker = index * 1000000 + (row + 10) * 10000 + ( col + 10) * 100 + (curr_Epoch + 10) vec.append(curr_marker) outlet.push_sample(vec) print("Now sending marker: \t" + str(curr_marker) + "\n") # create_marker_dict() root.after(0, change_color, curr_Epoch)
def csv_preprocessing(filename, subjectname, no_records): global default_name, default_filename print("Starting csv_preprocessing:") src_path = os.path.join(os.getcwd(), 'Easy') dest_path = os.path.join(os.getcwd(), 'Data') dest_path = os.path.join(dest_path, subjectname) for fname in os.listdir(os.path.join(os.getcwd(), 'Easy')): if fnmatch.fnmatch(fname, '*Session.easy'): default_filename = fname break def_filename = os.path.splitext(default_filename)[0] if (os.path.isfile(os.path.join(src_path, default_filename))): # Renaming other file formats like .info and .edf if (os.path.isfile(os.path.join(src_path, def_filename + ".info"))): os.rename(os.path.join(src_path, def_filename + ".info"), os.path.join(src_path, filename + ".info")) if (os.path.isfile(os.path.join(src_path, def_filename + ".edf"))): os.rename(os.path.join(src_path, def_filename + ".edf"), os.path.join(src_path, filename + ".edf")) # print(filename) os.rename(os.path.join(src_path, default_filename), os.path.join(src_path, filename + ".easy")) dest_csv_file = str(filename) + ".csv" src_easy_file = str(filename) + ".easy" source_file = os.path.join(src_path, src_easy_file) print(source_file) dest_file = os.path.join(dest_path, dest_csv_file) with open(source_file, "r") as infile: prev_val = marker = asciivalue = temp = epoch = 0 coordinates = [] prev_row = 0 ctr = -1 reader = csv.reader(infile, dialect="excel-tab") with open(dest_file, "w") as outfile: writer = csv.writer(outfile, delimiter=',') for row in reader: if (int(row[8], 10) > 0): if ctr > 0 and ctr < no_records: while ctr < no_records: ctr = ctr + 1 writer.writerow(prev_row) ctr = 0 prev_val = row[8] temp = fl(int(prev_val) % 1000000) marker = fl(int(prev_val) / 1000000) r = fl(temp / 10000) - 10 temp %= 10000 c = fl(temp / 100) - 10 epoch = temp % 100 - 10 asciivalue = c * 100 + r coordinates.clear() coordinates.append(c) coordinates.append(r) else: if (prev_val is 0): continue if (ctr < no_records): row[8] = marker row.append(asciivalue) row.append(epoch) ctr = ctr + 1 if (row[8] in coordinates): row.append(1) else: row.append(0) prev_row = row.copy() writer.writerow(row)
from sys import stdin as si from math import factorial as f, floor as fl if __name__ == '__main__': n = int(input()) for i in range(n): m = map(int, input()) total = sum(list(map(int, input().split()))) print(total + fl(total * (total - 1) / 2)) #print (fl(total*(total+1)/2)) ''' https://www.codechef.com/problems/CSUB '''
# # # Competition: Google Kickstart 2019 – Round G # # Problem 1: Book Reading # # Code by: Muhammad Azeem # # from math import floor as fl T = int(input()) for t in range(1, T + 1): N, M, Q = map(int, input().split()) m = map(int, input().split()) r = map(int, input().split()) hmap = {} for g in m: hmap[g] = None count = 0 for i in r: lim = fl(N / i) * i for p in range(1, lim + 1): page = p * i if page > lim: break if page not in hmap: count += 1 print('Case #' + str(t) + ': ' + str(count))
n = int(input('enter number:')) from math import sqrt as sq from math import floor as fl for i in range(1, n + 1): print(fl(i * sq(2)), end=' ')
def from_float(cls, value): if isinstance(value, float): return cls(fl(value)) return 'value is not a float'
from math import floor as fl a, b = map(int, input().split()) ans = -1 for i in range(1, 1250): if fl(i * 0.08) == a: if fl(i * 0.1) == b: ans = i break print(ans)
def f(x): return x*fl(x*fl(x*fl(x)))
import bisect as bi from math import floor as fl n=int(input()) a=[] for I in range(n): x=int(input()) bi.insort(a,x) si = len(a) if(si%2!=0): print(a[si//2]) else: print(fl((a[(si//2)-1]+ a[(si//2)])/2))
def main(): _sel_user = 4 _sel_game = "B" _work_file = get_selected_file_name(sel_user=_sel_user, sel_game=_sel_game) _dataframe = get_dataframe(_work_file) # global variables declaration s_rate = 512 _num_rows = 1024 _num_sequences = 20 _dtf_len = len(_dataframe) # /global variables declaration if _num_sequences is "max": _num_sequences = fl(_dtf_len / _num_rows) elif (_num_sequences * _num_rows) > _dtf_len: print("Data requested exceeds the accessible data.") print("Requested sequences: {}".format(_num_sequences)) print("Length of sequence: {}".format(_num_rows)) print("\tRows requested: {}".format(_num_sequences * _num_rows)) print("\tData available: {}".format(_dtf_len)) print( "If you want to use the full dataframe, set _num_sequences to 'max'" ) exit(1) print("Data requested can be obtained from the current data.") print("Requested sequences: {}".format(_num_sequences)) print("Length of sequence: {}".format(_num_rows)) print("\tRows requested: {}".format(_num_sequences * _num_rows)) print("\tData available: {}".format(_dtf_len)) delta_max_list = [] theta_max_list = [] alpha_max_list = [] beta_max_list = [] for i in range(0, _num_sequences): print("Sequence {0}/{1}".format(i + 1, _num_sequences)) f, d_a, t_a, a_a, b_a = get_assym(_dataframe, i, _num_rows) subplot_bands( y=f, delta=d_a, theta=t_a, alpha=a_a, beta=b_a, ylim_l=-0.2, ylim_h=0.2, folder="asym", fig_num=i, is_active=True, save_fig=True, xlab="epocs", ylab="index", ) delta_max_list.append( np.amax(get_values_between_l_h(d_a, f, _delta_lf, _delta_hf))) theta_max_list.append( np.amax(get_values_between_l_h(t_a, f, _theta_lf, _theta_hf))) alpha_max_list.append( np.amax(get_values_between_l_h(a_a, f, _alpha_lf, _alpha_hf))) beta_max_list.append( np.amax(get_values_between_l_h(b_a, f, _beta_lf, _beta_hf))) plt.close("all") fig, axes = plt.subplots(2, 2) axes[0, 0].plot(delta_max_list) axes[0, 0].set_title("Max DELTA") axes[0, 0].set(xlabel="epocs", ylabel="index") axes[0, 1].plot(theta_max_list) axes[0, 1].set_title("Max THETA") axes[0, 1].set(xlabel="epocs", ylabel="index") axes[1, 0].plot(alpha_max_list) axes[1, 0].set_title("Max ALPHA") axes[1, 0].set(xlabel="epocs", ylabel="index") axes[1, 1].plot(beta_max_list) axes[1, 1].set_title("Max BETA") axes[1, 1].set(xlabel="epocs", ylabel="index") fig.subplots_adjust(hspace=0.6) fig.subplots_adjust(wspace=0.5) plt.savefig("subplots/max/sub_max_USR{0}_{1}_#{2}.png".format( _sel_user, _sel_game, _num_sequences)) plt.close("all")
'''> numberOfTriangles(n) n : the sum of all three edges ------------------------------------------------- Count the number of triples with sum equal to 'n' that are triangular ------------------------------------------------- 1. bound := [([n/2]+1)/2] 2. answer := (bound) * (bound + 1) - [n/2] * bound + [n/3] - bound 3. k := [[n/3] / 2] 4. answer := answer + (n+1)*k - 3*k*(k+1) 5. if [n / 3] mod 2 is 1: 6. answer := answer + [(n - 3*(2*k+1)) / 2] 7. return answer ''' peymaneh = int(1e9 + 7) n = int(input()) from math import floor as fl bound = fl((fl(n / 2) + 1) / 2) answer = bound * (bound + 1) - fl(n / 2) * bound + fl(n / 3) - bound k = fl(fl(n / 3) / 2) answer = answer + (n + 1) * k - 3 * k * (k + 1) if ((fl(n / 3) % 2) == 1): answer = answer + fl((n - 3 * (2 * k + 1)) / 2) print(answer % peymaneh)
# For reading JSON data file with open(filename, 'r') as obj: dataset = list(json_readr(filename)) count = 1 # for Loading URL from dictionary and storing images and annotations of respective images for it in range(len(dataset)): width = dataset[it]['annotation'][0]['imageWidth'] height = dataset[it]['annotation'][0]['imageHeight'] top_left_x = dataset[it]['annotation'][0]['points'][0]['x'] top_left_y = dataset[it]['annotation'][0]['points'][0]['y'] bottom_right_x = dataset[it]['annotation'][0]['points'][1]['x'] bottom_right_y = dataset[it]['annotation'][0]['points'][1]['y'] # reading vehicle images for cropping out license plates img = cv2.imread( "C:\\Users\\Aj\\Desktop\\HumanAI\\vehicle-number-plate-detection Datasets\\data\\image%d.png" % count, 1) # using annotations( x and y points ) in json file for detection of license plates dx1 = fl(top_left_x * width) dx2 = fl(bottom_right_x * width) dy1 = fl(top_left_y * height) dy2 = fl(bottom_right_y * height) img = img[dy1:dy2, dx1:dx2] # storing the extracted license plates cv2.imwrite('image%d.jpg' % count, img) count += 1
from math import floor as fl, ceil as cl, sqrt as st import textwrap s = input().replace(' ', '') ln = len(s) mini, maxi = fl(st(ln)), cl(st(ln)) s = textwrap.wrap(s, width=maxi) i = 0 ans = '' while i < maxi: j = 0 while j < maxi: try: ans += s[j][i] except IndexError: pass j += 1 ans += ' ' i += 1 print(ans)
from math import floor as fl from math import log a1=[1]*31 for i in range(1,31): a1[i]=a1[i-1]*2 t=int(input()) for I in range(t): a,b=[int(i) for i in input().split()] lev1=fl(log(a,2)) lev2=fl(log(b,2)) mid1=(((3*a1[lev1])-1))//2 mid2=((3*a1[lev2])-1)//2 if(a==b): print(0) elif(lev1==0): print(lev2) elif(lev2==0): print(lev1) elif((lev1>=lev2 or lev2>=lev1) and ((a<(mid1+1) and (b>mid2)) or (b<mid2+1 and a>mid1))): print(lev1+lev2) else: count=0 while(a!=b): if(a>b): a//=2 count+=1 else: b//=2 count+=1 print(count)
from math import sqrt as sq from math import floor as fl n = int(input()) l = [] c = 0 for _ in range(n): l.append(list(map(str, input().split()))) for i in l: d_c = i.count('D') c += d_c print(fl(sq(c)))
def permutations(n: int): """ Функция возвращает кол-во перестановок n элементов n - всего элементов """ return int(fl(n))
def format_time(time, name): return name + ": " + str(fl(time.seconds / 3600)).rjust( 2, '0') + ":" + str(fl(time.seconds / 60)).rjust(2, '0') + ":" + str( fl(time.seconds % 60)).rjust(2, '0')
if __name__=='__main__': # solve x*floor(x*floor(x*floor(x))) = n, where n = 2020 e.g. def f(x): return x*fl(x*fl(x*fl(x))) n = 2020 numer = 1 denom = 1 # a = frac(1, 1) is_increment_numerator = True while True: a = frac(numer, denom) y = f(a) fl_y = fl(y) print("numer: {}, denom: {}, float(y): {}".format(numer, denom, float(y))) if y.numerator%y.denominator==0 and fl_y==n: break if is_increment_numerator: numer += 1 a_new = frac(numer, denom) # fl_a_new = fl(f(a_new)) if f(a_new)>n: # if fl_a_new>n: is_increment_numerator = False a = a_new else: