blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b5a59bf3163ad5642f780e5496d491c53f67c1ae
bossjoker1/algorithm
/pythonAlgorithm/Practice/917仅仅反转字母.py
607
3.84375
4
# python 字符串不可变,可以将其转为list后再用双指针解题 class Solution: def reverseOnlyLetters(self, s: str) -> str: chars = list(s) l, r = 0, len(s) - 1 while l < r: while l < r and not ( ord("A")<=ord(s[l])<=ord("Z") or ord("a")<=ord(s[l])<=ord("z")): l += 1 while l < ...
f61f1283405ee568597c27af2e4da3afccbeb0d8
bossjoker1/algorithm
/pythonAlgorithm/Practice/148排序链表.py
2,413
3.703125
4
# 归并,递归,空间复杂度为o(logn),即栈的深度 class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: # 退出条件 if not head or not head.next: return head # 快慢指针找中点 slow, fast = head, head.next while fast and fast.next: slow, fast = slow.next, ...
2e5c9a3cdfda17c3be985fa8b9a033a41b087a38
bossjoker1/algorithm
/pythonAlgorithm/Practice/hard/5237得到回文串的最少操作次数.py
606
3.71875
4
# tip: 贪心地匹配最左边(如何做到最小步数?) # 找与左边一致的最靠近右边的,如果没有说明是要放在中间的 class Solution: def minMovesToMakePalindrome(self, s: str) -> int: if not s: return 0 cnt, n = 0, len(s) temp = "" for i in range(n-1, -1, -1): if s[0] == s[i] and i != 0: temp = s[1:i] + s[i+1:] ...
b79863ba5364e471ec475c3f8577b0fefa9252cc
bossjoker1/algorithm
/pythonAlgorithm/Practice/ms01.py
541
3.5625
4
# 题目意思看错了... # 希望不会面试都进不去吧 from tkinter.tix import Tree def solution(S): n = len(S) if n == 1: return 1 res = 0 flag = True for i in range(n): if S[i] == "^" or S[i] == "v": res += 1 flag = True if S[i] == "<": if i == 0 or fl...
b2e4752e4fe7a52c9406c392cafa32e51599241b
bossjoker1/algorithm
/pythonAlgorithm/Practice/手撕快排.py
861
3.8125
4
# 随机pivot快速排序 import random class Solution: def sortArray(self, nums): n = len(nums) def QuickSort(left, right): if left >= right: return nums index = random.randint(left, right) pivot = nums[index] nums[index], nums[left] = nums[left], nums[index] ...
ff262297ad4605d9ed1a1cbc495099848b9b5d98
rolmos14/Zookeeper
/Problems/Good rest on vacation/task.py
201
3.59375
4
# put your python code here days = int(input()) food_day = int(input()) one_way_flight = int(input()) hotel_night = int(input()) print(days * food_day + 2 * one_way_flight + (days - 1) * hotel_night)
f86767b2b8c1f93abcadfe9986e90fe5733d6776
rolmos14/Zookeeper
/Problems/Numbers/task.py
93
3.734375
4
numbers = list(range(1, 11)) print(" ".join(str(x) for x in numbers)) print(*range(1, 11))
fe7d0c21fa5f3bdf21338ec94177a8e77e110ff1
petehe/PythonGame
/Fidget Spinner/spinner.py
629
3.703125
4
import turtle as t state = {'turn': 0} def spinner(): t.clear() angle = state['turn'] / 10 t.right(angle) t.forward(100) t.dot(120, "red") t.back(100) t.right(120) t.forward(100) t.dot(120, 'green') t.back(100) t.right(120) t.forward(100) t.dot(120, 'blue') ...
56ffbbb574a0aaa8ec5b0a06149b86b6c4b05b28
ByDFlower/D-maw
/maw.py
5,573
4.1875
4
def loopfunc(): if(DCom == "what is your age?" or DCom == "how old are you?" or DCom == "age?" or DCom == "age"): import datetime today = datetime.date.today() BDy = datetime.date(2018, 1, 5) print (today - BDy) import time time.sleep(1) top() elif(DCom == "what date is today?" or DCom == "what day i...
7051c32881bba5829cc1f6af1afc199a95d3a690
innhyu/Code-Snippets
/Python/Easy/simpleSymbol.py
362
3.96875
4
def SimpleSymbols(str): state = 0 for char in str: print char if char == "+": if state == 2: state = 0 else: state = 1 elif char =="=": state = state else: if state == 1: state = 2 else: return False print "State is" print state return True # keep this function call here print Sim...
ae2c842977696aba76c59abbe85377b97e8ff585
Bradley94/misc-theory-work
/Codewars/level7/Hungarian_vowel_harmony.py
1,354
3.875
4
""" Task: Your goal is to create a function dative() (Dative() in C#) which returns the valid form of a valid Hungarian word w in dative case i. e. append the correct suffix nek or nak to the word w based on vowel harmony rules. Vowel Harmony Rules (simplified) When the last vowel in the word is a front vowel (e, é...
dc86faabe770875fb056f1cfb143021a34ebdc97
Bradley94/misc-theory-work
/SQLite/insert_record.py
454
4.0625
4
import sqlite3 # Create a connection to our database, in the brackets if db doesn't exist it creates it conn = sqlite3.connect('customer.db') # Create a cursor (tells the db what to do) c = conn.cursor() c.execute("INSERT INTO customers VALUES ('John', 'Elder', 'john@codemy.com')") print("Command execu...
3fb5e1f7106a4a61e0af99037eef0c7e773ead9f
Bradley94/misc-theory-work
/Codewars/level7/int_reverser.py
654
4.34375
4
""" Impliment the reverse function, which takes in input n and reverses it. For instance, reverse(123) should return 321. You should do this without converting the inputted number into a string. """ # Theory on how the equation works # https://stackoverflow.com/questions/53688984/reversing-an-integer-without-using-re...
6abac2c0813fae8e97f3b490af81862def658543
Bradley94/misc-theory-work
/Codewars/level7/stones_on_table.py
822
4.09375
4
""" There are some stones on Bob's table in a row, and each of them can be red, green or blue, indicated by the characters R, G, and B. Help Bob find the minimum number of stones he needs to remove from the table so that the stones in each pair of adjacent stones have different colours. Examples: "RGBRGBRGGB" => 1...
9d1a7015bc8b3a6d673be0f50d4206e86046894a
Bradley94/misc-theory-work
/SQLite/insert_many_records.py
624
3.9375
4
import sqlite3 # Create a connection to our database, in the brackets if db doesn't exist it creates it conn = sqlite3.connect('customer.db') # Create a cursor (tells the db what to do) c = conn.cursor() many_customers = [ ('Wes', 'Brown', 'wes@brown.com'), ('Steph', 'Kuewa', 'steph@kuewa.com'),...
b5b972c2eb5308b7ff9be7d806afeff63064453b
merupy/Simple-Snake-Game-
/snake_game.py
3,594
3.71875
4
import turtle import time import random delay = 0.05 body=[] #For Screen wn = turtle.Screen() wn.title("Snake Game by Meru ") wn.bgcolor("black") wn.setup(width=600, height=600) #For Score score1 = 0 hscore= 0 #Score display score = turtle.Turtle() score.speed(0) score.shape("square") score.c...
1ff8fdc714e228ee8d10e4ae7dd6a4b0a4081463
AnastasiaP261/stepik_algorithms_1
/fibonachi_last_num.py
1,146
3.859375
4
''' Дано число 1 <= n <= n**7, необходимо найти последнюю цифру nn-го числа Фибоначчи. ''' def fib_digit(n): list = [] list.append(0) list.append(1) if n > 1: i = 2 while i <= n: num = str(list[i - 1] + list[i - 2]) list.append(int(num[-1])) ...
c62cb3d1c1352c3120b68ec15791cc745c2c75ce
dexterfloreza/Computing-Contest-Solutions
/CCC/CCC '06 J1 Canadian Calorie Counting.py
957
3.625
4
burgerChoice = eval(input()) sideChoice = eval(input()) drinkChoice = eval(input()) dessertChoice = eval(input()) if burgerChoice == 1: bcalories = 461 if burgerChoice == 2: bcalories = 431 if burgerChoice == 3: bcalories = 420 if burgerChoice == 4: bcalories = 0 if sideChoice == 1: ...
3ce8c1842ca594e2ffba487dcb53ecf6f3a2ac66
dexterfloreza/Computing-Contest-Solutions
/CCC/CCC07J2.py
702
3.796875
4
# define the emoticon list eList = ["CU", ":-)", ":-(", ";-)", ":-P", "(~.~)", "TA", "CCC", "CUZ", "TY", \ "YW"] # define the translation list tList = ["see you", "I'm happy", "I'm unhappy", "wink", "stick out my tongue", \ "sleepy", "totally awesome", "Canadian Computing Competition", "because", "thank-you", \ ...
1ace7d3be09454890fef69f531d2d3a9a5d41678
kcharellano/LcAns
/ByPattern/BinaryTree/BinaryTreeBFS/BinaryTreeLevelOrderTraversal.py
1,146
3.953125
4
# https://leetcode.com/problems/binary-tree-level-order-traversal ''' Algorithm: BFS Level Order Time: O(N) -- Processes all nodes in tree Space: O(M) where M = maximum number of nodes in any given level ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, r...
70a7c9fbe341dbd639f9c9474f3a108cebb29d0e
kcharellano/LcAns
/ByPattern/TopKNumbers/KthLargestElementInArray.py
952
3.859375
4
# https://leetcode.com/problems/kth-largest-element-in-an-array ''' Algorithm: Kth largest element - Use a minheap to constantly keep track of the kth largest element - keep the minheap below a certain size - if size capacity reached - if new element is >= minimum element in min...
557841976b535598592e3eb66f6ff18d8caf3799
kcharellano/LcAns
/ByPattern/NoPattern/MinimumNumberOfStepsToMakeAnagram.py
870
3.625
4
# https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/submissions/ ''' Algorithm: HashMap to check for letter differences - create letter counts for string s and string t - remove letters they have in common - remaining size of either(they will be the same) is the answer ...
36e2cbca20409ace44184ae8062d6f158d41a24d
kcharellano/LcAns
/ByCategory/ArraysAndStrings/MeetingRooms2.py
1,135
3.796875
4
''' https://leetcode.com/problems/meeting-rooms-ii/ ''' import heapq class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: if intervals == []: return 0 # sort meeting rooms by their start times in descending order # NOTE: Logically, we will b...
78d31d6106eaf3e25ae0c49d625f4b38a7160271
kcharellano/LcAns
/ByPattern/Greedy/MaximumUnitsOnTruck.py
868
3.796875
4
# https://leetcode.com/problems/maximum-units-on-a-truck ''' Algorithm: Greedy - Choose the boxes with the most units first Time: O(nlogn) Space: O(1) ''' class Solution: def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: boxTypes.sort(key=lambda x: x[1], reverse=Tru...
178650e9f37a964c3a20d08860db1d6ea5a78ece
kcharellano/LcAns
/AmazonTop50/MergeTwoSortedLists.py
1,157
3.890625
4
''' Algorithm: 3 Ptr Weaving - Maintain the inequality prev -> min(p1, p2) -> max(p1, p2) - Weave ptrs based on value since they are sorted - quit once any ptr points to none. No need to keep going Time: O(L1 + L2) Space: O(1) Other approches: - build 2 lists from l1 and l2 - Conca...
b2dae81a79244a48789768364a81571ae2254727
kcharellano/LcAns
/ByCategory/TreesAndGraphs/WordLadder.py
2,911
3.765625
4
''' https://leetcode.com/problems/word-ladder/solution/ ''' ''' Algorithm: - Form bidirectional graph using beginWord and wordList - Each node is a word, each edge represents a one letter transformation - Use dijkstra's algorithm to find shortest path from beginWord to endWord N...
be47d27d7961f0726e7252d46b563a8f0714fe90
kcharellano/LcAns
/ByPattern/ShortestPath/ShortestPathToGetFood.py
1,738
4.03125
4
# https://leetcode.com/problems/shortest-path-to-get-food from collections import deque ''' Algorithm: BFS to find shortest path - queue stores cells - append queue at tail and pop queue at head - each queue node stores the # of steps it has ''' class Solution: def findStart(self, grid,...
90cb7e62efb2889a37b0347a421c9353adac934f
kcharellano/LcAns
/ByPattern/DynamicProgramming/DynammicProg/Triangle.py
972
3.65625
4
# https://leetcode.com/problems/triangle/ ''' Algorithm: DP min/max path cost sum - Create dp table with same dimensions as triangle - Each cell in table is the min-cost path from root to that cell - The minimum cost path from top to bottom is the minimum val in the bottom of the dp table ''' from ...
9f6015c3458319c9532bcb0a17d1ad7a2f6415fd
kcharellano/LcAns
/ByCategory/Recursion/CombinationsOfAPhoneNumber.py
1,342
3.8125
4
''' https://leetcode.com/problems/letter-combinations-of-a-phone-number/ ''' ''' Algorithm: Backtracking - Create a mapping of digits to their letters on phone keys - Perform basic backtracking Time: unkown but either O(N * 4^N) or O(3^N * 4^M) Space: unkown but either O(N * 4^N) or O(3^...
f56bdaf0e1a1c60cdb4b81499eaaaa2968ab4598
kcharellano/LcAns
/ByPattern/DynamicProgramming/SlidingWindow/MinimumWindowSubstring.py
1,934
3.6875
4
#https://leetcode.com/problems/minimum-window-substring ''' Algorithm: Sliding Window -- dynamic variation - Keep a set of the original target characters (tchars) - keep a set of remaining characters needed to make window valid(missing) - Store target letter counts inside the window using a...
b77c20584be837c9fd5a1808df684b449e2c062d
kcharellano/LcAns
/ByPattern/BinaryTree/BinaryTreeBFS/AllNodesKDistanceInBinaryTree.py
1,743
4.09375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None ''' Algorithm: Bidirectional Search in Binary Tree + BFS - Create a mapping of every child to its parent - Perform a regular BFS starting from th...
e824e29d630a93b12e055e24f1964d0f7b290633
danielhac/python_oop
/poly_operator_overloading.py
601
4.4375
4
# Demonstrating polymorphism # Operator overloading: giving extended meaning beyond their predefined operational meaning. # Ex: add two integers as well as join two strings and merge two lists # This example takes two separate objects' passed in numbers 1, 5 and uses # operator overloading of the __add__ method so...
ac509c8d31cd60934cb1bf3f4a76b67fa6004f83
Uv1107/DecisionTree
/DecisionTree.py
7,496
3.65625
4
import csv import math import random class DecisionTree(): tree = {} def learn(self, training_set, attributes, target): self.tree = build_tree(training_set, attributes, target) # Class Node which will be used while classify a test-instance using the tree which was built earlier class Node(): va...
3feeb1147fdb5be7c87a09d145cbbda717a6715c
lizethbaldelomar/150-hashtag
/hello.py
6,980
3.53125
4
#switch class switch(object): value = None def __new__(class_, value): class_.value = value return True def case(*args): return any((arg == switch.value for arg in args)) nextChar = 'a' nextToken = 0 lexLen = 0 token = 0 a = 0 b = 0 c = 0 lexeme = [] charClass = "UNKNOWN"...
4e98e76814d59a8e37c5c912b048a0ecf241b374
bmolina-nyc/ByteAcademyWork
/Week3/Week3Day2/sample-code/join_class.py
888
3.515625
4
import sqlite3 import os DIRPATH = os.path.dirname(__file__) DBFILENAME = "school.db" DBPATH = os.path.join(DIRPATH, DBFILENAME) def join_class(studentname, coursename, dbpath=DBPATH): with sqlite3.connect(dbpath) as conn: conn.row_factory = sqlite3.Row curs = conn.cursor() SQL = "SELECT ...
9b6f2901e5105e0e2d44bdb16a3ef220eb071968
bmolina-nyc/ByteAcademyWork
/Week1/Week1Day2/3-matrix-sort/SAMPLE_matrix_sort.py
1,238
3.59375
4
# from tabulate import tabulate def matrix_sort(text_file): with open(text_file) as f: text = f.readlines() matrix = [] for line in text: matrix.append(list(map(int, line.split()))) row_sum = [] for i in range(len(matrix)): row_sum.append(sum(matrix[i])) col_...
8af37b553d0dde563e9723a35e3efe43ea0b46be
bmolina-nyc/ByteAcademyWork
/Week1/Week1Day4/worksheet.py
1,537
3.796875
4
# https://docs.python.org/3/library/json.html # https://docs.python.org/3/tutorial/inputoutput.html # https://docs.python.org/3/library/csv.html # #open a file, pass file name, # file_object = open('test.txt', 'r') # add the extra parameter end="" to kill the automatic newline characters # for line in file_object:...
997d803c60d5a96de96ed0bb19c7c423f10800c0
bmolina-nyc/ByteAcademyWork
/Week3/Week3Day1/day1-SQL-basic-CRUD/exercise/1-create-db-from-csv/my_db_creation/create_db_assignment.py
1,780
4
4
import sqlite3 import csv def create_tables(): with open('employees.csv', 'r') as file: rows = [] csv_file = csv.reader(file) next(csv_file, None) #skips header row for row in csv_file: if (len(row) == 6): rows.append(row) elif (len(row) == ...
615f5b78d89f8705509245ac37e5050e6efb110e
sanjaymurali/sudoku-solver
/ForwardCheck.py
1,447
4.21875
4
class ForwardCheck: """ Forward checking is mainly used for early detection of failures. Terminate search when any variable has no legal values. 1. assign value to a variable[a square or a box] 2. iterate over the peers of the square 3. if the peers is not already assigned a...
96c5b770b03638592ebfca0f36a1fad7ac1d9ed9
OldJohn86/Python_CPP
/CPP_LiaoPython_Exp/oop/use_enum.py
806
3.546875
4
from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) for name, member in Month.__members__.items(): print(name, '=>', member, ',', member.value) from enum import Enum, unique @unique class Weekday(Enum): Sun = 0 Mon = 1 Tue = 2 Wed = ...
e2e4ddfa648e61398fdfc67dbbe30b497cf75484
OldJohn86/Python_CPP
/CPP_LiaoPython_Exp/basic/ifcase.py
248
4.09375
4
age = 2 if age >= 18: print('your age is', age) print('adult') elif age >= 6: print('teenager') else: print('kid') x = [1] if x: print('True') s = input('birth: ') birth = int(s) if birth < 2000: print('00 Before') else: print('00 After')
c0465384c04f1501e4e208caa165e1557f0cc859
OldJohn86/Python_CPP
/CPP_LiaoPython_Exp/advance/do_slice.py
742
3.65625
4
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] print(L) print(L[:3]) print(L[-2:-1]) L1 = list(range(100)) print(L1) print(L1[:10]) print(L1[-10:]) print(L1[10:20]) print(L1[:10:2]) print(L1[::5]) print(L1[:]) def trim(s): while s[:1] == ' ': s = s[1:] trim(s) while s[-1:] == ' ': s = s[0:-1] trim(s) ret...
9f7c7e1230a4caa053cd952a0a73cb34bd91774a
OldJohn86/Python_CPP
/CPP_LiaoPython_Exp/function/param_func.py
1,118
3.96875
4
def power(x, n=2): s = 1 while n > 0: n = n -1 s = s * x return s print(power(5)) print(power(5, 3)) print(power(5, 4)) def enroll(name, gender, age=6, city='Beijing'): print('name:', name) print('gender:', gender) print('age:', age) print('city:', city) enroll('Sarah', 'F', 9) enroll('Jason', 'F', city='...
fdafbed2293c435082c8256fc8521e69482ec84b
G-Sudarshan/python
/Ternary_Search.py
923
4.1875
4
#Given a sorted array arr[] of size N and an integer K. # The task is to check if K is present in the array or not using ternary search. # Ternary Search- It is a divide and conquer algorithm that can be used # to find an element in an array. In this algorithm, we divide the # given array into three parts and deter...
91a4bd81d8f1d2aabf11e1b8ef3a89e6031824b5
SkeyLearing/Python3
/iterator/demo5.py
291
3.734375
4
from itertools import islice # 迭代器的切片操作 list = [x for x in range(20)] list = iter(list) # l1 = islice(list, 5, 10) # 每次使用 islice 都需要重新申请迭代器对象 l2 = islice(list, 15, None) # for i in l1: # print(i) for x in l2: print(x)
64041647484a6d3b9639c2383dbff4969f484164
15642625606/Isle-of-Man-TT
/section1/test3.py
390
3.546875
4
''' 编写程序,完成以下要求: 完成一个路径的组装 先提示用户多次输入路径,最后显示一个完成的路径,比如/home/python/ftp/share ''' path = "" flag = 1 j = 1 while flag: aPath = input("请输入路径%d(输入exit终止):"%j) if aPath == 'exit': path = path[0:-1] break path =path + aPath + "\\" j += 1 print(path)
4cb8ba07edfd4b664858506d5864b634ced8081e
15642625606/Isle-of-Man-TT
/section1/test2.py
481
3.875
4
''' 编写程序,完成以下要求: 统计字符串中,各个字符的个数 比如:“hello world” 字符串统计的结果为: h:1 e:1 l:3 o:2 d:1 r:1 w:1 ''' aStr = input("请输入您的字符串,我们将进行字符串统计:") list = list(aStr) #字符串转列表 print(list) count = dict() #dict()函数用于创建一个字典 for item in list: if item in count: count[item] += 1 else: count[item] = 1 print...
869553bf9eeee1083427325d5525e24cd3c08ac4
kookii99/coding
/HourRank 30/video_conference.py
1,278
3.546875
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'solve' function below. # # The function is expected to return a STRING_ARRAY. # The function accepts STRING_ARRAY names as parameter. # def solve( names ): m = set() p = {} results = [] for na...
5bf0a77e3ff41f384d0a694dba03abcf834d08d4
RomanKalsin/python-project-lvl1
/brain_games/games/gcd.py
484
3.953125
4
from random import randint from prompt import integer tutorial = "Find the greatest common divisor of given numbers." def game(): num1 = randint(0, 100) num2 = randint(0, 100) result = gcd(num1, num2) print("Question: {} {}".format(num1, num2)) ansver = integer("Question: ") is_...
4778f9256cd36f0ff877935588a89b66561041fb
sseidmed/AutomateTheBoringStuff
/commaCode.py
229
3.515625
4
def refine(mylist): mylist.insert(-1, "and") str1 = ', '.join(str(e) for e in mylist) str1 = str1.replace("and,", "and") print(str1) spam = ['apples', 'bananas', 'tofu', 'cats', 1, False, "monkey"] refine(spam)
6b48be9a04b209c63a8f6ffd0846589f98947495
Mint-Afk/EUROPEAN-GEOGRAPHY-CHAMPION-2K20--PRO-
/city_check/scripts/capitals.py
3,647
4.46875
4
#! /usr/bin/env python3 '''Capital module is core to the whole functioning of the program. This module contains two main functions: - load_csv: utilised to open and analyse csv file datas. - check_capitals: returns the correspondence asked. Check function called by the main_app taking argument place of the p...
e130f6ac9a23880a361506f0f1ca85e525f6b52d
MarcoDSilva/MIT6001x-Introduction-to-Computer-Science-and-Programming-in-Python
/final_exam/exe3.py
1,912
4
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 1 21:14:14 2020 You are given a dictionary aDict that maps integer keys to integer values. Write a Python function that returns a list of keys in aDict that map to dictionary values that appear exactly once in aDict. This function takes in a dictionary and returns...
b783e1b5f0309c891dc57e711d68a7983c96ea5b
MarcoDSilva/MIT6001x-Introduction-to-Computer-Science-and-Programming-in-Python
/week4/simpleDivide.py
771
3.9375
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 2 17:57:25 2020 This code raises a ZeroDivisionError exception for the following call: fancy_divide([0, 2, 4], 0) Your task is to change the definition of simple_divide so that the call does not raise an exception. When dividing by 0, fancy_divide should return a lis...
a88c8535b235ec110a43e04a7fd4dd957bac696d
MarcoDSilva/MIT6001x-Introduction-to-Computer-Science-and-Programming-in-Python
/week2/gcdIter.py
672
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 13 19:59:40 2020 The greatest common divisor of two positive integers is the largest integer that divides each of them without remainder. @author: MarcoSilva """ def gcdIter(a,b): ''' a, b: positive integers returns: a positive integer, the greatest co...
00c0cc4d21fe2dbba2fc66162cbc7c2568a6e9db
MarcoDSilva/MIT6001x-Introduction-to-Computer-Science-and-Programming-in-Python
/pset1/ps1c.py
2,256
3.734375
4
# -*- coding: utf-8 -*- """ Created on Wed May 20 13:37:04 2020 Pset1 , exercise 3 for MIT 6.0001s @author: MarcoSilva """ """ You have graduated from MIT and now have a great job! You move to the San Francisco Bay Area and decide that you want to start saving to buy a house.  As housing prices are very high in the B...
67251f9c405946be607d72c8926f4b7ffb122b97
qnomon/Python-Studies
/ex031.py
156
3.5625
4
d = float(input('Digite a distancia em KM a ser percorrida: ')) if d <= 200: v = d*0.5 else: v = d*0.45 print(f'O valor a ser pago é de R${v:.2f}')
3be44d36cde253f5951a129c950eecfaf5f2a4db
qnomon/Python-Studies
/ex045.py
1,035
3.734375
4
from random import randint p = int(input('Digite \n[1] para escolher Pedra, \n[2] para escolher Papel e \n[3] para escolher Tesoura: ')) m = randint(1, 3) if p == m : print('\033[33mEmpate') #condicional de empate elif p == 1 and m == 3 : print('Você escolheu Pedra e \033[34mVenceu') # Condicional para vitória ...
6ad8d9d5f3368188d612de5b44c6238c814941f7
qnomon/Python-Studies
/ex009.py
254
4.125
4
n1 = int(input('Digite um valor: ')) print(f'{n1} x 1 = {n1*1} \n{n1} x 2 = {n1*2} \n{n1} x 3 = {n1*3} \n{n1} x 4 = {n1*4} \n{n1} x 5 = {n1*5}') print(f'{n1} x 6 = {n1*6} \n{n1} x 7 = {n1*7} \n{n1} x 8 = {n1*8} \n{n1} x 9 = {n1*9} \n{n1} x 10 = {n1*10}')
5bda40a055967460517faf1f6794ae02a7c03d62
qnomon/Python-Studies
/Listas/ex001.py
173
3.796875
4
lista = [] while True: v = int(input('Digite um valor [0 Ou menos para parar]: ')) if v <= 0: break lista.append(v) print(f'A lista gerada foi {lista}')
1a4a380d2b5b2e89dae89ae9017b5f53cb898283
qnomon/Python-Studies
/ex013.py
147
3.6875
4
s1=float(input('Qual é o seu salário atual: ')) s2= s1*0.15 s3= s1+s2 print('O seu salário após o aumento de 15% será de R${:.2f}'.format(s3))
accbd3e9fe1ba9e17cea64617a9e5dcb74c44877
qnomon/Python-Studies
/ex079.py
528
3.84375
4
lista = list() cont = '' print('=-'*30) while True: v = int(input('Digite um valor: ')) if v in lista: print('O valor ja consta na lista. Adição cancelada.') else: lista.append(v) print('Valor adicionado com sucesso.') cont = str(input('Deseja continuar? [S/N] ')).strip().upper()...
0c9fa6217ba5618f0ed911a68d251af35d01d739
qnomon/Python-Studies
/Prova/Ex2.py
885
3.640625
4
A = [] B = [] R = [] c = 0 nA = int(input('Digite o tamanho da lista A: ')) while c < nA: valor = int(input('Digite um valor para inserir na lista A: ')) while valor in A: valor = int(input('Digite um valor NÃO REPETIDO para inserir na lista A: ')) A.append(valor) c +=1 c = 0 nB = int(input('Dig...
15b83cfb047ce6cf25e49dc04b970fc8e059cb1a
qnomon/Python-Studies
/Lista 1 Banin/ex13.py
230
4
4
x = float(input('Digite um valor [0]Para encerrar o programa: ')) tot = 0 while x != 0: tot +=x x = float(input('Digite um valor [0]Para encerrar o programa: ')) print(f'O total da soma dos números inseridos é de {tot}')
9ff926b73be5fcb23bccda2732784db1c0942cce
qnomon/Python-Studies
/ex082.py
578
3.75
4
lista = list() impar = list() par = list() while True: lista.append(int(input('Digite um valor: '))) c = str(input('Deseja Continuar?[S/N]: ')).strip().upper() while c not in 'SN': c = str(input('Deseja Continuar?[S/N]: ')).strip().upper() if c == 'N': break lista.sort() for cont, valor ...
7857ab64b232256e5f6af604936e077b628dd348
qnomon/Python-Studies
/ex042.py
592
4.09375
4
a = float(input('Digite o comprimento da reta A: ')) b = float(input('Digite o comprimento da reta B: ')) c = float(input('Digite o comprimento da reta C: ')) if (b-c)<a<(b+c) and (a-c)<b<(a+c) and (a-b)<c<(a+b): print('Essas retas podem formar um triângulo.') if a == b == c : print('O triangulo formado...
06c0696caa85605d1b6746d1b06125b5b4ab848f
qnomon/Python-Studies
/ex105.py
884
3.640625
4
def notas(*num, sit=False): """ -> Função para analisar notas e situações de vários alunos. :param num: uma ou mais notas dos alunos (aceita várias). :param sit: valor opcional, indicando se deve ou não adicionar a situação. :return: dificonario com várias informações sobre a situação da turma. ...
5eed4952bed5df75f71d47beebe515c0414cd342
qnomon/Python-Studies
/Lista 1 Banin/ex02.py
314
3.71875
4
n = 0 par = 0 impar = 0 while True: n = int(input('Digite um número [Digite 0 para parar]:')) if n == 0: break if n % 2 == 0: par += n else: impar += n print(f'A soma dos números pares digitados é de {par}') print(f'A soma dos números impares digitados é de {impar}')
94005ec0672f3a1576688638c90f403ebce031f6
jmitrevs/JivaTuning
/utils_misc.py
1,705
3.609375
4
# -*- coding: utf-8 -*- """ Various utilities Note: standard units are G, K, s Use the unitDict to convert to standard units if necessary Created on Sat Jan 18 10:50:22 2020 @author: Margaret @author: Jovan """ import re import logging log = logging.getLogger("SuperJIVA." + __name__) unitDict = { 'p': 1e-12,...
cc63037206d759b6551db478e0361bd697000d97
mrkiura/idiomatic-python
/chapter2/lists.py
2,139
4.09375
4
"""Idiomatic ways of dealing with lists.""" # Scenario 1: using list comprehension to transform an existing list # harmful some_other_list = range(10) some_list = list() for element in some_other_list: if is_prime(element): some_list.append(element + 5) # Idiomatic some_other_list = range(10) some_list = ...
b96f7e1b8abf85c9b5411f73a6d50376d85d3153
mrkiura/idiomatic-python
/chapter1/for_loops.py
1,380
4.125
4
"""Idiomatic ways of writing for loops.""" # Scenario 1: having an index variable in a for loop # harmful my_container = ['Larry', 'Moe', 'Curly'] index = 0 for element in container: print('{}{}'.format(index, element)) index += 1 # Idiomatic my_container = ['Larry', 'Moe', 'Curly'] for index, element in enum...
348d874d375bea1cf0e65d7baadb86aa82bb4e80
Metatronxl/MachineLearning
/kNN/kNN_sk.py
1,281
3.640625
4
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from utilities import load_data,file2Metrix from sklearn import neighbors,preprocessing def testKNN(): returnMat,classLabel = file2Metrix("datingTestSet2.txt") hoRatio = 0.10 num_neighbors = 3 normMat =...
db4b9253f45c97cdb5d9ff08f13de7180ef5e1c4
komo-fr/AtCoder
/past/past202104-2/a/main.py
304
3.6875
4
#!/usr/bin/env python3 S = input() targets = "0123456789" is_ok = True for i, s in enumerate(S): if i == 3: if s != "-": is_ok = False break else: if s not in targets: is_ok = False break ans = "Yes" if is_ok else "No" print(ans)
05dfe8945659273e5b6d2b9afd9c0566b34208b4
komo-fr/AtCoder
/arc/arc011/a/main.py
252
3.515625
4
#!/usr/bin/env python3 m, n, N = list(map(int, input().split())) now_short_m = N total = N c = 0 while now_short_m >= m: c += 1 new_n = (now_short_m // m) * n now_short_m = now_short_m % m + new_n total += new_n ans = total print(ans)
cd1f0d8b27d167429ce9d6801a50f49a121329ad
komo-fr/AtCoder
/abc/269/d/main.py
1,745
3.578125
4
#!/usr/bin/env python3 from collections import defaultdict N = int(input().split()[0]) xy_list = [] for _ in range(N): x, y = list(map(int, input().split())) xy_list.append((x, y)) def get_neighbors(i, j): neighbors = [ (i - 1, j - 1), (i - 1, j), (i, j - 1), (i, j + 1), ...
6c1b7ada226987845b922ec0208c6fb2c14290c4
komo-fr/AtCoder
/kujikatsu/N181/4/main.py
1,238
3.59375
4
#!/usr/bin/env python3 from collections import deque, namedtuple N, C, K = list(map(int, input().split())) t_list = [] Person = namedtuple("Person", ["at", "deadline"]) for _ in range(N): t = int(input().split()[0]) t_list.append(Person(t, t + K)) person_deque = deque(sorted(t_list)) bus_count = 0 bus_deque ...
1e172a6c0c7bff0a1a095428dad32af67ca80595
komo-fr/AtCoder
/abc/135/b.py
616
3.546875
4
n = int(input().split()[0]) p_list = list(map(int, input().split())) r_count = 0 target_index_dict = {} for i, number in enumerate(p_list): if i+1 != number: r_count += 1 target_index_dict[i] = number if not target_index_dict: ans = 'YES' else: if len(target_index_dict) >= 3: ans =...
aa49c29459266e2ddbe5cbdd7809a668935730a2
komo-fr/AtCoder
/abc/017/b/main.py
295
3.625
4
#!/usr/bin/env python3 x = input() x = "".join(list(reversed(x))) while x: if x[0] in ["o", "k", "u"]: x = "" if len(x) == 1 else x[1:] elif len(x) >= 2 and x[:2] == "hc": x = "" if len(x) == 2 else x[2:] else: break ans = "NO" if x else "YES" print(ans)
323b637c16a940e7873dec35dcb2200a733d89d9
komo-fr/AtCoder
/past/past202012-2/g/main.py
1,004
3.515625
4
#!/usr/bin/env python3 import networkx as nx # H, W = list(map(int, input().split())) H, W = list(map(int, input().split())) s_table = [] for y in range(H): s = input() s_table.append(s) G = nx.Graph() for y, s in enumerate(s_table): for x, char in enumerate(s): # ひとつ前、ひとつ上と道があったらつなぐ if x ...
1fd067e999e1217c892839d85f542b71409483c4
komo-fr/AtCoder
/others/cf17-final/a/main.py
251
3.609375
4
#!/usr/bin/env python3 import itertools S = input() patterns = itertools.product(["A", ""], repeat=4) target_list = [] for p in patterns: target_list.append(f"{p[0]}KIH{p[1]}B{p[2]}R{p[3]}") ans = "YES" if S in target_list else "NO" print(ans)
c7652cd6bdba071d7d0b6040c9f6dc8f3ae2a024
komo-fr/AtCoder
/past/past201912-open/a/main.py
214
3.84375
4
#!/usr/bin/env python3 S = input() is_ok = True ok_list = [str(i) for i in range(10)] for i in range(3): if S[i] not in ok_list: is_ok = False ans = str(int(S) * 2) if is_ok else "error" print(ans)
3a970e040734c8ac54d1722527e824b1fbdab38b
komo-fr/AtCoder
/others/code-formula-2014-qualb/b/main.py
247
3.703125
4
#!/usr/bin/env python3 N = int(input().split()[0]) even_sum = sum([int(x) for i, x in enumerate(reversed(str(N))) if (i + 1) % 2 == 0]) odd_sum = sum([int(x) for i, x in enumerate(reversed(str(N))) if (i + 1) % 2 == 1]) print(even_sum, odd_sum)
e9c2b58f979383f3db2cc292c375e01a62cbe229
komo-fr/AtCoder
/past/past202012-2/f/sub.py
1,322
3.546875
4
#!/usr/bin/env python3 from collections import defaultdict, Counter N, M = list(map(int, input().split())) abc_list = [] abc_set_list = [] for _ in range(M): a, b, c = list(map(int, input().split())) abc = list(sorted([a, b, c])) abc_set_list.append((a, b, c)) # abc_set_list = set(abc_set_list) for abc ...
b7d315603d50f3403afc96919dd8f0614bbc7041
komo-fr/AtCoder
/abc/144/b/main.py
223
3.625
4
#!/usr/bin/env python3 N = int(input().split()[0]) is_ok = False for x in range(1, 10): if N % x == 0: if 1 <= N // x <= 9: is_ok = True break ans = "Yes" if is_ok else "No" print(ans)
5fd40d8b13b664e623b4f86dad8691fef3be6d90
komo-fr/AtCoder
/agc/agc037/a/main.py
271
3.65625
4
#!/usr/bin/env python3 S = input() s_list = [] now_s = "" for i, char in enumerate(reversed(list(S))): if now_s + char not in s_list: now_s += char s_list.append(now_s) now_s = "" else: now_s += char ans = len(s_list) print(ans)
c7ac7fd26ce9ed8fb9eb25aff11c370b0ccf5acf
komo-fr/AtCoder
/past/past202005-open/f/main.py
570
3.703125
4
#!/usr/bin/env python3 N = int(input().split()[0]) s_table = [] for _ in range(N): s = set(list(input())) s_table.append(s) text = "" found_flag = True for i in range(N // 2): left = s_table[i] right = s_table[-(i + 1)] common = left & right if common: text += list(common)[0] els...
749b5cfc9a3ade54a24371ab975bcc7fd50df7f2
komo-fr/AtCoder
/agc/agc014/a/main.py
435
3.578125
4
#!/usr/bin/env python3 A, B, C = list(map(int, input().split())) def is_continue(x_list): for x in x_list: if x % 2 == 1: return False return True count = 0 while is_continue([A, B, C]): if A == B and B == C: count = -1 break a, b, c = A, B, C a = B // 2 + C...
821987201b41b1a3aa25532f3b82e3e936a5b4d2
komo-fr/AtCoder
/agc/agc003/a/main.py
260
3.625
4
#!/usr/bin/env python3 import collections S = input() c = collections.Counter(S) ans = "No" if (c["N"] > 0 and c["S"] > 0) or (c["N"] == 0 and c["S"] == 0): if (c["W"] > 0 and c["E"] > 0) or (c["W"] == 0 and c["E"] == 0): ans = "Yes" print(ans)
a38cbb263b8e8f152f0c49822ead89c1c46ab177
komo-fr/AtCoder
/arc/arc003/b/main.py
201
3.671875
4
#!/usr/bin/env python3 N = int(input().split()[0]) s_list = [] for _ in range(N): s = input() s = s[::-1] s_list.append(s) ans = "\n".join([s[::-1] for s in sorted(s_list)]) print(ans)
30c4b79bd09b9f560d329204b842f2772aaf8eae
komo-fr/AtCoder
/abc/025/c/c.py
1,811
3.59375
4
#!/usr/bin/env python max_score = 0 # 縦方向に一致していた場合の配点 b_table = [] for _ in range(2): b_list = list(map(int, input().split())) b_table.append(b_list) max_score += sum(b_list) # 横方向に一致していた場合の配点 c_table = [] for _ in range(3): c_list = list(map(int, input().split())) c_table.append(c_list) max_s...
8a822b8953da1cc2fc80e0efb9571a178c15f76d
komo-fr/AtCoder
/asakatsu/20210109/3/main.py
220
3.734375
4
#!/usr/bin/env python3 from collections import Counter S = input() count = 0 left_b_count = 0 for char in S: if char == "B": left_b_count += 1 else: count += left_b_count ans = count print(ans)
fabf59cfc6dd3f50028466a911ee1dd2dd069317
komo-fr/AtCoder
/abc/131/d.py
558
3.546875
4
# https://atcoder.jp/contests/abc131/tasks/abc131_d # D - Megalomania n = int(input().split()[0]) ab_list = [] is_ok = True for _ in range(n): a, b = list(map(int, input().split())) ab_list.append((a, b)) ab_list = sorted(ab_list, key=lambda x: x[1]) now_t = 0 is_ok = True for i, ab in enumerate(ab_list): ...
4e66d938f8e35ad8470f23f8e9f94ccbcaa7a9a2
trinhcanhphuc/code_wars
/increment_string.py
1,027
4.3125
4
""" Description: Your job is to write a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number. the number 1 should be appended to the new string. Examples: foo -> foo1 foobar23 -> foobar24...
036910be65adc89f17903581d972e3068e6987cd
jameskomo/Data-Structures-Algorithms-Implementations
/fstrings_classes.py
199
3.75
4
class A(object): def __init__(self, name, age): self.name=name self.age=age def sing(self): print(f"Hello, {self.name}. You are {self.age}.") p1=A("Tom", 30) f"{p1}"
892863b6d9975d7fe11f68e180c696d0b72916eb
jameskomo/Data-Structures-Algorithms-Implementations
/python_classes.py
751
3.96875
4
class Car: models="Toyota" def __init__(self, color, mileage): self.color=color self.mileage=mileage def __repr__(self): return f"The {self.color} has {self.mileage} miles" # INSTANCE METHOD def description(self): return f"I am a {self.color} Car" # CLASS METH...
828675f5cff2279916e005be5266a1ae7079aa32
AmeyAvhad/Wac-Winter-2020
/Day 3/Functions.py
3,318
4.28125
4
""" Functions def fun_name(para1, para2, ...) : statements return # optional """ # # this function will print hello world def hello_world() : print('hello, world') # hello_world() # to call a function # hello_world() # hello_world() # Function to welcome a user def hello_user(username) : print("he...
02b5ed57f3075f763866dbe9f1d47648c1573bc6
ckifonidis/chess_game
/chessboard.py
3,385
3.859375
4
from chess import * import copy class Chessboard: def __init__(self): self.board_dict = {} def _add_piece(self, pos, piece): self.board_dict[pos] = piece @property def king_pos(self): """ Property for returning the position of a king based on color. Closure ho...
78bd5e82c5e67bae3bceb0169f318e41d110219a
ckifonidis/chess_game
/chess/pawn.py
2,277
3.875
4
from chess.position import Position from chess.piece import Piece class Pawn(Piece): def default_rules(self): """ In any case for a pawn move to be considered valid the pawn must move to the next higher or lower rank depending on the pawn's colour. :return: boolean """ ...
cdd2a4e472720e08b0b7ea03fdceb2622f95527c
sladonia/comoutor-v1
/computor_v1/polynom/solver.py
2,999
3.703125
4
from math import sqrt class Solver: D_MESSAGE_POSITIVE = ('Discriminant is strictly positive,' ' the two solutions are:') D_MESSAGE_ZERO = 'Discriminant is zero, the solution is:' D_MESSAGE_NEGATIVE = ('Discriminant is negative,' ' the complex solutions...
35720d688614c42171c616ef89fade40c4c8606b
Captain02/LearningNotes
/python/code/lesson_03/07.练习.py
139
3.609375
4
# 1求100以内奇数和 i = 0; num = 0 while i <= 100: if i % 2 != 0: num += i i += 1 print("100以内奇数和为%d"%num)
89f9d8b262c83436defc145d88197e711ce43b75
Captain02/LearningNotes
/python/code/lesson_06/13类中的属性和方法.py
2,152
3.6875
4
#定义一个类 class A(object): # 类属性 # 实例属性 # 类方法 # 实例方法 # 静态方法 # 类属性,直接在类中定义的属性是类属性 # 类属性可以通过类或类的实例访问到 # 但是类属性只能通过类对象来修改,无法通过实例对象修改 count = 0 def __init__(self): #实例属性,通过实例对象添加的属性属于实例属性 #实例属性只能通过实例对象来访问和修改吗,类对象无法访问修改 self.name = '孙悟空' #实例方法 #在类中定义,...