blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
4c5afa810c04515bf7659fe1f3c50ef29776e132
songdanlee/python_code_basic
/day09/射击.py
4,865
3.546875
4
import time import sys import random # 创建枪对应的类型和弹夹,子弹伤害的关系 DICT_GUN = { "AWM": {"clip": 100, "bullet": 10}, "SRL": {"clip": 150, "bullet": 120}, "K98": {"clip": 80, "bullet": 200}, "Win94": {"clip": 30, "bullet": 50}, } # 封装子弹类 属性:伤害值 class Bullet(): def __init__(self, damage): self.damage = damage def move(self,enemy): print(f"子弹飞向{enemy.name}") # 封装弹夹类 # 属性:弹夹容量 存储子弹的列表 class Clip(): def __init__(self, size, bullets): self.size = size self.bullets = bullets def __str__(self): return f"弹夹容量为{self.size},当前有{len(self.bullets)}发子弹" # 封装枪类 # 属性:型号 弹夹 = None # 行为: # 射击(敌人) < 打出一颗子弹 > class Gun(): def __init__(self, type, clip): self.type = type self.clip = clip def shoot(self,enemy): print("射击,打出一个子弹") bullet = self.clip.bullets.pop() bullet.move(enemy) return bullet def __str__(self): return f"{self.type}枪,{self.clip}" # 封装狙击手类 # 属性:名字 枪 = None # 行为: # 捡枪(枪) # 装弹 < 创建弹夹,循环创建子弹,装进弹夹里,然后把弹夹装到墙上 > # 瞄准(敌人) # 射击(敌人) < 调用枪的射击方法 > class Sniper(): def __init__(self, name): self.name = name self.gun = None def pickGun(self, gun): if isinstance(gun, Gun): self.gun = gun print(f"{self.name}捡到一把{self.gun.type}") else: print("捡枪失败") def reload(self): print(self.gun.clip.size) if self.__checkGUN(): if self.gun.clip.size == len(self.gun.clip.bullets): print("弹夹已满") else: # 通过枪的型号获取子弹伤害 bullet = DICT_GUN.get(self.gun.type).get("bullet") # 弹夹容量 clip = self.gun.clip count = 0 while len(clip.bullets) < clip.size: time.sleep(0.001) clip.bullets.append(Bullet(bullet)) count += 1 if count % 10 == 0: print("装弹--------ing") count = 0 print(f"弹夹装填完毕,共有{clip.size}发子弹") def aim(self, enemy): if self.__checkGUN(): print("瞄准...........") time.sleep(2) print(f"瞄准{enemy.name}完毕") def shoot(self, enemy): if self.__checkBullets() == 0: self.reload() print("重新瞄准") self.aim(enemy) if self.__checkGUN(): bullet = self.gun.shoot(enemy) enemy.getShot(bullet) if enemy.isAlive(): print(f"{enemy.name}中弹,还有{enemy.hp}血") else: print(f"{self.name}用{self.gun.type}枪,击败了{enemy.name}") sys.exit(0) print(f"弹夹还有{len(self.gun.clip.bullets)}发子弹") def __checkGUN(self): if self.gun == None: print("当前没有可以操作的枪,请先捡枪") return 0 return 1 def __checkBullets(self): if len(self.gun.clip.bullets) > 0: return 1 else: print("已经没有子弹,正在准备装弹") return 0 # 5.封装敌人类 # 属性:名称 生命值 # 行为:是否死亡<根据生命值进行判断,如果<=0,应声倒下> class Enemy(): def __init__(self, name, hp): self.name = name self.hp = hp def isAlive(self): if self.hp > 0: return 1 else: return 0 def getShot(self,bullet): self.hp -= bullet.damage # 利用字典创建枪 # 随机向弹夹添加子弹 def GUNFactory(k): lis = [] # for i in range(random.randint(1, 20)): lis.append(Bullet(DICT_GUN.get(k).get("bullet"))) clp = Clip(DICT_GUN.get(k).get("clip"), lis) return Gun(k, clp) # 狙击手xxx捡起一把xx枪,装弹,瞄准敌人xxx,射击,敌人生命值归0,应声倒下 if __name__ == '__main__': enermy = Enemy("play01", 1000) # enermy.isAlive() gunlist = ["AWM", "SRL", "98K", "Win94"] # 创建四把枪 AWM = GUNFactory("AWM") SRL = GUNFactory("SRL") K98 = GUNFactory("K98") Win94 = GUNFactory("Win94") # print(AWM.clip.size) # print(SRL) # print(K98) # print(Win94) player = Sniper("sniper") player.pickGun(AWM) # player.reload() while enermy.hp > 0: player.aim(enermy) player.shoot(enermy)
bbb0397bbbe48de1d8f5bd9d0d2e62a2e29f151f
Kieran-Badesha/Data21Notes
/JSON_files/working_with_json.py
1,016
3.515625
4
import json # pet_data = { # "name": "Bob", # "food": "Carrots" # } # # # with open("new_json_file.json", "w") as jsonfile: # json.dump(pet_data, jsonfile) # # # with open("new_json_file.json") as jsonfile: # pet = json.load(jsonfile) # print(type(pet)) # print(pet) # print(pet["name"]) class RatesParser: def __init__(self, rates_file): rates_info = self._open_json_file(rates_file) self.base = rates_info["base"] self.rates = rates_info["rates"] self.gbp = self.rates["GBP"] def _open_json_file(self, file): try: with open(file) as rates: return json.load(rates) except FileNotFoundError: print('Sorry File Not Found') except FileExistsError: print('Sorry File Does Not Exist') finally: print('JSON open complete') rates_reader = RatesParser("exchange_rates.json") print(rates_reader.base) print(rates_reader.gbp)
c25839510812e2276a75af10167bfeb55947edd2
rishavhack/Data-Structure-in-Python
/Exception Handling/Exception Handling.py
666
3.703125
4
# IndexError, ImportError, IOError, ZeroDivisionError, TypeError. # Python program to handle simple runtime error a = [1, 2, 3] try: print "Second element = %d"%(a[1]) #Throw Error print "fourth element =%d" %(a[3]) except IndexError: print "An error occured" print "\n" try: a = 3 if a<4: b = a/(a-3) print "Value of b =",b except(ZeroDivisionError,NameError): print '\nError occured' print "\n" def AbyB(a,b): try: c = ((a+b)/(a-b)) except ZeroDivisionError: print "a/b result in 0" else: print c AbyB(2.0,3.0) AbyB(3.0,3.0) #Raising Exception: print "\n" try: raise NameError('Hi There') except NameError: print "An Exception" raise
69aab17feaf121144d9461af42c3a1339cbf6a2e
marciopocebon/abstract-data-types
/python/src/stack/stack_linked_list.py
900
3.796875
4
from stack_interface import StackInterface from src.list.node import Node class StackLinkedList(StackInterface): """ stack implementation using a linked list """ def __init__(self): """ create a new empty stack """ self.head = None self.length = 0 def isEmpty(self): """ verify is the stack is empty """ return (self.length == 0) def push(self, cargo): """ add a new node to the stack """ # TODO: implement me! # if not (isinstance(cargo, int) or isinstance(cargo, str)): raise ValueError node = Node(cargo) if not self.isEmpty(): node.next = self.head self.head = node self.length+=1 def pop(self): """ remove and return the last added node from the stack """ if self.isEmpty(): raise IndexError('the stack is empty!') toBeRemoved = self.head self.head = self.head.next self.length-=1 return toBeRemoved
deda1bf39cf777a5df09e6dda7de90e9684ee00a
uzairamer/hello-world
/re/WordAnalysisKit.py
2,150
4.21875
4
import re from collections import defaultdict class WordAnalysis(object): """WordAnalysis consists of static methods that helps in word analysis like checking frequency of each word in a file etc """ def __pretty_print_word_frequency(input_dict): """Private Method: Prints the word and its count in a pretty format Arguments: input_dict(dict): input dictionary with key as word and value as count Returns: VOID """ print("Word\t\t\tFrequency") print("{:-^{}}".format('', 28)) for key in input_dict.keys(): print("{:<{}}{}".format(key, 16, input_dict[key])) @classmethod def word_frequency_from_file(cls, filename, monocase = False, pretty_print=False): """Reads a txt file and does frequency calculation for each word Arguments: filename(str): Name of the candidate file for analysis, accepts any file that has raw text in it pretty_print(bool): Set this to true if you want to see a frequency report on console monocase(bool): If true then all words would be considered lowercase and similar words would merge Returns: result(dict): key is the word and value is the frequency """ # variable declarations all_words = [] # holds all the words word_pattern = r'[a-zA-Z]+' # file reading and regex logic with open(file=filename) as f: for line in f: # reading one line at a time match = re.findall(word_pattern, line) if match: # bingo if monocase: all_words += [x.lower() for x in match] # converting all to lowercase and appending to list else: all_words += match # converting all_words list to frequencies result = defaultdict(int) for word in all_words: result[word] += 1 # del all_words del all_words if pretty_print: WordAnalysis.__pretty_print_word_frequency(result) return result
fcf8d43024c0e0e223531ff8b9a890e97d84b315
iXploitID/multi
/5.py
218
3.59375
4
def pangkat(x,y): if y == 0: return 1 else: return x * pangkat(x,y-1) x = int(input("Masukan Nilai X : ")) y = int(input("Masukan Nilai Y : ")) print("%d dipangkatkan %d = %d" % (x,y,pangkat(x,y)))
b24b31fa39630f6da95352c5f3e9b788d9a8fd19
tairbr/homework_tms
/homework_9_2.py
410
4
4
# Создать lambda функцию, которая принимает на вход неопределенное количество именных аргументов и выводит словарь с # ключами удвоенной длины. {‘abc’: 5} -> {‘abcabc’: 5} func_1 = lambda **kwargs: {key*2: value for key, value in kwargs.items()} print(func_1(abc=5, chi=8, k=43, rik=12))
29d3487f279d7944b81a56ad719dace90824a0b2
tylergan/veryfirstproject
/Assingment /game_parser.py
3,171
3.84375
4
''' Author: Tyler Gan Date: 22 May 2020 Purpose: This file contains functions that will read my board configuration, strip it, and then output the file as a matrix of objects. ''' from cells import ( Start, End, Air, Wall, Fire, Water, Teleport ) cell_elements = { 'X': Start, 'Y': End, ' ': Air, '*': Wall, 'F': Fire, 'W': Water } def read_lines(filename): """Read in a file and return the contents as a list of strings. """ try: with open(filename, 'r') as txt: ls = [] finished = False while not finished: grid = txt.readline().strip() if grid == '': finished = True else: ls.append(grid) return ls except FileNotFoundError: print('{} does not exist!'.format(filename)) exit() def parse(lines): """Transform the input into a grid. Arguments: lines -- list of strings representing the grid Returns: list -- contains list of lists of Cells """ teleport_disp = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] grid = [] start_count = 0 end_count = 0 visited_pads = [] for row in lines: cell_row = [] for game_cell in row: if game_cell not in cell_elements and game_cell not in teleport_disp: raise ValueError('Bad letter in configuration file: {}.'.format(game_cell)) elif game_cell == 'X': start_count += 1 elif game_cell == 'Y': end_count += 1 elif game_cell in teleport_disp: cell = Teleport() cell.display = game_cell cell_row.append(cell) #checking to see if we have already visited the matching pads teleport_counter = 0 for visited in visited_pads: if visited in visited_pads: teleport_counter += 1 #if not, we are going to search for matching teleporting pads. if teleport_counter != 2: teleport_counter = 0 for searchRow in lines: for searchPair in searchRow: if game_cell == searchPair: teleport_counter += 1 visited_pads.append(searchPair) if teleport_counter != 2: raise ValueError(('Teleport pad {} does not have an exclusively matching pad.'.format((game_cell)))) if game_cell not in teleport_disp: cell = cell_elements[game_cell]() cell_row.append(cell) grid.append(cell_row) if start_count != 1: raise ValueError('Expected 1 starting position, got {}.'.format(start_count)) elif end_count != 1: raise ValueError('Expected 1 ending position, got {}.'.format(end_count)) return grid
54f56f3c16dc815eb0a5f06cae68f5780bf4e1ec
wise200/MouseMaze
/main.py
497
3.765625
4
from classes import Maze from random import choice def dfs(maze): mouse = maze.mouse visited = set() stack = [mouse.node] visited.add(mouse.node) count = 0 while len(stack) > 0: cell = stack.pop() mouse.moveTo(cell) if cell.hasCheese: count += 1 mouse.eatCheese() nbs = [nb for nb in cell.neighbors if nb not in visited] if len(nbs) > 0: nb = choice(nbs) visited.add(nb) stack.append(cell) stack.append(nb) maze.show(30) print(count) dfs(Maze(25,25,10,True))
0f83a439536fd3cd9c6531c2ef2ed6166617e925
xiaotdl/NLP
/test.py
246
3.515625
4
N = 5 T = 3 viterbi = [[0 for n in range(T)] for n in range(N+2)] print viterbi for s in range(1,5): print s l = [1,2,3,4,5,6,7,8] print l[::-1] print l.remove(8) print range(N) a = 1.6666666666666666 b = 3.444444444444444 print a*b
b9f7d49add9d9af4021d2e90ba44e7ecad7b5e6a
amanptl/LeetCode
/Easy/Sqrt(x).py
486
3.625
4
def mySqrt(self, x: int) -> int: if x == 0 or x == 1: return x if x == 2: return 1 lo = 0 hi = x - 1 while lo <= hi: mid = (lo+hi)//2 curr = mid * mid if curr == x: return mid elif curr > x: hi = mid - 1 else: lo = mid + 1 if hi * hi <= x: return hi return lo
0da04b7e64ae14b61c1988cf54fadddb77e281e1
possibleit/LintCode-Algorithm-question
/smallestDifference.py
3,026
3.5625
4
#usr/bin/env python # -*- coding:utf-8 -*- import sys #''' # 二分法求解,但是时间会超。 #''' # def smallestDifference(A, B): # sys.setrecursionlimit(1000000) # tem = sys.maxsize # listA = sorted(A) # listB = sorted(B) # i = len(listA) # j = len(listB) # if i < 2 and j < 2: # return abs(listB[0] - listA[0]) # if i < j: # for s in range(i): # # 二分查找listB中a的元素 # tem = min(tem, binsearch(listA[s], listB)) # else: # for s in range(j): # tem = min(tem, binsearch(listB[s], listA)) # return tem # # def binsearch(a, list): # l = len(list) # if l == 1: # return abs(a - list[0]) # if l == 2: # return min(abs(a - list[0]), abs(list[1] - a)) # x = int(l / 2) # ss = sys.maxsize # if a == list[x]: # ss = 0 # elif a > list[x]: # ss = binsearch(a, list[x:l]) # else: # ss = binsearch(a, list[0:x]) # return ss def smallestDifference(A, B): ''' @Author : possibleit @Date : 12:21 2019/3/31 @Description : 描述 给定两个整数数组(第一个是数组 A,第二个是数组 B),在数组 A 中取 A[i],数组 B 中取 B[j],A[i] 和 B[j]两者的差越小越好(|A[i] - B[j]|), 返回最小差。 挑战时间复杂度 O(n log n) @Example : 样例 1: 输入: A = [3, 6, 7, 4], B = [2, 8, 9, 3] 输出: 0 解释: A[0] - B[3] = 0 样例 2: 输入: A = [1, 2, 3, 4], B = [7, 6, 5] 输出: 1 解释: B[2] - A[3] = 1 挑战 时间复杂度 O(n log n) @Solution : 最开始我想到的解决方法是上边的方法,但是有两个问题,一是递归深度超标(sys.setrecursionlimit(1000000)), 二是运行到后边如果输入的数据量过大会超时。之后我在一个用户(@dxqwouTgUxyn)的笔记(two pointers in two arrays. ida and idb, these two pointers starting from beginning of A and B. then move from left to right, in the meantime, we will update minDif. then we will judge A[ida] ? B[idb]. in order to get minum difference, if A[ida] > B[idb], we need to enlarge B[idb], therefore idb++; samewise as A.)中找到了思路,具体方法就是用两个指针,分别指向A和B 比较指针所指向的数据,若其中一个数小于另一个数,则将指针右移,继续比较,在这个过程中记录最小的值。 比较的结束条件是遍历完一个数组。 ''' listA = sorted(A) listB = sorted(B) i = len(listA) j = len(listB) minx = sys.maxsize s = 0 m = 0 while 1: if s >= i or m >= j: break; if listA[s] > listB[m]: minx = min(minx, abs(listA[s] - listB[m])) m = m + 1 else: minx = min(minx, abs(listA[s] - listB[m])) s = s + 1 return minx
9b9ebeaa45a1e966c3bd1b3d3162e107d3af8f7a
hno3kyoz/Bofo
/input.py
1,124
3.515625
4
# -*- coding: cp936 -*- from tkinter import * root = Tk() root.title("ѯ") root.geometry('300x300') # x * l1 = Label(root, text="˻") l1.pack() # sideԸֵΪLEFT RTGHT TOP BOTTOM xls_text = StringVar() xls = Entry(root, textvariable=xls_text) xls_text.set(" ") xls.pack() l2 = Label(root, text="E-mail") l2.pack() # sideԸֵΪLEFT RTGHT TOP BOTTOM sheet_text = StringVar() sheet = Entry(root, textvariable=sheet_text) sheet_text.set(" ") sheet.pack() l3 = Label(root, text="") l3.pack() # sideԸֵΪLEFT RTGHT TOP BOTTOM loop_text = StringVar() loop = Entry(root, textvariable=loop_text) loop_text.set(" ") loop.pack() def on_click(): x = xls_text.get() s = sheet_text.get() l = loop_text.get() string = str("xls%s sheet%s ѭ%s ʱ䣺%s " % (x, s, l, sl)) print("xls%s sheet%s ѭ%s ʱ䣺%s " % (x, s, l, sl)) messagebox.showinfo(title='aaa', message=string) Button(root, text="press", command=on_click).pack() root.mainloop()
c8789376e8a6353c1659a34438ae7cad3060af62
chinuteja/100days-of-Code
/Sum of Pairs/solution.py
742
4.03125
4
""" Given an array of integers, and a number ‘sum’, find the number of pairs of integers in the array whose sum is equal to ‘sum’. Input : arr[] = {1, 5, 7, -1}, sum = 6 Output : 2 Pairs with sum 6 are (1, 5) and (7, -1) """ def function(array,sum_): dic = {} for i in array: if i not in dic: dic[i] = 1 else: # temp = dic[i] dic[i] += 1 twice_count = 0 for i in range(len(array)): if(dic[sum_ - array[i]] != None ): twice_count += dic[sum_-array[i]] if(sum_ - array[i] == array[i]): twice_count -= 1 print(twice_count//2) def main(): n = int(input()) array = [] for i in range(n): array.append(int(input())) sum_ = int(input()) function(array,sum_) if __name__ == '__main__': main()
2b87a199759fa1a8cc46d15852752f17c5293c96
Knork3/practicepython.org
/practicepython.org/13_fibunacci.py
399
4.03125
4
def fibunacci(i): fib = [1, 1] for element in range(0,i): fib.append(fib[element] + fib[element+1]) return fib fib = [] while True: x = int(input("How many Fibonacci-Numbers to calc? (0 = quit): ")) if x == 0: break else: for element in fibunacci(x-2): if element > 0: fib.append(element) print (element)
658ae466c1fec64e4be0f02697bf19b9f67e7f92
medishettyabhishek/Abhishek
/Abhishek/tiknter/Frames.py
718
4.3125
4
from tkinter import * # we are importing the tkinter and all other modules here root = Tk() # We are creating the Tk class and assigning that to the root object Frame1 = Frame(root) # This is adding of the frame to the root object Frame1.pack() # this is packing the frame to the Main view Frame2 = Frame(root) Frame2.pack(side=BOTTOM) # the second frame selected should be on the bottom side Button1 = Button(Frame1, text="Click", fg="red") # Creating a button for the frame 1 with text and colour Button1.pack() # Packing this button for the main view Button2 = Button(Frame2, text="continue", fg="Green") Button2.pack() root.mainloop() # this is to put the Created frame and views in the loop to view
b2902c2a3a99e9db0882ddaca756e48d70622b6e
louispeters/schoolwork
/drivetest.py
178
3.96875
4
age = int(input("enter your age")) test =(input("have you passed your test")) if age>16 and test=="yes": print("you can drive") else: print("you cant drive")
124aa46d7bc7c9708b6b1c3b67ff148e1fa77658
Riwaly/DWARF-Tensorflow
/external_packages/correlation3D/ops.py
4,302
3.515625
4
''' Correlation 3D in TensorFlow Given a tensor BxHxWxC, Correlation 2D would get back a tensor with shapes BxHxWxD^2, where D is 2d+1 with d=max_displacement. Correlation3D requires to call Correlation2D N times, with N equals to 2*max_depth_displacement+1 All the correlation2D results are concatenated along channel dimension, so the final tensor would have shape BxHxWxND^2 Author: Filippo Aleotti Mail: filippo.aleotti2@unibo.it ''' from __future__ import division import tensorflow as tf from external_packages.correlation2D.ops import correlation as correlation2D def correlation3D(tensor_a, tensor_b, pad, kernel_size, max_displacement, max_depth_displacement, stride_1, stride_2): ''' Compute correlation 3D Parameters: tensor_a (tensor BxHxWxC): first tensor tensor_b (tensor BxHxWxC): second tensor pad (int): padding value used in correlation2D kernel_size (int): length of kernel used in correlation2D max_displacement (int): number of elements looked at in neighborhood during correlation2D max_depth_displacement (int): number of elements looked at in neighborhood during correlation3D stride_1 (int): stride used for tensor_a stride_2 (int): stride used for tensor_b Returns: output_tensor tensor BxHxWxQ): resulting tensor. Q would be (max_displacement*2+1)**2 * (max_depth_displacement*2)+1 ''' assert max_depth_displacement >=0 with tf.variable_scope('correlation3D'): corr2D_params = { 'kernel_size': kernel_size, 'max_displacement': max_displacement, 'stride_1': stride_1, 'stride_2': stride_2 } correlation_results = [] for current_index in range(-max_depth_displacement, max_depth_displacement+1): correlation = _corr(current_index, tensor_a, tensor_b, corr2D_params) correlation_results.append(correlation) output_tensor = tf.concat(correlation_results, axis=-1) return output_tensor def _corr(current_index, tensor_a, tensor_b, corr2D_params): ''' Inner correlation op At each iteration, output_tensor accumulator must be update with the result of the 2D correlation applied with a slice of the original second tensor ''' with tf.variable_scope('operation'): b,h,w,c = tensor_a.get_shape().as_list() starting_channel = current_index if current_index>0 else 0 offset = c - abs(current_index) initial_pad = abs(current_index) if current_index<0 else 0 ending_pad = starting_channel tensor_slice = tf.pad(tensor_b[:,:,:,starting_channel:starting_channel+offset],[ [0,0],[0,0],[0,0],[initial_pad,ending_pad]]) corr2d_values = (2*corr2D_params['max_displacement']+1)**2 correlation = correlation2D(tensor_a, tensor_slice, pad=corr2D_params['max_displacement'], kernel_size=corr2D_params['kernel_size'], max_displacement=corr2D_params['max_displacement'], stride_1=corr2D_params['stride_1'], stride_2=corr2D_params['stride_2']) return correlation if __name__ == '__main__': import numpy as np shape = [2,256,256,64] tensor_a = tf.random_uniform(shape, minval=0, maxval=50.) tensor_b = tf.random_uniform(shape, minval=0, maxval=50.) max_displacement = 4 kernel_size=1 stride_1=1 stride_2=1 max_depth_displacement = 0 corr2d = correlation2D(tensor_a, tensor_b, pad=max_displacement, kernel_size=kernel_size, max_displacement=max_displacement, stride_1=stride_1, stride_2=stride_2) corr3d = correlation3D(tensor_a, tensor_b, pad=max_displacement, kernel_size=kernel_size, max_displacement=max_displacement, stride_1=stride_1, stride_2=stride_2, max_depth_displacement=max_depth_displacement) corr3d_2 = correlation3D(tensor_a, tensor_b, pad=max_displacement, kernel_size=kernel_size, max_displacement=max_displacement, stride_1=stride_1, stride_2=stride_2, max_depth_displacement=4) session = tf.Session() corr2D_res, corr3D_res = session.run([corr2d, corr3d]) assert np.array_equal(corr2D_res,corr3D_res) assert corr3D_res.shape == (2,256,256,81) corr3D_res = session.run(corr3d_2) assert corr3D_res.shape == (2,256,256,729)
d96f513036b3334c9d298c2dc03ff103e5f6ebbd
phanisai22/HackerRank
/Contests/Women Technologists Codesprint/Signal Classification.py
712
3.546875
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'classifySignals' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts following parameters: # 1. INTEGER_ARRAY freq_standard # 2. INTEGER_ARRAY freq_signals # def classify_signals(freq_standard, freq_signals): res = [] return res if __name__ == '__main__': first_multiple_input = input().rstrip().split() n = int(first_multiple_input[0]) q = int(first_multiple_input[1]) f = list(map(int, input().rstrip().split())) F = list(map(int, input().rstrip().split())) ans = classify_signals(f, F) for item in ans: print(ans)
62a6702431746e15d85a26c02d9e4c505b61ff03
smbenfield/coursera
/course3/chxnotes.py
789
3.9375
4
# Methods = functions that are part of a dictionary # Construct = create empty instance of object breaker = '----------' movies = list() movie1 = dict() movie1['Director'] = 'James Cameron' movie1['Title'] = 'Avatar' movie1['Release Date'] = '18 December 2009' movie1['Running Time'] = '162 Minutes' movie1['Rating'] = 'PG-13' movies.append(movie1) movie2 = dict() movie2['Director'] = 'David Finscher' movie2['Title'] = 'The Social Network' movie2['Release Date'] = '01 October 2010' movie2['Running Time'] = '120 Minutes' movie2['Rating'] = 'PG-13' movies.append(movie2) print movies keys = ['Title', 'Director', 'Rating', 'Running Time'] print breaker print movies print breaker print keys for item in movies: print breaker for key in keys: print key, ':', item[key] print breaker
689f17dfd1427505a7d7febf05dc0de91374a0a0
meetashok/projecteuler
/90-100/problem-91.py
735
3.640625
4
## Problem 91 ## Right triangles with integer coordinates import itertools def right_triangle(coor1, coor2): x1, y1 = coor1 x2, y2 = coor2 a2 = x1**2 + y1**2 b2 = x2**2 + y2**2 c2 = (x2 - x1)**2 + (y2 - y1)**2 return (a2 + b2 == c2) or (b2 + c2 == a2) or (c2 + a2 == b2) def main(): points = [] for x in range(51): for y in range(51): points.append((x, y)) count = 2500 for comb in itertools.combinations(points, 2): point1, point2 = comb if point2[1]*point1[0] < point1[1]*point2[0]: if right_triangle(point1, point2): count += 1 return count if __name__ == "__main__": answer = main() print(answer)
ef535fd5dcf67c81b4029482eba62575c4269eff
CVHS-TYM/Marpaung_Story
/Learning/Warmups/popquiz.py
495
3.703125
4
#1 #2 import random #for a in range(500): # print(random.randint(0,100)) #3 #c = "" #for i in range(100): # a = random.randint(0,100) # if a%2 == 0: # c = "even" # elif a%2 == 1: # c = "odd" # print(str(a)+" is "+c) #4 #accidently pushed lol evens = 0 l_evens = "Evens: " for i in range(100): a = random.randint(0,100) if a%2 == 0: evens += 1 l_evens = (l_evens+str(a)+" ") print("There are "+str(evens)+" evens.") print(l_evens) #5
7cc0e7a73ccf8849ef466c10445b1e2d8c8b4088
dylan-slack/TalkToModel
/explain/actions/what_if.py
2,958
4.25
4
"""The what if operation. This operation updates the data according to some what commands. """ from explain.actions.utils import convert_categorical_bools def is_numeric(feature_name, temp_dataset): return feature_name in temp_dataset['numeric'] def is_categorical(feature_name, temp_dataset): return feature_name in temp_dataset['cat'] def get_numeric_updates(parse_text, i): """Gets the numeric update information.""" update_term = parse_text[i+2] update_value = float(parse_text[i+3]) return update_term, update_value def update_numeric_feature(temp_data, feature_name, update_term, update_value): """Performs the numerical update.""" new_dataset = temp_data["X"] if update_term == "increase": new_dataset[feature_name] += update_value parse_op = f"{feature_name} is increased by {str(update_value)}" elif update_term == "decrease": new_dataset[feature_name] -= update_value parse_op = f"{feature_name} is decreased by {str(update_value)}" elif update_term == "set": new_dataset[feature_name] = update_value parse_op = f"{feature_name} is set to {str(update_value)}" else: raise NameError(f"Unknown update operation {update_term}") return new_dataset, parse_op def what_if_operation(conversation, parse_text, i, **kwargs): """The what if operation.""" # The temporary dataset to approximate temp_dataset = conversation.temp_dataset.contents # The feature name to adjust feature_name = parse_text[i+1] # Numerical feature case. Also putting id in here because the operations # are the same if is_numeric(feature_name, temp_dataset): update_term, update_value = get_numeric_updates(parse_text, i) temp_dataset['X'], parse_op = update_numeric_feature(temp_dataset, feature_name, update_term, update_value) elif is_categorical(feature_name, temp_dataset): # handles conversion between true/false and 1/0 for categorical features categorical_val = convert_categorical_bools(parse_text[i+2]) temp_dataset['X'][feature_name] = categorical_val parse_op = f"{feature_name} is set to {str(categorical_val)}" elif feature_name == "id": # Setting what if updates on ids to no effect. I don't think there's any # reason to support this. return "What if updates have no effect on id's!", 0 else: raise NameError(f"Parsed unknown feature name {feature_name}") processed_ids = list(conversation.temp_dataset.contents['X'].index) conversation.temp_dataset.contents['ids_to_regenerate'].extend(processed_ids) conversation.add_interpretable_parse_op("and") conversation.add_interpretable_parse_op(parse_op) return '', 1
ad107f17d0fbb57dc098987b5f8a564cbb9abd47
AlanaRosen/my-python-programs
/Tip Calculator.py
996
4
4
def calculate(check,tip,name): total_check = (check * (tip/100) + check) total_check = round (total_check, 2) print ("\n" + str(name) + ", if you would like to tip ", str(tip) + "%, then your total will be $" + str(total_check) + ".") def others(): while start == "yes": name = input("\nWhat name would you like to use? ") check = float (input ("\nWhat was the total for your check? $")) if check > 0: tip = float (input ("\nWhat percentage would you like to tip? ")) calculate(check,tip,name) more = input("\nIs there anyone else who would like to calculate their tip? Please answer 'yes' or 'no' accordingly. ") more = more.lower() else: print("Yeah, you're not doing this correctly, buddy. Try again.") others() start = input ("Is there someone who would like to calculate a tip? Please answer 'yes' or 'no' accordingly. ") start = start.lower() others()
bcf7adf4cd80ef503bc18c792d4a489f0f751855
rusalinastaneva/Python-Advanced
/01. Lists as Stacks and Queues/05. Truck Tour.py
259
3.5
4
n = int(input()) start_idx = 0 fuel = 0 for i in range(n): petrol, distance = [int(x) for x in input().split()] fuel += petrol if fuel >= distance: fuel -= distance else: start_idx = i + 1 fuel = 0 print(start_idx)
4474b554f849104f35c03a822a1b23918ea67d15
Exdenta/Algorithms
/Graphs/Shortest Path/dijkstra.py
1,581
4.09375
4
#!/usr/bin/env python3 import sys import numpy as np def Dijkstra(nodes, edges, source): """Dijkstra shortest path algorithm Args: nodes (:obj:`list` of :obj:`str`): names of all nodes. edges (:obj:`list` of :obj:`list`): graph adjacency matrix. source (:obj:`int`): source node index. Returns: """ # shortest path previous nodes prev = np.array([None] * len(nodes)) visited = np.array([False] * len(nodes)) # shortest distances to every node dist = np.array([inf] * len(nodes)) dist[source] = 0 while not np.all(visited): # among unvisited nodes find the node # with minimal distance to the source min_dist = np.amin(dist[~visited]) # get the node index for i, d in enumerate(dist): if d == min_dist and not visited[i]: node_idx = i break # check all paths node_edges = edges[node_idx] for i, w in enumerate(node_edges): if w != -1: alt = min_dist + w if alt < dist[i]: dist[i] = alt prev[i] = nodes[node_idx] visited[node_idx] = True return prev, dist inf = sys.maxsize nodes_ = np.array(['A', 'B', 'C', 'D', 'E']) edges_ = [[ 0, 6, -1, 1, -1], [ 6, 0, 5, 2, 2], [-1, 5, 0, -1, 5], [ 1, 2, -1, 0, 1], [-1, 2, 5, 1, 0]] edges_ = np.asarray(edges_) source_idx_ = 2 prev, dist = Dijkstra(nodes_, edges_, source_idx_) print(prev, dist)
fbccee51b92c1574a05b37c4eff79e69ce1c8441
flavianogjc/uri-online-judge-python
/iniciante/1008/1008.py
180
3.546875
4
if __name__ == '__main__': n = input() horas = input() valorHora = float(raw_input()) print("NUMBER = %d" % n) print("SALARY = U$ %.2f" % (horas * valorHora))
4e53df8b6f36a228ba6e462b93ab536ea16880ce
tjddbs2065/ToyProject
/Trader Tool/test.py
2,447
3.96875
4
''' tick: 몇분봉 데이터인지 avg_moving: 몇일선 데이터를 원하는지 list: 데이터 ''' def get_moving_avg_line(avg_moving, list): tmp_list = [] for position, data in enumerate(list): if position < (avg_moving-1): tmp_list.append(0) else: total = 0 for idx in range(avg_moving): total += list[position - idx] avg_value = int(total / avg_moving) if list[position] < 1000: tmp_list.append(avg_value - (avg_value % 1)) elif list[position] < 5000: tmp_list.append(avg_value - (avg_value % 5)) elif list[position] < 10000: tmp_list.append(avg_value - (avg_value % 10)) elif list[position] < 50000: tmp_list.append(avg_value - (avg_value % 50)) return tmp_list def get_gradient_list(list): tmp_list = [] for position, data in enumerate(list): if position < 1: tmp_list.append(0) else: if list[position-1] < 1000: tmp_list.append(int((list[position] - list[position-1]) / 1)) elif list[position-1] < 5000: tmp_list.append(int((list[position] - list[position-1])/ 5)) elif list[position-1] < 10000: tmp_list.append(int((list[position] - list[position-1]) / 10)) elif list[position-1] < 50000: tmp_list.append(int((list[position] - list[position-1]) / 50)) else: tmp_list.append(0) return tmp_list raw_data = [] f = open("C:/Users/SeongYun/Desktop/GitHub_ToyProject/KiwoomTrader/KiwoomTrader/bin/Debug/케이사인.txt") for line in f.readlines()[::-1]: data = line.split(';') raw_data.append(data[2]) f.close() raw_data.reverse() isToday = False price_today = [] for date in raw_data: if date == "20210226090000": isToday = True elif date == "20210226153000": isToday = False if isToday == True: price_today.append(raw_data[date]) #print(price_today) avg_moving_list = get_moving_avg_line(3, price_today) #print(avg_moving_list) gradient_moving_list = get_gradient_list(avg_moving_list) print(gradient_moving_list) print(len(gradient_moving_list)) #for i in gradient_moving_list: # if i < 0: # print("하락") # elif i == 0: # print("보합") # elif i > 0: # print("상승")
a0fadcdd909bae0f2d915983c5765bdb8e860916
CalBearsGrad/Big-RATINGS-Project
/templates/mike.py
126
3.84375
4
def add_num(x, y): """Adds x and y together""" return x + y x = 9 y = 8 something = add_num(x, y) print something
8c6d3db3dde0e6fe4d7717795015bf9bdc7c3b4e
kevinwei30/CodingProblems
/nQueens.py
579
3.609375
4
n = int(input('Queens N : ')) stack = [] ans_count = 0 def check(col, row): global stack global ans_count # print(stack, col, row) for tmp_col in range(len(stack)): tmp_row = stack[tmp_col] if row == tmp_row: return elif abs(row - tmp_row) == (col - tmp_col): return if col == n - 1: ans_count += 1 # print('Solution!') # print(stack) else: stack.append(row) for i in range(n): check(col+1, i) stack.pop() # print('pop') # print(stack, ans_count) return for i in range(n): check(0, i) print('Total Solution Counts : ' + str(ans_count))
0e2186fa4bf83a91c6aeeffdee1cf7bcfbf34076
Glengend/Amazon-test
/amazon.py
2,337
3.90625
4
print('amazon task') from math import * print('This will give 3 different outcomes from predetermined variables ') out_file = open ( 'outputt.txt' , 'w' ) in_file = open("inputt.txt","r") # Find the minimum text = in_file.readline() num_list= text[4:] num_array=num_list[:-1].split(',') min_num=num_array[0] for num in num_array: if (int(num) < int(min_num)): min_num=num min_output='The min output of ' + ', '.join(num_array) + ' is ' + min_num print(min_output) # Find the maximum text = in_file.readline() num_list= text[4:] num_array=num_list[:-1].split(',') max_num=num_array[0] for num1 in num_array: if (int(num1) > int(max_num)): max_num=num1 max_output='The max output of ' + ', '.join(num_array) + ' is ' + max_num print(max_output) # Find the average text = in_file.readline() num_list= text[4:] num_array=num_list.split(',') avg_num=num_array[0] num_total=0 for num2 in num_array: num_total=int(num_total)+int(num2) avg_output='The avg output of ' + ', '.join(num_array) + ' is ' + str(num_total/len(num_array)) print(avg_output) out_file.write(min_output + '\r\n') out_file.write(max_output + '\r\n') out_file.write(avg_output) out_file.close() in_file.close() #block showing the how results are calc. def sum1 (numbers): return sum(map(int, numbers)) def avg (numbers): average=str(sum(map(int, numbers)) / len(numbers)) return average def p90 (numbers): return percentile97(numbers,90) def p70 (numbers): return percentile97(numbers,70) def percentile97 (numbers,p): percentile=p/100*len(numbers) return str(numbers[floor(percentile)]) #print output print('') print('The solutions are as follows...') sum=sum1 file = open(r"inputt.txt","r") lines = file.readlines() for line in lines: stuff = line.split(":") func = stuff[0] numbers = stuff[1].replace('\n','').split(",") # print(("Funtion is " + func + ", numbers are " + str(numbers) + ", answer is ") + (str(eval(func + '(' + str(numbers) + ')')))) print(("Funtion is " + func + ", numbers are " + str(numbers) + ", answer is ") + (str(eval(func + "(" + str(numbers) + ")")) if func != 'avg' else str(sum(map(int, numbers)) / len(numbers))))
128603f61e6f04cc2c1c8348e194997803c9107f
mattrasband/advent_of_code_2020
/01/day01.py
468
3.546875
4
#!/usr/bin/env python3 import itertools import math def solve(lines, count=2, match=2020): for combo in itertools.combinations(lines, r=count): if sum(combo) == match: return math.prod(combo) print("part1 (test):", solve([1721, 979, 366, 299, 675, 1456])) with open("./input.txt") as f: print("part1:", solve([int(x.strip()) for x in f])) with open("./input.txt") as f: print("part2:", solve([int(x.strip()) for x in f], count=3))
1e1c35a482bfdc1236b6bbc35bd46e09f5664a00
LiA-zzz/sudoku
/board.py
1,459
3.578125
4
import os, random import solver class board: def __init__(self): self.board = [] #store the orignal board for the reset button of the gui. (resets state back to original board) prefix = os.getcwd() + "\\boards\\" openFile = open(prefix+random.choice(os.listdir("boards")),'r') for line in openFile: row = [val for val in line.split() if val != '\n'] self.board.append(row) openFile.close() self.solution = [row.copy() for row in self.board] self.solvingBoard = [row.copy() for row in self.board] #get the user input information and update the status of this board. solver.solve(self.solution) def __repr__(self): #temp console view of sudoku board. vert = "*===================================*\n" mid = "| {0} | {1} | {2} | {3} | {4} | {5} | {6} | {7} | {8} |" split = "|===|===|===|===|===|===|===|===|===|\n" retStr = vert counter = 0 for row in self.board: if counter%3 == 0 and counter != 0: retStr+=split retStr += mid.format(*row)+"\n" counter+=1 retStr+=vert return retStr def getSolution(self): return self.solution def getBoard(self): return self.board def modifyBoard(self,val,row,col): pass def compareToAnswer(self,board): pass
620e5773c45e0c617987a0cf4c583f063febbf41
jkbockstael/projecteuler
/euler007-proc.py
631
3.5
4
#!/usr/bin/env python3 # Problem 7: 10001st prime # https://projecteuler.net/problem=7 import sys def is_prime(primes, number): for prime in primes: if number % prime == 0: return False if prime ** 2 > number: break return True def euler007(count): primes = [2] candidate = 1 while len(primes) < count: candidate += 2 if is_prime(primes, candidate): primes.append(candidate) return primes[-1] def parse_input(lines): return int(lines[0].strip()) if __name__ == "__main__": print(euler007(parse_input(sys.stdin.readlines())))
45c0504ef71291bf90225f6063f44862cc747d3b
genken1/python-practice
/extra01/part1/task2.py
379
4.09375
4
import this import antigravity print((True * 2 + False) * -True) print(0.6 + 0.3 == 0.9) # Выражение равно 0.89999. Такова особенность представления чисел в формате float (некоторые числа # нельзя представить в формате с плавающей точкой с основанием 2)
470c2ba3f46ba002cc7574c2fe8201c9925c30ba
anhnguyendepocen/EE-Complexity17
/sol_lab_INTRO/Fibunacci_Andreas.py
559
3.953125
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 5 11:47:27 2017 @author: Andreas Lichtenberger """ # solution new: def fib_number (n): """ Fibunacci function """ if n >=3: x_n2 = 1 x_n1 = 1 i = 3 while i <= n: x_n = x_n2 + x_n1 i += 1 x_n2 = x_n1 x_n1 = x_n print("Fibunacci number: ", x_n) elif n == 1: print("Fibunacci is 1") elif n == 2: print("Fibunacci is 1") else: print("Enter a valid number!")
fc4a8d9178e17eccbea2d57d00bc99aadbf47626
LiliGuimaraes/100-days-of-code
/CURSO-EM-VIDEO-PYTHON3/REPETICOES/WHILE/guanabara_exerc_60.py
399
4.125
4
from math import factorial print("*" * 30) print("-- JOGO DO FATORIAL --") print("*" * 30) number = int(input("\nDigite um número que queira saber o seu fatorial:\n")) # f = factorial(number) # print("O valor de {}! é: {}".format(number, f)) c = number f = 1 while c > 0: print("{}".format(c), end='') print(' x ' if c > 1 else ' = ', end="") f *= c c -= 1 print("{}".format(f))
f5b61e9688d1a60ef20c63e5d6076ce9050fe522
JacobHayes/Pythagorean-Theorem
/Pythagorean Theorem.py
1,984
4.375
4
# Jacob Robert Hayes # Pythagorean Theorem # C^2 = B^2 + A^2 import math print "This program if for calculating the Pythagorean Theorem." print "If the program crashes, an invalid answer was entered, please restart." Solve_For = raw_input("\nWhich variable are you solving for; A, B, or C? ") while not Solve_For: Solve_For = raw_input("\nWhich variable are you solving for; A, B, or C? ") if Solve_For == "a" or Solve_For == "A": C = float(raw_input("\nPlease enter the value of C. ")) B = float(raw_input("Please enter the value of B. ")) if C <= B: raw_input("\nB cannot be larger than C, please restart.") elif C >= B: C2 = C * C B2 = B * B A = (C2) + (B2) Root_A = math.sqrt(A) print "\nA^2=", C, "\b^2 +", B, "\b^2" print "A^2=", C2, "\b +", B2, "\b" print "A=", Root_A, "or the square root of", A, "\b.\n" elif Solve_For == "b" or Solve_For == "B": C = float(raw_input("\nPlease enter the value of C. ")) A = float(raw_input("Please enter the value of A. ")) if C <= A: raw_input("\nA cannot be larger than C, please restart.") elif C >= A: C2 = C * C A2 = A * A B = (C2) + (A2) Root_B = math.sqrt(B) print "\nB^2=", C, "\b^2 +", A, "\b^2" print "B^2=", C2, "\b +", A2, "\b" print "B=", Root_B, "or the square root of", B, "\b.\n" elif Solve_For == "c" or Solve_For == "C": A = float(raw_input("\nPlease enter the value of A. ")) B = float(raw_input("Please enter the value of B. ")) A2 = A * A B2 = B * B C = (A2) + (B2) Root_C = math.sqrt(C) print "\nC^2=", A, "\b^2 +", B, "\b^2" print "C^2=", A2, "\b +", B2, "\b" print "C=", Root_C, "or the aquare root of", C, "\b.\n" else: print "\nPlease restart and enter either 'A' 'B' or 'C'" raw_input("Press Anything to exit.")
c7327ff76d6d2d866348002a0145cf5ef2d75bbd
fatimantifi/ALGO-DES-K-VOISINS
/Algo-k-plus-proches-voisins-avec-interface-graphique-master/KNN.py
7,651
3.859375
4
""" Presentation Du Projet : Simulation de réfrigérateur a l'aide d'un algorithme style 'k plus proches voisins'// Cette algo a pour but de comparer les réfrigérateurs d'une population par rapport a la votre, votre frigo etant la liste nommé: témoin[]// Pour afficher les réfrigérateurs qui sont comparés au votre pressez f5 puis appelez la liste prsn[], ces réfrigérateurs seront numérotés selon le nombre de 'gens' que vous avez choisi a la ligne 94 dans la fonction gens(x) (choisissez un nombre entre 1 et 10 car seulemnt cette tranche est represntable avec tkinter)et en deuxieme arguments de la ligne 258 le nombre de k voisins voulu (en fonction de celui entré dans gens()) """ import random from tkinter import * ingredient=['sauces','yaourts','fruits','legumes','viandes','eau','soda','glace','fromage','lait'] temoin=['sauces','yaourts','fruits'] prsn=[] path=r"C:/Users/maroc/Desktop/KNN" def gens(num): if num>10: print("nombres de frigo non supportés") var = 1 secu=[] prsn.clear() for i in range(num): a = random.randint(0,len(ingredient)-1) while a == 0: a = random.randint(0,len(ingredient)-1) b=frigo(a) if b in secu: b=frigo(a) b.append(var) var = var +1 prsn.append(b) secu.append(b) def frigo(num): L=[] cuse=[] for i in range (num): a=random.randint(0,len(ingredient)-1) b=ingredient[a] if b in L: a=random.randint(0,len(ingredient)-1) b=ingredient[a] else: L.append(b) return L def knn(temoin): vide=[] for elt in temoin: for i in range (len(prsn) - 1): a = prsn[i] for elts in a: if elt == elts: if a not in vide: vide.append(a) c=len(vide) dede='' for i in range(c): d=vide[i] x=d[-1] dede=dede+str(x)+"," if len(dede) == 2: print("le frigo similaire est le numero: "+dede) if len(dede) > 2 and len(dede)<10: print('les frigos similaires ont le numero:'+dede+"(ordre du plus proches au plus éloignés )") if vide==[]: print('aucun frigo similaire') return vide def autre(prsn,vide): zzz= [] for item in prsn: if item not in vide: zzz.append(item) return zzz def voisin(vide,K): if K > len(vide): print("vous avez dépassé le nombre d'element de la liste") else: T=vide[:K] beto='' for elt in T: q = elt[-1] beto = beto + str(q) + ',' print("les "+ " " + str(K)+" "+" plus proches voisins sont les numeros " + beto) gens(10) vide = knn(temoin) sss = autre(prsn,vide) vide.extend(sss) app = Tk() app.title("KNN") screen_x=int(app.winfo_screenwidth()) screen_y=int(app.winfo_screenheight()) window_x=1920 window_y=1080 posX= ( screen_x // 2) - (window_x // 2) posY= ( screen_y // 2) - (window_y // 2) geo="{}x{}+{}+{}".format(window_x,window_y,posX,posY) app.geometry(geo) app.configure(bg="#8c7ae6") xteille=[130,430,730,1030,1330,130,430,730,1030,1330] yteille=[120,120,120,120,120,630,630,630,630,630] eau=PhotoImage(file=path+"/eau.png") xcheese=[130,430,730,1030,1330,130,430,730,1030,1330] ycheese=[170,170,170,170,170,700,700,700,700,700] fromage=PhotoImage(file=path+"/fromage.png") xfru=[185,485,785,1085,1385,185,485,785,1085,1385] yfru=[120,120,120,120,120,635,635,635,635,635] fruits=PhotoImage(file=path+"/fruits.png") xhagen=[235,535,835,1135,1435,235,535,835,1135,1435] yhagen=[120,120,120,120,120,635,635,635,635,635] glace=PhotoImage(file=path+"/glace.png") xmilk=[185,485,785,1085,1385,185,485,785,1085,1385] ymilk=[170,170,170,170,703,703,703,703,703,703] lait=PhotoImage(file=path+"/lait.png") xvegetal=[140, 440,740,1040,1340,140,440,740,1040,1340] yvegetal=[280,280,280,280,280,780,780,780,780,780] legumes=PhotoImage(file=path+"/legumes.png") sauces=PhotoImage(file=path+"/sauces.png") xketchup=[250,550,850,1150,1450,250,550,850,1150,1450] yketchup=[290,290,290,290,290,790,790,790,790,790] xcoca=[200,500,800,1100,1400,200,500,800,1100,1400] ycoca=[290,290,290,290,290,790,790,790,790,790] soda=PhotoImage(file=path+"/soda.png") xviande=[135, 435,735,1035,1335,135,435,735,1035,1335] yviande=[330,330,330,330,330,830,830,830,830,830] steak=PhotoImage(file=path+"/steak.png") xyogurt=[230, 530,830,1130,1430,230,530,830,1030,1330] yyogurt=[330, 330,330,330,330,830,830,830,830,830] yaourt=PhotoImage(file=path+"/yaourt.png") def test(vide): if len(vide) >10: print() elif len(vide)<=10: for a in range(len(vide)): for o in range (len(vide[a])): if vide[a][o]=='legumes': leg= Button(app,image=legumes) leg.pack() leg.place(x=xvegetal[a],y=yvegetal[a]) if vide[a][o]=='sauces': sauc= Button(app,image=sauces) sauc.pack() sauc.place(x=xketchup[a],y=yketchup[a]) if vide[a][o]=='viandes': stak=Button(app,image=steak) stak.pack() stak.place(x=xviande[a],y=yviande[a]) if vide[a][o]=='yaourts': yaa = Button(app,image=yaourt) yaa.pack() yaa.place(x=xyogurt[a],y=yyogurt[a]) if vide[a][o]=='soda': sod= Button(app,image=soda) sod.pack() sod.place(x=xcoca[a],y=ycoca[a]) if vide[a][o]=="eau": teille = Button(app,image=eau) teille.pack() teille.place(x=xteille[a],y=yteille[a]) if vide[a][o] =='fromage': cheese = Button(app,image=fromage) cheese.pack() cheese.place(x=xcheese[a],y=ycheese[a]) if vide[a][o] =='fruits': fru= Button(app,image=fruits) fru.pack() fru.place(x=xfru[a],y=yfru[a]) if vide[a][o] == 'glace': hagen=Button(app,image=glace) hagen.pack() hagen.place(x=xhagen[a],y=yhagen[a]) if vide[a][o] =='lait': milk=Button(app,image=lait) milk.pack() milk.place(x=xmilk[a],y=ymilk[a]) vide.pop(-1) image= PhotoImage(file=path+"/frigo.png") X=[100,400,700,1000,1300,100,400,700,1000,1300,] Y=[100,100,100,100,100,600,600,600,600,600,] def affiche(o): if o > 10: print() elif o <= 10: for i in range (o): btn = Button(app,image=image) btn.pack() btn.place(x=X[i],y=Y[i]) def classification(vide): i=1 for item in vide: item[-1]=i i+=1 xmot=[200,500,800,1100,1400,200,500,800,1100,1400,] ymot=[70,70,70,70,70,570,570,570,570,570] def mot(vide): if len(vide) >10: print() elif len(vide)<=10: for i in range (len(vide)+1): mot=Button(app,text=str(i+1)) mot.pack() mot.place(x=xmot[i],y=ymot[i]) affiche(len(prsn)) test(vide) voisin(vide,3) mot(vide) app.mainloop()
baa7aa999a37fd0a522a7515bf05f9af73365f98
kailunfan/lcode
/226.翻转二叉树.py
1,666
3.84375
4
# # @lc app=leetcode.cn id=226 lang=python # # [226] 翻转二叉树 # # https://leetcode-cn.com/problems/invert-binary-tree/description/ # # algorithms # Easy (74.79%) # Likes: 443 # Dislikes: 0 # Total Accepted: 80.1K # Total Submissions: 106.5K # Testcase Example: '[4,2,7,1,3,6,9]' # # 翻转一棵二叉树。 # # 示例: # # 输入: # # ⁠ 4 # ⁠ / \ # ⁠ 2 7 # ⁠/ \ / \ # 1 3 6 9 # # 输出: # # ⁠ 4 # ⁠ / \ # ⁠ 7 2 # ⁠/ \ / \ # 9 6 3 1 # # 备注: # 这个问题是受到 Max Howell 的 原问题 启发的 : # # 谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。 # # # @lc code=start # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ # 递归 def build(node): if not node: return None node.left, node.right = build(node.right), build(node.left) return node build(root) return root # 迭代 # if not root: # return None # q = [root] # while q: # node = q.pop(0) # node.left,node.right = node.right,node.left # if node.left: # q.append(node.left) # if node.right: # q.append(node.right) # return root # @lc code=end
b8c304ad36de45db8c4ac03f587989726037b218
Akhil-64/python
/23 prog.py
424
3.671875
4
print("enter no") a=int(input()) num=a gh=len(str(a)) b=0 c=0 sum1=0 count=0 '''while(a>0): b=int(a%10) count+=1 a=int(a/10) a=int(input())''' while(num>0): c=int(num%10) # print("rem",c) sum1=sum1+(c**gh) #print("sum",sum1) num=int(num/10) # print("A",a) if(sum1==a): print("armstrong number") else: print("not an armstrog number")
c1198eff34a65fb701c825b68825e61f922c9964
cabustillo13/Mallku_Hackathon_2021
/Prediccion/main.py
1,180
3.65625
4
from sklearn.neighbors import KNeighborsClassifier import pandas as pd import matplotlib.pyplot as plt print("######################\n## STOP THE FIRE 4+ ##\n######################\n") """Cargar información""" df = pd.read_csv("Dataset_Excel2.csv", index_col=0) """Armar el dataset -> Variables""" X = [] y = [] # Cantidad de filas: len(df) for i in range(len(df)): X.append([]) # Cantidad de columnas: 3 X[i].append(df.at[i+1, 'Temperatura']) X[i].append(df.at[i+1, 'Humedad']) X[i].append(df.at[i+1, 'Viento']) y = list(df.Focos) """Procedimiento para KNN""" neigh = KNeighborsClassifier(n_neighbors=3) neigh.fit(X, y) KNeighborsClassifier(...) """Graficar el modelo""" pd.plotting.scatter_matrix(df, c=y, figsize=(12, 12), marker='o', s=20, alpha=.8) plt.show() var = input("Ingrese Temperatura, Humedad, Viento: ") """¿Se produce o no se produce un incendio?""" print(neigh.predict([[12, 50, 8]])) """Probabilidad que ocurra un incendio""" print(neigh.predict_proba([[12, 50, 8]])) """ Datos de prueba: 7 de enero 2018 14.4, 60.2, 10 16 de sept 2018 9, 83 ,7 7 de dic 2018 12, 50, 8 """
05f6c76af955c0421199e665bbc710e2eefb3558
HourGlss/Chess
/pieces/rook.py
2,134
3.578125
4
from pieces.piece import Piece class Rook(Piece): def __init__(self, color): super().__init__(color) self.symbol = "R" def is_valid_move(self:Piece, board, startx, starty, endx, endy, evaluate_only=True): tile_is_free = board.is_tile_free(endx,endy) opponents_piece_is_occupying = self.attempt_capture(board, endx, endy) valid_movement = False # DOWN if startx == endx or endy == starty: # DOWN if starty < endy: stopy = None for y in range(starty+1, endy+1): if not board.is_tile_free(endx,y): stopy = y break if stopy is None or (stopy == endy and opponents_piece_is_occupying): valid_movement = True # UP elif endy < starty: stopy = None for y in range(starty-1, endy-1, -1): if not board.is_tile_free(endx,y): stopy = y break if stopy is None or (stopy == endy and opponents_piece_is_occupying): valid_movement = True # LEFT elif endx < startx: stopx = None for x in range(startx-1, endx-1, -1): if not board.is_tile_free(x,endy): stopx = x break if stopx is None or (stopx == endx and opponents_piece_is_occupying): valid_movement = True # RIGHT if startx < endx: stopx = None for x in range(startx+1, endx+1): if not board.is_tile_free(x,endy): stopx = x break if stopx is None or (stopx == endx and opponents_piece_is_occupying): valid_movement = True if (tile_is_free or opponents_piece_is_occupying) and valid_movement: if not evaluate_only: self.moved = True return True return False
9bf015fced42b47258e162a8b14923e16eaff4d2
wookiekim/CodingPractice
/leetcode/maximum-69-number.py
319
3.546875
4
# Python 3 # https://leetcode.com/problems/maximum-69-number class Solution: def maximum69Number (self, num: int) -> int: numlist = list(str(num)) for i, n in enumerate(numlist): if n == '6': numlist[i] = '9' break return int(''.join(numlist))
346833c07b08f8ca097b51e917a167520f9c7247
13627058973/project
/hello/python 6 循环语句.py
1,845
3.71875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' # while循环 计算1到100的总和 n = 100 sum = 0 counter = 1 while counter <= n: sum = sum + counter counter += 1 print("1 到 %d 之和为: %d" % (n, sum)) #无限循环 var=1 while var ==1: #表达式永远为true num=int(input("你最帅:")) print("你输入的数字是:",num) print("good bye!") # 一直打印 按Ctrl+C中断循环 flag =1 while (flag):print("菜鸟教程") print() # for循环 遍历列表数据 lang=['c','b','a','p'] for x in lang: print(x) # break 语句,break 语句用于跳出当前循环体 sites = ["Baidu", "Google","Runoob","Taobao"] for site in sites: if site == "Runoob": print("菜鸟教程!") break print("循环数据 " + site) else: print("没有循环数据") print("完成循环!") #遍历数字序列 使用内置函数range()函数 会生成数列 for i in range(5): print(i) for i in range(5,9): print(i) for i in range(0,10,2): print(i) # break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行 for lettle in "inset": #第一个实例 if lettle == "t": break print("当前字母为:",lettle) var =10 while var > 0: #第二个实例 print("当期的变量为:",var) var =var -1 if var ==5: break print("good bye.") ''' # continue语句被用来告诉python跳过当前循环中的剩余语句 然后进行下一轮循环 for letter in 'Runoob': # 第一个实例 if letter == 'o': # 字母为 o 时跳过输出 continue print('当前字母 :', letter) var = 10 # 第二个实例 while var > 0: var = var - 1 if var == 5: # 变量为 5 时跳过输出 continue print('当前变量值 :', var) print("Good bye!")
5532efc53cb6a79416f7636bc35a1a1b7e37a018
garvitsaxena06/Python-learning
/3.py
72
3.671875
4
#convert upper case string = 'This is my string' print(string.upper())
642258b5d5a0ce6f2fce345ee01269775e28aeec
mattjtodd/FDApy
/FDApy/representation/basis.py
12,649
3.875
4
#!/usr/bin/env python # -*-coding:utf8 -* """Basis functions. This module is used to define a Basis class and diverse classes derived from it. These are used to define basis of functions as DenseFunctionalData object. """ import numpy as np import scipy from patsy import bs from .functional_data import DenseFunctionalData from .functional_data import tensor_product_ ####################################################################### # Definition of the basis (eigenfunctions) def basis_legendre(n_functions=3, argvals=None, norm=False): r"""Define Legendre basis of function. Build a basis of :math:`K` functions using Legendre polynomials on the interval defined by ``argvals``. Parameters ---------- n_functions: int, default=3 Maximum degree of the Legendre polynomials. argvals: numpy.ndarray, default=None The values on which evaluated the Legendre polynomials. If ``None``, the polynomials are evaluated on the interval :math:`[-1, 1]`. norm: boolean, default=True Should we normalize the functions? Returns ------- values: np.ndarray, shape=(n_functions, len(argvals)) An array containing the evaluation of `n_functions` functions of Legendre basis. Notes ----- The Legendre basis is defined by induction as: .. math:: (n + 1)P_{n + 1}(t) = (2n + 1)tP_n(t) - nP_{n - 1}(t), \quad\text{for} \quad n \geq 1, with :math:`P_0(t) = 1` and :math:`P_1(t) = t`. Examples -------- >>> basis_legendre(n_functions=3, argvals=np.arange(-1, 1, 0.1), norm=True) """ if argvals is None: argvals = np.arange(-1, 1, 0.1) if isinstance(argvals, list): raise ValueError('argvals has to be a numpy array!') values = np.empty((n_functions, len(argvals))) for degree in np.arange(0, n_functions): legendre = scipy.special.eval_legendre(degree, argvals) if norm: norm2 = np.sqrt(scipy.integrate.simps( legendre * legendre, argvals)) legendre = legendre / norm2 values[degree, :] = legendre return values def basis_wiener(n_functions=3, argvals=None, norm=False): r"""Define Wiener basis of function. Build a basis of :math:`K` functions using the eigenfunctions of a Wiener process on the interval defined by ``argvals``. Parameters ---------- n_functions: int, default=3 Number of functions to consider. argvals: numpy.ndarray, default=None The values on which the eigenfunctions of a Wiener process are evaluated. If ``None``, the functions are evaluated on the interval :math:`[0, 1]`. norm: boolean, default=True Should we normalize the functions? Returns ------- values: np.ndarray, shape=(n_functions, len(argvals)) An array containing the evaluation of `n_functions` functions of Wiener basis. Notes ----- The Wiener basis is defined as the eigenfunctions of the Brownian motion: .. math:: \phi_k(t) = \sqrt{2}\sin\left(\left(k - \frac{1}{2}\right)\pi t\right), \quad 1 \leq k \leq K Example ------- >>> basis_wiener(n_functions=3, argvals=np.arange(0, 1, 0.05), norm=True) """ if argvals is None: argvals = np.arange(0, 1, 0.05) if isinstance(argvals, list): raise ValueError('argvals has to be a numpy array!') values = np.empty((n_functions, len(argvals))) for degree in np.arange(1, n_functions + 1): wiener = np.sqrt(2) * np.sin((degree - 0.5) * np.pi * argvals) if norm: wiener = wiener / np.sqrt(scipy.integrate.simps( wiener * wiener, argvals)) values[(degree - 1), :] = wiener return values def basis_fourier(n_functions=3, argvals=None, period=2 * np.pi, norm=True): r"""Define Fourier basis of function. Build a basis of :math:`K` functions using Fourier series on the interval defined by ``argvals``. Parameters ---------- n_functions: int, default=3 Number of considered Fourier series. Should be odd. argvals: numpy.ndarray, default = None The values on which evaluated the Fourier series. If ``None``, the polynomials are evaluated on the interval :math:`[0, period]`. period: float, default=2*numpy.pi The period of the circular functions. norm: boolean, default=True Should we normalize the functions? Returns ------- values: np.ndarray, shape=(n_functions, len(argvals)) An array containing the evaluation of `n_functions` functions of Wiener basis. Notes ----- The Fourier basis is defined as: .. math:: \Phi(t) = \left(1, \sin(\omega t), \cos(\omega t), \dots \right) where :math:`\omega` is the period. Examples -------- >>> basis_fourier(n_functions=3, argvals=np.arange(0, 2*np.pi, 0.1)) """ n_functions = n_functions + 1 if n_functions % 2 == 0 else n_functions if argvals is None: argvals = np.arange(0, period, 0.1) if isinstance(argvals, list): raise ValueError('argvals has to be a numpy array!') values = np.empty((n_functions, len(argvals))) values[0, :] = 1 for k in np.arange(1, (n_functions + 1) // 2): sin = np.sin(2 * np.pi * k * argvals / period) cos = np.cos(2 * np.pi * k * argvals / period) if norm: sin_norm2 = np.sqrt(scipy.integrate.simps( sin * sin, argvals)) cos_norm2 = np.sqrt(scipy.integrate.simps( cos * cos, argvals)) sin = sin / sin_norm2 cos = cos / cos_norm2 values[(2 * k - 1), :] = sin values[(2 * k), :] = cos return values[:n_functions, :] def basis_bsplines(n_functions=5, argvals=None, degree=3, knots=None, norm=False): """Define B-splines basis of function. Build a basis of :math:`K` functions using B-splines basis on the interval defined by ``argvals``. Parameters ---------- n_functions: int, default=5 Number of considered B-splines. argvals: numpy.ndarray, default = None The values on which evaluated the B-splines. If ``None``, the polynomials are evaluated on the interval :math:`[0, 1]`. degree: int, default=3 Degree of the B-splines. The default gives cubic splines. knots: numpy.ndarray, (n_knots,) Specify the break points defining the B-splines. If ``knots`` are provided, the provided value of ``K`` is ignored. And the number of basis functions is ``n_knots + degree - 1``. norm: boolean, default=True Should we normalize the functions? Returns ------- values: np.ndarray, shape=(n_functions, len(argvals)) An array containing the evaluation of `n_functions` functions of Wiener basis. Examples -------- >>> basis_bsplines(n_functions=5, argvals=np.arange(0, 1, 0.01)) """ if argvals is None: argvals = np.arange(0, 1, 0.01) if isinstance(argvals, list): raise ValueError('argvals has to be a numpy array!') if knots is not None: n_knots = len(knots) n_functions = n_knots + degree - 1 else: n_knots = n_functions - degree + 1 knots = np.linspace(argvals[0], argvals[-1], n_knots) values = bs(argvals, df=n_functions, knots=knots[1:-1], degree=degree, include_intercept=True) if norm: norm2 = np.sqrt(scipy.integrate.simps(values * values, argvals, axis=0)) values = values / norm2 return values.T def simulate_basis(name, n_functions=3, argvals=None, norm=False, **kwargs): """Redirect to the right simulation basis function. Parameters ---------- name: str, {'legendre', 'wiener', 'fourier', 'bsplines'} Name of the basis to use. n_functions: int, default=3 Number of functions to compute. argvals: numpy.ndarray, default=None The values on which the basis functions are evaluated. If ``None``, the functions are evaluated on the diverse interval depending on the basis. norm: boolean Should we normalize the functions? Keyword Args ------------ period: float, default = 2*numpy.pi The period of the circular functions for the Fourier basis. degree: int, default = 3 Degree of the B-splines. The default gives cubic splines. knots: numpy.ndarray, (n_knots,) Specify the break points defining the B-splines. Returns ------- values: np.ndarray, shape=(n_functions, len(argvals)) An array containing the evaluation of `n_functions` functions of Wiener basis. Example ------- >>> simulate_basis('legendre', n_functions=3, >>> argvals=np.arange(-1, 1, 0.1), norm=True) """ if name == 'legendre': values = basis_legendre(n_functions, argvals, norm) elif name == 'wiener': values = basis_wiener(n_functions, argvals, norm) elif name == 'fourier': values = basis_fourier(n_functions, argvals, kwargs.get('period', 2 * np.pi), norm) elif name == 'bsplines': values = basis_bsplines(n_functions, argvals, kwargs.get('degree', 3), kwargs.get('knots', None), norm) else: raise NotImplementedError(f'Basis {name!r} not implemented!') return values ############################################################################### # Class Basis class Basis(DenseFunctionalData): r"""A functional data object representing an orthogonal basis of functions. Parameters ---------- name: str, {'legendre', 'wiener', 'fourier', 'bsplines'} Denotes the basis of functions to use. n_functions: int Number of functions in the basis. dimension: str, ('1D', '2D'), default='1D' Dimension of the basis to simulate. If '2D', the basis is simulated as the tensor product of the one dimensional basis of functions by itself. The number of functions in the 2D basis will be :math:`n_function^2`. argvals: dict The sampling points of the functional data. Each entry of the dictionary represents an input dimension. The shape of the :math:`j`th dimension is :math:`(m_j,)` for :math:`0 \leq j \leq p`. norm: bool, default=False Should we normalize the basis function? Keyword Args ------------ period: float, default = 2*numpy.pi The period of the circular functions for the Fourier basis. degree: int, default = 3 Degree of the B-splines. The default gives cubic splines. knots: numpy.ndarray, (n_knots,) Specify the break points defining the B-splines. """ def __init__(self, name, n_functions, dimension='1D', argvals=None, norm=False, **kwargs): """Initialize Basis object.""" self.name = name self.norm = norm self.dimension = dimension if argvals is None: argvals = {'input_dim_0': np.arange(0, 1, 0.01)} super()._check_argvals(argvals) if len(argvals) > 1: raise NotImplementedError('Only one dimensional basis are' ' implemented.') values = simulate_basis(name, n_functions, argvals['input_dim_0'], norm, **kwargs) if dimension == '1D': super().__init__(argvals, values) elif dimension == '2D': basis1d = DenseFunctionalData(argvals, values) basis2d = tensor_product_(basis1d, basis1d) super().__init__(basis2d.argvals, basis2d.values) else: raise ValueError(f"{dimension} is not a valid dimension!") @property def name(self): """Getter for name.""" return self._name @name.setter def name(self, new_name): if not isinstance(new_name, str): raise TypeError(f'{new_name!r} has to be `str`.') self._name = new_name @property def norm(self): """Getter for norm.""" return self._norm @norm.setter def norm(self, new_norm): self._norm = new_norm @property def dimension(self): """Getter for dimension.""" return self._dimension @dimension.setter def dimension(self, new_dimension): self._dimension = new_dimension
09df664d70b6d70591f2e04eb8c0a71c96512725
shuowenwei/LeetCodePython
/Medium/LC2115.py
1,319
3.703125
4
# -*- coding: utf-8 -*- """ @author: Wei, Shuowen https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/ LC797, LC207, LC210, LC2115 """ class Solution(object): def findAllRecipes(self, recipes, ingredients, supplies): """ :type recipes: List[str] :type ingredients: List[List[str]] :type supplies: List[str] :rtype: List[str] """ res = [] # supplies = set(supplies) dictRecipes = collections.defaultdict(set) dictIndegree = collections.defaultdict(int) for rep, ing_list in zip(recipes, ingredients): dictIndegree[rep] = len(ing_list) for ing in ing_list: dictRecipes[ing].add(rep) starters = [s for s in supplies if dictIndegree[s] == 0] q = collections.deque(starters) while q: cur_node = q.popleft() for nei_node in dictRecipes[cur_node]: dictIndegree[nei_node] -= 1 if dictIndegree[nei_node] == 0: q.append(nei_node) if nei_node in recipes:#and nei_node not in res: res.append(nei_node) # print(res, dictIndegree) return res
d3874254a614ad2e6c4bb112f9ed8ae2912d1a55
salma-shaik/python-projects
/ps_511_pf/GrowingLists.py
161
3.96875
4
list1 = [2,12,4] print(list1) list1 += [34,25,1] print(list1) list2 =[5,35,56] list3 = list1 + list2 print(list3) list1.extend([43, 7, 2]) print(list1)
b6f81160353e84ee924636680d11a645371e29c7
sbyeol3/Algorithm-Study
/LeetCode/Q1-Q500/Q2.py
1,063
3.734375
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode() result = head carry = 0 while (l1 or l2 or carry): if l1 and l2 : carry = (result.val + l1.val + l2.val) // 10 sum = result.val + l1.val + l2.val - (carry*10) result.val = sum elif l1 or l2 : c = l1 if l1 else l2 carry = (result.val + c.val) // 10 sum = result.val + c.val - (carry*10) elif carry : sum = carry carry = 0 l1 = l1.next if l1 else None l2 = l2.next if l2 else None result.val = sum if l1 or l2 or carry : result.next = ListNode(carry) else : result.next = None result = result.next return head
ab693577f530653ec10e13062e271813171dc01a
ElAwbery/Python-Practice
/Lists/w3_lists1-10.py
4,348
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 5 14:34:39 2018 @author: ElAwbery """ ''' Problems 1 - 10 from w3resource, lists: https://www.w3resource.com/python-exercises/list/ ''' ''' 1. Write a Python program to sum all the items in a list. ''' def items_sum(list): """ Adds the number of items in a list, returns sum """ count = 0 for item in list: count += 1 return count testlist = [5, 'ty', 'hello', 5, 6, 7, 000] print (items_sum(testlist)) # Alternately: print (len(testlist)) ''' 2. Write a Python program to multiply all items in a list of integers. ''' def multiply_items(list): """ Assumes list is a list of integers Returns product of all integers in list """ sum = 1 for item in list: sum *= item return sum integers = [5, 6, 4, 3, -2] print(multiply_items(integers)) ''' 3. Write a Python program to get the largest number from a list. ''' def get_max(list): """ Assumes list contains only numbers Returns largest number in list """ max = list[0] for item in list: if item > max: max = item return max numbers = [5, 6, 4.67, 3, -2, 764, 3.5, 764.43, -789.2] print(get_max(numbers)) ''' 4. Write a Python program to get the smallest number from a list. ''' def get_min(list): """ Assumes list contains only numbers Returns smallest number in list """ min = list[0] for item in list: if item < min: min = item return min numbers = [5, 6, 4.67, 3, -2, 764, 3.5, 764.43, -789.2] print(get_min(numbers)) ''' 5. Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. Sample List : ['abc', 'xyz', 'aba', '1221'] Expected Result : 2 ''' def count_strings(list): """ List is a list of strings counts number of strings in list where string length is greater than 2 and the first and last character of each string are the same """ count = 0 for string in list: if string[0] == string[-1] and len(string) > 2: count += 1 return count sample = ['abc', 'xyz', 'aba', '1221'] print(count_strings(sample)) sample2 = ['abca', 'xx', '00', '3a3', 'adef'] print(count_strings(sample2)) ''' 6. Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples. Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)] ''' def ordered_tuples(list): """ Assumes list is a list of tuples Returns a list with tuple elements sorted by their last element in increaing order """ def last(tuple): return tuple[-1] return sorted(list, key = last) test_list = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] print(ordered_tuples(test_list)) ''' 7. Write a Python program to remove duplicates from a list. ''' def remove_duplicates(list): """ Returns a list with no duplicates """ no_dup_list = [] for item in set(list): no_dup_list.append(item) return no_dup_list duplicates = [0, 0, 'a', 'ab', 'a', 'hi', 78, 4.3, 'hi', 4.3, 'nope', 00, '', ' '] print(remove_duplicates(duplicates)) ''' 8. Write a Python program to check a list is empty or not. ''' def is_empty(list): """ Returns True if list is empty, False if not """ return list == [] print(is_empty([])) print(is_empty([1])) ''' 9. Write a Python program to clone or copy a list. ''' print(duplicates.copy()) ''' 10. Write a Python program to find the list of words that are longer than n from a given list of words. ''' def longer_than_n(list, n): """ Assumes input is a list of words and n is an int Returns a list of all words in input list that are longer than n letters """ long_words = [] for word in list: if len(word) > n: long_words.append(word) return long_words fames_ac = ['fames', 'ac', 'turpis', 'egestas', 'Donec', 'facilisis', 'nibh', 'sit', 'amet', 'arcu', 'faucibus',] print(longer_than_n(fames_ac, 4))
1ba366f4e585f3d0c9705fb05afd232e18c1c675
snaplucas/python_api
/app.py
1,068
3.625
4
from flask import Flask, jsonify app = Flask('python_api') @app.route("/") def hello_world(): return "Hello World! <strong>I am learning Flask</strong>", 200 @app.route("/<name>") def index(name): if name.lower() == "lucas": return "Olá {}".format(name), 200 else: return "Not Found", 404 @app.route("/html_page/<nome>") def html_page(nome): return u""" <html> <head><title>Ainda não sei usar o Jinja2 :)</title></head> <body> <h1>Olá %s Coisas que você não deve fazer.</h1> <ul> <li> Escrever html direto na view </li> <li> Tentar automatizar a escrita de html via Python</li> <li> deixar de usar o Jinja2 </li> </ul> </body> </html> """ % nome @app.route("/json_api") def json_api(): pessoas = [{"nome": "Bruno Rocha"}, {"nome": "Arjen Lucassen"}, {"nome": "Anneke van Giersbergen"}, {"nome": "Steven Wilson"}] return jsonify(pessoas=pessoas, total=len(pessoas)) app.run(debug=True, use_reloader=True)
e32415e8110a0793b594e02d7ad9b9c1331398ce
mcode36/Code_Examples
/Python/Python_CodingBat/make_bricks.py
1,000
3.90625
4
''' # method 1 def make_bricks(small, big, goal): possible = False i = 0 for i in range(0,big+1): for j in range(0,small+1): # print(i,j,i*5+j) if i*5 + j == goal: possible = True break if possible: break return possible # method 2 def make_bricks(small, big, goal): i = 0 for i in range(0,big+1): for j in range(0,small+1): if i*5 + j == goal: return True return False ''' # method 3 def make_bricks(small, big, goal): if goal % 5 == 0: if big >= goal/5 or big*5 + small >= goal: return True else: return False else: if big >= (goal-(goal%5))/5 and small >= goal%5: return True elif big < (goal-(goal%5))/5 and small >= goal-(big*5): return True else: return False print(make_bricks(3, 1, 8)) # T print(make_bricks(3, 1, 9)) # F print(make_bricks(3, 2, 9)) # F print(make_bricks(3, 2, 10)) # T
e4565b5681c197d037aae4d3137c67795a0a1bad
edu-athensoft/stem1401python_student
/py210109b_python3a/day13_210403/homework/stem1403a_homework_11_0327_max_2.py
1,341
3.515625
4
""" Homework 11 """ from tkinter import * numbers = [25, 30, 98, 3150, 93, 260, 205, 57, 10] def response(i): # print("ok") def getlabel(x): Label(root, text=str(x)).pack(anchor=N) # label1['text'] = str(i) # label1.pack() # print(numbers[i]) return lambda:getlabel(i) root = Tk() root.title('Python GUI - Button') root.geometry('640x480+300+300') root.config(bg='#ddddff') buttons = [] for i in numbers: # print(i) # btn = Button(root, text=str(i), font='Helvetica 10',command=response(i)) btn = Button(root, text=str(i), font='Helvetica 10',command=response(i)) btn.pack(anchor=S, side=LEFT, ipadx=5, ipady=5) buttons.append(btn) # for i in range(len(numbers)): # buttons[i].config(command=lambda: response(i)) # buttons[0].config(command=lambda: response(0)) # buttons[1].config(command=lambda: response(1)) # buttons[2].config(command=lambda: response(2)) # buttons[3].config(command=lambda: response(3)) # buttons[4].config(command=lambda: response(4)) # buttons[5].config(command=lambda: response(5)) # buttons[6].config(command=lambda: response(6)) # buttons[7].config(command=lambda: response(7)) exit_btn = Button(root, text="Exit", font='Helvetica 10', command=lambda: root.destroy()) exit_btn.pack(anchor=N, side=RIGHT, ipadx=5, ipady=5) root.mainloop()
086589e79ac0a85bfb40541070a60da8da260dd6
wonder2025/validateIdentityNumder
/validateUtil.py
2,837
3.53125
4
from time import * import re class validateUtil: def __init__(self): pass def age(d,m,y): d=int(d) m = int(m) y = int(y) # get the current time in tuple format a = gmtime() # difference in day dd = a[2] - d # difference in month dm = a[1] - m # difference in year dy = a[0] - y # checks if difference in day is negative if dd < 0: dd = dd + 30 dm = dm - 1 # checks if difference in month is negative when difference in day is also negative if dm < 0: dm = dm + 12 dy = dy - 1 # checks if difference in month is negative when difference in day is positive if dm < 0: dm = dm + 12 dy = dy - 1 return dy def date(d,m,y): pattern = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)" ereg = re.compile(pattern) is_match =re.match(ereg, y+"-"+m+"-"+d) # is_match = re.match(pattern, y+"-"+m+"-"+d, re.S) if is_match: return 1 else: return 0 # 前17位为数字,最后1位校验码为数字或X(如为x请转为X) def validate2(value): ereg = re.compile("^\d{18}$|^\d{17}(\d|X|x)$") is_match = re.match(ereg,value) if is_match: return 1 else: return 0 def validate3(value): distrct = ['11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54', '61', '62', '63', '64', '65'] prefx = str(value[0:2]) if prefx in distrct: return 1 else: return 0 def validate4(value): yyyy = value[6:10] mm = value[10:12] dd = value[12:14] flag = 0 age = validateUtil.age(dd, mm, yyyy) if validateUtil.date(dd, mm, yyyy) and (age >= 18 and age <= 60): flag = 1 return flag def validate5(value): index = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] dict = { 0: 1, 1: 0, 2: "X", 3: 9, 4: 8, 5: 7, 6: 6, 7: 5, 8: 4, 9: 3, 10: 2 } sum=0; for i in range(len(value)-1): sum=sum+index[i]*int(value[i]) yu=sum%11 wei=dict[yu] mowei=value[17] if mowei=="x": mowei="X" if str(wei)==mowei: return 1 else: return 0
23834d8241a96cae127b117cb495f5f1698e27a1
HackerSpot2001/GUI-Quiz-App-with-Python3
/quiz.py
3,216
3.734375
4
#!/usr/bin/python3 from tkinter import * from tkinter import messagebox from random import randint width = 640 height = 480 serial = 1 quis = { "Which language is used to written my Code":"python", "Name of hero in Iron-Man Movie series":"tony stark", "Who is Created Facebook":"mark zuckerberg", "What is the capital of india":"delhi", "What is the full form of 'WHO'":"world health organization", "Which company is owned Whatsapp messanger":"facebook", "Which company is owned Instagram":"facebook", "What is the full form of TOR ":"the onion router", "Who is created Linux Operating System":"linus torvalds", "Who is created Windows Operating System":"bill gates", "Who is the Founder of Apple Company":"steve jobs", "which language is the skeleton of web development":"html", "which language is used in client side and server side web development":"javascript", "correct the word:- buel":"blue", "correct the word:- yelowl":"yellow", "correct the word:- apepl":"apple", } # questions = list(quis.keys()) # print("\t\t######\tQuiz Application\t######\t\t") # while True: # random_question = questions[randint(0,len(questions)-1)] # print(f"\t{serial}. {random_question}") # ans = str(input("Ans. ")).lower() # if ans == quis[random_question]: # print("Right Answer.\n") # if ans != quis[random_question]: # print("Wrong Answer.\n") # if not str(ans): # print("Please enter only String") def change_text(): global text_var,questions num = randint(0,len(questions)-1) random_question1 = questions[num] text_var.set(random_question1) def check(): global root,quis,random_question ans = answer.get() ans = ans.lower() if len(ans) >=1: if ans == quis[random_question]: messagebox.showinfo("Success","Your Answer is Right.") answer.delete(0,END) change_text() if ans != quis[random_question]: messagebox.showerror("Failure","You are Wrong.") answer.delete(0,END) if len(ans) == 0: messagebox.showwarning("Warning","Please Do not press submit button,\n before Entering the answer.") if __name__ == "__main__": questions = list(quis.keys()) random_number = randint(0,len(questions)-1) random_question = questions[random_number] width = 1080 height = 480 root = Tk() root.geometry(f"{width}x{height}+200+85") root.minsize(width,height) root.maxsize(width,height) root.title("Quiz Application | Python Project") root.configure(background="#4C4B4B") text_var = StringVar() text_var.set(f"{random_question}") lbl = Label(root,textvariable=text_var,font="sans-serif 19 bold",borderwidth=6,relief=GROOVE).pack(pady=30,ipadx=10) answer = Entry(root,font="sans-serif 15",width=40,fg="black",borderwidth=3,relief=SOLID,bg="white") answer.pack(pady=6,ipady=5) btn1 = Button(root,text="Submit".upper(),bg="#FF4848",font="sans-serif 18 bold",fg="black",command=check).pack(pady=10) root.mainloop()
82d16a87fe3ebb108ced4f363b573389dc3b9d47
Ukabix/machine-learning
/Machine Learning A-Z/Part 4 - Clustering/Section 24 - K-Means Clustering/run.py
1,745
3.75
4
# K-MEANS CLUSTERING #%reset -f # import libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt # import dataset dataset = pd.read_csv('Mall_Customers.csv') # creating matrix of features [lines:lines,columns:columns] X = dataset.iloc[:, [3,4]].values # not [:,1] bc we want a matrix for X! # using the elbow method to find the optimal num of clusters from sklearn.cluster import KMeans wcss = [] for i in range (1,11): kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) kmeans.fit(X) wcss.append(kmeans.inertia_) # plotting onto graph plt.plot(range(1, 11), wcss) plt.title('The Elbow Method') plt.xlabel('num of clusters') plt.ylabel('wcss') plt.show() # Apllying k-means to the dataset - fit_predict method kmeans = KMeans(n_clusters = 5, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) y_kmeans= kmeans.fit_predict(X) # Visualisation of clusters plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'cluster 1 - careful') plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'cluster 2 - standard') plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = 'green', label = 'cluster 3 - target') plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 100, c = 'cyan', label = 'cluster 4 - careless') plt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s = 100, c = 'magenta', label = 'cluster 5 - sensible') plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'centroids') plt.title('clusters of clients') plt.xlabel('annual income (k$)') plt.ylabel('spending score: 1-100') plt.legend() plt.show()
47dfffc749626926e4a03394a3e51c554d1adb65
ckt371461/python
/basic/0.py
237
3.71875
4
x = 23 y = 0 print() try: print(x/y) except ZeroDivisionError as e: print('Not allowed to division by zero') print() else: print('Something else went wrong') finally: print('This is cleanup code') print()
2b9511fcaa0fb6c4a5591527eec3493e3be004e2
hevalenc/Curso_Udemy_Python
/aula_82.py
1,340
3.765625
4
#aula sobre encapsulamento - utilizado para proteger o código """ Na programação orientada o objetos (OOP) public - os dados são públicos, ou seja, estão abertos para todos e pode ser modificado fora da classe protected - os dados são protegidos e não podem ser alterados fora da classe, somente dentro do módulo, usa-se ( _ ) private - os dados ficam protegidos e não há como alterar fora da classe, usa-se ( __ ) No Python não há proteções claras, usa-se por convenção '_' e '__' em frente as variáveis significa não alterar """ class BaseDeDados: def __init__(self): self.__dados = {} def inserir_cliente(self, id, nome): if 'clientes' not in self._dados: self._dados['clientes'] = {id: nome} else: self._dados['clientes'].update({id: nome}) def lista_clientes(self): for id, nome in self._dados['clientes'].items(): print(id, nome) def apaga_cliente(self, id): del self._dados['clientes'][id] bd = BaseDeDados() bd.inserir_cliente(1, 'Otávio') bd.inserir_cliente(2, 'Miranda') bd.inserir_cliente(3, 'Rosa') # bd.dados = 'Uma outra coisa' #esta linha de comando modificou o atributo '.dados' e sabota todo o programa # bd.inserir_cliente(4, 'Ronaldo') # bd.apaga_cliente(2) # bd.lista_clientes() # print(bd.dados)
d449012bbe5fa62db5970a08bd7a7221b3059c2f
wangyendt/LeetCode
/Hard/164. Maximum Gap/Maximum Gap.py
643
3.65625
4
# !/usr/bin/env python # -*- coding: utf-8 -*- # author: wang121ye # datetime: 2019/7/9 17:57 # software: PyCharm class Solution: def maximumGap(self, nums: list) -> int: def radixSort(A): for k in range(10): s = [[] for i in range(10)] for i in A: s[i // (10 ** k) % 10].append(i) A = [a for b in s for a in b] return A A = radixSort(nums) ans = 0 if len(A) == 0: return 0 prev = A[0] for i in A: if i - prev > ans: ans = i - prev prev = i return ans
5b83b4e929b26a43301d586ec9b2ed00660af12a
Isabel-Cumming-Romo/Classify-Falls-ML
/test_fwdprop.py
4,444
3.953125
4
import random # for w's initalizations import numpy # for all matrix calculations import math # for sigmoid import scipy import pandas as pd def sigmoid(x): return 1 / (1 + numpy.exp(-x)) def sigmoidGradient(z): #Parameters: z (a numerical input vector or matrix) #Returns: vector or matrix updated by return numpy.multiply(sigmoid(z), (1-sigmoid(z))) def computeGradient(upper_grad, w, X): # Return W_grad, h_grad #Params: upper_gradient (ie the gradient received from the layer above), W (the weight of one layer), #X (training data) W_grad = numpy.matmul(numpy.transpose(X), upper_grad) h_grad = numpy.matmul(upper_grad, numpy.transpose(w)) return W_grad, h_grad #BACKPROP def backProp(X, y, x_num_rows): layer1_activation=X; #TODO-temporarily use layer1_activation without the bias (i.e. the column of 1's) #ie each row is a training example. The first column of each row is now a 1. #so you just add a column -like "the one" feature #layer1_activation is our first layer3 #z_2 = w_1 * layer1_activation z_2 = numpy.matmul(layer1_activation, w_1) #intermediary variable (note: order is important for the multiplication so that dimensions match up) #Compute layer2_activation = sigmoid(z_2) layer2_activation= sigmoid (z_2) print("Layer 1 activation shape is") print(layer2_activation.shape) #Compute a_3 # Concatenate a bias column of all 1s with layer2_activation #all_ones = numpy.ones((x_num_rows,1)) #column of 1's #layer2_activation= numpy.hstack((all_ones,layer2_activation3))# i.e. add a column of 1's to the front of the layer2_activation #TODO-temporarily use layer2_activation without the bias (i.e. the column of 1's) # z_3 = w_2*layer2_activation z_3= numpy.matmul (layer2_activation, w_2) print("Layer 2 activation shape is") print(z_3.shape) # layer3_activation = sigmoid(z_3) layer3_activation = sigmoid(z_3) #Compute h (output layer activation...ie the hypothesis) #Concatenate bias column of all 1s with layer3_activation #all_ones = numpy.ones((x_num_rows,1)) #column of 1's #layer3_activation= numpy.hstack((all_ones,layer3_activation)) # i.e. add a column of 1's to the front of the layer3_activation #TODO-temporarily use layer3_activation without the bias (i.e. the column of 1's) # z_out = w_3*layer3_activation z_out= numpy.matmul (layer3_activation, w_3) # h = sigmoid(z_out) h = sigmoid(z_out) print("The prediction is\n") print(h) #Gradient of output layer output_layer_gradient = 2*numpy.subtract(h, y)/x_num_rows print("Output layer first. Gradient is size") print(output_layer_gradient.shape) #Now calculate gradient of layer 2 #TO-DO: Remove first column of w_3 W3_gradient, layer2_act_gradient = computeGradient(output_layer_gradient, w_3, layer3_activation) print("W3_grad:") print(W3_gradient.shape) print("layer2_act_grad:") print(layer2_act_gradient.shape) #In the ML prof's code, this was done element-wise, but that makes no sense to me #DOUBLE CHECK THIS #layer2_z_gradient = numpy.matmul(numpy.transpose(layer2_act_gradient), sigmoidGradient(layer2_activation)) layer2_z_gradient = numpy.multiply(layer2_act_gradient, sigmoidGradient(layer3_activation)) print("layer2_z_grad:") print(layer2_z_gradient.shape) #Now for layer 1 #TO-DO Remove first column of w_2 #SITE OF BIG CHANGES W2_gradient, layer1_act_gradient = computeGradient(layer2_act_gradient, w_2, layer2_activation) #Input layer #DOUBLE CHECK THIS layer1_z_gradient = numpy.multiply(layer1_act_gradient, sigmoidGradient(layer2_activation)) W1_gradient, throwAway = computeGradient(layer1_z_gradient, w_1, X) print(W1_gradient.shape) return 0 num_features=2; #this is the number of samples (i.e. rows) x_num_rows=3; #for now, have X being a matrix that is 600Xnum_features big filled with 5's X= numpy.matrix(numpy.random.random((x_num_rows, num_features))) print("X initialized:") print(X) y=numpy.array([[1],[1],[0]]) print("Y initialized:") print(y) # Initialize weights to random numbers: w_1, w_2, w_3 ...# TO DO: make sure the initialization numbers are small (between 0 and 1) w_1= numpy.matrix(numpy.random.random((num_features, 5))) #for now, since don't know what # of internal nodes will have (i.e. the latter dimension of this matrix), just make it 256 w_2= numpy.matrix(numpy.random.random((5, 4))) w_3= numpy.matrix(numpy.random.random((4, 1))) backProp(X,y,x_num_rows)
0b9cf3ee3faeb966bf88139dfcb45369ea3755f6
raitk3/Python
/ex13_blackjack/blackjack.py
6,805
3.703125
4
"""Simple game of blackjack.""" from textwrap import dedent import requests class Card: """Simple dataclass for holding card information.""" def __init__(self, value: str, suit: str, code: str): """Card properties.""" self.suit = suit self.value = value self.code = code def __repr__(self): """Represent card.""" return self.code class Hand: """Simple class for holding hand information.""" def __init__(self): """Create hand.""" self.score = 0 self.cards = [] self.ac_used = False self.ad_used = False self.ah_used = False self.as_used = False def add_card(self, card: Card): """Add new card.""" self.cards.append(card) if card.value in ['2', '3', '4', '5', '6', '7', '8', '9', '10']: self.score += int(card.value) if card.value in ['JACK', 'QUEEN', 'KING']: self.score += 10 if card.value == "ACE": self.score += 11 while self.score > 21: for card in self.cards: if card.code == "AS" and not self.as_used: self.score -= 10 self.as_used = True break elif card.code == "AD" and not self.ad_used: self.score -= 10 self.ad_used = True break elif card.code == "AC" and not self.ac_used: self.score -= 10 self.ac_used = True break elif card.code == "AH" and not self.ah_used: self.score -= 10 self.ah_used = True break break class Deck: """Class for holding deck information.""" def __init__(self, shuffle=False): """ Tell api to create a new deck. :param shuffle: if shuffle option is true, make new shuffled deck. """ if not shuffle: deck = requests.get("https://deckofcardsapi.com/api/deck/new").json() else: deck = requests.get("https://deckofcardsapi.com/api/deck/new/shuffle").json() self.id = deck["deck_id"] self.is_shuffled = deck["shuffled"] def shuffle(self): """Shuffle the deck.""" deck = requests.get(f"https://deckofcardsapi.com/api/deck/{self.id}/shuffle").json() self.is_shuffled = deck["shuffled"] def draw(self) -> Card: """ Draw card from the deck. :return: card instance. """ card = requests.get(f"https://deckofcardsapi.com/api/deck/{self.id}/draw").json() return Card(card["cards"][0]["value"], card["cards"][0]["suit"], card["cards"][0]["code"]) class BlackjackController: """Blackjack controller. For controlling the game and data flow between view and database.""" def __init__(self, deck: Deck, view: 'BlackjackView'): """ Start new blackjack game. :param deck: deck to draw cards from. :param view: view to communicate with. """ self.deck = deck if not self.deck.is_shuffled: deck.shuffle() self.view = view self.dealer = Hand() self.player = Hand() self.state = {"dealer": self.dealer, "player": self.player} self.player.add_card(self.deck.draw()) self.dealer.add_card(self.deck.draw()) self.player.add_card(self.deck.draw()) self.dealer.add_card(self.deck.draw()) while True: if self.player.score > 21: self.view.player_lost(self.state) return if self.player.score == 21: self.view.player_won(self.state) return action = self.view.ask_next_move(self.state) if action == "S": break if action == "H": self.player.add_card(self.deck.draw()) while True: if self.dealer.score > 21: self.view.player_won(self.state) return if self.dealer.score > self.player.score: self.view.player_lost(self.state) return self.dealer.add_card(self.deck.draw()) class BlackjackView: """Minimalistic UI/view for the blackjack game.""" def ask_next_move(self, state: dict) -> str: """ Get next move from the player. :param state: dict with given structure: {"dealer": dealer_hand_object, "player": player_hand_object} :return: parsed command that user has choses. String "H" for hit and "S" for stand """ self.display_state(state) while True: action = input("Choose your next move hit(H) or stand(S) > ") if action.upper() in ["H", "S"]: return action.upper() print("Invalid command!") def player_lost(self, state): """ Display player lost dialog to the user. :param state: dict with given structure: {"dealer": dealer_hand_object, "player": player_hand_object} """ self.display_state(state, final=True) print("You lost") def player_won(self, state): """ Display player won dialog to the user. :param state: dict with given structure: {"dealer": dealer_hand_object, "player": player_hand_object} """ self.display_state(state, final=True) print("You won") def display_state(self, state, final=False): """ Display state of the game for the user. :param state: dict with given structure: {"dealer": dealer_hand_object, "player": player_hand_object} :param final: boolean if the given state is final state. True if game has been lost or won. """ dealer_score = state["dealer"].score if final else "??" dealer_cards = state["dealer"].cards if not final: dealer_cards_hidden_last = [c.__repr__() for c in dealer_cards[:-1]] + ["??"] dealer_cards = f"[{','.join(dealer_cards_hidden_last)}]" player_score = state["player"].score player_cards = state["player"].cards print(dedent( f""" {"Dealer score":<15}: {dealer_score} {"Dealer hand":<15}: {dealer_cards} {"Your score":<15}: {player_score} {"Your hand":<15}: {player_cards} """ )) if __name__ == '__main__': BlackjackController(Deck(), BlackjackView()) # start the game.
a88781b7d5948b681e01d552603dc7f7e70c0e19
sverm/LibToHttp
/LibToHttp/data_structures.py
483
3.625
4
''' Simple Data Structures ''' class NoDuplicateDict(dict): '''Doesn't allow setting to a key if there's a value for it already ''' # http://stackoverflow.com/a/4999321/3399432 def __setitem__(self, key, value): if key in self.keys(): raise ValueError('{0} already has a value {1}, so cannot set {2}' .format(key, self[key], value)) else: return super(NoDuplicateDict, self).__setitem__(key, value)
4468aa080273759b4ddbc3a6837c66fdf496ddec
godmanvikky/Design-Pattern
/Design Pattern python/SOLID/Decoratory.py
1,384
4.03125
4
import time from abc import ABC,abstractmethod def wrap_func(func): def wrap(): print(time.ctime(time.time())) func() print(time.ctime(time.time())) return wrap @wrap_func def func(): print("Function is here") func() class Shape(ABC): def __str__(self): return '' class Circle(Shape): def __init__(self,radius): self.radius=radius def resize(self,fact): self.radius=self.resize*fact def __str__(self): return f'A circle of radius {self.radius}' class Square(Shape): def __init__(self,width): self.width=width def resize(self,fact): self.width=self.width*fact def __str__(self): return f'A circle of radius {self.width}' class ColoredShape: def __init__(self,shape,color): self.shape=shape self.color=color def __str__(self): return f'{self.shape} and color of {self.color}' c=Circle(2) print(c) colored=ColoredShape(c,"red") print(colored) class FileLogger: def __init__(self,file): self.file=file def writelines(self,string): self.file.writelines(string) print(f'wrote {len(string)} to file') def __getattr__(self,item): print(self.__dict__) return getattr(self.__dict__['file'],item) fil=open('Vikky.txt','w') f=FileLogger(fil) f.writelines(['Hello']) f.write('Vikky1234')
8d36e534c56470df0301b8f7cc10e0915614b021
DesignisOrion/Py-Project-Matplotlib
/scatterPlot.py
328
3.75
4
from matplotlib import pyplot as plt x_values = [1, 2, 3, 4] y_values = [5, 4, 6, 2] plt.scatter(x_values, y_values) other_x_values = [1, 2, 3, 4] other_y_values = [4, 2, 3, 9] plt.plot(other_x_values, other_y_values, color="navy") plt.title("sample plot title") plt.xlabel("X Values") plt.ylabel("Y Values") plt.show()
cb38e51ca9ed9503978e84c23e243e45a16c8da0
ilaydaezengin/textGenerator
/data.py
316
3.515625
4
with open('omerHayyam.txt', 'r') as data: book = data.read() chars = list(set(book)) book_size, vocab_size = len(book), len(chars) print ('data has %d chars, %d unique' % (book_size, vocab_size)) char_to_idx = { ch:idx for idx,ch in enumerate(chars)} idx_to_char = { idx:ch for idx, ch in enumerate(chars)}
020b5b1a23cd1d45dae43d9dcf1b6443b9aa5de8
Lizyll/PY4E_Code
/ch8_ex5.py
297
3.84375
4
fname = input('File name: ') try: fhand = open(fname) except: print('There is an exception.') exit() count = 0 for line in fhand: if not line.startswith('From'): continue count = count + 1 words = line.split() print(words[1]) print('There is ', count, ' From lines.')
d453506cf0f85d65f5e77b78443945e5a931f5c6
Raihan9797/Python-Crash-Course
/chapter_10/10.2_exceptions.py
4,138
4.25
4
## Exceptions print(5/0) # Exception object is created when you make an error # if an exception object is created, try: print(5/0) except ZeroDivisionError: print("you can't divide by zero") ## using exceptions to prevent crashes print("gimme 2 numbers to divide") print("press 'q' to quit") while True: fn = input("First number: ") if fn == 'q': break sn = input("second number: ") if sn == 'q': break try: ans = int(fn) / int(sn) except ZeroDivisionError: '''prevents the program from crashing''' print("bro you cant divide by 0") else: print(ans) ## Handling FileNotFoundError Exception fn = 'alice.txt' with open(fn) as fo: contents = fo.read() # filenotfounderror try: with open(fn) as fo: contents = fo.read() except FileNotFoundError: print("sry file: " + fn + " not found") ## Analyzing Text alice2 = 'D:\d Documents\VSCode workspace\python crash course\chapter_10/alice.txt' try: with open(alice2) as fo: contents = fo.read() except FileNotFoundError: print("sry file: " + alice2 + " not found") else: # count the number of words in the file '''split by space and stores the words in a list''' words = contents.split() num_words = len(words) print('word count: ' + str(num_words)) ## working with multiple files def count_words(filename): try: with open(filename) as fo: contents = fo.read() except FileNotFoundError: print("sry file: " + filename + " not found") else: # count the number of words in the file '''split by space and stores the words in a list''' words = contents.split() num_words = len(words) print('word count: ' + str(num_words)) count_words(alice2) # siddhartha.txt NOT siddartha.txt! error will be shown, but we want that sidd = 'D:\d Documents\VSCode workspace\python crash course\chapter_10\siddartha.txt' moby = 'D:\d Documents\VSCode workspace\python crash course\chapter_10\moby_dick.txt' lilw = 'D:\d Documents\VSCode workspace\python crash course\chapter_10\little_women.txt' filenames = [alice2, sidd, moby, lilw] for fn in filenames: count_words(fn) ## Failing Silently ''' sometimes, you don't want to show them the error. So we can just suppress it by using (pass) ''' def count_words2(filename): try: with open(filename) as fo: contents = fo.read() except FileNotFoundError: pass # ie ignore the error! else: # count the number of words in the file '''split by space and stores the words in a list''' words = contents.split() num_words = len(words) print('word count: ' + str(num_words)) for fn in filenames: count_words2(fn) # siddartha error not shown! ## 10.6 and 10.7 addition calculator print('-------- add 2 numbers ------') print('press q to quit') while True: fn = input('first number: ') if fn == 'q': break sn = input('second number: ') if sn == 'q': break try: ans = int(fn) + int(sn) except ValueError: print('numbers only!') else: print(ans) ## 10.8 andd 10.9 (Silent) Cats and Dogs # you can move it around to get the filenotfounderror c = 'D:\d Documents\VSCode workspace\python crash course\chapter_10\cats.txt' d = 'D:\d Documents\VSCode workspace\python crash course\chapter_10\dogs.txt' files = [c, d] for f in files: try: with open(f) as fo: names = fo.read() except FileNotFoundError: print("sry we can't find the file") # pass # or you can just suppress it!! else: print(names) ## 10.10 common words def count_the(filename): try: with open(filename) as file_object: text = file_object.read() except FileNotFoundError: print("sorry we can't find your file") else: num_the = text.lower().count('the') print("'the' count: " + str(num_the)) count_the("D:\d Documents\VSCode workspace\python crash course\chapter_10\siddhartha.txt")
ee7b6c69f66e1c9fa7495a59f35df3ce696454e7
gourav47/Let-us-learn-python
/Assignment 8 q9.py
278
4.15625
4
'''compare two tuples, whether they contain the same element in same order or not''' t1=eval(input("Enter the first tuple: ")) t2=eval(input("Enter the second tuple: ")) if t1==t2: print("Tuples are same and are in same order") else: print("Tuples are not same")
e910ca29e45114a2455a6c2190558bb65054c3eb
Othielgh/Cisco-python-course
/3.1.2.11.py
418
4.1875
4
wordWithoutVovels = "" userWord = input("Please input any word: ") userWord = userWord.upper() for letter in userWord: if letter == 'A': continue elif letter == 'E': continue elif letter == 'I': continue elif letter == 'O': continue elif letter == 'U': continue else: wordWithoutVovels = wordWithoutVovels + letter print(wordWithoutVovels)
af48c6c5ef73f436596264d8f299470f813a71c7
ranchunju147/jiaocai
/day2/list.py
1,070
3.84375
4
#删除某个 alist=['hhh',33,'你好',5,6,7,8] def listt(): a=alist.pop(2) print(alist) print((a)) #添加 def blist(): blist = [1, '2', 3, 4, 'sfds', 5, 6] blist.append('999') print(blist) blist.append(999) print(blist) clist=[9,8,7,] blist.extend(clist) print(blist) blist.append(clist) print(blist) #update def list_update(): wlist=[9,8,7,6,5,4] wlist[2]=200 print((wlist)) wlist[5]='中国' print(wlist) wlist[4]=666 print(wlist) #order by def list_order_by(): klist=[1,9,3,55,4,44,66] klist.sort() print(klist) klist.sort(reverse=True) print(klist) def list_distinct(): dlist=[1,1,12,3,16,4,5,6,6,7] dlist=list(set(dlist)) print(dlist) print(len(dlist)) def list_a(): listtt=[1,2,5,3,4,] print(listtt[2]) print(listtt[1:4]) a=listtt.pop(3) print(a) listtt.append(7) listtt.append(9) print(listtt) listtt[0]='5' print(listtt) print(len(listtt)) if __name__ == '__main__': list_a()
afebcb298818b112abb33aca8b4fa0f937e785a7
alexxxesss/PythonPY1001
/Занятие3/Лабораторные_задания/task2_3/main.py
311
3.625
4
if __name__ == "__main__": def func(str_slov): list_slov = str_slov.split() set_slov = set(list_slov) for word in set_slov: print(word) str_word = input('Введите несколько слов через пробел: ') print("-----") func(str_word)
344dd1dffcc4003708c1fd38c0bde2fbd823f683
samer2point0/uni
/FOC/lab1prog/guess.py
572
3.84375
4
from random import randint n=None while(n==None): key=input("enter e/E for easy, m/M for medium or h/H for hard diffuculty ") if key=='e' or key=='E': n=5; elif key=='m' or key=='M': n=10 elif key=='h' or key=='H': n=100 else: print("invalid entry mate! ") randnum= randint(0,n) num=int(input("Can you guess what number am I thinking of? ")) while(num != randnum): if(num<randnum): num=int(input("Too low, try again: ")) else: num=int(input("Too high, try again: ")) print("yaaaas mate!")
bc5dce9943bda683347e6cc112a3e02d51711710
Ibtihel-ouni/HackerRank_Submissions
/30 Days of Code/D6 Let's Review.py
303
3.765625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT num= int(input()) for i in range(num): s=input() even = '' odd = '' for j in range(len(s)): if j%2 == 0: even += s[j] else: odd+= s[j] print('{} {}'.format(even,odd))
fd90b284cdc758dabcea6ea014b32625d6ce159a
wuxvsuizhong/Li_pro
/进程和线程/计算密集型任务切换和不切换.py
759
3.671875
4
import time def f1(): n = 0 for i in range(1000000): n += i def f2(): n = 0 for i in range(1000000): n += 1 start = time.time() f1() f2() end = time.time() print(end-start) # 打印运行时间约为 0.0868065357208252 def ff1(): n = 0 for i in range(1000000): n += i yield def ff2(): n = 0 g = ff1() # 创建ff1的生成器 for i in range(1000000): n += 1 next(g) # 触发ff1的生成器g执行,从而实现ff1和ff2来回切换运行 start = time.time() ff1() ff2() end = time.time() print(end-start) # 打印运行时间约为 0.1312391757965088 # 对比可以看出,在计算密集型的任务中,任务切换反而导致了运行时间的增长
34ab11c95b31b0b990f7806057dbc3d8421a66ef
DavidBitner/Aprendizado-Python
/Curso/Challenges/URI/1011Sphere.py
118
3.96875
4
radius = int(input()) volume = (4 / 3) * 3.14159 * (radius * radius * radius) print("VOLUME = {:.3f}".format(volume))
90be877774322f773cc69ce13694242a498450f8
Khachatur86/FredBaptisteUdemy
/iteration_tools/slicing.py
644
3.75
4
import math def factorials(n): for i in range(n): yield math.factorial(i) facts = factorials(100) def slice_(iterable, start, stop): for _ in range(0, start): next(iterable) for _ in range(start, stop): yield next(iterable) from itertools import islice print(list(islice(factorials(100), 0, 10, 5))) print(type(slice_(factorials(10), 3, 10))) def factorials(): index = 0 while True: print(f"yielding factorial({index})...") yield math.factorial(index) index += 1 facts = factorials() for _ in range(0, 5): print(next(facts)) print(islice(factorials(), 3, 10)) print(list(islice(factorials(), 3, 10)))
89939d276faccf56b278f24a9b962858d2ed544e
juhyun0/python_except
/raise_again.py
560
3.6875
4
def some_function(): print("1~10 사이의 수를 입력하세요:") num=int(input()) if num<1 or num>10: raise Exception("유효하지 않은 숫자입니다. :{0}".format(num)) else: print("입력한 수는 {0}입니다.".format(num)) def some_function_caller(): try: some_function() except Exception as err: print("1) 예외가 발생했습니다. {0}".format(err)) raise try: some_function_caller() except Exception as err: print("2) 예외가 발생했습니다. {0}".format(err))
67e752a0b198abd6c1dfe416f734494dff1c492c
nsossamon/100daysofcode
/Day4/Randomization.py
477
4.25
4
# Python uses a Pseudorandom Number Generating Algorithm for generating random numbers # The Python Random module has a bunch of functions for generating random number import random random_integer = random.randint(0, 4) print(random_integer) random_float = random.random() print(random_float) love_score = random.randint(1, 100) print(f"Your love score is {love_score}") # random decimal between 0 and 5 (multiply float times the end range digit): print(random_float * 5)
8d06782bd86e3505fa847b82abc5b5daa6e0e67f
ChandraSiva11/sony-presamplecode
/tasks/final_tasks/dictionary/10.count_freq_word.py
140
3.578125
4
# Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary def main(): if __name__ == '__main__': main()
ac43712ec4bd1eb98b0b8de3dacdafb7812d9d67
Tsukumo3/Algorithm
/Algorithm/最短経路問題/dijkstra.py
6,827
3.921875
4
class Dijkstra(): ''' ダイクストラ法 重み付きグラフにおける単一始点最短路アルゴリズム * 使用条件 - 負のコストがないこと - 有向グラフ、無向グラフともにOK * 計算量はO(E*log(V)) * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい ''' class Edge(): ''' 重み付き有向辺 ''' def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self,_Vertexes): ''' 重み付き有向辺 無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい Args: Vertex(int): 頂点の数 ''' #隣接リスト := 頂点Uのi個目のリスト self.Graph = [ [] for i in range(_Vertexes)] #辺の数 self.Edges = 0 #頂点の数 self.Vertexes = _Vertexes @property def edges(self): ''' 辺数 無向グラフのときは、辺数は有向グラフの倍になる ''' return self._Edges @edges.setter def edges(self, input): self.Edges = input @property def vertexes(self): ''' 頂点数 ''' return self._Vertexes @vertexes.setter def vertexes(self, input): self.vertexes = input def add(self, _from, _to, _cost): ''' 2頂点と、辺のコストを追加する ''' #Graphの[_from]番目の配列にEdge(to,cost)を入れていく self.Graph[_from].append(self.Edge(_to, _cost)) #Graphを追加したので、辺数を追加する self._Edges += 1 def add_list(self, _list): """ 2頂点と、辺のコストをまとめてリストで追加する _from = item[0] _to = item[1] _cost = item[2] """ for item in _list: _from = item[0] _to = item[1] _cost = item[2] self.Graph[_from].append(self.Edge(_to, _cost)) self.Edges += 1 def directed_graph(self,_list): ''' 有向グラフ ''' self.add_list(_list) def undirected_graph(self,_list): ''' 無向グラフ ''' new_list = [] for item in _list: go = [item[0], item[1], item[2]] back = [item[1], item[0], item[2]] new_list.append(go) new_list.append(back) self.add_list(new_list) def shortest_path(self, start): """ 始点sから頂点iまでの最短路を格納したリストを返す Args: s(int): 始点s 0始まり Returns: d(list): d[i] := 始点sから頂点iまでの最短コストを格納したリスト。 到達不可の場合、値は10000 """ import heapq que = [] # プライオリティキュー(ヒープ木) #import sys #d = [sys.maxsize] * self.Vertexes # d[v] := 始点 s から頂点 v への最短経路長 d = [10000] * self.Vertexes d[start] = 0 heapq.heappush(que, (0, start)) # 始点の(最短距離, 頂点番号)をヒープに追加する while len(que) != 0: cost, aVertex = heapq.heappop(que) # キューに格納されている最短経路の候補がdの距離よりも大きければ、他の経路で最短経路が存在するので、処理をスキップ if d[aVertex] < cost: continue for i in range(len(self.Graph[aVertex])): # 頂点vに隣接する各頂点に関して、頂点vを経由した場合の距離を計算し、今までの距離(d)よりも小さければ更新する aEdge = self.Graph[aVertex][i] # vのi個目の隣接辺e if d[aEdge.to] > d[aVertex] + aEdge.cost: d[aEdge.to] = d[aVertex] + aEdge.cost # dの更新 heapq.heappush(que, (d[aEdge.to], aEdge.to)) # キューに新たな最短経路の候補(最短距離, 頂点番号)の情報をpush return d def shortest_route(self,start): """ 始点sから頂点iまでの最短路を通る道の数え上げリストを返す Args: s(int): 始点s 0始まり Returns: d(list): d[i] := 始点sから頂点iまでの最短コストの道の数のリスト。 到達不可の場合、値は10000 """ import heapq que = [] # プライオリティキュー(ヒープ木) #import sys #d = [sys.maxsize] * self.Vertexes # d[v] := 始点 s から頂点 v への最短経路長 d = [10000] * self.Vertexes # num[v] := 始点 s から頂点 v への最短経路数 num = [1] * self.Vertexes mod = 10**9+7 d[start] = 0 heapq.heappush(que, (0, start)) # 始点の(最短距離, 頂点番号)をヒープに追加する while len(que) != 0: cost, aVertex = heapq.heappop(que) # キューに格納されている最短経路の候補がdの距離よりも大きければ、他の経路で最短経路が存在するので、処理をスキップ if d[aVertex] < cost: continue for i in range(len(self.Graph[aVertex])): # 頂点vに隣接する各頂点に関して、頂点vを経由した場合の距離を計算し、今までの距離(d)よりも小さければ更新する aEdge = self.Graph[aVertex][i] # vのi個目の隣接辺e if d[aEdge.to] > d[aVertex] + aEdge.cost: d[aEdge.to] = d[aVertex] + aEdge.cost # dの更新 heapq.heappush(que, (d[aEdge.to], aEdge.to)) # キューに新たな最短経路の候補(最短距離, 頂点番号)の情報をpush elif d[aEdge.to] == d[aVertex] + aEdge.cost: num[aEdge.to] += num[aVertex]; num[aEdge.to] %= mod; return num if __name__ == '__main__': #sampleコピペ用 ''' 8 10 0 1 1 0 2 7 0 3 2 1 4 2 1 5 4 2 5 2 2 6 3 3 6 5 5 7 6 6 7 2 0 1 2 3 4 5 6 7 0 0 1 7 2 - - - - 1 1 0 - - 2 4 - - 2 7 - 0 - - 2 3 - 3 2 - - 0 - - 5 - 4 - 2 - - 0 1 - - 5 - 4 2 - 1 0 - 6 6 - - 3 5 - - 0 2 7 - - - - - 6 2 0 ''' N,K = map(int,input().split()) A = [list(map(int,input().split())) for i in range(K)] djk = Dijkstra(N) djk.undirected_graph(A) print("各ノードまでの最小コスト") print(djk.shortest_path(0)) print("各ノードまでの最小コストでいける道の数") print(djk.shortest_route(0))
64a7940da747ee71480d257463fc8eafd05afeef
ambosing/PlayGround
/Python/Problem Solving/ETC_algorithm_problem/5-7-2 Curriculum design.py
305
3.515625
4
from collections import deque nec = input() for i in range(int(input())): s = deque(input()) res = "" while s: c = s.popleft() if c in nec and c not in res: res += c if nec == res: print("#%d YES" % (i + 1)) else: print("#%d NO" % (i + 1))
59fb44cf51a1dc891425fca82c20576400c2d6f8
jamalsyed00/LR--FoDS
/final_assignment_2.py
8,953
3.5
4
import random import numpy as np import pandas as pd import matplotlib.pyplot as plt from numpy.linalg import inv """DATASET LOADING AND PREPROCESSING""" df = pd.read_csv("insurance.txt") df.insert(0,'x_0',1) df = df.sample(frac=1) def standardize(num,mu,sd): return (num-mu)/sd def preprocessing_data(df): age_mean = df.mean()['age'] age_sd =df.std()['age'] bmi_mean = df.mean()['bmi'] bmi_sd = df.std()['bmi'] children_mean = df.mean()['children'] children_sd = df.std()['children'] charges_mean = df.mean()['charges'] charges_sd = df.std()['charges'] df['age'] = df['age'].apply(lambda num : standardize(num,age_mean,age_sd)) df['bmi'] = df['bmi'].apply(lambda num : standardize(num,bmi_mean,bmi_sd)) df['children'] = df['children'].apply(lambda num : standardize(num,children_mean,children_sd)) df['charges'] = df['charges'].apply(lambda num : standardize(num,charges_mean,charges_sd)) return df df = preprocessing_data(df) """FUNCTIONS""" #Predicted Value def predict(theta,x): return np.dot(x,theta) #RMSE def rmse(y_obs,y_pred): return np.sqrt(((y_obs - y_pred) ** 2).mean()) #Cost Function def cost_fun(pred,y): return (np.sum((pred-y)**2))/2 #Normal Eqaution def normal_eqn(train_X,train_Y): return inv(train_X.transpose().dot(train_X)).dot(train_X.transpose()).dot(train_Y) #Gradient Descent def grad_descent(x, y, alpha, epochs): feature_count = np.size(x[0]) total_cases = np.size(x) theta = np.random.rand(4) pred= np.dot(x,theta) diff = np.subtract(pred,y) theta = theta - (1/total_cases)*alpha*(x.T.dot(diff)) cost= 1/(2*total_cases) * np.sum(np.square(diff)) for i in range(epochs): pred= np.dot(x,theta) diff = np.subtract(pred,y) theta = theta - (1/total_cases)*alpha*(x.T.dot(diff)) cost_temp= 1/(2*total_cases) * np.sum(np.square(diff)) return theta #Stochastic Gradient Descent def stoch_grad_des(x, y, alpha, epochs): theta = np.random.randn(4) l = len(y) for i in range(epochs) : rand_num = np.random.randint(0,l) pred= np.dot(x[rand_num],theta) diff = np.subtract(pred,y[rand_num]) theta = theta - alpha*(x[rand_num].T.dot(diff)) cost_temp= 1/(2*l) * np.sum(np.square(np.dot(x,theta)-y)) return theta """TRAINING AND TESTING""" training_errors_normal = [] training_errors_gd = [] training_errors_sgd = [] train_sse_normal = [] train_sse_gd = [] train_sse_sgd = [] train_sse_normal = [] test_sse_gd = [] test_sse_sgd = [] test_sse_normal = [] test_errors_gd = [] test_errors_sgd = [] test_errors_normal = [] parameters_list_normal = [] parameters_list_gd = [] parameters_list_sgd = [] for i in range(20): #Training df = df.sample(frac=1, random_state=i*100) df = df.reset_index(drop=True) train_ratio = int(0.7*len(df)) train_X = np.array(df.drop(['charges'], axis=1)[:train_ratio]) test_X = np.array(df.drop(['charges'], axis=1)[train_ratio:]) train_Y = np.array(df['charges'][:train_ratio]) test_Y = np.array(df['charges'][train_ratio:]) parameters = normal_eqn(train_X, train_Y) parameters_list_normal.append(parameters) parameters = grad_descent(train_X,train_Y, 0.001, 10000) parameters_list_gd.append(parameters) parameters = stoch_grad_des(train_X, train_Y, 0.001, 10000) parameters_list_sgd.append(parameters) y_train_predict = predict(parameters_list_normal[i],train_X) tr_error = rmse(train_Y, y_train_predict) training_errors_normal.append(tr_error) train_sse_i = cost_fun(y_train_predict,train_Y) train_sse_normal.append(train_sse_i) y_train_predict = predict(parameters_list_gd[i],train_X) tr_error = rmse(train_Y, y_train_predict) training_errors_gd.append(tr_error) train_sse_i = cost_fun(y_train_predict,train_Y) train_sse_gd.append(train_sse_i) y_train_predict = predict(parameters_list_sgd[i],train_X) tr_error = rmse(train_Y, y_train_predict) training_errors_sgd.append(tr_error) train_sse_i = cost_fun(y_train_predict,train_Y) train_sse_sgd.append(train_sse_i) #Testing y_test_predict = predict(parameters_list_normal[i],test_X) test_sse_i = cost_fun(y_test_predict,test_Y) test_sse_normal.append(test_sse_i) test_error = rmse(test_Y , y_test_predict) test_errors_normal.append(test_error) y_test_predict = predict(parameters_list_gd[i],test_X) test_sse_i = cost_fun(y_test_predict,test_Y) test_sse_gd.append(test_sse_i) test_error = rmse(test_Y , y_test_predict) test_errors_gd.append(test_error) y_test_predict = predict(parameters_list_sgd[i],test_X) test_sse_i = cost_fun(y_test_predict,test_Y) test_sse_sgd.append(test_sse_i) test_error = rmse(test_Y , y_test_predict) test_errors_sgd.append(test_error) """RESULTS""" #Normal Equation print('NORMAL EQUATION METHOD RESULTS:') print("Training data : SSE mean = {} variance of SSE = {}".format(np.mean(train_sse_normal),np.var(train_sse_normal))) print("Test data : SSE mean = {} variance of SSE = {}".format(np.mean(test_sse_normal),np.var(test_sse_normal))) print("Training data : mean RMSE = {} variance RMSE = {}".format(np.mean(training_errors_normal),np.var(training_errors_normal))) print("Test data : mean RMSE = {} variance RMSE = {}".format(np.mean(test_errors_normal),np.var(test_errors_normal))) print('\n WEIGHTS 20 MODELS (Normal Equation)') for index,i in enumerate(parameters_list_gd): print("Model {} :".format(index+1),i) #Gradient Descent print('\nGRADIENT DESCENT METHOD RESULTS:') print("Training data : SSE mean = {} variance of SSE = {}".format(np.mean(train_sse_gd),np.var(train_sse_gd))) print("Test data : SSE mean = {} variance of SSE = {}".format(np.mean(test_sse_gd),np.var(test_sse_gd))) print("Training data : mean RMSE = {} variance RMSE = {}".format(np.mean(training_errors_gd),np.var(training_errors_gd))) print("Test data : mean RMSE = {} variance RMSE = {}".format(np.mean(test_errors_gd),np.var(test_errors_gd))) print('\n WEIGHTS 20 MODELS (Gradient Descent)') for index,i in enumerate(parameters_list_gd): print("Model {} :".format(index+1),i) #Stochastic Gradient Descent print('\nSTOCHASTIC GRADIENT DESCENT METHOD RESULTS:') print("Training data : SSE mean = {} variance of SSE = {}".format(np.mean(train_sse_sgd),np.var(train_sse_sgd))) print("Test data : SSE mean = {} variance of SSE = {}".format(np.mean(test_sse_sgd),np.var(test_sse_sgd))) print("Training data : mean RMSE = {} variance RMSE = {}".format(np.mean(training_errors_sgd),np.var(training_errors_sgd))) print("Test data : mean RMSE = {} variance RMSE = {}".format(np.mean(test_errors_sgd),np.var(test_errors_sgd))) print('\n WEIGHTS 20 MODELS (Stochastic Gradient Descent)') for index,i in enumerate(parameters_list_sgd): print("Model {} :".format(index+1),i) """PLOTS""" for k in range(3): df = df.sample(frac=1, random_state=k*100) df = df.reset_index(drop=True) train_ratio = int(0.7*len(df)) train_X = np.array(df.drop(['charges'], axis=1)[:train_ratio]) train_Y = np.array(df['charges'][:train_ratio]) alpha = [1e-2, 1e-3, 1e-4] feature_count = np.size(train_X[0]) total_cases = np.size(train_X) theta = np.random.rand(4) error_fun = [] for i in range(10000): pred= np.dot(train_X,theta) diff = np.subtract(pred,train_Y) theta = theta - (1/total_cases)*alpha[k]*(train_X.T.dot(diff)) cost_temp= 1/(2*total_cases) * np.sum(np.square(diff)) error_fun.append(cost_temp) print('\n\nCOST FUNCTION VALUES: GRADIENT DESCENT LR=', alpha[k],'\n') for n in range(40): print("Cost after {} epochs :".format(n*250), error_fun[n*250]) plt.plot(error_fun) plt.xlabel('EPOCHS', fontsize = 12) plt.ylabel('ERROR', fontsize = 12) print('\n Lerning rate = ',alpha[k]) plt.title('GRADIENT DESCENT', fontsize = 18) plt.show() for k in range(3): df = df.sample(frac=1, random_state=k*100) df = df.reset_index(drop=True) train_ratio = int(0.7*len(df)) train_X = np.array(df.drop(['charges'], axis=1)[:train_ratio]) train_Y = np.array(df['charges'][:train_ratio]) alpha = [0.01 , 0.001 , 0.0001 ] feature_count = np.size(train_X[0]) total_cases = np.size(train_X) theta = np.random.randn(4) error_fun = [] l = len(train_Y) for i in range(10000): rand_num = np.random.randint(0,l) pred= np.dot(train_X[rand_num],theta) diff = np.subtract(pred,train_Y[rand_num]) theta = theta - alpha[k]*(train_X[rand_num].T.dot(diff)) cost_temp= 1/(2*l) * np.sum(np.square(np.dot(train_X,theta)-train_Y)) error_fun.append(cost_temp) print('\n\nCOST FUNCTION VALUES: STOCHASTIC GRADIENT DESCENT LR=', alpha[k],'\n') for n in range(40): print("Cost after {} epochs :".format(n*250), error_fun[n*250]) plt.plot(error_fun) plt.xlabel('EPOCHS', fontsize = 12) plt.ylabel('ERROR', fontsize = 12) print('\n Learning rate = ',alpha[k]) plt.title('STOCHASTIC GRADIENT DESCENT', fontsize = 18) plt.show()
8b470ba49310265caeddd303fb919d62a241f1ee
surmayi/CodePython
/PythonLearning/Arrays/TwoSumProblem.py
546
3.515625
4
def twoSumProblem(num,target,method): if method==1: for i in range(0,len(num)-1): if target-num[i] in num[i+1:]: return(num[i], target-num[i]) else: f=0 l=len(num)-1 while f<l: if num[f]+num[l]==target: return (num[f],num[l]) elif num[f]+num[l]<target: f+=1 else: l-=1 return None A = [-2, 1, 2, 4, 7, 11] target = 13 print(twoSumProblem(A,target,1)) print(twoSumProblem(A,target,2))
443469228fc99b2bf78f1f4442332c7961c704ef
Sidhus234/Python-Dev-Course
/Codes/Section 11 Modules in Python/GuessGame/main.py
402
4
4
import sys import random min_value = int(sys.argv[1]) max_value = int(sys.argv[2]) print(f'Please guess a number between {min_value} and {max_value}') while(True): print(f"Is your number {random.randint(min_value, max_value)}?") user_input = input("Please enter Y for Yes and N for No") if(user_input.lower() == 'y'): print("Yay!!!!!") break import game12
c6740816fe50007a7f5c1f7064522d20dce3c242
aurelienO/sdia-python
/src/sdia_python/lab2/box_window.py
3,836
3.546875
4
import numpy as np from sdia_python.lab2.utils import get_random_number_generator class BoxWindow: """Representation of a box defines by [a1,b1] x [a2,b2] x ...""" def __init__(self, bounds): """Constructor of a BoxWIndow Args: bounds (numpy.array): The bounds of the box. It must be of dimension N * 2 """ assert isinstance(bounds, np.ndarray) if bounds.shape[1] != 2: raise Exception("The dimension of the argument bounds is not correct") if not np.all(np.diff(bounds) >= 0): raise Exception("The bounds are not in the right order") self.bounds = bounds def __str__(self): """Returns the representation of a box, for example the following string : "BoxWindow: [a_1, b_1] x [a_2, b_2]" Returns: str: The representation of the box """ s = "BoxWindow: " bounds_list = [f"{list(e)}" for e in self.bounds] sep = " x " return s + sep.join(bounds_list) def __len__(self): """Returns the len of the box, ie the dimension. Returns: int: the dimension of the box """ return len(self.bounds) def __contains__(self, point): """Returns True if the point belongs to the box Args: point (numpy.array): the point Returns: Boolean: True if the point belongs to the box """ assert len(point) == self.dimension() return all(a <= x <= b for (a, b), x in zip(self.bounds, point)) def dimension(self): """Returns the dimension of the box, ie the number of segment. Returns: int: the dimension of the box """ return len(self) def volume(self): """Returns the volume of the box, ie the multiplication of the measure of each segment. Returns: int: the volume of the box """ return np.prod(np.diff(self.bounds)) def indicator_function(self, points): """Returns True if the point belongs to the box Args: point (numpy.array): the point Returns: boolean: True if the point belongs to the box """ return self.__contains__(points) def center(self): """Return the array with the coordinates of the center of the box. Returns: numpy array: The array with the coordinates of the center of the box. """ return np.sum(self.bounds, axis=1) / 2 def rand(self, n=1, rng=None): """Generate n points uniformly at random inside the BoxWindow. Args: n (int, optional): the number of points. Defaults to 1. rng (numpy.random._generator.Generator, optional): Random number generator. Defaults to None. Returns: A list of n points generated uniformly at random inside the BoxWindow. """ rng = get_random_number_generator(rng) points = np.array( [[rng.uniform(a, b) for a, b in self.bounds] for i in range(n)] ) return points class UnitBoxWindow(BoxWindow): """Represent a BoxWindow where all the segment over all dimensions have a size of one.""" def __init__(self, center): """Returns a unit box window, with segments of length 1 for each dimension, centered on args if the center is precised, else, it is centered on (0,0,...,0). Args: dimension (int): The dimension of the box window center (numpy.array, optional): The array of the center of each segment of the box window. Defaults to None. """ assert isinstance(center, np.ndarray) bounds = np.add.outer(center, [-0.5, 0.5]) super().__init__(bounds)
c48745b0761848d2f0d59fbc5f78314847b5d014
jake94a/PHYS3330
/HW1.3.py
1,737
4.15625
4
""" Description: Find the max common factor of two user-inputted numbers a and b Max factor is the largest number that each a and b are divisible by while the quotient returns an integer (It is possible to use a while loop here, but I elected not to) Example, 15 and 25 have a max common factor of 5 because 15/5=3 and 25/5=5, but any number larger than 5 returns decimals. Function: Prompt user for two integer inputs, a and b Define strings to return to the user either with the answer or with an error if a > b then create a range from 1:a (inclusive) if a < b then create a range from 1:b (inclusive) if a = b then just return a (because the max common factor of n and n is n) Iterate through the created list and if the modulo of a/n and b/n is 0, then store n in a list Determine the max value in the stored list """ import tkinter from tkinter import messagebox from tkinter import simpledialog def max_common_factor(): root = tkinter.Tk() root.withdraw() a = simpledialog.askinteger("Input", "Input first value") b = simpledialog.askinteger("Input", "Input second value") error_string = "Nope" equal_string = f'Max factor is {a} because the inputted values are equal' if a > b: this_range = range(1, a + 1) elif b > a: this_range = range(1, b + 1) else: return equal_string this_list = [] for i in this_range: if a % i == 0 and b % i == 0: this_list.append(i) max_factor = max(this_list) answer_string = f'The max factor of {a} and {b} is {max_factor}' messagebox.showinfo("Answer", answer_string) return answer_string if __name__ == '__main__': max_common_factor()
7c4ccfe504baed51f8708c7fafdc301b3ce5fbde
Zhaokun1997/UNSW_myDemo
/COMP9021/COMP9021_quiz_4/quiz_4.py
3,056
3.96875
4
# COMP9021 19T3 - Rachid Hamadi # Quiz 4 *** Due Thursday Week 5 # # Prompts the user for an arity (a natural number) n and a word. # Call symbol a word consisting of nothing but alphabetic characters # and underscores. # Checks that the word is valid, in that it satisfies the following # inductive definition: # - a symbol, with spaces allowed at both ends, is a valid word; # - a word of the form s(w_1,...,w_n) with s denoting a symbol and # w_1, ..., w_n denoting valid words, with spaces allowed at both ends # and around parentheses and commas, is a valid word. import sys lower_alpha = list(map(chr, range(97, 123))) upper_alpha = list(map(chr, range(65, 91))) Alpha = lower_alpha + upper_alpha Alpha.extend([',', ' ', '_']) def check_symbol(str_value): for letter in str_value: # if (letter in ['(', ')']) or \ # (not (letter.isalpha() or (letter is '_'))): # 如果存在括号或者不是字母以及下划线,则不符合 0 参数条件 if letter not in Alpha: return False return True # arity is the number of parameters # word is consisting of nothing but alphabetic characters and underscores def is_valid(word_input, num_para): word_input = word_input.replace(' ', '') # 去掉所有的空格 if num_para == 0: # 参数个数为 0 的情况(不允许有括号存在) return check_symbol(word_input) else: # 参数个数> 0 的情况(允许有括号存在) word_input = word_input.replace(',', ' ') # 去掉所有的空格 word_input = word_input.replace('(', ' ( ') # 替换括号为括号左右加空格 word_input = word_input.replace(')', ' ) ') # print('word : ', word) word_input = word_input.split() # 默认分割全部所有的“空”字符 # print('after split word : ', word) if word_input.count('(') != word_input.count(')'): # 左右括号的数量不同,则不符合 return False else: # 左右括号相同时 stack = [] for element in word_input: stack.append(element) # 持续入栈 if element == ')': # 当匹配到右括号时,计算括号内的元素数量 count = 0 while len(stack) > 0: # 持续出栈 temp = stack.pop() if temp != '(': # 计算括号内的元素数量 count += 1 else: # 若匹配到左括号,则跳出局部计算区域 break if count != num_para + 1: return False return True # REPLACE THE RETURN STATEMENT ABOVE WITH YOUR CODE try: arity = int(input('Input an arity : ')) if arity < 0: raise ValueError except ValueError: print('Incorrect arity, giving up...') sys.exit() word = input('Input a word: ') if is_valid(word, arity): print('The word is valid.') else: print('The word is invalid.')
07ca874705f4e92b5f011bded36b3af2e9602d1a
rinkeigun/linux_module
/python_source/getNikkeiWebPageTitle.py
373
3.515625
4
# -*- coding: utf-8 -*- #import urllib as myurllib from urllib.request import urlopen from bs4 import BeautifulSoup url = "http://www.nikkei.com/" #html = myurllib.urlopen( url ) html = urlopen( url ) #soup = BeautifulSoup( html, "htmlparser" ) soup = BeautifulSoup( html, "html5lib" ) title_tag = soup.title title = title_tag.string print( title_tag ) print( title)
f19d4075f091a4b8ae76724a2d963ae68b6a0941
vkumar62/practice
/maze.py
1,142
3.75
4
#!/usr/bin/python3 import pdb def get_all_neighbors(maze, cur): neighbors = [] x,y = cur for xo in range(-1, 2): for yo in range(-1, 2): xi = x+xo yi = y+yo if xi < 0 or xi >= len(maze): continue if yi < 0 or yi >= len(maze[0]): continue if maze[xi][yi] == 0: neighbors.append((xi, yi)) return neighbors def solve_maze_helper(maze, cur, e, path): if (cur == e): return True x,y = cur if maze[x][y] == 1: return False maze[x][y] = 1 path.append(cur) for neighbor in get_all_neighbors(maze, cur): solved = solve_maze_helper(maze, neighbor, e, path) if solved: return True path = path[-1] return False def solve_maze(maze, s, e): path = [] solved = solve_maze_helper(maze, s, e, path) return solved, path maze = [ [ 0, 0, 1, 0, 1, 0, 0 ], [ 0, 0, 0, 1, 0, 0, 0 ], ] solved, path = solve_maze(maze, (0,0), (1, 6)) if solved: print(path) else: print("No solution") #pdb.set_trace()
c4df7b4195348b0448c3865de9ff3a59657e6e38
UCAS-BigBird/Algorithm
/SA_SLL3.py
852
3.6875
4
#第一种解法的思路看起来很难,实际与前面存在着一定的联系 #这里引入了id函数 #>>>a = 'runoob' #>>> id(a) #4531887632 储存id的值 # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ map={} while head: if id(head) in map: return True else: map[id(head)]=True head=head.next return False def hasCycle2(self,head): slow=fast=head while fast and fast.next: slow=slow.next fast=fast.next if slow==fast: return True return False
8d69297de0c78b87ce1f03fea54ee848812682e8
GustavoMDantas/My-Studies
/tt.py
269
3.828125
4
n = int(input().strip()) result = n % 2 if result == 0 or range(2, 5): print('Not Weird') if result == 0 and result > 20: print('Not Weird') if result == 0 and range(6,20): print('Weird') elif result == 1: print('Weird')
9e583c8c3b3b2b3e2a5d210ea04ece8029f1b9b1
RacerChen/pythonLearn2
/oop2_vector.py
1,394
4.125
4
from math import hypot class Vector: # 特殊方法一般只有解释器才会调用(eg. x.__bool__) # 唯一例外的是__init__方法,因为一般子类会去调用超类的构造器 def __init__(self, x=0, y=0): # 构造函数和属性定义 self.x = x self.y = y def __repr__(self): # 实现print函数,也可以实现__str__函数 # 但推荐使用本函数,因为__str__会自动被替代 return 'Vector(%r, %r)' % (self.x, self.y) def __abs__(self): return hypot(self.x, self.y) # Return the Euclidean distance, sqrt(x*x + y*y). def __bool__(self): # Vector(0, 0)不是向量 return bool(abs(self)) def __add__(self, other): x = self.x + other.x y = self.y + other.y return Vector(x, y) def __mul__(self, scalar): return Vector(self.x * scalar, self.y * scalar) vec1 = Vector(1, 2) vec2 = Vector(3, 4) vec3 = Vector(0, 0) print(vec1) print(abs(vec2)) print(bool(vec1)) print(bool(vec3)) print(vec1 * -3) # 为什么是len而不是普通方法: # 当len(x)中的x是一个内置类型的实例时,那么len(x)的速度会非常快, # 背后的原因是CPython会直接从一个C结构体中读取对象长度,完全不需要调用任何方法, # 在str、list、memoryview等类型上,该方法必须高效。
c5cf30564d1307438e4ce459337a6be219be5144
oneshan/Leetcode
/accepted/159.longest-substring-with-at-most-two-distinct-characters.py
1,347
3.890625
4
# -*- coding: utf8 -*- # # [159] Longest Substring with At Most Two Distinct Characters # # https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters # # algorithms # Hard (41.72%) # Total Accepted: 31.1K # Total Submissions: 74.7K # Testcase Example: '"eceba"' # # # Given a string, find the length of the longest substring T that contains at # most 2 distinct characters. # # # # For example, # # Given s = “eceba”, # # # # T is "ece" which its length is 3. # # class Solution(object): def lengthOfLongestSubstringTwoDistinct(self, s): """ :type s: str :rtype: int """ count = 0 ans = j = 0 table = {} for i in range(len(s)): while count <= 2 and j < len(s): if table.get(s[j], 0) == 0: count += 1 table[s[j]] = table.get(s[j], 0) + 1 j += 1 if count == 3: ans = max(ans, j - i - 1) else: ans = max(ans, j - i) if j == len(s): break table[s[i]] -= 1 if table[s[i]] == 0: count -= 1 return ans if __name__ == "__main__": sol = Solution() assert(sol.lengthOfLongestSubstringTwoDistinct("eceba") == 3)
ce3ae2eb354d53950fc82fa0896f8e11e083f622
zbay/linear-algebra
/IntersectionQuizzes/GaussianElimination2/vector.py
5,261
3.71875
4
import math from myDecimal import MyDecimal from decimal import Decimal class Vector(object): def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = coordinates self.dimension = len(coordinates) except ValueError: raise ValueError('The coordinates must be nonempty') except TypeError: raise TypeError('The coordinates must be an iterable') def __str__(self): return 'Vector: {}'.format(self.coordinates) def __eq__(self, v): if self.dimension != v.dimension: return False for i in range(self.dimension): if not MyDecimal(self.coordinates[i] - v.coordinates[i]).is_near_zero(): return False return True def __iter__(self): return iter(self.coordinates) def __getitem__(self,index): return self.coordinates[index] def __setitem__(self,index,value): self.coordinates[index] = value def add(self, v): newCoordinates = [0] * self.dimension if self.dimension == v.dimension: for i in range(self.dimension): newCoordinates[i] = self.coordinates[i] + v.coordinates[i] return Vector(newCoordinates) else: return "The vectors have different dimensions, and thus cannot be added together." def subtract(self, v): newCoordinates = [0] * self.dimension if self.dimension == v.dimension: for i in range(self.dimension): newCoordinates[i] = self.coordinates[i] - v.coordinates[i] return Vector(newCoordinates) else: return "The vectors have different dimensions, and thus cannot be subtracted." def scalar_multiply(self, scalar): newCoordinates = [0] * self.dimension for i in range(self.dimension): newCoordinates[i] = self.coordinates[i] * scalar return Vector(newCoordinates) def magnitude(self): magnitude = 0 for i in range(self.dimension): magnitude += (self.coordinates[i] * self.coordinates[i]) return math.sqrt(magnitude) def unit_size(self): newCoordinates = [0] * self.dimension magnitude = self.magnitude() for i in range(self.dimension): newCoordinates[i] = (self.coordinates[i] / magnitude) return Vector(newCoordinates) def dot_product(self, v): dotProduct = 0 for i in range(self.dimension): dotProduct += self.coordinates[i] * v.coordinates[i] return dotProduct def angle(self, v, radians): dotProduct = self.dot_product(v) magnitudeProduct = self.magnitude() * v.magnitude() if MyDecimal(Decimal(magnitudeProduct)).is_near_zero(): return 0 elif radians: return math.acos(dotProduct/magnitudeProduct) else: if round(Decimal(dotProduct)/Decimal(magnitudeProduct), 6) == 1.0000: return 0 else: return math.degrees(math.acos(Decimal(dotProduct)/Decimal(magnitudeProduct))) def parallel_to(self, v): #angle is close enough to zero, adjusting for rounding error angle = self.angle(v, False) return MyDecimal(Decimal(angle)).is_near_zero() or MyDecimal(Decimal(angle - 180)).is_near_zero() def orthogonal_to(self, v): #dot product is close enough to zero, adjusting for rounding error dotProduct = self.dot_product(v) return MyDecimal(Decimal(dotProduct)).is_near_zero() def projection_on(self, basis): #the parallel component of v, extracted from self's component in that direction. unitVector = basis.unit_size() #unit vector in basis direction vParallelLength = self.dot_product(unitVector) #length of Vparallel is the basis unit vector dot V return unitVector.scalar_multiply(vParallelLength) #VParallel is the basis unit vector times the length of Vparallel def perpendicular_component_of(self, basis): #the perpendicular component of v, derived from self's component in its direction return self.subtract(self.projection_on(basis)) #Vperpendicular is V minus Vparallel def cross_product(self, v): # the cross product is the determinant of the two vectors with the i, j, k components if self.dimension == 3 and v.dimension == 3: newCoordinates = [0]*3 newCoordinates[0] = (self.coordinates[1] * v.coordinates[2]) - (self.coordinates[2] * v.coordinates[1]) newCoordinates[1] = -(self.coordinates[0] * v.coordinates[2]) + self.coordinates[2] * v.coordinates[0] newCoordinates[2] = (self.coordinates[0] * v.coordinates[1]) - (self.coordinates[1] * v.coordinates[0]) return Vector(newCoordinates) else: return "Error: the cross product operation is only possible between vectors of three dimensions each." def parallelogram_area(self, v): return self.cross_product(v).magnitude() def triangle_area(self, v): return 0.5 * self.parallelogram_area(v)
65b59ff90f8b69f99905943526a5f28165441b98
Chenlei-Fu/Interview-Preperation
/Lc_solution_in_python/0110.py
575
3.59375
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isBalanced(self, root: TreeNode) -> bool: """ method: recursion """ self.check = True self.maxDepth(root) return self.check def maxDepth(self, root): if not root: return 0 l = self.maxDepth(root.left) r = self.maxDepth(root.right) if abs(l - r) > 1: self.check = False return 1 + max(l, r)
74bdb00be3204e28809b633363dca8e7dd7d0ec1
bmacri/Python-HTTP-Server
/server.py
1,620
3.703125
4
import socket #this library allows Python to interface with the operating system's socket API def get_req(site,port): s=socket.socket() #socket() returns a socket object and assigns it to the variable s s.connect((site,port)) #tells the socket object to connect at a particular socket address s.send('GET / \r\n\r\n') #not sure if i need the \r's here for universal new line support (http://docs.python.org/library/functions.html#open) response=s.recv(1024) #the socket object receives requests on port 1024, and returns a string which is assigned to response response_bucket=[] while response: #while there is a response string response_bucket.append(response) #append response to response_bucket response=s.recv(1024) #updates value of response to avoid infinite loop bucket_join = "".join(response_bucket) #concatenates elements in the response_bucket list return bucket_join #returns a string server_socket=7000 def server_side(): s=socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #setsockopt takes socket.setsockopt(level, optname, value) s.bind(('10.242.11.81', server_socket)) #binds the socket object to an IP address (first parameter) at a particular port (second parameter) print 'ip to hit:' print '10.242.11.81:' + str(server_socket) s.listen(5) while True: ephemeral, client_ip = s.accept() #s.accept() returns a port and an ip address print "sending response" ephemeral.send('HTTP/1.1 200 OK \r\n\r\n Response!') ephemeral.close() #should accept another response on the same port; needs to create another ephemeral #loop after listen server_side()
a1048fdf29e771d27616e233020ccf40b29bd5aa
XBOOS/leetcode-solutions
/ungly_number_II.py
1,534
4.34375
4
#!/usr/bin/env python # encoding: utf-8 """ Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. Note that 1 is typically treated as an ugly number. Hint: The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).""" """ My original mistake is that use if-else to update the ptr.which results in duplicates in the result list. should all update the ptr if nextMin==min_pow""" class Solution(object): def nthUglyNumber(self, n): """ :type n: int :rtype: int """ dp = [1] ptr2 = ptr3 = ptr5=0 while len(dp)<n: min_pow2 = dp[ptr2]*2 min_pow3 = dp[ptr3]*3 min_pow5 = dp[ptr5]*5 nextMin = min(min_pow2,min_pow3,min_pow5) if nextMin==min_pow2: ptr2+=1 if nextMin==min_pow3: ptr3+=1 if nextMin ==min_pow5: ptr5+=1 dp.append(nextMin) return dp[-1]
6a9957b768d0ad4a8068e0070e15bbe326dc49e0
dhirensr/Programs
/coins.py
277
3.765625
4
values={} values[0]=0 values[1]=1 def coins(n): if n in values: return values[n] else: values[n] = max(n,coins(n/2)+coins(n/3)+ coins(n/4)) return values[n] try: while True: n = int(input()) print(coins(n)) except: pass
fdf16547c6f1e039b207e5d8f2b1ef294fd03f7a
MewtR/super-duper-invention
/utilities.py
225
3.890625
4
def purge_string(s): #Remove everything that isn't a letter s = ''.join(c for c in s if ((ord(c) > 96 and ord(c) < 123) or (ord(c) > 64 and ord(c) < 91))) #Make it lower case s = s.lower() return s