blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
660a467f0428f2564fdeec4da7f5dc171b7a2e65
DivijeshVarma/CoreySchafer
/Decorators2.py
2,922
4.46875
4
# first class functions allow us to treat functions like any other # object, for example we can pass functions as arguments to another # function, we can return functions and we can assign functions to # variable. Closures-- it will take advantage of first class functions # and return inner function that remembers and has access to variables # local to scope in which they were created. def outer_func(mg): def inner_func(): print(mg) return inner_func hi_func = outer_func('hi') hello_func = outer_func('hello') hi_func() hello_func() # Decorator is function that takes another function as an argument # add some functionality and returns another function, all of this # without altering source code of original function you passed in. # Decorating our functions allow us to easily add functionality to # our existing functions, by adding functionality inside wrapper # without modifying original display function in any way and add # code in wrapper in any way def decorator_func(original_func): def wrapper_func(*args, **kwargs): print(f"wrapper function executed {original_func.__name__}") original_func(*args, **kwargs) return wrapper_func @decorator_func def display(): print('display function') @decorator_func def display_info(name, age): print(f"name:{name}, age:{age}") display() display_info('divi', 27) print('--------------------------------') ################################## class decorator_class(object): def __init__(self, original_func): self.original_func = original_func def __call__(self, *args, **kwargs): print(f"call method executed {self.original_func.__name__}") return self.original_func(*args, **kwargs) @decorator_class def display(): print('display function') @decorator_class def display_info(name, age): print(f"name:{name}, age:{age}") display() display_info('divi', 27) print('--------------------------------') ################################## def decorator_func(func): def wrapper_func(*args, **kwargs): print(f"wrapper executed before {func.__name__}") func(*args, **kwargs) print(f"wrapper executed after {func.__name__}") return wrapper_func @decorator_func def display_info(name, age): print(f"display function with {name} and {age}") display_info('divijesh', 27) print('--------------------------------') #################################### def prefix_decorator(prefix): def decorator_func(func): def wrapper_func(*args, **kwargs): print(f"{prefix} wrapper executed before {func.__name__}") func(*args, **kwargs) print(f"{prefix} wrapper executed after {func.__name__}") return wrapper_func return decorator_func @prefix_decorator('LOG:') def display_info(name, age): print(f"display function with {name} and {age}") display_info('divijesh', 27)
b1ebc3eeeceebdf1eb6760c88d00be6b40d9e5cd
DivijeshVarma/CoreySchafer
/generators.py
809
4.28125
4
def square_nums(nums): result = [] for i in nums: result.append(i * i) return result sq_nums = square_nums([1, 2, 3, 4, 5]) print(sq_nums) # square_nums function returns list , we could convert # this to generator, we no longer get list # Generators don't hold entire result in memory # it yield 1 result at a time, waiting for us to ask # next result # when you convert generators to list you lose performance # like list(sq_nums) def square_nums(nums): for i in nums: yield (i * i) sq_nums = square_nums([1, 2, 3, 4, 5]) print(sq_nums) print(next(sq_nums)) for num in sq_nums: print(num) # list comprehensions sqs = [x * x for x in [1, 2, 3, 4, 5]] print(sqs) # create generator sqs = (x * x for x in [1, 2, 3, 4, 5]) print(sqs) for num in sqs: print(num)
e328a29edf17fdeed4d8e6c620fc258d9ad28890
DivijeshVarma/CoreySchafer
/FirstclassFunctions.py
1,438
4.34375
4
# First class functions allow us to treat functions like # any other object, i.e we can pass functions as argument # to another function and returns functions, assign functions # to variables. def square(x): return x * x f1 = square(5) # we assigned function to variable f = square print(f) print(f(5)) print(f1) # we can pass functions as arguments and returns function # as result of other functions # if function accepts other functions as arguments or # return functions as a result i.e higher order function # adding paranthesis will execute function. # # we can pass functions as arguments:-- def square(x): return x * x def my_map(func, arg_list): result = [] for i in arg_list: result.append(func(i)) return result squares = my_map(square, [1, 2, 3, 4]) print(squares) # to return a function from another function, one of the # aspects for first class function # log variable is equal to log_message function, so we can # run log variable as just like function, it remembers # message from logger function def logger(msg): def log_message(): print(f"log: {msg}") return log_message log = logger('hi') log() # it remembers tag we passed earlier def html_tag(tag): def wrap_text(msg): print(f"<{tag}>{msg}<{tag}>") return wrap_text p_h1 = html_tag('h1') p_h1('Test headline') p_h1('Another headline') p_p1 = html_tag('p1') p_p1('Test paragraph')
e12ff9f3f050bebe315f0d0926a1ad4fcf930044
MarkGadsby/TurtleGraphics
/SnowFlakes/FlowerVariousPetals.py
633
3.6875
4
from turtle import Turtle, Screen window = Screen() window.bgcolor("black") elsa = Turtle() elsa.speed("fastest") elsa.pencolor("White") elsa.fillcolor("White") elsa.penup() def DrawFlower(nPetals): elsa.pendown() for Petal in range(nPetals): for i in range(2): elsa.forward(50) elsa.right(60) elsa.forward(50) elsa.right(120) elsa.right(360/nPetals) elsa.penup() elsa.setpos(0,0) DrawFlower(5) elsa.setpos(-150,-150) DrawFlower(7) elsa.setpos(150,-150) DrawFlower(12) elsa.setpos(-150,150) DrawFlower(20) elsa.setpos(150,150) DrawFlower(16)
c1e0993722488e329ebd63543bc5171cf55c04c2
Joph25/ATI-Experiment
/stepper_motor.py
2,500
3.59375
4
import random CLOCKWISE = 1 COUNTERCLOCKWISE = 0 class StepperMotor: # ----------------------------------------------------------------------------------------------------- def __init__(self): self.counter_A = 0 self.counter_B = 0 self.counter_I = 0 self.cur_rel_pos = 0 # percent value >=0 <= 100 self.last_signal_A = False # --------------------------------------------------------------------------------------------------------- def reset(self): # move to real world 0 position while not self.check_end(): self.step(COUNTERCLOCKWISE) self.counter_A=0 self.counter_B=0 self.counter_I=0 print("Motor is reset") # ----------------------------------------------------------------------------------------------------- def step(self, direction): print("motor stepped in " + str(direction) + " direction") # --------------------------------------------------------------------------------------------------------- def go_position(self, new_rel_pos): assert new_rel_pos >= 0 & new_rel_pos <= 100 delta = new_rel_pos - self.cur_rel_pos if delta != 0: self.move(delta) # ----------------------------------------------------------------------------------------------------- def move(self, delta): if delta > 0: direction = CLOCKWISE else: direction = COUNTERCLOCKWISE counter_start = self.counter_A self.read_counter_A(direction) while (self.counter_A - counter_start) < delta: self.step(direction) self.read_counter_A(direction) # ----------------------------------------------------------------------------------------------------- def read_counter_A(self, direction): signal_A = self.read_signal_A() if signal_A != self.last_signal_A: if direction == CLOCKWISE: self.counter_A += 1 else: self.counter_A -= 1 print("Counter A: " + str(self.counter_A)) # ----------------------------------------------------------------------------------------------------- def read_signal_A(self): return bool(random.random() * 2) # ----------------------------------------------------------------------------------------------------- def check_end(self): tmp=random.random() * 1.1 tmp=bool(tmp//1) return tmp
eb7ba234432e4c448849469b58ba2a96aa151531
vandinhovicosa/CursoLuizOtavio
/Aula7/aula7.py
339
3.5625
4
""" Formatando Strings """ nome = 'Vanderson' idade = 41 altura = 1.75 peso = 76 ano_atual = 2021 imc = peso / (altura **2) nasceu = ano_atual - idade print('{} nasceu em {} e tem {} de altura.'.format(nome, nasceu, altura)) print('{} tem {} anos de idade e seu imc é {:.2f} tendo Obesidade grau 3 (mórbida)'.format(nome, idade, imc))
ab03adfb440665ca54b99af83c325217af0397ab
nathanielshak/advancedprogramming
/Projects/hangman/hangman3.py
1,712
3.921875
4
def start_hangman(): print("Let's Start playing Hangman!") def start_hangman(): print("Let's Start playing Hangman!\n") man1 = """ ____ | | | | | _|_ | |_____ | | |_________| """ man2 = """ ____ | | | o | | _|_ | |_____ | | |_________| """ man3 = """ ____ | | | o | | | _|_ | |_____ | | |_________| """ man4 = """ ____ | | | o | /| | _|_ | |_____ | | |_________| """ man5 = """ ____ | | | o | /|\\ | _|_ | |_____ | | |_________| """ man6 = """ ____ | | | o | /|\\ | / _|_ | |_____ | | |_________| """ man7 = """ ____ | | | o | /|\\ | / \\ _|_ | |_____ | | |_________| """ secret_word = "MINI" dashes = ["_", "_", "_", "_"] # Welcome message print("Welcome to Hangman!") print(man1) print("Guess the letter :") print(dashes) guessed_letter = raw_input() if guessed_letter in secret_word: for position in range(len(secret_word)): if secret_word[position] == guessed_letter: dashes[position] = guessed_letter print("Good Job, guess again!") else: print(man2) print("Oh no, wrong letter! Try again!") print(dashes) start_hangman()
677f1b968380ff52502748fbfc013b671d52f5a4
nathanielshak/advancedprogramming
/Lesson10/exercises.py
9,337
3.84375
4
import itertools import os import random # 1. File exists def file_exists(directory, file): # TODO return False # 2. Choosing sums def sum_to_target(numbers, target): # TODO return False def sum_to_target_challenge(numbers, target): # TODO return None # 3. Generating subsets def subsets_of_size(items, count): # TODO return [] # 4. Maze solving def solve_maze(maze, x, y, goal_x, goal_y): # TODO return False def solve_maze_challenge(maze, x, y, goal_x, goal_y): # TODO return None # You don't need to change anything below here - everything below here just # tests whether your code works correctly. You can run this file as # "python exercises.py" and it will tell you if anything is wrong. def test_sum_to_target(): cases = [ ([2, 4, 8], 10, True), ([2, 4, 8], 14, True), ([2, 4, 8], 9, False), ([2, 4, 8], 0, True), ] for items, target, expected in cases: actual = sum_to_target(items, target) if actual != expected: print('sum_to_target(%r, %r) returned %r, but it should have returned %r' % ( items, target, actual, expected)) return print('sum_to_target is correct') def test_sum_to_target_challenge(): cases = [ ([2, 4, 8], 10, [2, 8]), ([2, 4, 8], 14, [2, 4, 8]), ([2, 4, 8], 9, None), ([2, 4, 8], 0, []), ] for items, target, expected in cases: actual = sum_to_target_challenge(items, target) if actual != expected: print('sum_to_target_challenge(%r, %r) returned %r, but it should have returned %r' % ( items, target, actual, expected)) return print('sum_to_target_challenge is correct') def test_file_exists(): if not file_exists('.', 'README.md'): print('file_exists did not find README.md') return if not file_exists('.', 'you_found_it.txt'): print('file_exists did not find you_found_it.txt') return if file_exists('.', 'not_a_real_file.txt'): print('file_exists found not_a_real_file.txt, but it does not exist') return print('file_exists is correct') def test_subsets_of_size(): cases = [ ([1, 2, 3, 4], 0, [[]]), ([1, 2, 3, 4], 1, [[1], [2], [3], [4]]), ([1, 2, 3, 4], 2, [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]), ([1, 2, 3, 4], 3, [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]), ([1, 2, 3, 4], 4, [[1, 2, 3, 4]]), ([1, 2, 3, 4], 5, []), ] for items, target, expected in cases: actual = subsets_of_size(items, target) if sorted(actual) != sorted(expected): print('subsets_of_size(%r, %r) returned %r, but it should have returned %r (order doesn\'t matter)' % ( items, target, actual, expected)) return print('subsets_of_size is correct') def test_solve_maze_error(maze, path, message): maze.print_field() print('Your solution was: %r' % (path,)) print('Solution failed: %s' % (message,)) def test_solve_maze_path(maze, path): maze.clear_visited() if path is None: test_solve_maze_error(maze, path, 'no solution was returned') x, y = 1, 1 maze.mark_visited(x, y) for i, direction in enumerate(path): if direction.lower() == 'up': y -= 1 elif direction.lower() == 'down': y += 1 elif direction.lower() == 'left': x -= 1 elif direction.lower() == 'right': x += 1 else: test_solve_maze_error(maze, path, 'direction %d (%s) is not up, down, left, or right' % ( i, direction)) return False if maze.is_wall(x, y): test_solve_maze_error(maze, path, 'direction %d (%s) took us into a wall at (%d, %d)' % ( i, direction, x, y)) return False if maze.was_visited(x, y): test_solve_maze_error(maze, path, 'direction %d (%s) took us into a cell we had already visited: (%d, %d)' % ( i, direction, x, y)) return False maze.mark_visited(x, y) if (x, y) != (maze.width() - 2, maze.height() - 2): test_solve_maze_error(maze, path, 'path doesn\'t end at the goal (%d, %d); instead it ends at (%d, %d)' % ( maze.width() - 2, maze.height() - 2, x, y)) return False return True def test_solve_maze(test_path=False): # test some basic mazes mazes = ( (['#####', '# #', '#####'], 5, 3, True), (['#######', '# # #', '# # # #', '# # #', '#######'], 7, 5, True), (['#########', '# # #', '# ### # #', '# # #', '### ### #', '# # #', '#########'], 9, 7, True), (['#####', '# # #', '#####'], 5, 3, False), (['#######', '# # #', '# ### #', '# # #', '#######'], 7, 5, False), (['#########', '# # #', '# ##### #', '# # #', '### ### #', '# # #', '#########'], 9, 7, False)) for maze, w, h, solvable in mazes: f = Field(w, h, fixed_maze=''.join(maze)) ret = solve_maze(f, 1, 1, w - 2, h - 2) if ret != solvable: print('the following maze is %s, but solve_maze returned %r:' % ( 'solvable' if solvable else 'not solvable', ret)) f.print_field() return False if test_path: f.clear_visited() path = solve_maze_challenge(f, 1, 1, w - 2, h - 2) if solvable: if not test_solve_maze_path(f, path): return False elif path is not None: print('the following maze is not solvable, but solve_maze_challenge returned %r:' % ( path,)) f.print_field() return False # test larger always-solvable mazes for size in (5, 15, 25, 35): f = Field(size, size, generate_columns=True, generate_maze=True) ret = solve_maze(f, 1, 1, size - 2, size - 2) if not ret: print('the following maze is solvable, but solve_maze returned %r:' % (ret,)) f.print_field() return if test_path: f.clear_visited() path = solve_maze_challenge(f, 1, 1, size - 2, size - 2) if not test_solve_maze_path(f, path): return False if test_path: print('solve_maze_challenge is correct') else: print('solve_maze is correct') return True class Field(object): def __init__(self, w, h, fixed_maze=None, generate_columns=True, generate_maze=True): # w and h must be odd numbers assert (w & 1) and (h & 1), "width and height must be odd numbers" assert generate_columns or not generate_maze, \ "generate_columns must be True if generate_maze is True" if fixed_maze is not None: assert len(fixed_maze) == w * h # generate the base field self.data = [] for y in range(h): line = [] for x in range(w): line.append(fixed_maze[y * w + x] != ' ') self.data.append(line) else: # all (odd, odd) spaces are walls # all edge spaces are walls # all (even, even) spaces are open # generate the base field self.data = [] for y in range(h): line = [] for x in range(w): is_edge = (x == 0) or (x == w - 1) or (y == 0) or (y == h - 1) is_column = generate_columns and (not ((x & 1) or (y & 1))) is_wall = generate_maze and (not ((x & 1) and (y & 1))) line.append(is_edge or is_column or is_wall) self.data.append(line) # generate a maze if requested if generate_maze: visited_stack = [] current_x, current_y = 1, 1 cells_pending = set(itertools.product(range(1, w, 2), range(1, h, 2))) cells_pending.remove((1, 1)) while cells_pending: unvisited_neighbors = filter(lambda z: z in cells_pending, [ (current_x - 2, current_y), (current_x + 2, current_y), (current_x, current_y - 2), (current_x, current_y + 2)]) if unvisited_neighbors: new_x, new_y = random.choice(unvisited_neighbors) visited_stack.append((current_x, current_y)) self.data[(current_y + new_y) / 2][(current_x + new_x) / 2] = False current_x, current_y = new_x, new_y cells_pending.remove((current_x, current_y)) elif visited_stack: current_x, current_y = visited_stack.pop(-1) self.clear_visited() def print_field(self): print('y\\x ' + ''.join('%3d' % i for i in range(len(self.data[0])))) for y, line in enumerate(self.data): print(('%3d ' % y) + ''.join(('###' if x else ' ') for x in line)) def print_visited(self): print('y\\x ' + ''.join('%3d' % i for i in range(len(self.visited[0])))) for y, line in enumerate(self.visited): print(('%3d ' % y) + ''.join(('---' if x else ' ') for x in line)) def is_wall(self, x, y): return self.data[y][x] def was_visited(self, x, y): return self.visited[y][x] def mark_visited(self, x, y): self.visited[y][x] = True def clear_visited(self): self.visited = [] while len(self.visited) < self.height(): self.visited.append([False] * self.width()) def width(self): return len(self.data[0]) def height(self): return len(self.data) if __name__ == '__main__': test_sum_to_target() test_sum_to_target_challenge() test_file_exists() test_subsets_of_size() if test_solve_maze(): test_solve_maze(test_path=True)
68fc84dfacfe80537760cbad2cf0e8b403b060ac
Kyeongrok/python_crawler
/test/01_largest.py
402
3.578125
4
A = [3, 2, -2, 5, -3] def solution(A): positive = [] negative = [] result = [] for n in A: if n > 0: positive.append(n) elif n < 0: negative.append(n) for ne in negative: if abs(ne) in positive: result.append(ne) if len(result) == 0: return 0 else: result.sort() return abs(result[0])
3f7d7a26357da8a52fb3e075badd79e83f3b4c07
Kyeongrok/python_crawler
/lecture/lecture_gn6/week2/01_print_gugudan.py
366
3.765625
4
# 2 * 1 = 2 를 console에 출력 해보세요. # printGugudan() 이라는 함수를 만들어서 출력해보세요. # 함수 선언 def printGugudan(dan): for num in range(1, 9 + 1): print(dan, "*", num,"=", dan * num) print("-------------") # 함수 호출 for dan in range(2, 9 + 1): printGugudan(dan) # 2단, 3단 동시에 출력하기
4cc0ce9f7fbb5650d901b2f834b00bc9711cefa3
Kyeongrok/python_crawler
/lecture/taling/week1_function/12_variable.py
196
3.5
4
# 변수 variable # 변하는 수(값), 상수 항상 같은 수(값) result = 10 print(result) result = 20 print(result) # 상수 "" 따옴표 grade = "A" print(grade) grade = "B" print(grade)
9f5d037c97bf95b6866ff32f934fd85bf41ac3fc
Kyeongrok/python_crawler
/lecture/lecture_gn/week8/07_filter.py
214
3.609375
4
import pandas as pd df = pd.read_json("./search_result.json") df2 = df[['bloggername', 'link', 'title']] df3 = df[df['bloggername'] == '허니드롭'] print(df3['title']) for link in df3['link']: print(link)
560043e5d1c9d6e31f9b9f6d4b86c02ac5bff325
Kyeongrok/python_crawler
/lecture/lecture_gn5/week2/01_function.py
859
4.21875
4
# plus라는 이름의 함수를 만들어 보세요 # 파라메터는 val1, val2 # 두개의 입력받은 값을 더한 결과를 리턴하는 함수를 만들어서 # 10 + 20을 콘솔에 출력 해보세요. def plus(val1, val2): result = val1 + val2 return result def minus(val1, val2): return val1 - val2 def multiple(val1, val2): return val1 * val2 def divide(val1, val2): return val1 / val2 result = plus(10, 20) print(result) print(minus(10, 20)) # (10 + 20) * (30 - 40) / 20 result1 = plus(10, 20) result2 = minus(30, 40) result3 = multiple(result1, result2) result4 = divide(result3, 20) print("result4:", result4) result5 = divide(multiple(plus(10, 20), minus(30, 40)), 20) print("result5:", result5) def something(v1, v2, v3, v4, v5): return (v1 + v2) * (v3 - v4) / v5 print("sth:", something(10, 20, 30, 40, 20))
899535ec4bca9e1365bdcc425e9525f15c5dfb35
Kyeongrok/python_crawler
/lecture/lecture_gn5/week1/05_for.py
365
3.9375
4
def print1To20(): for num in range(1, 10 + 1): print(num) # print1To20() # print2To80 이라는 이름의 함수를 만들고 # 2부터 80까지 출력을 해보세요. 2 4 6 8 10 def print2To80(): for num in range(2, 80): print(num) # print2To80() def print1To79(): for num in range(0, 40): print(num * 2 + 1) print1To79()
4e4c3fcd655c2e9399dae7d84a1fec88406e9c72
Kyeongrok/python_crawler
/lecture/taling/week1_function/14_recursive.py
116
3.671875
4
def multiple(n, a): if(n == 1): return a return multiple(n-1, a) + a result = multiple(4, 5) print(result)
0dd5af66873254961a72bfdb503f092274ff3235
Kyeongrok/python_crawler
/lecture/lecture_gn3/week2/09_bs4.py
729
3.515625
4
import requests # 크롤링 from bs4 import BeautifulSoup # 파싱 def crawl(codeNum): url = "https://finance.naver.com/item/main.nhn?code={}".format(codeNum) data = requests.get(url) return data.content # return을 dictionary로 해보세요. # 필드(field)는 name, price입니다. def getCompanyInfo(string): bsObj = BeautifulSoup(string, "html.parser") wrapCompany = bsObj.find("div", {"class":"wrap_company"}) atag = wrapCompany.find("a") noToday = bsObj.find("p", {"class":"no_today"}) blind = noToday.find("span", {"class":"blind"}) return {"name":atag.get_text(), "price":blind.text} codes = ["000660", "068270", "064350"] for code in codes: print(getCompanyInfo(crawl(code)))
34948205bcc26de524c5e6ff823e644f8ada980e
Kyeongrok/python_crawler
/lecture/lecture_gn3/week7/04_print_list_for.py
189
3.609375
4
# <li></li> 가 5개 들어있는 list를 만들어보세요. # .append() 쓰지 않고 list = ["<li></li>","<li></li>","<li></li>","<li></li>","<li></li>"] for li in list: print(li)
1f6f9b70f408ad17f79d7ed238de675f13520987
Kyeongrok/python_crawler
/lecture/lecture_gn6/week3/04_crawler.py
1,183
3.515625
4
# crawl, parse함수를 만들어 보세요. # library 라이브러리, module 모듈 -> 누가 미리 만들어 놓은것 import requests from bs4 import BeautifulSoup # 문자열을 주소로 접근할 수 있게 가공해줍니다 # 무엇을 넣어서 무엇을 나오게(return) 할까? # crawl함수는 url(주소)을 넣어서 pageSting(data) return def crawl(url): data = requests.get(url) print(data, url) return data.content # 무엇을 넣어서 무엇을 리턴(나오게) 합니까? def parse(pageString): bsObj = BeautifulSoup(pageString, "html.parser") noToday = bsObj.find("p", {"class":"no_today"}) # noToday blind = noToday.find("span", {"class":"blind"}) price = blind.text # 회사 이름도 출력 해보세요. wrapCompany = bsObj.find("div", {"class":"wrap_company"}) aTag = wrapCompany.find("a") name = aTag.text return {"name":name, "price":price} # 067630, 000660 def printCompanyInfo(code): url = "https://finance.naver.com/item/main.nhn?code={}".format(code) pageString = crawl(url) companyInfo = parse(pageString) print(companyInfo) printCompanyInfo("055550") printCompanyInfo("000660")
c76f89d5eaf600a531f0f78e34217d71e3278acd
Kyeongrok/python_crawler
/test_data/01_slice.py
203
3.5
4
splitted = "hello world bye".split(" ") print(splitted[1]) targetString = "aa=19" start = len(targetString) - 3 end = len(targetString) result = targetString[start:end] print(result.replace("=", ""))
f6b5087d3d6bd679b4cffb8d4c2010e5713d265f
Kyeongrok/python_crawler
/lecture/lecture_gn6/week5/01_naver_shopping.py
822
3.515625
4
# 함수 function crawl하는 함수를 만들어 보세요 # 이름crawl -> url을 받아서 pageString return # parse(pageString) -> list [] import requests from bs4 import BeautifulSoup def crawl(url): data = requests.get(url) print(data, url) return data.content def parse(pageString): bsObj = BeautifulSoup(pageString, "html.parser") # bsObj에서 상품 정보'들'을 뽑는 기능 ul = bsObj.find("ul", {"class":"goods_list"}) lis = ul.findAll("li", {"class":"_itemSection"}) print(len(lis)) print(lis[0]) # 첫번째 제품의 이름을 출력 해보세요 return [] url = "https://search.shopping.naver.com/search/all.nhn?query=%08%EC%97%90%EC%96%B4%EC%BB%A8&cat_id=&frm=NVSHATC" pageString = crawl(url) productInfos = parse(pageString) print(productInfos)
ea8b245b513e7cf41b73cd0aea05fc2b17e63766
Kyeongrok/python_crawler
/com/chapter03_python_begin/03_function/07_f_o_g.py
167
3.515625
4
# f라는 함수 선언 def f(param1): return param1 + 10 # g함수 선언 def g(param1): return param1 * 20 # 합성함수 # f o g(10) = 210 print(f(g(10)))
847e50326329804fe47d9e68eac15a2204d9ad19
lucabenedetto/r2de-nlp-to-estimating-irt-parameters
/r2de/utils/data_manager.py
3,166
3.546875
4
import pandas as pd from r2de.constants import ( CORRECT_HEADER, DESCRIPTION_HEADER, QUESTION_ID_HEADER, QUESTION_TEXT_HEADER, ) def generate_correct_answers_dictionary(answers_text_df: pd.DataFrame) -> dict: """ Given the dataframe containing the text of the answers (i.e. possible choices), it returns a dictionary containing for each question (the question IDs are the keys) a string made of the concatenation of all the correct answers to that question. """ correct_answers_text_df = answers_text_df[answers_text_df[CORRECT_HEADER]] return generate_answers_dictionary(correct_answers_text_df) def generate_wrong_answers_dictionary(answers_text_df: pd.DataFrame) -> dict: """ Given the dataframe containing the text of the answers (i.e. possible choices), it returns a dictionary containing for each question (the question IDs are the keys) a string made of the concatenation of all the wrong answers to that question. """ wrong_answers_text_df = answers_text_df[~answers_text_df[CORRECT_HEADER]] return generate_answers_dictionary(wrong_answers_text_df) def generate_answers_dictionary(answers_text_df: pd.DataFrame) -> dict: """ Given the dataframe containing the text of the answers (i.e. possible choices), it returns a dictionary containing for each question (the question IDs are the keys) a string made of the concatenation of all the answers to that q. """ answers_text_dict = dict() for q_id, text in answers_text_df[[QUESTION_ID_HEADER, DESCRIPTION_HEADER]].values: if q_id not in answers_text_dict.keys(): answers_text_dict[q_id] = str(text) else: answers_text_dict[q_id] = answers_text_dict[q_id] + ' ' + str(text) return answers_text_dict def concatenate_answers_text_into_question_text_df( question_text_df: pd.DataFrame, answers_text_df: pd.DataFrame, correct: bool = True, wrong: bool = True ) -> list: """ creates a unique text made by concatenating to the text of the question the text of the correct choices and/or the text of the wrong choices (which ones to concatenate depends on the aguments). """ if correct: correct_answers_text_dict = generate_correct_answers_dictionary(answers_text_df) question_text_df[QUESTION_TEXT_HEADER] = question_text_df.apply( lambda r: r[QUESTION_TEXT_HEADER] + ' ' + correct_answers_text_dict[r[QUESTION_ID_HEADER]] if type(correct_answers_text_dict[r[QUESTION_ID_HEADER]]) == str else r[QUESTION_TEXT_HEADER], axis=1 ) if wrong: wrong_answers_text_dict = generate_wrong_answers_dictionary(answers_text_df) question_text_df[QUESTION_TEXT_HEADER] = question_text_df.apply( lambda r: r[QUESTION_TEXT_HEADER] + ' ' + wrong_answers_text_dict[r[QUESTION_ID_HEADER]] if type(wrong_answers_text_dict[r[QUESTION_ID_HEADER]]) == str else r[QUESTION_TEXT_HEADER], axis=1 ) return question_text_df[QUESTION_TEXT_HEADER]
4f9c1ddb562de274a644e6d41e73d70195929274
sairamprogramming/learn_python
/book4/chapter_1/display_output.py
279
4.125
4
# Program demonstrates print statement in python to display output. print("Learning Python is fun and enjoy it.") a = 2 print("The value of a is", a) # Using keyword arguments in python. print(1, 2, 3, 4) print(1, 2, 3, 4, sep='+') print(1, 2, 3, 4, sep='+', end='%') print()
64c62c53556f38d9783de543225b11be87304daf
sairamprogramming/learn_python
/pluralsight/core_python_getting_started/modularity/words.py
1,204
4.5625
5
# Program to read a txt file from internet and put the words in string format # into a list. # Getting the url from the command line. """Retrive and print words from a URL. Usage: python3 words.py <url> """ import sys def fetch_words(url): """Fetch a list of words from a URL. Args: url: The url of UTF-8 text document. Returns: A list of strings containing the words from the document. """ # Importing urlopen method. from urllib.request import urlopen # Getting the text from the url given. story = urlopen(url) story_words = [] for line in story: line_words = line.decode('utf8').split() for word in line_words: story_words.append(word) story.close() return story_words def print_items(items): """Prints items one per line. Args: An iterable series of printable items. """ for item in items: print(item) def main(url): """Prints each word from a text document from a URL. Args: url: The url of UTF-8 text document. """ words = fetch_words(url) print_items(words) if __name__ == '__main__': main(sys.argv[1])
3da8f3debbff75cf957c6c7cdc07118cb867a92d
liyaozong1991/Sorting
/src/sort.py
2,050
3.703125
4
# coding: utf8 to_sort_list = [1, 10, 9, 4, 5, 3] def quick_sort(sort_list): left_list, middle_list, right_list = [], [], [] if len(sort_list) == 0: return [] pivot = sort_list[0] for item in sort_list: if item < pivot: left_list.append(item) elif item == pivot: middle_list.append(item) else: right_list.append(item) return quick_sort(left_list) + middle_list + quick_sort(right_list) def quick_sort_inplace_helper(sort_list, start, end): if start == end: return start pivot = sort_list[start] i = start + 1 j = start + 1 while j <= end: if sort_list[j] < pivot: sort_list[j], sort_list[i] = sort_list[i], sort_list[j] i += 1 j += 1 sort_list[i-1], sort_list[start] = sort_list[start], sort_list[i-1] return i - 1 def quick_sort_inplace(sort_list, start, end): if start >= end: return index = quick_sort_inplace_helper(sort_list, start, end) quick_sort_inplace(sort_list, start, index - 1) quick_sort_inplace(sort_list, index+1, end) #print(quick_sort(to_sort_list)) #quick_sort_inplace(to_sort_list, 0, len(to_sort_list)-1) #print(to_sort_list) def heap_sort_adjust_down(sort_list, start, length): i = start * 2 + 1 while i < length: if i + 1 < length and sort_list[i] < sort_list[i+1]: i += 1 if sort_list[start] >= sort_list[i]: break sort_list[i], sort_list[start] = sort_list[start], sort_list[i] start = i i = i * 2 + 1 def heap_sort_build_max_heap(sort_list): length = len(sort_list) i = int(length / 2) - 1 if length % 2 == 0 else int(length / 2) while i >= 0: heap_sort_adjust_down(sort_list, i, length-1) i -= 1 def heap_sort(sort_list): heap_sort_build_max_heap(sort_list) for i in range(len(sort_list)-1, 0, -1): sort_list[0], sort_list[i] = sort_list[i], sort_list[0] heap_sort_adjust_down(sort_list, 0, i)
94ea01591941cddf01b8a7b71d13d4328b5c7b31
tnewham23/advent-of-code-2020
/day01/p2.py
364
3.546875
4
# extract numbers from input file with open('input.txt', 'r') as f: nums = [int(n) for n in f.readlines()] # first number for i in range(len(nums)): # second number for j in range(len(nums)): # third number for k in range(len(nums)): # three numbers sum to 2020 if nums[i] + nums[j] + nums[k] == 2020: print(nums[i]*nums[j]*nums[k]) exit()
4b592e0fb43b431e3e411705cec611989a90dff3
gotdang/edabit-exercises
/python/time_for_milk_and_cookies.py
576
3.921875
4
""" Is it Time for Milk and Cookies? Christmas Eve is almost upon us, so naturally we need to prepare some milk and cookies for Santa! Create a function that accepts a Date object and returns True if it's Christmas Eve (December 24th) and False otherwise. Examples: time_for_milk_and_cookies(datetime.date(2013, 12, 24)) ➞ True time_for_milk_and_cookies(datetime.date(2013, 1, 23)) ➞ False time_for_milk_and_cookies(datetime.date(3000, 12, 24)) ➞ True Notes All test cases contain valid dates. """ time_for_milk_and_cookies = lambda x: x.month == 12 and x.day == 24
99bd7e715f504ce64452c252ac93a026f426554d
gotdang/edabit-exercises
/python/factorial_iterative.py
414
4.375
4
""" Return the Factorial Create a function that takes an integer and returns the factorial of that integer. That is, the integer multiplied by all positive lower integers. Examples: factorial(3) ➞ 6 factorial(5) ➞ 120 factorial(13) ➞ 6227020800 Notes: Assume all inputs are greater than or equal to 0. """ def factorial(n): fact = 1 while n > 1: fact *= n n -= 1 return fact
30d9fe50769150b3efcaa2a1628ef9c7c05984fa
gotdang/edabit-exercises
/python/index_multiplier.py
428
4.125
4
""" Index Multiplier Return the sum of all items in a list, where each item is multiplied by its index (zero-based). For empty lists, return 0. Examples: index_multiplier([1, 2, 3, 4, 5]) ➞ 40 # (1*0 + 2*1 + 3*2 + 4*3 + 5*4) index_multiplier([-3, 0, 8, -6]) ➞ -2 # (-3*0 + 0*1 + 8*2 + -6*3) Notes All items in the list will be integers. """ def index_multiplier(lst): return sum([i * v for i, v in enumerate(lst)])
e634a798aa245d2bb8ae9501203f62f9675bfdcb
verhagenkava/ebanx-take-home
/src/domain/use_cases/withdraw_account.py
376
3.5
4
from abc import ABC, abstractmethod from typing import Dict from src.domain.models import Accounts class WithdrawAccount(ABC): """Interface for Withdraw Account use case""" @abstractmethod def withdraw(self, account_id: int, amount: float) -> Dict[bool, Accounts]: """Withdraw Account use case""" raise Exception("Method should be implemented")
0a229bee2379b5de55b2ffafa5e09395208e3394
rkapali-zz/copy
/set1/pygrep
231
3.625
4
#!/usr/bin/python import sys, gzip string = str(sys.argv[1]) filename = sys.argv[2] if filename.endswith('gz'): f = gzip.open(filename, 'r') else: f = open (filename, 'r') for line in f: if string in line: print line f.close
994b398a38d8fa95d5d29a06a66a3e65f8e7e9c7
Carine-SHS-Digital-Tech/dodge-pygame-Minecraf09
/main.py
2,490
4.09375
4
# Basic Pygame Structure import pygame # Imports pygame and other libraries import random pygame.init() # Pygame is initialised (starts running) # Define classes (sprites) here class Fallingobject(pygame.sprite.Sprite): def _init_(self): pygame.sprite.Sprite._init_(self) self.timecreated = pygame.time.get.ticks() # Note the time the object is created in. self.image = pygame.Surface({30,30}) # Create a surface on which to display graphics. self.image.set_colourkey(black) # Set a colour to be transparent. self.rect = self.image.get_rect() # These lines create the regular sprite, self.rect.x = random.randint(0,670) # the same size as the image surface and then self.rect.y = 0 # assigns it coordinates. def setImage(self,graphicSelected): fallingObjectsImage = pygame.image.load(graphicSelected) # Load in passed image file self.image.blit(fallingObjectsImage,(0,0)) # Draw that graphic onto the surface screen = pygame.display.set_mode([700,500]) # Set the width and height of the screen [width,height] pygame.display.set_caption("Dodge") background_image = pygame.image.load("OrchardBackground.jpg").convert()# Load in the background image done = False # Loop until the user clicks the close button. clock = pygame.time.Clock() # Used to manage how fast the screen updates black = ( 0, 0, 0) # Define some colors using rgb values. These can be white = ( 255, 255, 255) # used throughout the game instead of using rgb values. # Define additional Functions and Procedures here allFallingObjects = pygame.sprite.Group() # -------- Main Program Loop ----------- while done == False: for event in pygame.event.get(): # Check for an event (mouse click, key press) if event.type == pygame.QUIT: # If user clicked close window done = True # Flag that we are done so we exit this loop # Update sprites here screen.blit(background_image, [0,0]) pygame.display.flip() # Go ahead and update the screen with what we've drawn. clock.tick(20) # Limit to 20 frames per second pygame.quit() # Close the window and quit.
20cd86be5fb538a196a84ce517659e9edac3997f
antonidass/BaumanStudy
/sem2/python_sem_2/lab4.py
7,387
3.515625
4
from tkinter import * import random # Построение элементов def create_entry(): global entry, input_l, canvas input_l = Label(root, text="Введите координаты X и Y через пробел", font=("ComisSansMS", 15), bg='#FFEFD5') input_l.place(relx=0.005, rely=0.005, relwidth=0.4, relheight=0.1) entry = Entry(root, font=("ComisSansMS", 18), selectborderwidth=5) entry.place(relx=0.005, rely=0.1, relwidth=0.4, relheight=0.1) b_point = Button(root, text="Ввести координаты", font=("ComisSansMS", 18), fg="#00CED1", bg="#F8F8FF", activebackground="#FDF5E6", activeforeground="#1E90FF", command=lambda: enter('<Return>'), width=8, bd=4) b_point.place(relx=0.02, rely=0.2, relwidth=0.35, relheight=0.1, anchor='nw') b_find = Button(root, text="Поиск", font=("ComisSansMS", 18), fg="#00CED1", bg="#F8F8FF", activebackground="#FDF5E6", activeforeground="#1E90FF", command=find_answer, width=5, bd=4) b_find.place(relx=0.02, rely=0.31, relwidth=0.35, relheight=0.12, anchor='nw') b_clear = Button(root, text="Стереть построения", font=("ComisSansMS", 18), fg="#00CED1", bg="#F8F8FF", activebackground="#FDF5E6", activeforeground="#1E90FF", command=clear, width=5, bd=4) b_clear.place(relx=0.02, rely=0.44, relwidth=0.35, relheight=0.12, anchor='nw') canvas = Canvas(root, bg="white") canvas.place(relx=0.41, rely=0.1, relwidth=0.58, relheight=0.88, anchor='nw') y = Label(root, text="Y(600)", bg="#FFFAF0", font=("ComisSansMS", 20)) y.place(relx=0.33, rely=0.91, anchor='nw') x = Label(root, text="X(700)", bg="#FFFAF0", font=("ComisSansMS", 20)) x.place(relx=0.9, rely=0.04, anchor='nw') def find_triangle_sides(x1, y1, x2, y2, x3, y3): AB = ((x2 - x1)**2 + (y2 - y1)**2) ** 0.5 BC = ((x2 - x3)**2 + (y2 - y3)**2) ** 0.5 AC = ((x3 - x1)**2 + (y3 - y1)**2) ** 0.5 return AB, BC, AC # Условие существования треугольника def tringle_condition(AB, BC, AC): if (AB + BC <= AC) or (AB + AC <= BC) or (BC + AC <= AB): return False return True # Поиск суммы биссектрис def find_sum_bisectors(a, b, c): bs_c = (a * b * (a + b + c) * (a + b - c)) ** 0.5 / (a + b) bs_a = (b * c * (a + b + c) * (b + c - a)) ** 0.5 / (b + c) bs_b = (c * a * (a + b + c) * (c + a - b)) ** 0.5 / (a + c) return bs_c + bs_a + bs_b # Поиск треугольника def find_answer(): global min_coords, bisec_cooords1, bisec_cooords2, bisec_cooords3 min_sum = 10**20 flag = 0 for i in range(0, len(coords)-5, 2): for j in range(i + 2, len(coords)-3, 2): for k in range(j + 2, len(coords)-1, 2): a, b, c = find_triangle_sides(coords[i], coords[i+1], coords[j], coords[j+1], coords[k], coords[k+1]) cur_sum = find_sum_bisectors(a, b, c) if tringle_condition(a, b, c) and cur_sum < min_sum: min_sum = cur_sum #Стираем предыдущие построения if len(min_coords) > 0 and flag == 0: canvas.create_line(min_coords[0], min_coords[1], min_coords[2], min_coords[3], fill='white') canvas.create_line(min_coords[0], min_coords[1], min_coords[4], min_coords[5], fill='white') canvas.create_line(min_coords[2], min_coords[3], min_coords[4], min_coords[5], fill='white') bisec_cooords1 = ((min_coords[0] + min_coords[2]) / 2, (min_coords[1] + min_coords[3]) / 2) canvas.create_line(min_coords[4], min_coords[5], bisec_cooords1[0], bisec_cooords1[1], fill="white") bisec_cooords2 = ((min_coords[0] + min_coords[4]) / 2, (min_coords[1] + min_coords[5]) / 2) canvas.create_line(min_coords[2], min_coords[3], bisec_cooords2[0], bisec_cooords2[1], fill="white") bisec_cooords3 = ((min_coords[2] + min_coords[4]) / 2, (min_coords[3] + min_coords[5]) / 2) canvas.create_line(min_coords[0], min_coords[1], bisec_cooords3[0], bisec_cooords3[1], fill="white") flag = 1 min_coords = [coords[i], coords[i+1], coords[j], coords[j+1], coords[k], coords[k+1]] if (min_sum == 10**20): input_l.config(text="Невозможно построить треугольник!!!", font=("ComisSansMS", 14), fg="Red") return input_l.config(text="Успех ", font=("ComisSansMS", 14), fg="Green") canvas.create_line(min_coords[0], min_coords[1], min_coords[2], min_coords[3]) canvas.create_line(min_coords[0], min_coords[1], min_coords[4], min_coords[5]) canvas.create_line(min_coords[2], min_coords[3], min_coords[4], min_coords[5]) bisec_cooords1 = ((min_coords[0] + min_coords[2]) / 2, (min_coords[1] + min_coords[3]) / 2) canvas.create_line(min_coords[4], min_coords[5], bisec_cooords1[0], bisec_cooords1[1], fill="red") bisec_cooords2 = ((min_coords[0] + min_coords[4]) / 2, (min_coords[1] + min_coords[5]) / 2) canvas.create_line(min_coords[2], min_coords[3], bisec_cooords2[0], bisec_cooords2[1], fill="red") bisec_cooords3 = ((min_coords[2] + min_coords[4]) / 2, (min_coords[3] + min_coords[5]) / 2) canvas.create_line(min_coords[0], min_coords[1], bisec_cooords3[0], bisec_cooords3[1], fill="red") def mousec_coords(event): point_x_y = (event.x, event.y) coords_l = Label(root, text="x = "+str(point_x_y[0]) + "\ny = " + str(point_x_y[1]), bg="#FFFAF0", font=("ComisSansMS", 15)) coords_l.place(relx=0.33, rely=0.6, anchor='nw') # Добавление точек def update_points(coords_for_update): colors = ['red', 'green', 'blue', 'brown', 'orange', 'grey', 'purple', 'pink', '#FF1493', '#9ACD32', '#4682B4', '#00008B', '#A52A2A', '#00FFFF', '#00FF00', '#8A2BE2', '#FFD700', '#FFA07A', '#FA8072', '#00FA9A', '#ADFF2F', '#2F4F4F', '#FF00FF', '#BDB76B'] color = random.choice(colors) for i in range(0, len(coords_for_update)-1, 2): canvas.create_oval(coords_for_update[i], coords_for_update[i+1], coords_for_update[i], coords_for_update[i+1], outline=color, width=10) # Ввод данных def enter(event): cur_coords = list(map(float, entry.get().split())) if len(cur_coords) & 1 == 1: input_l.config(text="Введено нечетное количество координат", font=("ComisSansMS", 12), fg="Red") return input_l.config(text="Введите координаты X и Y через пробел", font=("ComisSansMS", 15), fg="black") for x in cur_coords: coords.append(x) entry.delete(0, END) update_points(cur_coords) def clear(): global coords coords = list() canvas.delete("all") root = Tk() root.geometry("1200x700+300+200") root.title('Лабораторная работа 4. Поиск наименьших длин биссектрис треугольника') root.config(bg="#FFFAF0") create_entry() min_coords = list() coords = list() root.bind('<Return>', enter) canvas.bind('<Motion>', mousec_coords) root.mainloop()
36f7db179bcc0339c7969dfa9f588dcd51c6d904
adarshsree11/basic_algorithms
/sorting algorithms/heap_sort.py
1,200
4.21875
4
def heapify(the_list, length, i): largest = i # considering as root left = 2*i+1 # index of left child right = 2*i+2 # index of right child #see if left child exist and greater than root if left<length and the_list[i]<the_list[left]: largest = left #see if right child exist and greater than root if right<length and the_list[largest]<the_list[right]: largest = right #change root if larger number caught as left or right child if largest!=i: the_list[i],the_list[largest]=the_list[largest],the_list[i] # heapify the new root heapify(the_list, length, largest) def heapSort(the_list): n = len(the_list) #heapify the full list for i in range(n//2-1, -1, -1): #heapify from last element with child to top heapify(unsorted_list, n, i) #heapsort sxtracting elements one by one for i in range(n-1, 0, -1): #swapping the root element which is max to its position the_list[i],the_list[0] = the_list[0],the_list[i] #heapify from root again length reduced to 'i' to keep sorted elements unchanged heapify(the_list, i, 0) if __name__ == '__main__': unsorted_list = [17,87,6,22,54,3,13,41] print(unsorted_list) heapSort(unsorted_list) print(unsorted_list)
62019a39bd185d59b2d8a861c572afa3851c70dc
adarshsree11/basic_algorithms
/data structures/linked_list_stack.py
2,270
3.890625
4
class node(object): def __init__(self, data, next_node = None): self.data = data self.next_node = next_node def get_next(self): return self.next_node def set_next(self, next_node): self.next_node = next_node def get_data(self): return self.data def set_data(self,data): self.data = data class LinkedList(object): def __init__(self, tail = None): self.tail = tail self.size = 0 def get_size(self): return self.size def add(self, data): new_node = node(data,self.tail) self.tail = new_node self.size += 1 def remove(self, data): this_node = self.tail prev_node = None while this_node: if this_node.get_data() == data: if prev_node: prev_node.set_next(this_node.get_next()) else: self.tail = this_node.get_next() self.size -= 1 return True else: prev_node = this_node this_node = this_node.get_next() return False def find(self, data): this_node = self.tail pos = 0 while this_node: if this_node.get_data() == data: return data, pos else: this_node = this_node.get_next() pos += 1 return None def printList(self): this_node = self.tail linked_arr = [] while this_node: linked_arr.append(this_node.get_data()) this_node = this_node.get_next() return linked_arr if __name__ == '__main__': new_list = LinkedList() live = True while(live): choice = int(input("Choose\n\n1.add\n2.remove\n3.find\n4.get_size\n5.Print\n6.Exit\n")) if choice == 1: value = int(input("Data: ")) new_list.add(value) elif choice == 2: value = int(input("Remove: ")) if new_list.remove(value): print("removed: " + str(value) + "\n") else: print("Err404: "+ str(value) + " not Found\n") elif choice == 3: value = int(input("Find = ")) if new_list.find(value): print("Found: " + str(new_list.find(value)[0]) + " at: " + str(new_list.find(value)[1]) + "\n") else: print("Err404: "+ str(value) + " not Found\n") elif choice == 4: print("Current size of List: " + str(new_list.get_size())) elif choice == 5: li_array = new_list.printList() for data in li_array: print(str(data) + "\n") elif choice == 6: live = False
b66f00cd727e040d850e8b59544ff4fd385e3063
GabrielGhe/CoderbyteChallenges
/easy_DashInsert.py
398
4.09375
4
def odd(ch): return ch in '13579' ############################## # Inserts dashes between odd # # digits # ############################## def DashInsert(num): result = [] prev = ' ' for curr in str(num): if odd(prev) and odd(curr): result.append('-') result.append(curr) prev = curr return ''.join(result) print DashInsert(raw_input())
3ce56297221edaccb5243050a8f4cfa7334bb709
GabrielGhe/CoderbyteChallenges
/easy_FirstReverse.py
99
3.5
4
#Reverses string def FirstReverse(str): return str[::-1] print FirstReverse(raw_input())
d3068a90f85ae19efbd46bfa65948b0ffd5a9c2c
GabrielGhe/CoderbyteChallenges
/easy_SecondGreatLow.py
367
4
4
""" Finds the second greatest and second lowest value in an array """ def SecondGreatLow(arr): arr = list(set(arr)) arr.sort() stri = "{0} {1}".format(arr[0], arr[0]) if len(arr) == 2: stri = "{0} {1}".format(arr[0], arr[1]) elif len(arr) > 2: stri = "{0} {1}".format(arr[1], arr[-2]) return stri print SecondGreatLow(raw_input())
bed3f009ee3c3b97119b2452df06eb78210f2f79
lgong30/python-performance-investigate
/list_remove.py
798
3.953125
4
"""This script compares different methods to remove elements from it. """ import timeit setup = ''' from copy import deepcopy n = 10000 x = range(n) y = range(20,2001) ''' test_group = 1 test_num = 10000 s = ''' i = 20 while i < 2000: y[i - 20] = x[i] i += 1 ''' print "splicing: ", timeit.Timer('[z for z in x[20:2001]]', setup=setup).repeat(test_group, test_num)[0] print "list creating: ", timeit.Timer('[x[i] for i in xrange(20,2001)]', setup=setup).repeat(test_group, test_num)[0] print "while loop: ", timeit.Timer(s, setup=setup).repeat(test_group, test_num)[0] print "removing first element: ", timeit.Timer('del x[0]', setup=setup).repeat(test_group, test_num)[0] print "removing the last element: ", timeit.Timer('del x[-1]', setup=setup).repeat(test_group, test_num)[0]
25e90005ec5be4d6f02c2c5c188eebe06ff0c7df
joselitofilho/aulas-programacao-modulo1
/aula2/aula_2_clausula_condicional_if.py
137
3.75
4
A = True B = True expressao = not (A and B) # (not A) or (not B) # De morgan if expressao: print ("Deu certo!"); print ("Terminou.");
44fc8822ec305e0015957db20106959b8e89f33b
joselitofilho/aulas-programacao-modulo1
/aula2/aula_2_operador_not.py
636
4.03125
4
A = True B = True resultado = A or (not B) #print ("A OR (NOT B) =", resultado); A = False B = True resultado = A or (not B) #print ("A OR (NOT B) =", resultado); A = False B = False resultado = (not A) or B #print ("(NOT A) OR B =", resultado); A = True B = False resultado = (not A) and B #print ("(NOT A) AND B =", resultado); A = True B = False resultado = (not A) and (not B) #print ("(NOT A) AND (NOT B) =", resultado); A = False B = False resultado = not ((not A) and (not B)) #print ("NOT ((NOT A) AND (NOT B)) =", resultado); A = True B = True resultado = not (A and (not B)) #print ("NOT (A AND (NOT B)) =", resultado);
c398f3db4c1a2be3ec6c30d0610bfe0785292ef4
nguyenducmanh1206/nguyenducmanh-fundamental-c4e21
/sisson4.1/baitap.py
676
3.546875
4
r1={ "#":1, "name":"huy", "level":25, "hour":14, } r2={ "#":2, "name":"hoa", "level":20, "hour":7, } r3={ "#":3, "name":"tam", "level":15, "hour":20, } salary_list=[r1, r2, r3] total_wage =0 wage_list= [] for salary in salary_list: name = salary["name"] hour = salary["hour"] level = salary["level"] wage_info={ "name":name, "wage":hour * level, "hour":hour, } wage_list.append(wage_info) wage = hour * level total_wage += wage print("total wage: ", total_wage) import pyexcel pyexcel.save_as(records=wage_list, dest_file_name="bangluong.xlsx")
2002e154eb83119ddb9632b831eee54c64930e1f
nguyenducmanh1206/nguyenducmanh-fundamental-c4e21
/sission3/baitap1.py
317
3.578125
4
menu_items = ["pho bo", "my xao", "com rang"] # for index, item in enumerate(menu_items): # print(index + 1,".", item, sep=" ") # print("*" *10 ) # print(*menu_items, sep=",") n =int(input("vi tri ma ban muon update ")) new =input("ban muon thay doi gi :") menu_items[n-1] =new print(*menu_items, sep=" ")
0a441aa633971320fa95db0068be0fa78846e6cf
JakeRoggenbuck/Paper
/src/papervars.py
825
3.625
4
import error class Var: def __init__(self, data, name): self.data = data self.name = name def __repr__(self): return f"{self.name}({self.data})" class String(Var): def __init__(self, data): super().__init__(data, "String") def __repr__(self): return f"String(\"{self.data}\")" class Int(Var): def __init__(self, data): try: super().__init__(int(data), "Int") except: error.PaperTypeError() class Float(Var): def __init__(self, data): try: super().__init__(float(data), "Float") except: error.PaperTypeError() class Bool(Var): def __init__(self, data): try: super().__init__(bool(data), "Bool") except: error.PaperTypeError()
3ca5272ce257f3e629527f211e1225830b2e936c
tanzilsheikh/PythonWorkshop
/DAY_1/surfaceAreaofCone.py
538
3.765625
4
import math pi = math.pi # Function To Calculate Surface Area of Cone def surfacearea(r, s): return pi * r * s + pi * r * r # Function To Calculate Total Surface Area # of Cylinder def totalsurfacearea(r, h): tsurf_ar = (2 * pi * r * h) + (2 * pi * r * r) return tsurf_ar # Driver Code radius = float(5) height = float(12) slat_height = float(13) r = 5 h = 8 print( "Surface Area Of Cone : ", surfacearea(radius, slat_height) ) print("Total Surface Area Of Cylinder = ",totalsurfacearea(r,h))
090e9d95c5447aeae11e799f04368d50ce8198ff
GreatStephen/MyLeetcodeSolutions
/1contest221/1.py
353
3.609375
4
class Solution: def halvesAreAlike(self, s: str) -> bool: vowel = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} def count(s): ans = 0 for c in s: if c in vowel: ans += 1 return ans l = len(s) return count(s[:l//2])==count(s[l//2:])
5a19ec86aa69b16aa92643a644e5187af8ea28a2
GreatStephen/MyLeetcodeSolutions
/Maximum Width of Binary Tree/Maximum Width of Binary Tree.py
853
3.515625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int: self.left, self.right = [1], [1] self.ans = 0 def DFS(node, level, idx): if level>=len(self.left): self.left.append(idx) else: self.left[level] = min(self.left[level], idx) if level>=len(self.right): self.right.append(idx) else: self.right[level] = max(self.right[level], idx) self.ans = max(self.ans, self.right[level]-self.left[level]+1) if node.left: DFS(node.left, level+1, idx*2) if node.right: DFS(node.right, level+1, idx*2+1) DFS(root, 0, 1) return self.ans
a1ebdbd847a84c2adc04da4cb8a7372b3fbc7cc7
GreatStephen/MyLeetcodeSolutions
/Inorder Successor in BST II/Inorder Successor in BST II.py
851
3.75
4
""" # Definition for a Node. class Node: def __init__(self, val): self.val = val self.left = None self.right = None self.parent = None """ class Solution: def inorderSuccessor(self, node: 'Node') -> 'Node': # 两种情况,位于node的右子树的最左端,或者位于node的某一个大于node的parent if node.right: # 存在右子树,那么一定在右子树 cur = node.right while cur.left: cur = cur.left return cur else: # 不存在右子树,那么就往上找到第一个val>cur.val的parent prev = node cur = node.parent while cur and cur.val<prev.val: prev = cur cur = cur.parent return cur # 如果找不到合适的,cur会等于None
65c7e429d2a43202708f30830e0477807a43f9a1
GreatStephen/MyLeetcodeSolutions
/Rotate List/better.py
676
3.71875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if not head: return None tail, count = head, 1 while tail.next: tail = tail.next count += 1 if k==count: return head k = count - (k%count) # move left by k steps now n = head for _ in range(1, k): n = n.next # find the kth node from the left tail.next = head head = n.next n.next = None return head
c2f298c6288f74dbe40243e6057bfaf04840af82
ArtemSmirnov/smrn
/dz3/proc27.py
676
3.921875
4
import random import math def IsPowerN(K,N): x = int(round(math.log(K,N))) if K == N**x: return True return False def IsPowerNa(K,N): while K > 1: K /= N if K == 1.0: return True return False s = 0 s2 = 0 N = random.randrange(2,10) print("N = ",N) L = [N**random.randrange(1,10)+random.randrange(0,2) for i in range(0,10)] for i in range(0,len(L)): x = L[i] #print(x,end="; ") s += int(IsPowerN(x,N)) s2 += int(IsPowerNa(x,N)) print(x,":",IsPowerN(x,N),":",IsPowerNa(x,N)) print("\nКоличество от IsPowerN:",s) print("\nКоличество от IsPowerN:",s2)
f3a593ff7d5198379cdc341d2a1cc35cf49cb345
alexhwoods/monte-carlo
/monte_carlo/components/models/Card.py
2,358
4.09375
4
# Author: Alex Woods <[email protected]> class Card(object): """A card from a standard card deck. Cards have the following properties: Attributes: rank: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace suit: There are four suits - hearts, diamonds, clubs, and spades. They're represented as strings. faceUp: A boolean, true if the card is faceUp in the game. """ suits = ("CLUBS", "DIAMONDS", "HEARTS", "SPADES") # note that 1 is the same as ace ranks = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "JACK", "QUEEN", "KING", "ACE") # for sorting out which card is the most valuable in a high card situation value = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'JACK':11, 'QUEEN':12, 'KING':13, 'ACE':14} def __init__(self, suit, rank): # making sure suit is entered in the right form if suit.upper() in Card.suits: self.suit = suit.upper() elif not isinstance(suit, basestring): raise ValueError("Suit must be a string.") else: raise ValueError("Invalid suit type, must be of form" + str(Card.suits)) # making sure rank is entered in the right form if rank.upper() in Card.ranks or rank == "1": if rank.upper() == "1": rank = "ACE" self.rank = rank.upper() elif not isinstance(rank, basestring): raise ValueError("Rank must be a string") else: raise ValueError("Must enter a valid rank, of the form " + str(Card.ranks)) self.faceUp = False def same_rank(self, card): if self.rank == card.rank: return True else: return False def get_rank(self): return self.rank def get_suit(self): return self.suit def flip(self): # I decided it makes no sense to flip a card that's face up back over, in Texas Hold'em at least self.faceUp = True # DON'T DELETE (it breaks the equality operator) def __hash__(self): return hash(self.__dict__.values()) def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __str__(self): return str(self.rank) + " OF " + str(self.suit)
5042fd49bdadc4af7ca64b0e9265c70187357332
mattknox/twitter_sicp
/2/6_robey.py
302
3.515625
4
#!/usr/bin/env python zero = lambda f: lambda x: x def add1(n): return lambda f: lambda x: f(n(f)(x)) one = lambda f: lambda x: f(x) two = lambda f: lambda x: f(f(x)) def add(a, b): return lambda f: lambda x: a(f)(b(f)(x)) # for testing: def numberize(n): return n(lambda x: x + 1)(0)
88bf240c30c8373b3779a459698223ec3cb74e24
mliu31/codeinplace
/assn2/khansole_academy.py
836
4.1875
4
""" File: khansole_academy.py ------------------------- Add your comments here. """ import random def main(): num_correct = 0 while num_correct != 3: num1 = random.randint(10,99) num2 = random.randint(10,99) sum = num1 + num2 answer = int(input("what is " + str(num1) + " + " + str(num2) + "\n>>")) if sum == answer: num_correct += 1 print("Correct. You've gotten " + str(num_correct) + " problem(s) right in a row! ") if num_correct == 3: print("Congratulations! you've mastered addition") else: print("Incorrect. the expected answer is " + str(sum)) num_correct = 0 # This provided line is required at the end of a Python file # to call the main() function. if __name__ == '__main__': main()
4feb346e3c70cf717602c1184168a95a52095903
mliu31/codeinplace
/section3/iat.py
2,001
3.625
4
import time import random TEST_LENGTH_S = 10 ''' This is an alternative program for sections where you are concerned about colorblindness getting in the way. It is basically the exact same problem. We will get you a handout with details Monday night PDT. recall that students don't know lists yet! ''' def main(): n_forward = run_phase(False) print('\n====================\n') n_backward = run_phase(True) print('standard', n_forward) print('flipped', n_backward) def run_phase(flipped): print_intro(flipped) start_time = time.time() n_correct = 0 while time.time() - start_time < PHASE_TIME_S: is_correct = run_single_test(is_phase_1) if is_correct: n_correct += 1 return n_correct def run_single_test(flipped): print('') animal = random_animal() association = get_association(animal, flipped) print(animal) response = input('Type the association: ') if response != association: print('Correct answer was ' + association) return response == association def print_intro(flipped): if flipped: print('Association test, standard') else: print('Association test, flipped!') print('You will be asked to answer three questions.') print('You should associate animals as follows:') print('puppy', get_association('puppy', flipped)) print('panda', get_association('panda', flipped)) print('spider', get_association('spider', flipped)) print('bat', get_association('bat', flipped)) input('Press enter to start... ') def random_animal(): return random.choice(['puppy', 'panda', 'spider', 'bat']) def get_association(animal, flipped): if animal == 'puppy' or animal == 'panda': if flipped: return 'scary' else: return 'cute' if animal == 'bat' or animal == 'spider': if flipped: return 'cute' else: return 'scary' if __name__ == '__main__': main()
66702fbd180f0bc54cec3fea6c57b802616d186c
mliu31/codeinplace
/section4/section_filter.py
637
3.875
4
from simpleimage import SimpleImage def main(): """ This program loads an image and applies the narok filter to it by setting "bright" pixels to grayscale values. """ image = SimpleImage('images/simba-sq.jpg') # visit every pixel (for loop) for pixel in image: # find the average average = (pixel.red + pixel.green + pixel.blue) // 3 # if average > "bright" if average > 153: # set this pixel to grayscale pixel.red = average pixel.green = average pixel.blue = average image.show() if __name__ == '__main__': main()
346d3af90d21411c4265d7e232786fc4078f82fc
Tanay-Gupta/Hacktoberfest2021
/python_notes1.py
829
4.4375
4
print("hello world") #for single line comment '''for multi line comment''' #for printing a string of more than 1 line print('''Twinkle, twinkle, little star How I wonder what you are Up above the world so high Like a diamond in the sky Twinkle, twinkle little star How I wonder what you are''') a=20 b="hello" c=39.9 #here a is variable and its datatype is integer print(a) #how to print the datatype of a print(type(a)) print(type(c)) #how to print arithmetic results a=5 b=3 print ("the sum of a+b is",a+b) print ("the diff of a-b is",a-b) print ("the product of a*b is",a*b) # comparison operators a=(82<=98) print(a) # type conversion and type casting a="45" #this is a string # to convert into int a=int(a) print(type(a)) b= 34 print(type(b)) b=str(b) print(type(b))
9be1cf0969c39542732f8fc56137061d3f005a90
KarlLichterVonRandoll/learning_python
/DataStructure/sort/02-select.py
1,272
3.6875
4
""" 选择排序 时间复杂度: O(n^2) 额外空间: O(1) 特点: 适合数据量较少的情况 基本思想: 第一次,在待排序的数据 r(1)~r(n) 中选出最小的,将它与 r(1) 交换; 第二次,在待排序的数据 r(2)~r(n) 中选出最小的,将它与 r(2) 交换; 以此类推... 第 i 次,在待排序的数据 r(i)~r(n) 中选出最小的,将它与 r(i) 交换 """ import random import time def select_sort(list_): for i in range(len(list_) - 1): min_index = i # 已排序好的序列的最后一个元素的下标 i for j in range(i + 1, len(list_)): if list_[j] < list_[min_index]: # 找出未排序的序列中最小值的下标 min_index min_index = j if min_index != i: # 对应的元素值交换 list_[i], list_[min_index] = list_[min_index], list_[i] list01 = [random.randint(1, 999) for i in range(10000)] list02 = list01.copy() print(list01[:50]) start01 = time.clock() select_sort(list01) print("选择排序结果:", time.clock() - start01) print(list01[:50]) start02 = time.clock() list02.sort() print("sort() 函数排序结果:", time.clock() - start02) print(list02[:50])
476b151ef7163cd29a6bd86126f12263be074094
KarlLichterVonRandoll/learning_python
/month05/AI/day03/demo04_sigmoid.py
217
3.546875
4
""" sigmoid 函数 """ import numpy as np import matplotlib.pyplot as mp def sigmoid(x): return 1 / (1 + np.exp(-x)) x = np.linspace(-50, 50, 500) y = sigmoid(x) mp.plot(x, y) mp.grid(linestyle=':') mp.show()
f9f7e50a92722a94b0d387c61b00a216e556219d
KarlLichterVonRandoll/learning_python
/month01/code/day01-04/exercise03.py
1,842
4.1875
4
""" 录入商品单价 再录入数量 最后获取金额,计算应该找回多少钱 """ # price_unit = float(input('输入商品单价:')) # amounts = int(input('输入购买商品的数量:')) # money = int(input('输入你支付了多少钱:')) # # Change = money - amounts * price_unit # print('找回%.2f元' % Change) """ 获取分钟、小时、天 计算总秒数 """ # minutes = int(input('输入分钟:')) # hours = int(input('输入小时:')) # days = int(input('输入天数:')) # # seconds = minutes * 60 + hours * 3600 + days * 86400 # print('总共是%d秒' % seconds) """ 一斤10两 输入两,计算几斤几两 """ # weights = int(input('输入几两:')) # result1 = weights // 10 # result2 = weights % 10 # print("%d两是%d斤%d两" % (weights, result1, result2)) """ 录入距离、时间、初速度 计算加速度 x = v0 + 1/2 * a * (t^2) """ # distance = float(input('输入距离:')) # speed0 = float(input('输入初速度:')) # time = float(input('输入时间:')) # # Acceleration = (distance - speed0) * 2 / (time ** 2) # print('加速度为%.2f' % Acceleration) """ 录入四位整数 计算每位数相加的和 """ # number = int(input('输入一个四位整数:')) # number1 = number % 10 # number2 = number % 100 // 10 # number3 = number // 100 % 10 # number4 = number // 1000 # sum = number1 + number2 + number3 + number4 # # print('%d+%d+%d+%d=%d' % (number4, number3, number2, number1, sum)) # ========================================================================== # number_str = input('输入一个四位整数:') # result = 0 # for i in number_str: # result += int(i) # print(result) # sex = input('输入性别:') # if sex == "男": # print("你好,先生!") # elif sex == "女": # print("你好,女士!") # else: # print("输入有误!")
dbb60661e2076ec21c88220cab1ced9d6547a260
KarlLichterVonRandoll/learning_python
/month02/code/Concur_Program/day02/chat_server.py
1,988
3.671875
4
""" 服务端 接受请求,分类: 进入:维护一个用户信息 离开: 聊天:将信息发送给其他用户 """ from socket import * import os, sys # 定义全局变量 ADDR = ("0.0.0.0", 9527) # 服务器地址 user = {} # 存储用户 {name:address} # 处理进入聊天室请求 def do_login(s, name, addr): if name in user or "管理员" in name: s.sendto("用户已存在".encode(), addr) return s.sendto(b"OK", addr) # 通知其他人 msg = "欢迎'%s'进入聊天室" % name for i in user: s.sendto(msg.encode(), user[i]) # 将新用户插入字典 user[name] = addr # 处理聊天请求 def do_chat(s, name, msg): msg = name + ":" + msg for i in user: s.sendto(msg.encode(), user[i]) # 处理退出请求 def do_exit(s, name): msg = "%s 退出了聊天室" % name for i in user: if i != name: s.sendto(msg.encode(), user[i]) else: s.sendto(b"EXIT", user[i]) del user[name] # 请求处理函数 def do_request(s): while True: data, addr = s.recvfrom(1024) tmp = data.decode().split(" ") # 根据不同请求类型具体执行不同事情 # L 进入 C 聊天 D 退出 if tmp[0] == "L": do_login(s, tmp[1], addr) # 执行具体工作 elif tmp[0] == "C": text = " ".join(tmp[2:]) do_chat(s, tmp[1], text) elif tmp[0] == "Q": do_exit(s, tmp[1]) # 搭建网络 def main(): s = socket(AF_INET, SOCK_DGRAM) s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) s.bind(ADDR) pid = os.fork() if pid < 0: sys.exit() elif pid == 0: while True: text = input("管理员消息") msg = "C 管理员 "+text s.sendto(msg.encode(), ADDR) else: do_request(s) if __name__ == "__main__": main()
8869c3dd9d8e376bb073a100fa326e65ba43cbeb
KarlLichterVonRandoll/learning_python
/month01/code/day06/exercise02.py
3,029
4.0625
4
""" 输入日期(年月),输出一年中的第几天,借助元组 例如: 3月5日 1月天数 + 2月天数 + 5 """ # month_tuple = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) # month = int(input("输入月份(1-12):")) # day = int(input("输入日期(1-31):")) # total_days = 0 # # 方法一 # for item in range(month - 1): # total_days += month_tuple[item] # print("这是一年中的第%d天" % (total_days + day)) # # 方法二 # print("这是一年中的第%d天" % (sum(month_tuple[:month-1]) + day)) # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ 循环录入商品信息(名称,单价) 如果名称录入空字符,则停止录入 将信息逐行打印 """ # dict01 = {} # while True: # name = input("输入商品名称:") # if name == "": # break # price = input("输入商品单价:") # dict01[name] = price # # for item in dict01: # print("%s 单价为 %s $" % (item, dict01[item]) # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ 录入学生信息 (姓名,年龄,成绩,性别) 输入空字符,则停止输入,打印信息 """ # dict_student_info = {} # while True: # name = input("输入学生姓名:") # if name == "": # break # # dict_student_info[name] = {} # age = input("输入学生年龄:") # score = input("输入学生成绩:") # sex = input("输入学生性别:") # dict_student_info[name] = {"age": age, "score": score, "sex": sex} # # for item in dict_student_info.items(): # print(item) # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ 列表内嵌字典 """ # list_student_info = [] # while True: # name = input("输入学生姓名:") # if name == "": # break # age = input("输入学生年龄:") # score = input("输入学生成绩:") # sex = input("输入学生性别:") # dict_student_info = {"name": name, "age": age, "score": score, "sex": sex} # list_student_info.append(dict_student_info) # # for item in list_student_info: # print(item) # # print(list_student_info) # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ 录入多个人的多个喜好 """ # people_dict = {} # while True: # name = input("输入姓名:") # if name == "": # break # list_hobby = [] # while True: # hobby = input("输入你的第%d个喜好:" % (len(list_hobby) + 1)) # if hobby == "": # break # list_hobby.append(hobby) # people_dict[name] = list_hobby # # for k, v in people_dict.items(): # print("%s的喜好有%s" % (k, v)) list01 = [] for i in range(100, 1000): number01 = i // 100 number02 = i % 100 // 10 number03 = i % 10 if number01**3 + number02**3 + number03**3 == i: list01.append(i) print(list01) print(sum(list01))
6d30f737753174c9454d15af8a322dea21865a9b
KarlLichterVonRandoll/learning_python
/month01/code/day11/exercise02.py
520
4.0625
4
""" 封装设计思想 需求:老张开车去东北 """ class Person: def __init__(self, name): self.name = name @property def name(self): return self.__name @name.setter def name(self, value): self.__name = value def goto(self, str_pos, type): print(self.__name, "去", str_pos) type.run(str_pos) class Car: def run(self, str_pos): print("行驶到:", str_pos) lz = Person("老张") car = Car() lz.goto("东北", car)
61e9e28a216ed8774fe5cd8096151d798604d348
KarlLichterVonRandoll/learning_python
/month01/code/day08/exercise03.py
2,194
4.03125
4
commodity_info = { 101: {"name": "屠龙刀", "price": 10000}, 102: {"name": "倚天剑", "price": 10000}, 103: {"name": "九阴白骨爪", "price": 8000}, 104: {"name": "九阳神功", "price": 9000}, 105: {"name": "降龙十八掌", "price": 8000}, 106: {"name": "乾坤大挪移", "price": 10000} } # 选择商品 def choose_commodity(): display_commodity() create_order() print("添加到购物车。") # 生成订单 def create_order(): while True: cid = int(input("请输入商品编号:")) if cid in commodity_info: break else: print("该商品不存在") count = int(input("请输入购买数量:")) shopping_cart.append({"cid": cid, "count": count}) # 打印商品信息 def display_commodity(): for key, value in commodity_info.items(): print("编号:%d,名称:%s,单价:%d。" % (key, value["name"], value["price"])) # 结算 def payment_commodity(): amount_of_money = 0 amount_of_money = generate_bill(amount_of_money) pay_bill(amount_of_money) # 支付账单 def pay_bill(amount_of_money): while True: money_input = float(input("总价%d元,请输入金额:" % amount_of_money)) if money_input >= amount_of_money: print("购买成功,找回:%d元。" % (money_input - amount_of_money)) shopping_cart.clear() break else: print("金额不足.") # 生成账单,计算总价 def generate_bill(amount_of_money): for item in shopping_cart: commodity = commodity_info[item["cid"]] print("商品:%s,单价:%d,数量:%d." % (commodity["name"], commodity["price"], item["count"])) amount_of_money += commodity["price"] * item["count"] return amount_of_money # 购物 def shopping(): while True: item = input("1键购买,2键结算,3键退出。") if item == "1": choose_commodity() elif item == "2": payment_commodity() elif item == "3": print("谢谢惠顾") break if __name__ == "__main__": shopping_cart = [] shopping()
715ca3cbf7fddbda0e8ba5ffa3e97b853feb5890
KarlLichterVonRandoll/learning_python
/month05/datascience/day06/02-vec.py
741
4.03125
4
""" 矢量化 """ import numpy as np import math as m def foo(x, y): return m.sqrt(x ** 2 + y ** 2) a = 3 b = 4 print(foo(a, b)) # 把foo函数矢量化,使之可以处理矢量数据 foovec = np.vectorize(foo) a = np.array([3, 4, 5, 6]) b = np.array([4, 5, 6, 7]) print(foovec(a, b)) # 使用frompyfunc可以完成与vectorize一样的功能 func = np.frompyfunc(foo, 2, 1) print(func(a, b)) c = np.array([70, 80, 60, 30, 40]) # 针对源数组中的每一个元素,检测其是否符合条件序列中的每一个条件, # 符合哪个条件就用取值系列中与之对应的值, # 表示该元素,放到目标 数组中返回。 d = np.piecewise( c, [c < 60, c == 60, c > 60], [-1, 0, 1]) print(d)
7b8280ba67d8b79daf606d50352bb37f29c5bbce
KarlLichterVonRandoll/learning_python
/fluent_python/1.data_model/pokercard.py
1,065
4.03125
4
import collections from collections import Iterable, Iterator # collections.namedtuple会产生一个继承自tuple的子类,与tuple不同的是,它可以通过名称访问元素 # 以下创建了一个名为"Card"的类,该类有两个属性"rank"和"suit" Card = collections.namedtuple('Card', ['rank', 'suit']) class PokerCard: ranks = [str(n) for n in range(2, 11)] + list('JQKA') suits = 'spades diamonds clubs hearts'.split() def __init__(self): self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks] def __len__(self): return len(self._cards) def __getitem__(self, position): return self._cards[position] poker = PokerCard() print(poker) print(len(poker)) # 调用__len__方法 print(poker[0]) # 调用__getitem__方法 # 仅仅是实现了__getitem__方法, pockercard 就可以使用for遍历,但不属于可迭代对象或者迭代器 print(isinstance(poker, Iterator)) print(isinstance(poker, Iterable)) for card in poker[:5]: print(card)
a1f7cd46adb9915bacf7893eb370da1a5c0961fe
KarlLichterVonRandoll/learning_python
/month05/datascience/day01/numpy05.py
1,183
3.703125
4
""" 多维数组的组合与拆分 """ import numpy as np ary01 = np.arange(1, 7).reshape(2, 3) ary02 = np.arange(10, 16).reshape(2, 3) # 垂直方向完成组合操作,生成新数组 ary03 = np.vstack((ary01, ary02)) print(ary03, ary03.shape) # 垂直方向完成拆分操作,生成两个数组 a, b, c, d = np.vsplit(ary03, 4) print(a, b, c, d) # 水平方向完成组合操作,生成新数组 ary04 = np.hstack((ary01, ary02)) print(ary04, ary04.shape) # 水平方向完成拆分操作,生成两个数组 e, f = np.hsplit(ary04, 2) print(e, '\n', f) a = np.arange(1, 7).reshape(2, 3) b = np.arange(7, 13).reshape(2, 3) # 深度方向(3维)完成组合操作,生成新数组 i = np.dstack((a, b)) print(i.shape) # 深度方向(3维)完成拆分操作,生成两个数组 k, l = np.dsplit(i, 2) print("==========") print(k) print(l) a = np.array([1,2,3,4]).reshape(2,2) print(a) print(np.split(a, 2, axis=1)) a = np.arange(1,9) #[1, 2, 3, 4, 5, 6, 7, 8] b = np.arange(9,17) #[9,10,11,12,13,14,15,16] #把两个数组摞在一起成两行 c = np.row_stack((a, b)) print(c) #把两个数组组合在一起成两列 d = np.column_stack((a, b)) print(d)
04be3ee93ec8a3ca44e2c2e67cddbc868e9e16d0
KarlLichterVonRandoll/learning_python
/month02/code/Concur_Program/day02/process02.py
611
3.609375
4
""" multiprocessing 创建多个进程 """ from multiprocessing import Process import time import os def func01(): time.sleep(2) print("chi fan......") print(os.getppid(), '---', os.getpid()) def func02(): time.sleep(3) print("shui jiao......") print(os.getppid(), '---', os.getpid()) def func03(): time.sleep(4) print("da dou dou......") print(os.getppid(), '---', os.getpid()) funcs = [func01, func02, func03] processes = [] for func in funcs: p = Process(target=func) processes.append(p) p.start() for process in processes: process.join()
bbcf509fc54e792f44a9ff9dc57aea493cd7d89c
KarlLichterVonRandoll/learning_python
/month01/code/day14/exercise02.py
1,511
4.25
4
""" 创建Enemy类对象,将对象打印在控制台 克隆Enemy类对像 """ # class Enemy: # # def __init__(self, name, hp, atk, defense): # self.name = name # self.hp = hp # self.atk = atk # self.defense = defense # # def __str__(self): # return "%s 血量%d 攻击力%d 防御力%d" % (self.name, self.hp, self.atk, self.defense) # # def __repr__(self): # return 'Enemy("%s",%d,%d,%d)' % (self.name, self.hp, self.atk, self.defense) # # # enemy = Enemy("灭霸", 100, 80, 60) # print(enemy) # # str01 = repr(enemy) # print(str01) # enemy02 = eval(str01) # enemy02.name = "洛基" # print(enemy02) """ 运算符重载 """ class Vector1: def __init__(self, x): self.x = x def __str__(self): return "一唯向量的分量是 %d" % self.x def __add__(self, other): return Vector1(self.x + other) def __iadd__(self, other): self.x += other return self def __sub__(self, other): return Vector1(self.x - other) def __mul__(self, other): return Vector1(self.x * other) def __radd__(self, other): return Vector1(self.x + other) def __rsub__(self, other): return Vector1(self.x - other) def __rmul__(self, other): return Vector1(self.x * other) vec01 = Vector1(2) print(vec01) print(vec01 + 3) print(vec01 - 4) print(vec01 * 5) print() print(3 + vec01) print(4 - vec01) print(5 * vec01) vec01 += 1 print(vec01)
c01ac25e7c517caaf6fc23b5edab41131cba70bb
sydney0zq/opencourses
/blog-python/oop/01_student.py
626
3.90625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2017-06-18 Sydney <[email protected]> """ """ class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): print ("%s: %s" % (self.name, self.score)) def get_level(self): if self.score >= 90: return "A" elif self.score >= 60: return "B" else: return "C" bart = Student("Bart Ass", 70) lisa = Student("Ali Adam", 55) bart.print_score() lisa.print_score() print (bart.get_level()) print (lisa.get_level())
f284bdf3b3929131be1fe943b3bd5761119f4c2e
sydney0zq/opencourses
/byr-mooc-spider/week4-scrapy/yield.py
1,088
4.53125
5
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it'll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return. The generator is considered empty once the function runs but does not hit yield anymore. It can be because the loop had come to an end, or because you do not satisfy an "if/else" anymore. """ def gen(n): print("outside") for i in range(8): print ("inside") yield i ** 2 for i in gen(5): print (i, " ") print ("*" * 50) def gen2(n): print("outside") for i in range(n): print ("inside") yield i ** 2 n = 3 for i in gen2(n): #n = 10 this statement does NO effect print (i) print ("*" * 50) def square(n): print ("inside") ls = [i**2 for i in range(n)] return ls for i in square(5): print(i)
5e4d5d10de44c2c756ce850375298baf03ec41c1
ullasgithub/BST
/delete_node.py
1,187
3.875
4
def minValueNode(node): current = node # loop down to find the leftmost leaf while (current.left is not None): current = current.left return current def delete_node(root, data): # Base Case if root is None: return root # If the key to be deleted is smaller than the root's if data < root.data: root.left = delete_node(root.left, data) # If the kye to be delete is greater than the root's key elif (data > root.data): root.right = delete_node(root.right, data) # If key is same as root's key, then this is the node # to be deleted else: # Node with only one child or no child if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp # Node with two children: Get the inorder successor temp = minValueNode(root.right) # Copy the inorder successor's content to this node root.key = temp.key # Delete the inorder successor root.right = delete_node(root.right, temp.key) return root
1773ec755bb338e87fb6a7d2db910184607fac13
jobgunwiz/winter_raspi2020_codes
/fun.py
203
3.6875
4
def add(a,b,c): res = a+b+c return res def sub(a,b,c): res = a-b-c return res def main(): print("funct start") print(add(1,2,3)) value = sub(3,0,1) print(value) main()
cdc60a5d0ae63254a3186e80e83dc75a149f5f1a
Sinder20/Ejercicios2Python
/EjerciciosImpares.py
3,707
3.984375
4
class Impares(): def ejercicio1(self): print("* * * Programa que lee un número y muestra su tabla de multiplicar * * *") num= int(input("Ingrese el número que desea mostrar su tabla de multiplicar: ")) for i in range(0,11): resultado=i*num print(("%d X %d = %d")%(num, i, resultado)) print(" ") def ejercicio3(self): n=0 print("* * * Programa que lee una secuencia de números y se detiene hasta ingresar un Número NEGATIVO * * *") num= int(input("Ingrese un número: ")) while num >=0: n+=num num= int(input("Ingrese un número: ")) print("La suma de los números positivos es:", n, "\n") def ejercicio5(self): print("* * * División por medio de Restas * * *") dividendo=int(input("Ingrese el dividendo: ")) divisor= int(input("Ingrese el divisor: ")) if divisor==0: print("ERROR EL DIVISOR NO TIENE QUE SER 'CERO'") else: cociente=0 resto=dividendo while resto>=divisor: resto-=divisor cociente+=1 print("El cociente es:", cociente) print("El residuo es:", resto) print(" ") def ejercicio7(self): lista = [] print("* * * Programa que lee una secuencia de números y muestra el Mayor * * *") cantidad = int(input("¿Cuántos números deseas ingresar? ")) mayor = 0 i = 1 while (cantidad > 0): numero = int(input("Número #" + str(i) + ": ")) lista.append(numero) i = i + 1 cantidad = cantidad - 1 mayor = max(lista) print("\n Los números que ingresó son: ", lista) print("\n El número mayor es: ", mayor, "\n") def ejercicio9(self): suma = 0 print("* * * Programa que suma los números divisibles entre 5, comenzando desde el 2 y va de 3 en 3 * * *") limit = int(input("Ingrese el rango hasta dónde quiere llegar: ")) for x in range(2, limit, 3): print(x, end=", ") if x % 5 == 0: suma += x print("\nLa suma de los números generados que son divisibles entre 5 es:", suma, "\n") def ejercicio11(self): print("* * * Sucesión de Fibonacci * * *") limit= int(input("Ingrese la cantidad de términos que desea imprimir: ")) num1=1 num2=0 num3=1 for x in range(0, limit): num3+=1 print(num2, end=" ") sum= num2 + num1 num2=num1 num1=sum print(" ") def ejercicio13(self): sum=0 stop='' print("* * * Programa que lee una secuencia de números y luego muestra la suma de los Números Pares * * *") while stop!='N': num = int(input("Ingrese un número entero: ")) stop= str(input("Desea Continar? N=No / Presione otra letra para continuar: ")) if num % 2 == 0: sum += num print(sum) elif num % 2 !=0: continue print("La suma de los números pares es:", sum, "\n") def ejercicio15(self): from math import factorial print("* * * Programa para calcular el factorial de un número * * *") num= int(input("Ingrese el número: ")) print("El factorial de", num, "es", factorial(num), "\n") Impares=Impares() #Impares.ejercicio1() #Impares.ejercicio3() #Impares.ejercicio5() #Impares.ejercicio7() #Impares.ejercicio9() #Impares.ejercicio11() #Impares.ejercicio13() #Impares.ejercicio15()
853a482a0b44d1dd6883966eaabe2af9fa6103f7
Soundphy/diapason
/diapason/core.py
2,364
3.546875
4
""" Core diapason code. """ from io import BytesIO from numpy import linspace, sin, pi, int16 from scipy.io import wavfile def note_frequency(note, sharp=0, flat=0, octave=4, scientific=False): """ Returns the frequency (in hertzs) associated to a given note. All the frequencies are based on the standard concert pitch or standard piano key frequencies, meaning that A4 (using scientific picth notation) is at 440 hertzs. Parameters ---------- note : string Note to calculate the associated frequency from. Valid notes are characters from A to G. octave : int Octave position. Middle C and A440 being in the 4th octave. sharp : int Return a frequency higher in pitch by `sharp` semitones. flat : int Return a frequency lower in pitch by `flat` semitones. scientific : bool Use scientific pitch instead: C4 is set to 256 Hz. Returns ------- float The frequency (in hertzs) associated to the given note. """ if note not in list('ABCDEFG'): raise ValueError('Invalid note {}'.format(note)) if sharp and flat: raise ValueError('Cannot set both sharp and flat parameters!') position = dict(C=0, D=2, E=4, F=5, G=7, A=9, B=11) if scientific: # C4 at 256 Hz base_note = 'C' base_octave = 4 base_frequency = 256. else: # A4 at 440 Hz base_note = 'A' base_octave = 4 base_frequency = 440. note_position = position[note] - position[base_note] + \ (octave - base_octave) * 12 note_position += sharp note_position -= flat frequency = 2 ** (note_position / 12.) * base_frequency return frequency def generate_wav(frequency, duration, rate=44100): """ Generate a WAV file reproducing a sound at a given frequency. Parameters ---------- frequency : float Frequency, in hertzs, of the sound. duration : float Duration of the sound. rate : int Sample rate. Returns ------- BytesIO The in-memory WAV file. """ amplitude = 10000 t = linspace(0, duration, duration * rate) data = sin(2 * pi * frequency * t) * amplitude data = data.astype(int16) note_io = BytesIO() wavfile.write(note_io, rate, data) return note_io
3f1884e738e6582e62ff078fd863cb6bbda9dc27
cvickers23/Noreasters-Tic-Tac-Toe
/main.py
9,390
4
4
#Tic Tac Toe game #COM 306 Software Engineering #Noreasters: Craig Haber, Chelsea Vickers, Jacob Nozaki, Tessa Carvalho #12/10/2020 #A command line interface tool for playing tic tac toe import random import logging import logging.handlers import os #Create a logging object log = logging.getLogger("script-logger") #Config log level to be set to info log.setLevel(logging.INFO) handler = logging.handlers.WatchedFileHandler(os.environ.get("LOGFILE", "game_log.log")) formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s","%Y:%m:%d:%H:%M:%S") handler.setFormatter(formatter) log.addHandler(handler) #Function to print the rules of Tic Tac Toe def print_rules(): print("""\nRules of the game: 1. The game is played on a 3x3 square grid. 2. One player's token is X and the other player's token is O. 3. Players take turns putting their token in empty squares in the grid. 4. The first player to get 3 of their tokens in a row (up, down, across, or diagonally) is the winner. 5. When all 9 squares of the grid are full, the game is over. If no player has 3 marks in a row, the game ends in a tie.""") example_board() #Function to print a game board with indices def example_board(): print("""\nExample Game Board (with Indices): 1 | 2 | 3 ----------- 4 | 5 | 6 ----------- 7 | 8 | 9 \n""") #Function to allow players to input their names through the command line #Returns: # The two player name strings p1 and p2 def enter_names(): #Accept input of two separate player names p1 = input("Enter name of player 1: ") p2 = input("Enter name of player 2: ") while(True): if (p1 == ""): p1 = input("Players cannot have empty names. Please enter name of player 1: ") elif (p2 == ""): p2 = input("Players cannot have empty names. Please enter name of player 2: ") elif (p1 == p2): p2 = input("Players cannot have the same name. Please enter name of player 2: ") else: break return(p1, p2) #Function to play a single game of tic tac toe def play_game(): #Load global variables global first_turn_player global second_turn_player #Game set up p1, p2 = enter_names() first_turn_player, second_turn_player = choose_turn_order(p1, p2) choose_token(input_token()) cur_player = first_turn_player display_board() #Game play while game_over == False: print() play_turn(cur_player) if cur_player == first_turn_player: cur_player = second_turn_player else: cur_player = first_turn_player ask_play_again() #Function to determine which player goes first #Returns: # The two player name strings in the order of their randomly chosen turn order (player going first, player going second) def choose_turn_order(p1, p2): players = [p1, p2] #Randomly choose player to go first (50/50 odds) first_turn = random.choice(players) if (first_turn == p1): print(p1, " has been randomly chosen to go first") return p1, p2 else: print(p2, " has been randomly chosen to go first") return p2, p1 #Function to let the first turn player choose their game token, and assigns other token to other player #Args: # token: String of token that user inputted def choose_token(token): #Load global variables global first_turn_player_token global second_turn_player_token while(True): if (token == "X" or token == "x"): #First turn player entered X/x first_turn_player_token, second_turn_player_token = "X", "O" #First turn player gets X, second gets O break #Tokens assigned, end loop elif (token == "O" or token == "o"): # First turn player entered O/o first_turn_player_token, second_turn_player_token = "O", "X" #First turn player gets O, second gets X break #Tokens assigned, end loop else: #First turn player entered invalid input print("Please enter either X/x or O/o.") token = input_token() # Display assigned tokens print(first_turn_player + " is " + first_turn_player_token + ", " + second_turn_player + " is " + second_turn_player_token + ".\n") #Function to get user input of token #Returns: # The user's choice of token def input_token(): return input(first_turn_player + ", enter your choice of token (X/x or O/o): ") #Function to play a single turn in a game of tic tac toe #Args: # turn_player: A string that contains the name of the player whose has the current turn def play_turn(turn_player): log.info(f'{turn_player} is the turn player') get_next_move(turn_player) display_board() determine_game_over() #Function to get the next move from the player whose turn it is and add it to the board #Args: # turn_player: A string that contains the name of the player that has the current turn def get_next_move(turn_player): #Load global variables global board #Loops through to make sure there is proper input while(True): move = input(turn_player + " enter an index 1-9 that corresponds to an open spot: ") #Checks if move is a valid input if move not in {'1', '2', '3', '4', '5', '6', '7', '8', '9'}: print("That is an invalid input. Try again with a number 1-9.") #If empty, the spot will be filled with the proper player token elif board[int(move)-1] == " ": if turn_player == first_turn_player: board[int(move)-1] = first_turn_player_token log.info(first_turn_player + " placed an " + first_turn_player_token + " in spot " + move) else: board[int(move)-1] = second_turn_player_token log.info(second_turn_player + " placed an " + second_turn_player_token + " in spot " + move) break #Board spot is full else: print("That spot has already been filled! Try again.") #Function to display the current game board def display_board(): print(" " + board[0] + " | " + board[1] + " | " + board[2]) # Row 1 print("----------------") print(" " + board[3] + " | " + board[4] + " | " + board[5]) # Row 2 print("----------------") print(" " + board[6] + " | " + board[7] + " | " + board[8]) # Row 3 #Determine if the game has ended, showing the results and allowing user to restart the game if the game has ended def determine_game_over(): global game_over #Indices 0-2 are for first row, 3-5 are for second row, 6-8 are for third row win_state_indices = [ #Row win state indicies [0,1,2], [3,4,5], [6,7,8], #Column win state indices [0,3,6], [1,4,7], [2,5,8], #Diagonal win state indices [0,4,8], [2,4,6] ] for triple in win_state_indices: is_all_same_token = board[triple[0]] == board[triple[1]] == board[triple[2]] is_token_empty = board[triple[0]] == " " if is_all_same_token and (not is_token_empty): #Since a player has won, all tokens in the triple are the same, so any token in the triple is the winning token winner_token = board[triple[0]] #Determine/print the name of the winning player if first_turn_player_token == winner_token: print("CONGRATULATIONS " + first_turn_player + " YOU WIN!!!\n") log.info(f'Game has ended. {first_turn_player} won') elif second_turn_player_token == winner_token: print("CONGRATULATIONS " + second_turn_player + " YOU WIN!!!\n") log.info(f'Game has ended. {second_turn_player} won') game_over = True break #Check if there's a tie if not game_over: #Ensure that every space in the board has been filled if all([token != " " for token in board]): print("THE GAME HAS ENDED, IT IS A TIE.") log.info('Game has ended in a tie') game_over = True if not game_over: log.info('Game is still in progress') #Function to determine if the players want to play again def ask_play_again(): global board global game_over while True: #Determine if the players would like to play again play_again_choice = input("Would you like to play again (yes/no)?: ") if play_again_choice in ["YES", "Yes", "YeS", "YEs", "yES", "yEs", "yeS", "yes", "y", "Y"]: board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] game_over = False log.info('Players have chosen to play again.') example_board() play_game() break elif play_again_choice in ["No", "no", "NO", "nO", "n", "N"]: print("\nThanks for playing!") break else: print("\nThat was not a valid input, please try again.\n") def main(): #Initialize global variables global first_turn_player, first_turn_player_token, second_turn_player, second_turn_player_token, game_over, board first_turn_player = "" first_turn_player_token = "" second_turn_player = "" second_turn_player_token = "" game_over = False board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] print_rules() play_game() if __name__ == "__main__": main()
941df0f3c376d06c87274a8648b0cf72ff98464e
turk0v/miptctf
/python1/tm.py
365
3.515625
4
password = 'e3f7d1980f611d2662d116f0891d7f3e' print(password.lower()) if password.lower() != password: print('loser1') elif len(password) != 32: print('loser2') else: if password != password[::-1]: print('loser3') try: if int(password[:16], 16) != 16426828616880430374: print('loser4') except: print('loser5') print('yooo')
88806f1c3ee74fe801b26a11b0f66a3c7d6c881d
Kajabukama/bootcamp-01
/shape.py
1,518
4.125
4
# super class Shape which in herits an object # the class is not implemented class Shape(object): def paint(self, canvas): pass # class canvas which in herits an object # the class is not implemented class Canvas(object): def __init__(self, width, height): self.width = width self.height = height self.data = [[' '] * width for i in range(height)] # setter method which sets row and column def setpixel(self, row, col): self.data[row][col] = '*' # getter method that will get the values of row and column def getpixel(self, row, col): return self.data[row][col] def display(self): print "\n".join(["".join(row) for row in self.data]) # the subclass Rectangle which inherits from the Shape Superclass # inheritance concept class Rectangle(Shape): def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h # a method to draw a horizontal line def hline(self, x, y, w): self.x = x self.y = y self.w = w # another method that will draw a vertical line def vline(self, x, y, h): self.x = x self.y = y self.h = h # this method calls the other three methods # and draws the respective shapes on a camnvas def paint(self, canvas): hline(self.x, self.y, self.w) hline(self.x, self.y + self.h, self.w) vline(self.x, self.y, self.h) vline(self.x + self.w, self.y, self.h)
c9a6708eaf8e4deb40eebee4cfcfb2db934fab33
jwu424/Leetcode
/ShortestUnsortedContinuousSubarray.py
1,442
3.8125
4
# Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. # You need to find the shortest such subarray and output its length. # 1. sort the nums and compare the sorted nums with nums from beginning and end. # Time complexity: o(NlogN) # 2. Start from left, try to find the maximum. If nums[i] < max, then left part of i need to be sorted. # Start from right, try to find the minimum. If nums[i] > min, then the right part of i need to be sorted. # Time complexity: O(N) class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int: sorted_num = sorted(nums) l1, l2 = 0, len(nums)-1 while l1 <= l2 and nums[l1] == sorted_num[l1]: l1 += 1 while l1 <= l2 and nums[l2] == sorted_num[l2]: l2 -= 1 return l2 - l1 + 1 def findUnsortedSubarray2(self, nums: List[int]) -> int: l_max = nums[0] l = 0 for i in range(len(nums)): if nums[i] > l_max: l_max = nums[i] elif nums[i] < l_max: l = i r_min = nums[-1] r = 0 for i in range(len(nums)-1, -1, -1): if nums[i] < r_min: r_min = nums[i] elif nums[i] > r_min: r = i if r >= l: return 0 return l - r + 1
593086984f741a8ebd50163f4925b2fad3debdd9
jwu424/Leetcode
/GameofLife.py
4,885
4
4
# According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." # Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): # Any live cell with fewer than two live neighbors dies, as if caused by under-population. # Any live cell with two or three live neighbors lives on to the next generation. # Any live cell with more than three live neighbors dies, as if by over-population.. # Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. # Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. # 1. Not in place. fist calculate the neighboor of each elem in board. And then apply the rule. # Time complexity: O(N^2) # 2. In place. The idea is similar. # Let's assume 2 means in this stage it is dead, but in the next stage, it will alive. # Assme 3 means in this stage it is alive, but in the next stage it will dead. # When will calculating count, we can use '%2'. # Time complexity: O(N^2) # 3. Infinite dimensions. # https://leetcode.com/problems/game-of-life/discuss/73217/Infinite-board-solution class Solution1: def gameOfLife(self, board): """ Do not return anything, modify board in-place instead. """ n, m = len(board), len(board[0]) res = [] for i in range(n): res.append([]) for j in range(m): temp = self.helper(board, i, j, n, m) if board[i][j] == 1: if temp < 2: res[i].append(0) elif temp == 2 or temp == 3: res[i].append(1) else: res[i].append(0) else: if temp == 3: res[i].append(1) else: res[i].append(0) board[:] = res def helper(self, board, i, j, n, m): count = 0 if i > 0 and j > 0: count += board[i-1][j-1] if i > 0: count += board[i-1][j] if i > 0 and j < m-1: count += board[i-1][j+1] if j > 0: count += board[i][j-1] if j < m-1: count += board[i][j+1] if i < n-1 and j > 0: count += board[i+1][j-1] if i < n-1: count += board[i+1][j] if i < n-1 and j < m-1: count += board[i+1][j+1] return count class Solution2(object): def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: None Do not return anything, modify board in-place instead. """ n, m = len(board), len(board[0]) for i in range(n): for j in range(m): temp = self.helper(board, i, j, n, m) if board[i][j] == 0 or board[i][j] == 2: if temp == 3: board[i][j] = 2 else: if temp < 2 or temp > 3: board[i][j] = 3 for i in range(n): for j in range(m): if board[i][j] == 2: board[i][j] = 1 if board[i][j] == 3: board[i][j] = 0 def helper(self, board, i, j, n, m): count = 0 if i > 0 and j > 0: count += board[i-1][j-1]%2 if i > 0: count += board[i-1][j]%2 if i > 0 and j < m-1: count += board[i-1][j+1]%2 if j > 0: count += board[i][j-1]%2 if j < m-1: count += board[i][j+1]%2 if i < n-1 and j > 0: count += board[i+1][j-1]%2 if i < n-1: count += board[i+1][j]%2 if i < n-1 and j < m-1: count += board[i+1][j+1]%2 return count class Solution3(object): def gameOfLife(self, board): live = {(i, j) for i, row in enumerate(board) for j, live in enumerate(row) if live} live = self.gameOfLifeInfinite(live) for i, row in enumerate(board): for j in range(len(row)): row[j] = int((i, j) in live) def gameOfLifeInfinite(self, live): ctr = collections.Counter((I, J) for i, j in live for I in range(i-1, i+2) for J in range(j-1, j+2) if I != i or J != j) return {ij for ij in ctr if ctr[ij] == 3 or ctr[ij] == 2 and ij in live}
89fcd5001ca1ea29530b5253e93440f743316083
jwu424/Leetcode
/ContainsDuplicate.py
594
3.953125
4
# Given an array of integers, find if the array contains any duplicates. # First, we use hash table. That is, using dictionary to store value. # Time complexity: O(n) # Second, Use set to delete duplicate value. # Time complexity: O(n) class Solution: def containsDuplicate1(self, nums: List[int]) -> bool: dictt = {} for elem in nums: if elem not in dictt: dictt[elem] = 1 else: return True return False def containsDuplicate2(self, nums: List[int]) -> bool: return len(nums) != len(set(nums))
157b4ad717a84f91e60fb5dc108bcab8b2a21a12
jwu424/Leetcode
/RotateArray.py
1,275
4.125
4
# Given an array, rotate the array to the right by k steps, where k is non-negative. # 1. Make sure k < len(nums). We can use slice but need extra space. # Time complexity: O(n). Space: O(n) # 2. Each time pop the last one and inset it into the beginning of the list. # Time complexity: O(n^2) # 3. Reverse the list three times. # Time complexity: O(n) class Solution: def rotate1(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ k %= len(nums) nums[:] = nums[-k:] + nums[:-k] def rotate2(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ k %= len(nums) for _ in range(k): nums.insert(0, nums.pop()) def rotate3(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ k %= len(nums) self.reverse(nums, 0, len(nums)-1) self.reverse(nums, 0, k-1) self.reverse(nums, k, len(nums)-1) def reverse(self, nums, left, right): while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1
b7e8607db52e485c9c5235824d1a56dfc03230a3
Yanmo/language.processing
/py/q008.py
856
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import codecs import io # for python 2.x # sys.stdout = codecs.getwriter('utf_8')(sys.stdout) # for python 3.x sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') #与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ. # - 英小文字ならば(219 - 文字コード)の文字に置換 # - その他の文字はそのまま出力 # この関数を用い,英語のメッセージを暗号化・復号化せよ. def encrypt(sequences): encrypted = list() for seq in sequences: if seq.islower(): encrypted.append(chr(219-ord(seq))) else: encrypted.append(seq) return encrypted text = list(u"AaBbCc") print(text) text2 = encrypt(list(text)) print(text2) print(encrypt(list(text2)))
b1279922b6295452d236fed7aabd572e79b662fa
Yanmo/language.processing
/py/q000.py
335
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #文字列"stressed"の文字を逆に(末尾から先頭に向かって)並べた文字列を得よ. import sys import codecs str = "stressed" print(str[::-1]) #why? str2 =list(sum(zip(str),())) #string->tuple->list str2.reverse() #reverse print("".join(str2)) #join list->string
7ff62f8cb07d0e287e97ee0daa0ebcdc88366692
odysseus/gopy
/goban.py
14,923
4.09375
4
from stone import * from group import * class BoardError(Exception): """Empty class to simply rename the basic Exception""" pass class Goban(object): """ The code to represent the Goban and the stones placed on it. Along with the functionality associated with "whole-board" issues. Eg: Anything that requires knowledge of the board size or the stones on it will likely be handled in this class """ def __init__(self, size): """ Initializes a board object :param size: The size of the board, must be odd and less than 35 :return: Returns the initialized board """ if size % 2 == 0: raise BoardError("Board sizes must be odd numbers") elif size > 35: raise BoardError("Board sizes greater than 35 are not supported") else: vals = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" self.base_values = list(vals[:size]) self.size = size self.board = [None for _ in range(size * size)] self.groups = [] self.history = [] self.undo = None def get(self, index): """ Gets the item on the board at the given index :param index: The integer index of the position, to convert to an integer index from a positional tuple, use the index_from_position_tuple method :return: Returns the item at the index, this will either be None, or a Stone object """ return self.board[index] def __str__(self): """ :return: The board represented as a string: empty vertices are denoted with a dot white stones with *, and black stones with o. Coordinate numbers are marked along all sides """ s = "\n " for i in range(self.size): s += "{0} ".format(self.base_values[i]) for i in range(len(self.board)): if i % self.size == 0: s += "\n{0} ".format(self.base_values[i // self.size]) v = self.board[i] if v is None: s += ". " else: s += "{} ".format(v) if i % self.size == self.size - 1: s += "{0}".format(self.base_values[i // self.size]) s += "\n " for i in range(self.size): s += "{0} ".format(self.base_values[i]) s += "\n" return s def position_tuple_for_index(self, index): """ Converts an integer index into the corresponding position tuple :param index: A single integer within the range of the self.board list :return: A tuple of two strings with the X and Y coordinates of the position, respectively """ x = self.base_values[index % self.size] y = self.base_values[index // self.size] return x, y def index_from_position_tuple(self, position): """ Translates a positional tuple into an integer index. :param position: Either a tuple of strings, or a string containing the X and Y coordinates of the move, in that order :return: Returns the index for self.board that corresponds with the given position """ x = self.base_values.index(position[0]) y = self.base_values.index(position[1]) return y * self.size + x def valid_move(self, stone_color, index): """ Tests whether a given move is valid :param stone_color: A member of the StoneColor enum :param index: The integer index of the intended stone placement :return: True if the move is valid, false otherwise """ if self.get(index) is not None: print("Invalid move - Space it occupied") return False elif self.is_suicide(stone_color, index): print("Invalid move - Suicide") return False else: return True def is_suicide(self, stone_color, index): """ Boolean method that checks to see if making a move would result in the destruction of one's own pieces :param stone_color: The StoneColor color of the move to be made :param index: The integer index of the move to be made :return: Returns False if the move is *not* suicide, True otherwise """ cardinal_indices = self.cardinal_indices(index) # First check to see if there are any immediate liberties for ci in cardinal_indices: stone = self.get(ci) if stone is None: # There is an empty liberty so the move is not suicide return False # No liberties, so all spaces around the stone are filled # Two conditions will save us, an enemy group being captured, # or a single friendly group having more than 1 liberty. for ci in cardinal_indices: stone = self.get(ci) # Adjacent group is friendly if stone.color == stone_color: # And we are not filling its last liberty if self.group_liberties(ci) > 1: return False # Adjacent group is foe else: # But we *are* filling its last liberty if self.group_liberties(ci) == 1: return False # If none of the above is true, this is an invalid move return True def place_stone(self, stone_color, position): """ Places a stone of the given color at the position indicated by the positional tuple :param stone_color: A member of the StoneColor enum :param position: A tuple of the X and Y coordinates for the move :return: Returns True if the move was successful, False otherwise """ # Copy the current board positions as the 'undo' board self.undo = self.board[:] # Get the index from the position tuple index = self.index_from_position_tuple(position) # Check to see if the move is valid if self.valid_move(stone_color, index): # If so, initialize the stone stone = Stone(stone_color) # Add it to the board self.board[index] = stone # Create a new group for the stone # and link it to all contiguous groups self.link_stone(index) self.process_captures(index) # Ko Violations: # The only way to easily check for Ko violations is to process # the captures first then see if this board has been seen before bstring = self.board_string() for hstring in self.history: if bstring == hstring: print("Invalid Move - Ko Violation") self.board = self.undo return False self.history.append(self.board_string()) return True else: return False def link_stone(self, index): """ Creates a new group for a newly placed stone, and if needed links that to all contiguous groups of the same color :param index: Integer index of a newly added stone :return: Returns None """ stone = self.get(index) # Create a group of a single stone first, # this way every stone will have a group group = Group(self) group.add_member(index) stone.group = group # Add this new group to the list of all groups self.groups.append(group) # Now check for contiguous groups contiguous = self.contiguous_groups(index) # Add the single stone group to the list contiguous.append(group) # Link all of these together self.link_groups(contiguous) def contiguous_groups(self, index): """ Called on a group of a single stone, when the stone is added to the board,for the purpose of connecting the stones to the contiguous groups :param index: The index of the stone being tested (generally the one just placed on the board) :return: A list containing any groups that are the same color and contiguous to the stone """ # A container to hold contiguous groups contiguous = [] # The stone object itself stone = self.get(index) # The objects at the four vertices surrounding the stone cardinal_stones = [self.get(i) for i in self.cardinal_indices(index)] for s in cardinal_stones: # If it is a stone, and if the stone is the same color if s is not None and s.color == stone.color: # Add it to the list of contiguous groups contiguous.append(s.group) return contiguous def link_groups(self, groups): """ Links groups together, but does not directly test to see that they are contiguous The smaller groups are merged into the largest one :param groups: a list of groups to be linked :return: Returns None """ # Find the largest group max_group = groups[0] for group in groups: if group.size > max_group.size: max_group = group # Remove it from the list groups.remove(max_group) # Iterate over the smaller groups for group in groups: # Merge the sets containing the stones in that group max_group.add_members(group.members) for stone_index in group.members: self.get(stone_index).group = max_group # And remove the smaller group from the global list self.groups.remove(group) def process_captures(self, index): """ Takes the index of a newly placed stone and checks to see if any of the surrounding groups were captured by its placement :param index: The index of a newly placed stone :return: Returns None """ cardinal_indices = self.cardinal_indices(index) for i in cardinal_indices: if self.get(i) is not None: if self.group_captured(i): self.remove_group(i) def white_play_at(self, position): """Shorthand method for playing a move as white""" self.place_stone(StoneColor.white, position) def black_play_at(self, position): """Shorthand method for playing a move as black""" self.place_stone(StoneColor.black, position) def north_index(self, index): """ Gets the index of the stone directly to the "north" :param index: The integer index of the current stone :return: The integer index of the northern stone """ return index - self.size def east_index(self, index): """ Gets the index of the stone directly to the "east" :param index: The integer index of the current stone :return: The integer index of the eastern stone """ # Add a check for the edge of the board if index % self.size == self.size - 1: # Indices of < 0 are filtered out in cardinal_indices() return -1 else: return index + 1 def south_index(self, index): """ Gets the index of the stone directly to the "south" :param index: The integer index of the current stone :return: The integer index of the southern stone """ return index + self.size def west_index(self, index): """ Gets the index of the stone directly to the "west" :param index: The integer index of the current stone :return: The integer index of the western stone """ if index % self.size == 0: return -1 else: return index - 1 def cardinal_indices(self, index): """ Returns a list of indices that are contiguous to the index provided :param index: Integer index :return: A list of indices """ cardinals = [ self.north_index(index), self.east_index(index), self.south_index(index), self.west_index(index) ] return [i for i in cardinals if 0 < i < (self.size * self.size)] def highlight_group_at(self, position): """ If there is a stone at the given position tuple, highlights the group :param position: A position tuple or string indicating a single stone in the group :return: Returns None """ index = self.index_from_position_tuple(position) stone = self.get(index) group = stone.group if stone.color == StoneColor.black: highlight_color = StoneColor.highlight_black else: highlight_color = StoneColor.highlight_white for stone_index in group.members: self.get(stone_index).color = highlight_color def group_liberties(self, index): """ Counts the liberties for a group :param index: The index of a single stone in the group :return: An integer representing the number of unique liberties """ group = self.get(index).group liberties = set() for i in group.members: cardinal_indices = self.cardinal_indices(i) for ci in cardinal_indices: if self.get(ci) is None: liberties.add(ci) return len(liberties) def group_captured(self, index): """ Tests to see if a group is captured :param index: The index of a stone in the group :return: True if the group has been captured, False if it has not """ return self.group_liberties(index) == 0 def remove_group(self, index): """ Removes a captured group from the board :param index: The index of a single stone from the group to be removed :return: Returns None """ group = self.get(index).group for stone_index in group.members: self.board[stone_index] = None def board_string(self): """ Creates a compact string of the current board positions, useful in recognizing Ko and for keeping game records :return: A string summarizing the current board positions """ s = "" for i, v in enumerate(self.board): # if i % 81 == 0: # s += "\n" if v is None: s += "0" else: if v.color == StoneColor.black: s += "1" else: s += "2" return s
0554ad87dd36f234aec71c24549d6260928436fb
euphoria-paradox/practicar
/shape.py
688
3.953125
4
class Shape(): def __init__(self, shape): self.shape = shape def what_am_i(self): print("I am a " +self.shape) class Rectangle(Shape): def __init__(self, width, length): self.width = width self.length = length self.shape = "Rectangle" def calculate_perimeter(self): return 2*(self.width+self.length) class Square( Shape): def __init__(self , s1): self.s1= s1 self.shape = 'Square' def calculate_perimeter(self): return 4*self.s1 rect = Rectangle(5 , 15) print(rect.calculate_perimeter()) rect.what_am_i() squ = Square(4) print(squ.calculate_perimeter()) squ.what_am_i()
73532432fc6684fe15a36a7ef4624ec52c8af242
dreamnotover/Python-Shell-Script
/生成器和迭代器学习py脚本/迭代.py___jb_tmp___
688
4
4
# d = {'a': 1, 'b': 2, 'c': 3} # for key in d: # print(key) # from collections import Iterable # print(isinstance('abc', Iterable)) # str是否可迭代 # print(isinstance([1,2,3], Iterable)) # list是否可迭代 # print(isinstance(123, Iterable)) # 整数是否可迭代 # for i, value in enumerate(['A', 'B', 'C']): # print(i, value) # # for x, y in [(1, 1), (2, 4), (3, 9)]: # print(x, y) def findMinAndMax(L): if len(L)>0: max,min=L[0],L[0] for i in L : if i<min : min = i if i>max : max = i print(min,max) else: return (None, None) findMinAndMax([1,2,3,45,6])
b4b717df217eedd0591e36e92ebc68095fb9e269
icescrub/data-structures-algorithms
/dynamic_programming.py
1,741
3.546875
4
""" coin change prob 0-1 knapsack unbounded knapsack edit distance Longest common subseq (LCS) longest incr subseq (LIS) longest palindrome subseq (LPS) TSP (iterative AND recursive) min weight perfect matching (graph prob) exec(open('/home/duchess/Desktop/dp').read()) values = [60,100,120] weights = [10,20,30] capacity = 50 knapsack(values, weights, capacity) """ def knapsack(values, weights, capacity): """ Decision version of knapsack is NP-complete, but we can achieve pseudopolynomial time complexity with DP implementation. For each of n items: item i --> (values[i], weights[i]). Return the maximum value of items that doesn't exceed capacity. """ def knapsack_helper(values, weights, w, m, i): """Return maximum value of first i items attainable with weight <= w. m[i][w] will store the maximum value that can be attained with a maximum capacity of w and using only the first i items This function fills m as smaller subproblems needed to compute m[i][w] are solved. value[i] is the value of item i and weights[i] is the weight of item i for 1 <= i <= n where n is the number of items. """ if m[i][w] >= 0: return m[i][w] if i == 0: q = 0 elif weights[i] <= w: decide_NO = knapsack_helper(values, weights, w, m, i-1) decide_YES = knapsack_helper(values, weights, w-weights[i]) + values[i], m, i-1) q = max(decide_NO, decide_YES) else: q = decide_NO m[i][w] = q return q table = [[-1]*(capacity + 1) for _ in range(len(values))] return knapsack_helper(values, weights, capacity, table, len(values)-1)
da8890ff1f941e97b8174bc6e111272b6ffa0b20
OliverMorgans/PythonPracticeFiles
/Calculator.py
756
4.25
4
#returns the sum of num1 and num 2 def add(num1, num2): return num1 + num2 def divide(num1, num2): return num1 / num2 def multiply(num1, num2): return num1 * num2 def minus (num1, num2): return num1 - num2 #*,-,/ def main(): operation = input("what do you want to do? (+-*/): ") if(operation != "+" and operation != "-" and operation != "*" and operation != "/"): #invalid operation print("You must enter a valid operation (+-*/)") else: num1 = int(input("Enter num1: ")) num2 = int(input("Enter num2: ")) if(operation == "+"): print(add(num1, num2)) elif(operation == "-"): print(minus(num1, num2)) elif(operation == "*"): print(multiply(num1, num2)) elif(operation == "/"): print(divide(num1, num2)) main()
d2cc189fca2ee474dcaa8ddf961517e29267df7b
milannic/intern_code
/intern_course/python/list_merge.py
2,303
3.9375
4
#! /usr/local/bin/python # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a ListNode # @param head, a ListNode # @return a ListNode def sortList(self, head): if head == None: return head if head.next == None: return head if head.next.next == None: if head.val > head.next.val: temp_val = head.val head.val = head.next.val head.next.val = temp_val return head pointer_1x = head pointer_2x = head # we go to the last of the singly linklist. while pointer_2x != None and pointer_2x.next != None: pointer_2x = pointer_2x.next.next pointer_1x = pointer_1x.next #de-link pointer_2x = pointer_1x pointer_1x = pointer_1x.next pointer_2x.next = None mysolution = Solution() new_head1 = mysolution.sortList(head) new_head2 = mysolution.sortList(pointer_1x) startflag = False while new_head1 != None and new_head2 != None: if new_head1.val < new_head2.val : if startflag == False : new_head = new_head1 startflag = True current_pointer = new_head else : current_pointer.next = new_head1 current_pointer = new_head1 new_head1 = new_head1.next else: if startflag == False : new_head = new_head2 startflag = True current_pointer = new_head else : current_pointer.next = new_head2 current_pointer = new_head2 new_head2 = new_head2.next if startflag == False: if new_head1 == None: return new_head2 else: return new_head1 else: if new_head1 == None: current_pointer.next = new_head2 else : current_pointer.next = new_head1 return new_head
261a8ec6e763de736e722338241d2cf39a34c9b0
Rggod/codewars
/Roman Numerals Decoder-6/decoder.py
1,140
4.28125
4
'''Problem: Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order. Example: solution('XXI') # should return 21 ''' def solution(roman): """complete the solution by transforming the roman numeral into an integer""" values = {'I' : 1 ,'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000} sum = 0 count = 0 while(count < len(roman)): cur = values.get(roman[count],' ') if count == len(roman) -1 or (cur >= values.get(roman[count+1],' ')): sum = sum + cur else: sum = sum +(values.get(roman[count+1],' ')-cur) count = count +1 count = count +1 return sum
a7ee00fd9f9dac5ec77d96e7b1ab8c1a1dbe1b4f
Rggod/codewars
/is alphanumerical/solution.py
592
4.15625
4
''' In this example you have to validate if a user input string is alphanumeric. The given string is not nil, so you don't have to check that. The string has the following conditions to be alphanumeric: At least one character ("" is not valid) Allowed characters are uppercase / lowercase latin letters and digits from 0 to 9 No whitespaces/underscore ''' #Solution def alphanumeric(string): for letter in string: if letter.isalpha(): continue elif letter.isdigit(): continue else: return False return True
fe851161d4f3ef73f6bab3d9eef56b8fc1f38905
OsouzaTI/URI
/URI_Python_UFRR/1012.py
381
3.8125
4
linha1 = input().split(" ") pi = 3.14159 A, B, C = linha1 a_ = (float(A) * float(C))/2 b_ = pi * (float(C)**2) c_ = ((float(A) + float(B))*float(C))/2 d_ = float(B)**2 e_ = float(A) * float(B) print('TRIANGULO: {:.3f}'.format(a_)) print('CIRCULO: {:.3f}'.format(b_)) print('TRAPEZIO: {:.3f}'.format(c_)) print('QUADRADO: {:.3f}'.format(d_)) print('RETANGULO: {:.3f}'.format(e_))
6503af81150e0906e8ba7ddc6373962f3c11d8fd
OsouzaTI/URI
/URI_Python_UFRR/1050.py
342
3.515625
4
# -*- coding: utf-8 -*- n = int(input()) err = 1 ddd = [ (61,71,11,21,32,19,27,31), ('Brasilia','Salvador','Sao Paulo','Rio de Janeiro','Juiz de Fora','Campinas','Vitoria','Belo Horizonte') ] for i in range(len(ddd[0])): if n == ddd[0][i]: print(ddd[1][i]) err = 0 if(err == 1): print('DDD nao cadastrado')
99839f599cf60f678ec5ff647313aa549f6e24f7
OsouzaTI/URI
/URI_Python_UFRR/1065.py
102
3.6875
4
pares = 0 for i in range(5): n = float(input()) if n%2==0:pares += 1 print('%i valores pares'%pares)
60612f98363116d4508680cee96688c745fce41c
Changyoon-Lee/TIL
/Algorithm/programmers/정수 삼각형.py
360
3.515625
4
# DFS하려다가 오래걸릴거같아서 안함 def solution(triangle): for i in range(len(triangle)-2,-1,-1): for j in range(len(triangle[i])): if triangle[i+1][j]>triangle[i+1][j+1]: triangle[i][j] += triangle[i+1][j] else : triangle[i][j] += triangle[i+1][j+1] return triangle[0][0]
d42902b04e014ea651d0cd92ed384bebba85d2dc
uashogeschoolutrecht/ADDB-PM
/week1/uitwerkingen/som.py
148
3.546875
4
getal1 = input("geef het eerste getal: ") getal2 = input("geef het tweede getal: ") som = int(getal1) + int(getal2) print("De som is " + str(som))
a2782f257e999f2e2874983ef2ba659f2876423a
jan25/code_sorted
/leetcode/weekly185/3_frogs.py
1,621
3.546875
4
''' https://leetcode.com/contest/weekly-contest-185/problems/minimum-number-of-frogs-croaking/ ''' class Solution: def minNumberOfFrogs(self, croakOfFrogs: str) -> int: cr = 'croak' def nextChar(c): if c == cr[-1]: return for i, cc in enumerate(cr): if c == cc: return cr[i + 1] stacks = {c: [] for c in cr[1:]} for i, c in enumerate(croakOfFrogs): if c != cr[0]: stacks[c].append(i) for c in stacks: stacks[c].reverse() def pop_and_get_ki(i): c = cr[1] j = None while nextChar(c): if stacks[c]: j = stacks[c].pop() if j > i: i = j c = nextChar(c) else: return else: return if not stacks[c]: return j = stacks[c].pop() if j > i: return j h = [] f = 0 for i, c in enumerate(croakOfFrogs): if c == 'c': ki = pop_and_get_ki(i) if ki is None: return -1 if len(h) > 0: if h[0] > i: f += 1 heapq.heappush(h, ki) else: heapq.heappop(h) heapq.heappush(h, ki) else: f = 1 h.append(ki) for c in stacks: if stacks[c]: return -1 return f
51731f8e5b7bff4e912a640e2da7d6c0f7da5bb7
jan25/code_sorted
/leetcode/weekly169/3_jumps.py
615
3.578125
4
''' https://leetcode.com/contest/weekly-contest-169/problems/jump-game-iii/ ''' class Solution: def canReach(self, arr: List[int], start: int) -> bool: n = len(arr) vis = set() def walk(i): if i < 0 or i >= n: return False if arr[i] == 0: return True t = False if (i, 0) not in vis: vis.add((i, 0)) t = t or walk(i - arr[i]) if (i, 1) not in vis: vis.add((i, 1)) t = t or walk(i + arr[i]) return t return walk(start)
c5df770ffadb8bc330143a8a8766c35fb5dd2166
jan25/code_sorted
/leetcode/weekly166/2_people_and_groups.py
468
3.59375
4
''' https://leetcode.com/contest/weekly-contest-166/problems/group-the-people-given-the-group-size-they-belong-to/ ''' class Solution: def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: groups = [] h = {} for n, g in enumerate(groupSizes): if g not in h: h[g] = [] h[g].append(n) if len(h[g]) == g: groups.append(h[g]) h[g] = [] return groups
a50b8b9a73fb850f8c19108757e46762e0864d1c
jan25/code_sorted
/leetcode/weekly169/2_2_binary_trees.py
753
3.78125
4
''' https://leetcode.com/contest/weekly-contest-169/problems/all-elements-in-two-binary-search-trees/ ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: h = [] def traverse(r): if r is None: return h.append(r.val) traverse(r.left) traverse(r.right) traverse(root1) traverse(root2) heapq.heapify(h) sorted_h = [] while len(h) > 0: sorted_h.append(heapq.heappop(h)) return sorted_h