blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
8b3ad6b46ad1693f72ac7e78e1cc3989889721b1
jan25/code_sorted
/leetcode/weekly163/1_shift_grid.py
568
3.71875
4
''' https://leetcode.com/contest/weekly-contest-163/problems/shift-2d-grid/ ''' class Solution: def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: n, m = len(grid), len(grid[0]) r = [[] for _ in range(n)] k %= (n * m) # treat grid as a flattened ...
aa3d6c986bdff216acbb1b913f2e35e8c5f21dc5
jan25/code_sorted
/leetcode/weekly168/3_max_occ_of_substrs.py
575
3.515625
4
''' https://leetcode.com/contest/weekly-contest-168/problems/maximum-number-of-occurrences-of-a-substring/ ''' class Solution: def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: max_c = 0 c = {} for i in range(0, len(s) - minSize + 1): current_s = s[i:...
834279e8959ee912ec3d142366c7f3f80f21176d
jan25/code_sorted
/leetcode/weekly163/3_sum_divisible_threes.py
1,210
3.625
4
''' https://leetcode.com/contest/weekly-contest-163/problems/greatest-sum-divisible-by-three/ ''' class Solution: def maxSumDivThree(self, nums: List[int]) -> int: # put nums into sorted remainder buckets b = [[] for _ in range(3)] nums.sort() for n in nums: b[n % 3].appe...
231ba12d25aa243173c4122fcc9f158f75f9547a
jan25/code_sorted
/leetcode/weekly177/2_validate_binary_tree.py
536
3.546875
4
''' https://leetcode.com/contest/weekly-contest-177/problems/validate-binary-tree-nodes/ ''' class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: seen = set() edges = 0 for i in range(n): l, r = leftChil...
364f8f81f838ccb1995a2908200c18c6da85bcfd
jan25/code_sorted
/leetcode/weekly181/3_grid_roads.py
1,727
3.71875
4
''' https://leetcode.com/contest/weekly-contest-181/problems/check-if-there-is-a-valid-path-in-a-grid/ DFS algorithm with checks of possible previous cells for a currently visiting cell ''' class Solution: def hasValidPath(self, grid: List[List[int]]) -> bool: pre = [None, (0, -1), (-1, 0), (0, -1), (0, 1)...
f673b24e2d34cb1d5b66db2c69460b4f40c9f470
jan25/code_sorted
/leetcode/weekly173/1_remove_subseq_palins.py
256
3.71875
4
''' https://leetcode.com/contest/weekly-contest-173/problems/remove-palindromic-subsequences/ ''' class Solution: def removePalindromeSub(self, s: str) -> int: if len(s) == 0: return 0 if s == s[::-1]: return 1 return 2
569b78a242c30db15beb7a6d3ab018058091824e
jan25/code_sorted
/leetcode/weekly155/1_abs_diff.py
416
3.765625
4
''' https://leetcode.com/contest/weekly-contest-155/problems/minimum-absolute-difference/ ''' class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() min_diff = 10**7 for i in range(1, len(arr)): min_diff = min(min_diff, arr[i] - arr[i - 1]) ...
d8fbbe107348901260e321b8b3872c4a0a88000f
jan25/code_sorted
/leetcode/weekly175/3_tweets_freq.py
1,642
3.53125
4
''' https://leetcode.com/contest/weekly-contest-175/problems/tweet-counts-per-frequency/ This is still unaccepted. No ideas whats wrong :( ''' from collections import defaultdict class TweetCounts: def __init__(self): self.per_min = {} self.per_sec = {} def recordTweet(self, tweetName: str, ...
3044dfccbf45b7ec5c743786e7e562e8ce641ae3
jan25/code_sorted
/leetcode/weekly181/3_longest_prefix_suffix.py
661
3.609375
4
''' https://leetcode.com/contest/weekly-contest-181/problems/longest-happy-prefix/ Algorithm: Construct longest prefix length for every possible string s[:i] This same prefix length array is used in KMP algorithm for pattern matching ''' class Solution: def longestPrefix(self, s: str) -> str: pre...
bfcefba16f48ec16e1da8f15169a4e4a7acd374e
7dongyuxiaotang/python_code
/study_7_20.py
1,290
3.921875
4
# 先定义类 驼峰体 class Student: # 1、变量的定义 stu_school = 'PUBG' def __init__(self, name, age, gender, course): self.stu_name = name self.stu_age = age self.stu_gender = gender self.sut_course = course # 2、 功能的定义 def tell_stu_info(self): pass def set_info(self)...
ecfec28ffd3b8e077a17af891e74133455c5548a
7dongyuxiaotang/python_code
/study_5_29.py
2,517
3.6875
4
# x = 10 # y = x # z = x # del x # 解除变量名x与值10的绑定关系,10的引用计数变为2 # # print(x) # print(y) # print(z) # # z=1324 再次赋值也可以使得引用计数减少 # 命名风格: # 1. 纯小写加下划线 # age_of_alex = 73 # print(age_of_alex) # # 2. 驼峰体 # AgeOfAlex = 73 # print(AgeOfAlex) # 变量值三个重要特征 # name ='GPNU' # id:反映的是变量值的内存地址,内存地址不同id则不同 # print(id(name)) # type:不同...
9b1c1c56bdd3f47af1d3e818c85ef9601180904a
7dongyuxiaotang/python_code
/study_7_23.py
1,687
4.21875
4
# class Parent1(object): # x = 1111 # # # class Parent2(object): # pass # # # class Sub1(Parent1): # 单继承 # pass # # # class Sub2(Parent1, Parent2): # 多继承 # pass # # # print(Sub1.x) # print(Sub1.__bases__) # print(Sub2.__bases__) # ps:在python2中有经典类与新式类之分 # 新式类:继承了object类的子类,以及该子类的子类 # 经典:没有继承object类的子...
814efde818fa56515e26396b7b9725543c5a2b05
Steven71111/Steven-s-Assignment4
/mapper.py
235
3.921875
4
#!/usr/bin/env python import sys for num in sys.stdin: num = int(num.strip()) if (num % 2) == 0: # num is even print("%s\t%s") % ("even", 1) else: # num is odd print("%s\t%s") % ("odd", 1)
e8ae0804c720e867b918992acf03bb7eafd6946f
falondarville/practicePython
/element.py
552
4.09375
4
# Write a function that takes an ordered list of numbers (a list where the elements are in order from smallest to largest) and another number. The function decides whether or not the given number is inside the list and returns (then prints) an appropriate boolean. items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] def check_...
3a281cfcad8aa72dc92fdec8b84fcd1b553b5f36
falondarville/practicePython
/listComprehension.py
217
3.890625
4
# Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it. a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] evens = [n for n in a if n % 2 == 0] print(evens)
57813ddd83679b08db0ca6b7d29ad27d25e32252
falondarville/practicePython
/birthday_dictionary/months.py
495
4.5625
5
# In the previous exercise we saved information about famous scientists’ names and birthdays to disk. In this exercise, load that JSON file from disk, extract the months of all the birthdays, and count how many scientists have a birthday in each month. import json from collections import Counter with open("info.json",...
9b505fd7c9d15fedb84b90c9c8443e791d8a9e61
falondarville/practicePython
/birthday_dictionary/json_bday.py
696
4.46875
4
# In the previous exercise we created a dictionary of famous scientists’ birthdays. In this exercise, modify your program from Part 1 to load the birthday dictionary from a JSON file on disk, rather than having the dictionary defined in the program. import json with open("info.json", "r") as f: info = json.load(f...
4e0ee7b43407043bf7a5bdb394be9c728833eb63
KrisNguyen135/Project-Euler
/solutions/p527.py
1,595
3.578125
4
from timeit import default_timer as timer from math import log def B(n): def recur_B(n): if n in result: return result[n] temp_result = 1 index1 = (n + 1) // 2 - 1 index2 = n - (n + 1) // 2 temp_result += (index1 * recur_B(index1) + index2 * recur_B(index2)) / n re...
66c5df684ff9f63f89daeb61bc8a84c9dd483cc2
SGNetworksIndia/J.A.R.V.I.S
/software/non_ai/greet_startup.py
566
3.75
4
from datetime import datetime ''' initiate greeting sequence to be played on jarvis startup ''' def greet(): greet_text = "" hour = int(datetime.now().hour) if hour >= 0 and hour < 12: greet_text = "Good Morning Sir. " elif hour >= 12 and hour < 18: greet_text = "Good Afternoon Sir. " else: greet_text = "...
c931dd02e26c57930e28b4925088cf7b3a7e301c
deepwzh/leetcode_practice
/8.py
1,017
3.5625
4
""" 思路:总体思路是通过正则匹配把源字符串分为三部分 比如字符串" abc1.23eee" 第一部分是" abc", 第二部分是"1",第三部分是".23eee" 对于第一部分,如果忽略前导空格后仍然包含乱起八糟的字符,则根据题意我们应该返回0 对于第二部分,需要注意的是为空时或者越界时返回0,另外,我们需要结合第一部分判断正负 对于第三部分,直接忽略即可 详细代码如下 """ class Solution: def myAtoi(self, str): """ :type str: str :rtype: int """ a,b,c =...
31e740f1b79e7be85fc5fb29ec52208cb9ae8bd6
deepwzh/leetcode_practice
/36.py
1,224
3.828125
4
class Solution: def __init__(self): self.board = None def validate_board(self, r, c, w): for i in range(w): u1 = dict() u2 = dict() for j in range(w): if self.board[i][j] == '.' or self.board[i][j] not in u1: u1[self.boar...
4164b823de5962f4b1e9958aec6908fb537b0e6a
deepwzh/leetcode_practice
/142.py
824
3.703125
4
""" 快慢指针,证明详见百度 """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ high = head ...
4042c26ff9de43ff3eb90f8c3c7fe3bf4e5ab59a
romainjayles/GAC_solver
/parser.py
1,814
3.578125
4
#! /usr/bin/python # -*- coding:utf-8 -*- import vertex class Parser: """ Allow to parse a path file """ def __init__(self, input_file): self.input_file = input_file self.vertex_list = [] self.number_of_verticle = None self.number_of_edge = None self.min_y = 0 self.max_y = 0 self.min_x = 0 self.max...
4f24d9446df29b4d6cbdca225764559bb6dfbc29
rymo90/kattis
/mixedfractions.py
314
3.703125
4
while True: numerator, denominator = map(int, input().split()) if numerator == 0 and denominator == 0: break else: holenum= numerator//denominator reminder= numerator%denominator mixFraction= str(reminder) + " / " + str(denominator) print(holenum, mixFraction)
a6208f4a6e4ea3d39dc1736bdf992fe26f309038
rymo90/kattis
/estimatingtheareaofacircle.py
292
3.609375
4
import math stop = False while not stop: r, m, c = map(float, input().split()) if r == 0 and m == 0 and c == 0: stop = True else: areaOne = math.pi * math.pow(r, 2) temp = (c / m) areaTwo = temp * math.pow(2 * r, 2) print(areaOne, areaTwo)
0252fdb9ed126aee248d59471c21f4c92763b6d4
rymo90/kattis
/stopwatch.py
309
3.546875
4
n = int(input()) suma= 0 fore = 0 if (n%2 == 0): i=0 while i < n: temp=int(input()) if i== 0: fore = temp else: suma =abs(fore-temp) fore = suma # print(fore,temp,i) i+=1 print(suma) else: print("still running")
990801ee689ee9f61e310c63be18e2eb57c472b0
rymo90/kattis
/greetings2.py
149
3.5
4
g = input() num = 0 s= "e" for _ in range(len(g)): if g[_] == "e": num += 1 sv = "".join([char*(num*2) for char in s]) print("h"+sv+"y")
aa7ea8fc5291d423e6e13a27a717661ae8d8965e
the-strawman/cspath-datastructures-capstone-project
/Soho-Restaurants-master/script.py
4,457
4.25
4
from trie import Trie from data import * from welcome import * from hashmap import HashMap from linkedlist import LinkedList # Printing the Welcome Message print_welcome() # Entering cuisine data food_types = Trie() eateries = HashMap(len(types)) for food in types: food_types.add(food) eateries.assign(food, L...
61234f3e7b500aeec9bcca947e9931514b0e793f
UndedInside/CodeExamples
/python/userInput.py
128
4
4
name = input("What is your name? ") if name == "Unded": print("Hello", name) else: print("Nice to meet you", name)
03515f7e841491e5a4679790eca1259a8c9bc083
zzy1120716/cs224n-zzy
/python-review/01-language-basics.py
3,949
3.875
4
def QuickSort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return QuickSort(left) + middle + QuickSort(right) # Brackets --> Indents def fib(n): # Ind...
5a63f6c803542ae7402e2e73ec4489b81f4a63fc
Tems-git/Python_advanced
/tuples_and_sets/02_students'_grades.py
1,355
3.8125
4
n = int(input()) students = {} for i in range(n): command = tuple(input().split()) name, grade = command grade = grade.format() if name not in students: students[name] = [] students[name].append(float(grade)) for key, value in students.items(): value_as_str = ["{:.2f}".fo...
128469770f49907a7cbb201ac9272c5776973caa
Tems-git/Python_advanced
/lists_as_stacks_and_queues/06e_balanced_parentheses.py
1,276
4
4
# parentheses = input() # stack = [] # # balanced = True # # for paren in parentheses: # if paren in "{[(": # stack.append(paren) # elif paren in "}])": # if stack: # open_paren = stack.pop() # # if paren == "}" and open_paren == "{": # # continue # ...
fe8c35b13ecc12fd043023795917be731beda765
alexdistasi/palindrome
/palindrome.py
937
4.375
4
#Author: Alex DiStasi #File: palindrome.py #Purpose: returns True if word is a palindrome and False if it is not def checkPalindrome(inputString): backwardsStr ="" #iterate through inputString backwards for i in range(len(inputString)-1,-1,-1): #create a reversed version of inputString ...
811e968599ff959fb84f372837f366e0ec1461a4
baixc1/course
/python/liaoxf/2/19.py
619
3.640625
4
import re def is_valid_email(addr): re_email = re.compile(r'^[a-zA-Z]+[a-zA-Z\.]*@[a-zA-Z\.]+[a-zA-Z]+$') if re.match(re_email, addr): return True else: return False def name_of_email(addr): re_name = re.compile(r'^(<(.*?)>)|((.*?)@).*') groups = re.match(re_name,addr).groups() ...
3b310b45ebd2535f2f70316663fa9bbb904da646
immzz/leetcode_solutions
/next permutation.py
802
3.6875
4
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ l = len(nums) - 2 while l >= 0 and nums[l] >= nums[l+1]: l -= 1 if l == -1: nums[:...
44f1c70ca31e90e7d3e49fb7b154f509e7c94a07
immzz/leetcode_solutions
/TreeTraversal.py
2,584
3.71875
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of integers def preorderTraversal(self, root): if root == None: r...
00e08a0512e2761c342a27005751a31d2b8aa672
immzz/leetcode_solutions
/LRU Cache.py
5,936
3.6875
4
class ListNode(object): def __init__(self,val,key): self.val = val self.key = key self.next = None self.prev = None class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.head = None self.tail = None ...
1ef57ca29b5604845c3323f087b3da14b000584c
immzz/leetcode_solutions
/surrounded regions.py
1,742
3.734375
4
class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ if not board: return for i in xrange(len(board)): if board[i][0] == 'O': se...
4979a47f2a05aee5dc531f8ecfa2415572df91d1
immzz/leetcode_solutions
/merge k sorted lists.py
1,075
3.84375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode[]} lists # @return {ListNode} # corner case: [[],[1]] def mergeKLists(self, lists): if not lists: ret...
a984cccd6ce2265f0f9e340f390f86c59a15a1db
immzz/leetcode_solutions
/closest binary search tree value II.py
1,396
3.703125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def closestKValues(self, root, target, k): """ :type root: TreeNode :type target: float :...
c1a842fa5839ec84dec4bfb7e496434ffae93b87
viegasdev/pong_game
/pong_game.py
3,871
4.125
4
# The famous and classic pong! # Made by viegasdev # Import modules import turtle import os # Inserting player names player_a = str(input("Insert player A name: ")) player_b = str(input("Insert player B name: ")) # Game window configuration window = turtle.Screen() window.title('Pong Game by viegasdev')...
7c348a55efae221b384611ade24f40141972d6d1
paul-yamaguchi/2021_forStudy
/11_01両端キュー.py
272
3.65625
4
from collections import deque #deque : double-ended que(両端キュー) D = deque() #空のキュー[]を作成 D.append("A") D.append("B") D.append("C") D.pop() #C:右端から削除された要素 D.popleft() #A:左端から削除された要素 print(D) #deque("B")
5efe4bf11b54fe0752c60821f291e4408c606067
paul-yamaguchi/2021_forStudy
/06_01分割統治法フィボナッチ.py
258
3.8125
4
def fib(n): if n < 2: return n else: a = fib(n - 1) #再帰的定義 b = fib(n - 2) c = a + b return c print(fib(5)) #この場合返り値cがあるので、ターミナルに表示するにはprintが必要
5b1f21a6426a4fc8bdbf0c29de9bf4fd2efe3687
paul-yamaguchi/2021_forStudy
/14_02ミニマックス法三目並べ.py
1,552
3.515625
4
def leaf(n): #盤面nで勝敗が決まっているか判定する return((triple(n, "0") and not triple(n, "X")) or (not triple(n, "0") and triple(n, "X") or ("_" not in n[0] + n[1] + n[2]))) def triple(n, p): #盤面nの中でpが縦横斜めに一列に揃っているかどうかを判定 for (a,b,c) in [(0,0,0), (1,1,1),(2,2,2),(0,1,2)]: if(n[a][0] == n[b][1] == n[c][2] == p or n[2]...
63cfd662441dee6c851b70171d7248cb227d4f76
jinwoo0710/python
/0528/threeSpuare.py
323
3.578125
4
# -*- coding: utf-8 -*- """ Created on Fri May 28 14:28:50 2021 @author: Mac_1 """ import turtle as t def drawRect(length): for i in range(4): t.forward(length) t.left(90) for i in range(-200,400,200): t.up() t.goto(i,0) t.down() drawRect(100) t.done(...
ea55381c9511f905b3216fc225880434796ea0d5
jinwoo0710/python
/0528/nPolyon.py
295
3.921875
4
# -*- coding: utf-8 -*- """ Created on Fri May 28 14:50:54 2021 @author: Mac_1 """ import turtle as t def n_polygon(n, length): for i in range(n): t.forward(length) t.left(360/n) for i in range(20): t.left(20) n_polygon(6, 100) t.done()
bb12347a447c97b331f87b0f5565350ed8262508
Viinu07/Python_Programming
/interiorangle.py
118
3.5625
4
a,b,c = input().split() a = int(a) b = int(b) c = int(c) sum = a+b+c if sum ==180: print("yes") else: print("no")
353b341eb43b497f5e6618cd93a7ac169e03ccb7
JennyCCDD/fighting_for_a_job
/LC 反转字符串.py
1,064
4.125
4
# -*- coding: utf-8 -*- """ @author: Mengxuan Chen @description: 反转字符串 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。 @revise log: 2021.01.11 创建程序 解题思路:双指针 """ class Solution(object): def reverseS...
209962037719fae0422ee5668dc3af4ce8a293cb
JennyCCDD/fighting_for_a_job
/LC 删除排序数组中的重复项.py
660
3.671875
4
# -*- coding: utf-8 -*- """ @author: Mengxuan Chen @description: 删除排序数组中的重复项 https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2gy9m/ @revise log: 2021.01.05 创建程序 """ class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int...
496c08f32796ccaf58688b36bf91548b7e0a4528
JennyCCDD/fighting_for_a_job
/LC 反转链表.py
744
3.796875
4
# -*- coding: utf-8 -*- """ @author: Mengxuan Chen @description: 反转链表 进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? @revise log: 2021.01.16 创建程序 2021.01.17 解题思路: # """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self....
639e5f0f5eef308239f53618d6d663956058799e
JennyCCDD/fighting_for_a_job
/LC 将有序数组转换为二叉搜索树.py
1,591
4.03125
4
# -*- coding: utf-8 -*- """ @author: Mengxuan Chen @description: 将有序数组转化为二叉搜索树 @revise log: 2021.02.09 创建程序 一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 中序遍历,总是选择中间位置右边的数字作为根节点 """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # ...
8ebfcdfeba3a5e2a8adc7f70ea6bf85a3e423e68
abrambueno1992/Intro-Python
/src/fileio.py
526
4.40625
4
# Use open to open file "foo.txt" for reading object2 = open('foo.txt', 'r') # Print all the lines in the file # print(object) # Close the file str = object2.read() print(str) object2.close() # Use open to open file "bar.txt" for writing obj_bar = open("bar.txt", 'w') # Use the write() method to write three lines to ...
4114af720b73a8e32cdf1870413fb4a6cbf2d166
EthanShapiro/PythonForDataScience
/Numpy/NumpyArrays.py
1,122
3.65625
4
import numpy as np my_list = [1,2,3] print(my_list) np_array = np.array(my_list) print(np_array) my_mat = [[1,2,3], [4,5,6], [7,8,9]] np_mat = np.array(my_mat) print(np_mat) print(np.arange(0, 10)) # returns a np array from 0-9 print(np.arange(0, 11, 2)) # returns a np array from 0-10 going by 2's print(np.zeros(...
aff920f0a7f70f361bc8104b5f996c7192f8c994
TMor1/Old-Python-Regex-Scripts
/MobileNumber.py
3,779
4.5
4
#! python3 #T.M 11/07/21 import sys, re print('This is a collection of 3 script\'s to verify or find a mobile number.\n\n') #===== Script 1 ===== #Develop a script to find a mobile number with the prefix XXX-XXXXXXX without using Regex #Included comments used to test script below print('Script 1'.center(...
b10d04f81038c8cbb44659ab948cc506c6a6fae8
DiegoFigueroa98/CursoPython
/HolaMundo.py
162
3.8125
4
a = int(input("Ingrese un número entero: ")) b = int(input("Ingrese un número entero: ")) c = a + b print(f"El resultado de la suma de {a} más {b} es: {c}")
6fe91047964236052658ccf013d70992eff27b65
DiegoFigueroa98/CursoPython
/Minijuego.py
457
3.53125
4
import random from random import randrange def iniciarJuego(): j1 = random.randint(1,6) j2 = random.randint(1,6) print(f"\nEl jugador 1 obtuvo {j1} puntos") print(f"\nEl jugador 2 obtuvo {j2} puntos") if j1>j2: print("\nEl ganador es el jugador 1") elif j1==j2: print("\nHubo u...
ba8d7a3ed6f25495a3a39622f004f0b4047e7866
mackmillar/static_dynamic_testing
/specs/card_game_tests.py
673
3.65625
4
import unittest from src.card import Card from src.card_game import CardGame class TestCardGame(unittest.TestCase): def setUp(self): self.card1 = Card("Hearts", 10) self.card2 = Card("Spades", 1) self.cardGame = CardGame() self.cards = [self.card1, self.card2] def test_ch...
f0342b0265c883d87ea58c750f0ca8c92d2d14b1
alexkursell/alexchat
/TCPSocket.py
3,012
3.796875
4
import socket from time import sleep from MySocket import MySocket class TCPSocket(MySocket): ''' A class that represents a TCP connection with a specified host. Wraps around an actual socket.socket, and implements send and receive methods for easier usage. ''' def __init__(self, ip, po...
e6b95f7637894d491a069276b5bb53ea4be830d5
snktagarwal/TCCodes
/codejam/EuroPython2011/monk.py
938
3.5625
4
def readNextInput(): cases = int(raw_input()) for i in range(cases): node = int(raw_input()) desc = raw_input().strip() [nodes, edges] = constructGraph(desc, node) print "Case #"+str(i+1)+": " for day in range(node): print findConnectedNodes(nodes, edges, day) def constructGraph(desc, n...
8397f17194679522c228d4765f805ec499c110a4
chenyapeng1/4-1
/函数九九乘法表.py
726
3.84375
4
#while语句的九九乘法表 # def chengfabiao(rows): # row=1 # while row<=rows: # col=1 # while col<=row: # print("%d*%d=%d" %(col,row,col*row), end="\t") # col+=1 # print("") # row+=1 # # chengfabiao(9) # chengfabiao(10) #for语句的九九乘法表 def stars(rows): start = 1; ...
54760b32ee5aa588d2b0ba5fd626da5308eacff6
jeeves990/tkinterTutorial
/tkinterTutorial/tkinterTutorial_1.py
1,661
3.765625
4
#!/usr/bin/env python3 """ ZetCode Tkinter e-book In this script , we change the default style for the label widget class. Author: Jan Bodnar Last modified: January 2016 Website: www.zetcode.com """ from tkinter import Tk, BOTH from tkinter.ttk import Frame , Label , Style, Entry class Example(Frame): def __init_...
81cb9114c1fdd16e8b12863531fdaf860080943b
udbhavkanth/Algorithms
/Find closest value in bst.py
1,756
4.21875
4
#in this question we have a bst and #a target value and we have to find # which value in the bst is closest #to our target value. #First we will assign a variable closest #give it some big value like infinity #LOGIC: #we will find the absolute value of (target-closest) And # (target - tree value) # if th...
b3860f1282d9658108ed63e184fa5528945c5d9e
baevres/fizz_buzz_projects
/FizzBuzz.py
1,550
4.0625
4
""" Read README.md for explaining about problems in realisation """ def fizz_buzz(string): """ At first function checks: has a string more than one words or not. Then 'string' will be converted to list which function checks by iterations. """ if ' ' in string: lst = string.lower().split(' ') else: lst = [s...
238d1756503e704ab2a91b06fe29d2b25ba5a8ea
BurningUnder/Learning-Python
/new_code/day01_to_day15/day05/craps_games.py
919
3.9375
4
""" Craps赌博游戏 游戏规则如下:玩家掷两个骰子,点数为1到6, 如果第一次点数和为7或11,则玩家胜, 如果点数和为2、3或12,则玩家输, 如果和为其它点数,则记录第一次的点数和,然后继续掷骰,直至点数和等于第一次掷出的点数和,则玩家胜, 如果在这之前掷出了点数和为7,则玩家输。 """ from random import randint a = randint(1,6) b = randint(1,6) sum = a + b print('和为%d' % sum) if sum == 7 or sum == 11: print('you win') elif su...
5783c75d4b94b3b0d55a37e28f63ddd1f6daa74f
edgardeng/python-data-science-days
/day06-numpy-array-function/index.py
3,429
3.65625
4
# day 6 Numpy Array Function import numpy as np import time from timeit import timeit np.random.seed(0) def compute_reciprocals(values): output = np.empty(len(values)) for i in range(len(values)): output[i] = 1.0 / values[i] return output # time loop # value1 = np.random.randint(1, 10, size=5) ...
8c22861d27a06ebe3270f6f21bf8f63a6947c2f4
ujjwal002/100daysofDSA
/day-1/array/reversal_algorithm.py
428
3.9375
4
def reverse_array(arr, start, end): while start<end: temp = arr[start] arr[start] = arr[end] arr[end] = temp start=start+1 end= end-1 def left_rotated(arr,d,n): if d == 0: return None d = d%n reverse_array(arr,0,d-1) reverse_array(arr,d,n-1) rever...
1846137f7bce8222b34daf7d60a3605f550303b5
daoge1205/python
/studentManage.py
1,582
3.78125
4
#!/usr/bin/python3.5 class studentManage: def __init__(self,student): """ menu为输入菜单选项的变量 并且每个class函数必须有一个self变量 """ if type(student) != type({}): print("构建存储的学生信息的存储结构有误,请使用字典结构") self.menu=-1 self.students=student def menuBook(self): print ("\n") print("***************") print("欢迎使用学生管理系统") ...
8de813f519101ad2723d7a51099696b33dcd5632
ammoyer/python-challenge
/PyPoll/Resources/main.py
1,679
3.5625
4
import os import csv electioncsv = os.path.join("PyPoll/Resources/election_data.csv") totalvotes = 0 candidate_votes = {} with open (electioncsv) as electiondata: reader = csv.reader(electiondata) header = next(electiondata) print(header) #The total number of votes cast for row in reader: ...
953fd68ee3c3f5be6a8359985cfd77f61019744b
turanoff/MRTI2920
/Lessons/Lesson 09-25/lsp_part_two.py
723
3.890625
4
class Engine: def __init__(self, max_speed): self.max_speed = max_speed def move_vehicle(self): print(f"moving at {self.max_speed} speed") class Vehicle: def __init__(self, name, engine): self.name = name self.engine = engine def move(self): self.engine.move_...
83ab50397f4bc5fc235735fea69a9781ebd9f1fd
turanoff/MRTI2920
/Lessons/Lesson 09-04/test.py
553
3.671875
4
class Hero: hp = 100 damage = 10 __test = "don't touch me" def get_test(self): return self.__test def __init__(self, name): self.name = name def __str__(self): return f"hero {self.name}" def __repr__(self): return f"hero object {self.name} {self.damage} ...
817b478a996ab1437ca35dbaee2a42999fc20593
turanoff/MRTI2920
/Tasks/Task1/furman.py
273
4.03125
4
a = int(input("Введите сумму (рубли): ")) b = int(input("Введите процет дипозита: ")) z = int(input("Введите срок дипозита (годы): ")) before = 100 * a after = int(before * (100 + z*b) / 100) print(after // 100)
5892c7fbaf8a41c575b37345f7ff97c049eabc48
GitaShaviraPratiwi/Pemrograman-Desktop-C
/NO1.py
412
3.609375
4
#Mencari nilai rata-rata dari beberapa data var1 = float(input("Masukkan data yang ke-1 = ")) var2 = float(input("Masukkan data yang ke-2 = ")) var3 = float(input("Masukkan data yang ke-3 = ")) var4 = float(input("Masukkan data yang ke-4 = ")) var5 = float(input("Masukkan data yang ke-5 = ")) n_var = 5 rata_...
7c0ede8af1b25fd43d39e7e3f36e0a3ab20e52f3
manavmishra96/ANN-on-Schrodinger-eqns
/train_the_nn.py
5,857
3.828125
4
""" Python code to train the Neural Network using numpy package. It is a pure pythonic code using no exclusive third party library functions """ import numpy as np import json import random as ra from matplotlib.pylab import * from load_data import load_data_nn training_data, validation_data = load_data_nn() class...
7ad8ffef03a979fb5a983ff577b93209f559c90e
brahmaduttan/ProgrammingLab-Python
/CO1/qn7-list-operations.py
395
3.625
4
lst1 = [6,9,3,5,7] lst2 = [9,6,4,2,0,7,2] print("lst1=",lst1) print("lst2=",lst2) a = len(lst1) b = len(lst2) if a == b: print("SAME LENGTH") else: print("NOT SAME LENGTH") s1 = sum(lst1) s2 = sum(lst2) if s1 == s2: print("SUM IS SAME") else: print("SUM IS NOT SAME") lst1 = set(lst1) lst2 = s...
d87cda127f8f239f689dc4e58a576fd046a2d2ee
brahmaduttan/ProgrammingLab-Python
/CO5/Q1.File_List.py
168
3.53125
4
newFile = open("text.txt","a") newFile.write("Python programming…! \n") newFile.close() readFile = open("text.txt","r") print(readFile.readlines()) readFile.close()
6dd094d3d9abf531dab180e297a75149f2a782b7
efarsarakis/keras-playground
/keras_cnn_example.py
1,809
3.984375
4
## Example from: ## https://elitedatascience.com/keras-tutorial-deep-learning-in-python#step-3 ## More accurate code can be found at : ## https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py import numpy as np np.random.seed(123) from keras.models import Sequential from keras.layers import...
88d8ea096c76aabe18875a33875c055b22afae3b
RaulVan/JustPythonCode
/day1.py
543
3.765625
4
__author__ = 'ElevenVan' # #if # # x=int(input("Plz enter an integer:")) # if x < 0: # x=0 # print("Negative changed to zero") # elif x==0: # print("zero") # elif x==1: # print("single") # else: # print("more") # # for # # a=['cat','windows','defebestrate'] # for x in a: # print(x,len(x)) # ...
b4daa28be288e7ac442f9237663bbf5b831cfb29
omritz/Decision-Tree
/decisionTree.py
9,204
3.671875
4
import pandas as pd import numpy as np import math from scipy.stats import chi2 """ This script build a decision tree from scratch by recursive functions and data frames from pandas, it is take a few seconds to build tree so please be patient """ class TreeNode(object): def __init__(self, attribut...
75f8d90d254d177a3a715e744c72b5422b971740
Nika1411/Laba5
/ind3.py
377
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Вариант 17 # Дано ошибочно написанное слово алигортм. Путем перемещения его букв получить слово # алгоритм. if __name__ == '__main__': s = 'алигортм' n = s.find('и') s = s[:n] + s[n+1:n+4] + s[n] + s[n+4:] print(s)
1a9052ff14cddd92a70f97d936caf7edf8dbe3bb
tiy-lv-python-2016-02/palindrome
/test_palindrome.py
807
3.703125
4
from unittest import TestCase from palindrome import palindrome class PalindromeTests(TestCase): def test_even(self): self.assertTrue(palindrome("toot")) def test_odd(self): self.assertTrue(palindrome("tot")) def test_simple(self): self.assertTrue(palindrome("stunt nuts")) ...
7ae09111a112f74117a7a8326845737b8129e790
shijiezhao/IBD_Biomarker
/Select_sequence.py
1,205
3.578125
4
""" Selecting sequences that begin with certain sequences """ from Bio import SeqIO import argparse, os # Read in arguments for the script def parse_args(): usage = "%prog -i INPUT_FASTA_FILE -s Sequence_to_select -o Output_FASTA" # Parse command line arguments parser = argparse.ArgumentParser() parser....
87a612aaf9e7ff1af6943808c5542097694ed5cf
thomasmorgan/Eden
/eden.py
4,026
3.625
4
"""The Eden app.""" from Tkinter import Frame, Tk from simulation import Simulation from ui import UI import utility from utility import log from operator import attrgetter import settings class EdenApp(): """The EdenApp class is the overall app. When it runs it creates two objects: The simulation, that...
3faa3caf5ce4178c897e5fca39866b1360564140
Tatnie/tatni
/les 5/5_5.py
318
3.53125
4
def gemiddelde(): willeukeurigezin=input('doe maar een zin') Allewoorden=willeukeurigezin.strip.()split() aantalwoorden=len(allewoorden) accumulator=0 for woord in allewoorden: accumulator += len(woord) print('De gemiddelde lengte van het aantal woorden in deze zin: {}'.format(gem))
f132e65fb3e884765ab28eded1b9ededdb09a1b1
artalukd/Data_Mining_Lab
/data-pre-processing/first.py
1,964
4.40625
4
#import statement https://pandas.pydata.org/pandas-docs/stable/dsintro.html import pandas as pd #loading dataset, read more at http://pandas.pydata.org/pandas-docs/stable/io.html#io-read-csv-table df = pd.read_csv("iris.data") #by default header is first row #df = pd.read_csv("iris.data", sep=",", names=["petal_...
9e836216cb7a71b753cd1eaafe53a92962f221ae
jshubham2304/c-program
/infix.py
1,105
3.515625
4
values=[] op=[] def opt(a1,a2,opp): if opp=='+': return a1 + a2 if opp=='-': return a1 - a2 if opp=='*': return a1 * a2 if opp=='/': return a1//a2 def check(op): if op in ('+','-'): return 1 elif op in ('*','/'): return 2 else: return 0 braces=['(','{','['] braces1=[']','}',')'] ...
9c11bc4989a14b64d65cb6df51c4b12de337108e
natac13/My-Projects
/GoFish/go_fish.py
8,224
4.125
4
# Project: Go Fish game vs computer. # By: Natac import random import sys import time suits = ['Spade', 'Heart', 'Club', 'Diamond'] values = list(map(str, range(2, 11))) + ['A', 'J', 'Q', 'K'] def make_deck(): '''Generate list of tuples, which are the card of a deck''' deck = [(rank, suit) for rank in value...
a11e94ed6d4a744bdba7e74cc02efd2a4205576d
sniperswang/dev
/leetcode/L401/test.py
1,812
4.0625
4
""" A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. 8 4 2 1 32 16 8 4 2 1 For example, the above binary watch reads "3:25". Given a non-negative integer ...
6019bb30ca868623718771b5ac2e3beeb96c3665
sniperswang/dev
/leetcode/L452/test.py
1,578
4.03125
4
""" There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller t...
b3a6e632568dd13f128eda2cba96293e2bd0d3cd
sniperswang/dev
/leetcode/L265/test.py
1,452
3.640625
4
""" There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is represented by a n x k ...
988dab09d39206865788bc0f8d7c3088b551b337
VictoriaEssex/Codio_Assignment_Contact_Book
/part_two.py
2,572
4.46875
4
#Define a main function and introduce the user to the contact book #The function is executed as a statement. def main(): print("Greetings! \nPlease make use of my contact book by completing the following steps: \na) Add three new contacts using the following format: Name : Number \nb) Make sure your contacts hav...
844b799722ef7c3e3ca6c01431c04663aa3f47d7
rkobismarck/dcp
/random/fibonacci.py
263
4.0625
4
""" Please calculate the first n numbers of a fibonacci series. n = 8 0,1,1,2,3,5,8,13 """ def fibonacci(n): if(n == 1): return 1 if(n == 0): return 0 return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(7))
c9679d4d03aaa0520d9d245a9289e4bf3b64b92f
MrMugiwara/RKE
/tools/scripts/manchester-encode.py
414
3.609375
4
#!/usr/bin/env python3 # # Applies manchester encoding to the given bitstream import sys import binascii data = binascii.unhexlify(sys.stdin.read().strip()) output = [] for byte in data: bits = format(byte, '0>8b') for c in bits: if c == '0': output.append('01') elif c == '1': ...
d6561bfc99721cd864195a426d59584a82f7b1a7
Jasonmes/Single_link_list
/Module_Use.py
1,179
3.609375
4
# def Modele(): # print("欢迎进入模块的世界") zhang = ["张三", 18, "man"] lisi = ["李四", 28, "female"] laowu = ["老五", 34, "gay"] feiwu = ["废物", 189, "freak"] # 全部名片 Lu = [zhang, lisi, laowu, feiwu] # 新建名片 def Creat_NewName(): New_One = [] newname = input("新的名字:") New_One.append(newname) newage = int(input("年...
90978c6cf43a6a450b95d84a7291e894819e1d78
jqdsouza/algos
/CTCI/python-sols/Chapter2/partition.py
1,272
4.09375
4
""" 2.4 Partition Write code to a parttion a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x. The partition element x can appear anywhere in the "right pa...
eefd7782ae06bcc6a738e2cc1a99bd2c199e2da6
RawatMeghna/BestPricedApartment_YouTube
/simple-linear-regression.py
1,889
3.53125
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.read_excel('apartment_prices.xlsx') ##df = df.set_index('Property') print(df.head()) price = df['Price'] #Prices of all apartments size = df['m2'] #Sizes of all apartments Property = df['Property'] #List of all properties apartments = [100...
757b60fbc021114cc77faa07b7e828a12ea00072
aholyoke/language_experiments
/python/Z_combinator.py
1,285
4.28125
4
# ~*~ encoding: utf-8 ~*~ # Implementation of recursive factorial using only lambdas # There are no recursive calls yet we achieve recursion using fixed point combinators # Y combinator # Unfortunately this will not work with applicative order reduction (Python), so we will use Z combinator # Y := λg.(λx.g (x x)) (λx....
a579cab53ea98d7711744ff818ed3fd90544268e
shrilakshmishastry/NN-Practice-models
/kannada_phonetically_similar_words.py
10,368
3.734375
4
#program to generate phonetically similar words of a given kannada word # input_word = input() # word = list(input_word) word_set = [] with open("converted_word.txt","r") as cv_file: # print(cv_file) stripped = (line for line in cv_file) # t = stripped.split(",") # print(t) for k in stripped: ...
6924c1a2527b8344c92a05788d34974e54079be3
luozhiping/leetcode
/middle/minesweeper.py
1,412
3.671875
4
# 529. 扫雷游戏 # https://leetcode-cn.com/problems/minesweeper/ class Solution(object): def updateBoard(self, board, click): """ :type board: List[List[str]] :type click: List[int] :rtype: List[List[str]] """ if board[click[0]][click[1]] == 'M': board[click[0...
7e07e839c0ec7167bbab93d54cf958b5376aa12d
luozhiping/leetcode
/middle/reverse_nodes_in_k_group.py
1,802
3.65625
4
# 25. k个一组翻转链表 # https://leetcode-cn.com/problems/reverse-nodes-in-k-group/ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseKGroup(self, head, k): """ :type head: ListNode ...
eba9799e6a330d640966f14db1762c4f9ad751eb
luozhiping/leetcode
/middle/longest_mountain_in_array.py
1,138
3.609375
4
# 845. 数组中的最长山脉 # https://leetcode-cn.com/problems/longest-mountain-in-array/ class Solution(object): def longestMountain(self, A): """ :type A: List[int] :rtype: int """ if not A: return 0 bpUp = [1 for _ in range(len(A))] bpDown = [1 for _ in ra...