blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b568c739e219902040273690c70dfe8d0c0878a6
OcanoMark/CodingBat
/Python/Warmup-2/06_array_count9.py
165
3.765625
4
# Given an array of ints, return the number of 9's in the array. def array_count9(nums): count = 0 for x in nums: if x == 9: count += 1 return count
b4e36d78ecb5311c7533b7dc2ec014141835b43f
OcanoMark/CodingBat
/Python/List-1/02_same_first_last.py
204
3.671875
4
# Given an array of ints, return True if the array is length 1 or more, # and the first element and the last element are equal. def same_first_last(nums): return (len(nums) > 0 and nums[0] == nums[-1])
5c60edabdd103e6e91d75c8d9264bc4ce26efff3
JoshPrim/ECG-Pipeline
/utils/extract_utils/extract_utils.py
5,604
3.515625
4
""" Authors: Nils Gumpfer, Joshua Prim Version: 0.1 Utils for extraction Copyright 2020 The Authors. All Rights Reserved. """ import pandas as pd import numpy as np import math import matplotlib.pyplot as plt from PyPDF2 import filters def rotate_origin_only(x, y, radians): """ rotates one point aro...
21a879184504a21bcc1d1208395c4787f0a830b7
dankar/orbit
/vector_math.py
2,498
3.515625
4
import math class vector: def __init__(self, _x, _y, _z): self.x = _x self.y = _y self.z = _z def magnitude(self): return math.sqrt(self.x*self.x + self.y*self.y + self.z*self.z) def __mul__(self, scalar): return vector(self.x * scalar, self.y * sca...
e0971671d262d7f8dca0975ed7e981b4316a111c
shouliang/Development
/Python/PythonFromZero/func_test5.py
717
3.921875
4
# 带参数的函数装饰器 # def tips(func): # def nei(a, b): # print('start') # func(a, b) # print('end') # # return nei # # # @tips # def add(a, b): # print(a + b) # # # @tips # def sub(a, b): # print(a - b) # # # add(2, 4) # sub(4, 1) # 再套上一层函数,就可以实现装饰器带参数 def new_tips(argv): def tips(...
7204d827818c599ea18fc04c0e0546c8185b024d
shouliang/Development
/Python/SwordOffer/last_remaining.py
516
3.59375
4
''' 题目: 0,1,...n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数字,求出这个圆圈里剩下的最后一个数字。 实质约瑟夫环的公式是: f(n, m) = 0           (n = 1) f(n, m) = [f(n-1, m) +m] % n  (n > 1) ''' class Solution: def LastRemaining_Solution(self, n, m): if n == 0 or m < 1: return -1 last = 0 for i in range(2, n + 1): ...
b835facf397b8652354829063ccc258ce9e240d8
shouliang/Development
/Python/PythonFromZero/func_test.py
1,852
4
4
# print('abc', end='\n\n') # print('abc', end='\n\n') # # # def func(a, b, c): # print('a = %s' % a) # print('b = %s' % b) # print('c = %s' % c) # # # func(1, 2, 3) # # # 关键字参数可以忽略参数顺序 # func(1, c=3, b=2) # 可变长参数 # def howlong(first, *other): # print(1 + len(other)) # # # howlong(3) # howlong(3, 4) # ...
1201c22b11346b91ded6f46f4dffc209ccb8ddc9
shouliang/Development
/Python/PythonBasic/var.py
430
4.25
4
# 变量只需被赋予某一值,不需要声明或者定义数据类型 # 建议使用四个空格来索引 i = 5 print(i) # 下面将发生错误,注意行首有一个空格 # print(i) i = i + 1 print(i) s = '''This is a multi-line string. This is the second line.''' print(s) # 显示行连接: 故结果为:This is a string. This continues the string s = 'This is a string. \ This continues the string ' print(s)
bfc96ee49c0bb9e9cf360b6e3de2f5e8e45869f5
shouliang/Development
/Python/PyDS/sort/n2/bubble_sort_02.py
343
3.796875
4
def bubbleSort(lyst): n = len(lyst) while n > 1: i = 1 while i < n: if lyst[i - 1] > lyst[i]: swap(lyst, i - 1, i) i = i + 1 n = n - 1 def swap(lyst, i, j): temp = lyst[i] lyst[i] = lyst[j] lyst[j] = temp lyst = [4,5,6,3,2,1] bubbl...
b6cdfd9d3ba190a3f5981e1fb7eb36a8f3320b2f
shouliang/Development
/Python/PythonFromZero/hello_world.py
263
3.890625
4
# 这是我的第一个Python程序 import time # 我导入的一个时间模块 print(time.time()) # 在屏幕上打印从1970年1月1日0:00 到现在经过了多少秒 if 10 - 9 > 0: # 这行需要缩进,缩进用4个空格ß print('10大于9')
0835269d04b5481cd556d9781a374f989cb9c03a
shouliang/Development
/Python/PythonBasic/ds_using_set.py
387
3.75
4
# 集合是简单对象的无序集合,涉及到数学中的基础集合知识,例如:子集、交集等 bri = set(['brazil', 'russia', 'india']) print('india in bri is', 'india' in bri) print('usa in bri is', 'usa' in bri) bric = bri.copy() bric.add('china') bric.issuperset(bri) print(bri) print(bric) bri.remove('russia') print(bri) print(bric) # 交集 print(bri & bric)
c41a4fee0dd3f42420d06c3ad5eecce0ec3d7161
shouliang/Development
/Python/PyDS/search/binary_search.py
1,199
3.921875
4
# coding=utf-8 # 二分查找: 返回的是待查找的值位于数组中的下标 # 依赖顺序表结构,即数组,针对有序数据; # 不太适用动态数组,因为插入删除都需要移动元素 # 不太适用数据小的数组,数据量少不如直接使用顺序查找 # 不太适用数据特别大的数组,因为需要使用连续的内存空间,太大内存可能不够分配 def binarySearch(nums, value): if not nums: return -1 low = 0 high = len(nums) - 1 # 循环终止条件是 low > high while low <= high: ...
6af58914d1e81c27ee24d70d37e242862cdbd787
shouliang/Development
/Python/SwordOffer/duplication_in_array_01.py
1,123
3.6875
4
# coding=utf-8 # 题目描述 # 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。 # 请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。 # 思路:通过Python对字典的key的存储方式为哈希表,其查找速度为O(1)。但以空间换时间,字典需要开辟额外的存储空间,具有较高的空间复杂度 class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False ...
910829db099d39d6237f9be3169a4cdb8c1f6ef3
shouliang/Development
/Python/PyDS/sort/logn/quick_sort_03.py
837
3.875
4
# coding=utf-8 # 通常做法 def partition(alist, low, high): middle = (low + high) // 2 pivot_value = alist[middle] swap(alist, middle, high) # 两端向中间扫描,然后交换 while low < high: while low < high and alist[high] >= pivot_value: high -= 1 swap(alist, low, high) while low...
ad7a7319c79eeb44fc740e8f0345e8d69a30e499
shouliang/Development
/Python/LeetCode/ByteDance/155_min_stack.py
1,150
4
4
''' 最小栈 155. Min Stack:https://leetcode.com/problems/min-stack/ ''' import heapq class MinStack: def __init__(self): self.stack_data = [] # 存储数据的stack self.heap = [] # 小顶堆,维护min def push(self, x): self.stack_data.append(x) # 正常push heapq.heappush(self.heap, x) # ...
874b07ebb6a73f8e35f3a349e04a4b4936b764bc
shouliang/Development
/Python/SwordOffer/is_symmetrical_in_binary_tree.py
1,444
3.75
4
# coding=utf-8 ''' 请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。 思路:(设二叉树左子树为,右子树为root2,root1、root2均指向左右子树的根) 递归:root1和root2的值相等,并且root1的左子树与root2的右子树对称,root1的右子树与root2的左子树对称 ''' # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None c...
cd3d022d29d9a9b4e80c9b0d2bd2d36dc61d812e
shouliang/Development
/Python/SwordOffer/print_from_top_to_bottom_in_tree_01.py
1,555
4.15625
4
# coding=utf-8 ''' 题目描述: 不分行按层次打印二叉树: 结果放在一维数组中 从上往下打印出二叉树的每个节点,同层节点从左至右打印 思路:使用双向队列完成。访问节点将其压入队列,在出队列的同时判断是否有左右子树,有的话将其分别进入队列,直到队列为空 ''' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFr...
e19faad96bc5dc9563f592b189047b205d7bc5e7
shouliang/Development
/Python/LeetCode/ByteDance/14_longest_common_prefix.py
1,485
3.796875
4
''' 最长公共前缀 14. Longest Common Prefix:https://leetcode.com/problems/longest-common-prefix/ ''' class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return "" return longestCommonPrefix_helper(strs, 0...
da983b9acb4a4b274937a23ed93b8ba988cdbba5
shouliang/Development
/Python/SwordOffer/tree_depth.py
995
4.125
4
# coding=utf-8 ''' 题目描述 输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 ''' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def TreeDepth(self, pRoot): if not pRoot: return 0 print(pRoot.val)...
05a1cbea357573b314ce1b467c6a8d23dfc91b84
shouliang/Development
/Python/PythonBasic/str_format.py
1,083
4.3125
4
# coding=utf-8 # 字符串是不可变的 # 一串字符串是字符的序列 age = 20 name = 'Swaroop' # 索引是从0开始计数,以此类推 print('{0} was {1} years old when he wrote this book'.format(name, age)) print('Why is {0} playing with that python?'.format(name)) # 索引是一个可选项 print('{} was {} years old when he wrote this book'.format(name, age)) print('Why is {} play...
20649fb28fb2bee6dda3c5b69f57093c976b4e2d
shouliang/Development
/Python/PyDS/graph/bfs_02.py
639
4.125
4
# https://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/ # 广度优先搜索 def bfs(graph, start): visited, queue = set(), [] visited.add(start) queue.append(start) while queue: vertex = queue.pop(0) print(vertex) for i in graph[vertex]: if i not in...
269984689781231f4f11ece3c2458bfa21504aea
shouliang/Development
/Python/LeetCode/50_my_pow.py
660
3.8125
4
''' 求x的n次方 50. Pow(x, n):https://leetcode.com/problems/powx-n/ ''' class Solution: def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ # 处理n小于的情况 if n < 0: x = 1 / x n = -n pow = 1 while n: ...
89a3dd2d5d977a6c6ad380397b42faaffcd130a3
shouliang/Development
/Python/Scrapy/beautifulSoup/simple_more.py
1,336
3.890625
4
from bs4 import BeautifulSoup html = ''' <html><head><title>The Dormouse's story</title></head> <body> <p class="title" name="dormouse"><b> The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http:example.com/elsie" class="sister" id="link1"><!-...
992c9024e4f2d0bd4576be4f33505a668cda1165
shouliang/Development
/Python/SwordOffer/power.py
1,349
4.34375
4
# coding=utf-8 ''' 需要注意的地方: 当指数为负数的时候 当底数为零切指数为负数的情况 在判断底数base是不是等于0的时候,不能直接写base==0, 因为计算机内表示小数时有误差,只能判断他们的差的绝对值是不是在一个很小的范围内 当n为偶数, a^n = a^(n/2) * a^(n/2) 当n为奇数, a^n = a^((n-1)/2) * a^((n-1)/2)) * a 利用右移一位运算代替除以2 利用位与运算代替了求余运算法%来判断一个数是奇数还是偶数 优化代码速度 ''' class Solution: def Power(self, base, exponent): if...
3c1b311d02211bb08bdd94372cca6e663346bf05
shouliang/Development
/Python/LeetCode/242_isAnagram.py
1,430
3.609375
4
''' 有效字母的异位词 242. Valid Anagram:https://leetcode.com/problems/valid-anagram/description/ 思路:利用两个哈希表分别记录两个字符串中每个字母的数量,然后再判断这两个哈希表是否相等 ''' class Solution: def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ hash_map1, hash_map2 = {}, {} ...
072fad1f881fafca5e0035c9dee4583a3fadba19
shouliang/Development
/Python/LeetCode/ByteDance/148_linked_lists_sort.py
1,667
4.03125
4
''' 排序链表 148. Sort List:https://leetcode.com/problems/sort-list/ 解释: 在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。 示例 1: 输入: 4->2->1->3 输出: 1->2->3->4 示例 2: 输入: -1->5->3->4->0 输出: -1->0->3->4->5 ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # se...
0e3484d5696c911cc3e0cd0ac1f9ec31879da76b
shouliang/Development
/Python/PyDS/sort/logn/quick_sort_02.py
419
4.0625
4
# coding=utf-8 # 有辅助数组的做法 def quick_sort(array): if not array: return [] less,greater = [],[] pivot_value = array.pop() for value in array: if value < pivot_value: less.append(value) else: greater.append(value) return quick_sort(less) + [pivot_value...
1e612f0df8db03f52712b59fbb1a90a3adf264ad
shouliang/Development
/Python/LeetCode/ByteDance/160_get_intersection_node.py
1,202
3.6875
4
''' 160. Intersection of Two Linked Lists: https://leetcode.com/problems/intersection-of-two-linked-lists/ 思路1:把a、b链表弄成等长,然后一起遍历,最先相等的结点就是交点。 思路2:双指针法: ListB + ListA = Bb + intersection + A + intersection 用大A表示ListA里面非共有 Bb表示listB里面非共有的,可以看到在第二个intersection的开头两个链表长度是一样的,必然相等 ...
353561bf33b0ec90193de7888bc94149f3d5d59a
shouliang/Development
/Python/LeetCode/ByteDance/2_add_two_numbers.py
2,719
3.84375
4
''' 求两数之和 2. Add Two Numbers:https://leetcode.com/problems/add-two-numbers/ ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2:...
17ffd5423b8b59cd895dc13d87db2ae07aed4151
munen56/developpez_exo
/developpez_exo/numero6.py
332
3.875
4
n = int(input("Entrez un entier strictement positif :")) while n < 1: n = int(input("Entrez un entier STRICTEMENT POSITIF, s.v.p. :")) div = [] for i in range(2,n): if n%i == 0: div.append(i) if not div: print(n, "est premier") else : print("diviseur propre de 12", div, "soit %s diviseurs" ...
fdd5ddd6913f364e7c8d5b0b2837669a548f01b1
malayandi/paperclip-staple-game
/game.py
1,921
3.859375
4
import numpy as np class Game: """ The Game class defines the dynamics of the game and contains the specific parameters of the game being played. """ def __init__(self, _theta, _num_objects, _human_prod_cap, _robot_prod_cap, _delta): """ Initializes an instance of the Game c...
650634a1b73ff4007bc11e06c09b3155cae746ed
DrCarolineClark/CtCI-6th-Edition
/Python/Chapter 1/13URLify.py
710
3.53125
4
import unittest #O(N) def URLify(string, length): count=len(string)-1 out=list(string) for i in range(length-1,-1,-1): if out[i]==" ": out[count] = "0" out[count-1] = "2" out[count-2] = "%" count-=3 else: out[count] = string[i] ...
6686ed532f42bfc7fd5b857760ea4f5959d76bbb
InjiChoi/pirogramming13
/파이썬 과제/Unit_19/star.py
219
4.0625
4
height = int(input()) blank = height -1 for i in range(height): for j in range(height+i): if j<blank: print(' ',end='') else: print('*',end='') print() blank= blank-1
1ba615a345ff370cde99d102842666da96dea953
shoot-tree-search/sts
/alpacka/networks/keras.py
7,769
3.578125
4
"""Network interface implementation using the Keras framework.""" import functools import gin import numpy as np import tensorflow as tf from tensorflow import keras from alpacka import data from alpacka.networks import core def _make_inputs(input_signature): """Initializes keras.Input layers for a given signa...
4151fc703cbf33b5068dea65b037ff951101582f
justinattw/HackAssembler
/Assembler/Assembler.py
9,904
4
4
#!/usr/bin/env python3 import sys from typing import List from SymbolTable import SymbolTable from Parser import Parser from Code import Code class Assembler: """ The Assembler class contains the main logic of the Hack Assembler. """ def __init__(self): self.symbol_address = 16 self...
d0a6a5d7bbaefa7c4f41d31ff2ec7f3ecdf1c826
brainsz/algorithms_py
/offer6.py
878
3.90625
4
#coding=utf-8 ''' 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 ''' class Node: def __init__(self,data,left,right): self.data=data self.left=left self.right=right def construct_tree(pre_order,mid_order): #递归出口条件 if len(pre_order)==0: return None #前序的第一个节点...
1a4603dbdd5f031586a0aefe76b99fb1f7b61ce4
brainsz/algorithms_py
/508. Most Frequent Subtree Sum.py
1,906
4.09375
4
#coding=utf-8 """ <<<<<<< HEAD Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie...
32f5e134fe17740a5dcaa123968321454f657ef9
brainsz/algorithms_py
/offer15.py
1,284
3.625
4
#coding=utf-8 ''' ''' class Node(object): def __init__(self,val,p=0): self.data=val self.next=p class LinkList(object): def __init__(self): self.head=0 #初始化链表 def initLinkList(self,data): # 初始化链表 self.head = Node(0) p = self.head for i in data: ...
1add1ef63bf57d321d919fa61f6912c4d6be4f7b
Jonasfg1319/sequenciaCrscente.py
/sequenciaCrescente.py
2,684
3.734375
4
def sequencia_crescente(lista): #variavel que vai verificar se o valor atual no laço é menor que o próximo resultado = "" #variavel que vai definir se a lista pode ou não ser uma sequência crescente condicao = "false" #verificação inicial, se a lista tiver apenas um elemento o resultado será true if(len(li...
164cfbe766429aa6b1bc362937b2d2736d0e3c03
alexh13/practicing-using-pandas
/data-extraction.py
696
4.1875
4
# use jupyter notebook or ipython in terminal import pandas df1 = pandas.read_json("supermarkets.json") # read json file print(df1) # get in the habit of applying new variables when changing existing data frames df2 = df1.set_index("Address") # set index to the address, change that variable print(df2) # to slice ...
c9d0f8b842cb43d0202e52b2df41bdb0713c2cef
Nvardharutyunyan/group-sudo
/nvard/python/#3/evenDiv.py
87
3.609375
4
#!/usr/bin/env python3 list = [i // 2 for i in range(1, 11) if i % 2 == 0] print(list)
2020401264c3871b63272a9f7ead83dc739693d9
Nvardharutyunyan/group-sudo
/nvard/python/#4/shapeClass.py
1,450
4.25
4
#!/usr/bin/env python3 import math class Shape(object) : def __eq__(self, other) : return self.area() == other.area() def __lt__(self, other) : return self.circum() < other.circum() class Rectangle(Shape) : def __init__(self, length, width) : self.length = length self.width =...
482fe2ccda729035a82fe405b9580f73b6fd907f
Nvardharutyunyan/group-sudo
/nvard/python/#3/pythagore.py
157
3.59375
4
#!/usr/bin/env python3 list = [(i, j, k) for i in range(1, 28) for j in range(i + 1, 29) for k in range(i + 2, 30) if k ** 2 == i ** 2 + j ** 2] print(list)
daa48f206bf4a493130e42b78dc62b5096570a9d
Nvardharutyunyan/group-sudo
/nvard/python/#1/palindrom.py
292
4.28125
4
#!/usr/bin/env python3 word = input("Write the word : ") palindrom = 1 length = len(word) for i in word : if i == word[length -1] : length -= 1 else : palindrom = 0 if palindrom == 1 : print ("Word is palindrom") else : print ("Word is not palindrom")
cd0167d0da169f20403b88f6f0222aadb24eb36c
Ivan-Widjanarko/OneWayHash
/oneWayHash.py
3,491
3.53125
4
# import the library import os # for clearConsole() import sys # for sleepTime() and exit() import time # for timeSleep() import hashlib # for md5Function() and sha1Function() def menu(): """Display the hashing menu""" print(""" Please choose the Hashing Methods below \t0....
6d5c37a4f6b63a8a920d5ccd9e549126a83f7ce0
UCLALibrary/sinai_metadata
/scripts/utilities/rm_leading_zeros.py
1,206
3.703125
4
import os import csv import re # Prompt the user to input the directory path where the CSV files are located directory_path = input("Enter the directory path: ") # Define a regular expression pattern to match "f. " followed by anything up to the first number between 1 and 9 pattern = r"(f\.\s*)([^1-9]*)([1-9])" # Lo...
f16bc5b5d939c8807e6a833aa330e8db749ed3aa
UCLALibrary/sinai_metadata
/scripts/utilities/csv_merge.py
327
3.578125
4
import pandas as pd # Load the CSV files into dataframes df1 = pd.read_csv("file1.csv") df2 = pd.read_csv("file2.csv") # Merge the dataframes using the "filename" column as a key merged_df = pd.merge(df1, df2, on="key", how="outer") # Write the merged dataframe to a new CSV file merged_df.to_csv("merged.csv", index=...
c7682583d4cc811fa085a861b34ceb5808265373
RP-Eswar/SortAlgo
/Selection_sort.py
1,029
4.34375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: ''' This is an approach to solve : Write a function selection_sort(mylist) that takes a list of numbers and sorts it using the selection sort algorithm. You can read about the selection sort algorithm online - here is one resource (https://www.hackerearth.com/practice/a...
40d940c35ae353f876e6149dd638f53f1e5c0403
tejalgajare/Projects
/ITMD513 - Open Source Programming/workspace/MP3/MiniProject3/task.py
1,521
3.734375
4
''' Created on Jul 14, 2013 @author: tejalgajare ''' import datetime,time #Create a class Task having three attributes: task_id,time_stamp and description... class Task: task_id=0 time_stamp='' description='' def __init__(self,timestamp ,description): #Define a __init__ method for objec...
31bc6712c5c613a98bd170a8e6f85ba826516898
danathughes/pyNeuralNetwork
/CRBM/digits.py
1,807
3.6875
4
from Tkinter import * def load_digits(filename): """ """ f = open(filename, 'r') # We'll return a list of digit vectors and class vectors digits = [] classes = [] # Loop through while f.readline(): # Just the instance name - unused # The next 14 lines indicate a new digit ...
5e5e99a423bf02a6a553d22c6e8670955ddd2256
nathancoulson/micro-app-3-bbk
/app_3_func.py
1,176
3.53125
4
import random import math def list_gen(num): num_list = [] for i in range(num*5): num_list.append(random.randint(num, num*5)) return num_list def partition(array, begin, end): pivot_idx = begin for i in range(begin+1, end+1): if array[i] <= array[begin]: pivot_idx += ...
2c95787698f73c7aa27cfbefebb57070065265f3
anthonyanader/BrainMatrixGame
/BrainMatrixGame.py
6,343
4
4
import random def create_board(size): '''int->(list of str) Precondition: size is even positive integer between 2 and 52 ''' if size % 2 == 0 and size > 1 and size < 53: board = [None]*size letter='A' for i in range(len(board)//2): ...
e38f4456869e73aa55f3cbcfe3e89692fe0f0fe0
iriswang02/leetcode-practice
/solutions/removeNthNodeFromEndOfList-19/removeNthNodeFromEndOfList-19.py
702
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 removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: curr = head l = 0 while curr: curr = ...
fae3570c9e3a23f7dc1715e1bdedde60ecaf43eb
doublevcodes/gravitron
/tokens/integer.py
2,417
3.96875
4
from tokens.string import String class Integer: def __init__(self, val: int, base: int) -> None: """ Represents the primitive integer object. :param val: The numeric value that the primitive Integer object represents. :type val: int. :param base: The base of the numeric o...
920bf25a3ce3173a40a68aca975a3f479f385cef
nutcheer/pythonlearning
/pr6_1.py
238
3.828125
4
names = { 'first_name': 'mclean', 'last_name': 'tiffany', 'age': '20', 'city': 'Berlin', } print(names['first_name']+" "+names['last_name']+" is "+ names['age']+" years old now and she lives in " + names['city'])
0c16cb1aa6a0abe7549b689493729f1f3bd60fd6
nutcheer/pythonlearning
/pr10_8.py
363
3.5625
4
filename1 = "cats.txt" filename2 = "dogs.txt" try: with open(filename1) as f_obj1: content1 = f_obj1.read() except FileNotFoundError: print("Can not find " + filename1) else: print(content1.strip()) try: with open(filename2) as f_obj2: content2 = f_obj2.read() except FileNotFoundError: print("Can not find " ...
3d0cd4779be7d7313ede1dc1b382e04a72429b1c
nutcheer/pythonlearning
/pr7_4.py
182
4.25
4
pizza = input("Please enter some items of pizza:") while pizza != 'quit': print("We will add the "+pizza+" to the pizza!") pizza = input("Please enter some items of pizza:")
9c7b457275d196b7bd91e971155b6dfe2504532d
nutcheer/pythonlearning
/pr7_1.py
90
3.703125
4
car = input("Which car do you want to get?") print("Let me see if I can find you a "+car)
fabc6f32877bfe3c9a2bd237d88fdceea65017f5
nutcheer/pythonlearning
/motorcycles.py
1,395
4
4
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles[0] = 'ducati' print(motorcycles) motorcycles[0] = 'honda' motorcycles.append('ducati') print(motorcycles) motorcycles = [] motorcycles.append('honda') motorcycles.append('yamaha') motorcycles.append('suzuki') print(motorcycles) motorcycles ...
0e5791997af89b32471171f6a9c57ac74468fc86
nutcheer/pythonlearning
/pr6_9.py
231
3.671875
4
favorite_places = { 'tiffany': ['1', '2', '3'], 'einstein': ['4', '5'], 'nutcheer': ['6', '7', '8'], } for name, places in favorite_places.items(): print(name+":") for place in places: print("\t"+place)
5ad5a53c30371092c3a6dddab3d9fed7aa55a5d8
nutcheer/pythonlearning
/pr9_11_import.py
1,051
3.671875
4
class User(): def __init__(self, first_name, last_name): self.first = first_name.title() self.last = last_name.title() self.login_attempts = 0 def describe_user(self): print(self.first + " " + self.last) print(self.login_attempts) def greet_user(self): ...
b21e7e434b8a8ea50fa1b75ac99b72165e6891e1
LuiggySilva/python-haskell-prolog-cpp
/perceptron/perceptron-python/perceptron.py
2,079
3.53125
4
import pandas as pd import numpy as np class Perceptron: def __init__(self, number_of_inputs, epochs=100, learning_rate=0.01): self.epochs = epochs self.learning_rate = learning_rate self.weights = np.zeros(number_of_inputs) self.bias = np.zeros(1) def predict(self,...
794a5f8d9428fb1e17ce23076c0deff8f6467c92
Searge/DiveinPython
/w_1/game.py
654
3.828125
4
import random number = random.randint(0, 101) print("Вгадайте число від 0 до 100") print("Для того, щоб вийти, введіть: q") while True: answer = input("Введіть число: ") if not answer or answer == "q": break if not answer.isdigit(): print("Введіть правильне число") continue ...
82a2a7d0995ee4aca8ab30f7b50a94d70a2eadf2
Searge/DiveinPython
/w_5/playground/iterator_.py
504
3.9375
4
class MyRangeIterator: def __init__(self, top): self.top = top self.current = 0 def __iter__(self): return self def __next__(self): if self.current >= self.top: raise StopIteration current = self.current self.current += 1 return current ...
332b5f9014c0e0807c3f9020d19990d73f7cf83d
wata-pon/Python_basicA
/A-6.py
82
3.546875
4
odd_numbers = [1, 3, 5, 7, 9] for odd_number in odd_numbers: print(odd_number)
9f808a06c160c56e471132fa8e3d8f2e4c85da78
AasthaGoyal/Rock-Paper-Scissor-Game-
/prog_2.py
1,134
3.9375
4
import os import sys import re #mylist = [] count =0 try_count = 1 mylist= input("Enter the password:") count = len(mylist) if (try_count<=7): if(count>=5 and count<=10): pass else: print("The password should have minimum 5 characters and maximum 10 characters") #phrase = ...
6b9d8d25fe6eb96a7bcbbabba43ca2ed3c6fd303
gkedts/annotation-utilities
/anno_checker.py
9,372
3.6875
4
#!/user/bin/python import sys class Sentence(object): def __init__(self, numbered_lines): self.lines = filter(lambda l: l != None, map(Line.parse_numbered_line,numbered_lines)) def __str__(self): return " ".join(map(lambda line: line.word, self.nlines)) def validate(self): if self...
a43d72b157083001065ed2ab4bfc1d81e066267d
BeautterLife/Algorithms
/kakao/2019겨울인턴/크레인인형뽑기게임.py
546
3.53125
4
""" board를 90도 회전하면 for i in board: for doll in i: ~~ 로 접근할 수 있을 듯 """ def solution(board, moves): answer = 0 stack = [] arrLen = len(board) for move in moves: for i in range(arrLen): if board[i][move-1] !=0: stack.append(board[i][move-1]) ...
8495fe6967193a89793aaa21ee4c1a7f3ea42539
juangagz/tarea2
/fibonacci.py
200
3.6875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def fib(n): # escribe la serie de Fibonacci hasta n """Escribe la serie de Fibonacci hasta n""" a, b = 0, 1 while b < n: print b, a, b = b, a+b
40ea99f29a7da433e699ebedc70fe79296e9d50a
MaxwellMGomes/Python_Cisco
/2.1.1.19 LAB.py
2,128
4.0625
4
print("Programming","Essentials","in ",end='',sep='*') print("Python") def seta_padrao(): print(" *") print(" * *") print(" * *") print(" * *") print("*** ***") print(" * *") print(" * *") print(" *****") print() def multi_seta(): qset = int(input ('Quan...
3c1799bfc46cca415837fa5ec20cf08c7dab51af
shemjabasteen/POS-
/pos tagging.py
491
3.75
4
from collections import Counter import nltk #text=input("Enter your input:") f=open("sample.txt", "r") if f.mode == 'r': text =f.read() print(text) lower_case = text.lower() tokens = nltk.word_tokenize(lower_case) tags = nltk.pos_tag(tokens) counts = Counter( tag for word, tag in tags) print(counts)...
0a704c14dec3771c84aca8043c87b0d45a5d272f
Renujoshi29/TCSXplore-CPA-python
/movie.py
2,195
3.734375
4
class Movie: def __init__(self, movie_id, movie_name, ticket_cost, cost_category="Default" ): self.movie_id = movie_id self.movie_name = movie_name self.ticket_cost = ticket_cost self.cost_category = cost_category def Price_category(self): if self.ticket_cost>0 and self....
33c730b5980005ebfb46e05a51330841000975e3
sinitsa2001/h_work
/Lesson1/Home1.2.py
699
4.21875
4
#2. Пользователь вводит время в секундах. # Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. # Используйте форматирование строк. user_time = int(input("Введите время в секундах: ")) hour = str(user_time//3600) minute = (user_time//60)%60 second = user_time % 60 if minute<10: minute = ("0"+ ...
cdd0b6f44875703dfbe7206d275f8286f4fb7691
sinitsa2001/h_work
/lesson3/hw 3.5.py
1,482
4.0625
4
#Программа запрашивает у пользователя строку чисел, разделенных пробелом. # При нажатии Enter должна выводиться сумма чисел. # Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. # Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. # Но если вместо числа вводится с...
c814b6615bdfbe2095e9681e90314e7ae7775913
rvarsha180/Python_Learning
/st.py
191
3.5625
4
a = raw_input("enter a string") l=[] for i in a: if i != "=" and i != ";": l.append(i) print l t=[] for i in range(len(l)): if i>0 and i%2==1: t.append(((l[i-1]),(l[i]))) print t
07ab4039995cc7f99dde26c61b90e3ea3cdf02bf
kendrarepo/SI206
/kjrepoHW3/twitterhw3b.py
1,184
3.65625
4
# In this assignment you must do a Twitter search on any term # of your choice. # Deliverables: # 1) Print each tweet # 2) Print the average subjectivity of the results # 3) Print the average polarity of the results # Be prepared to change the search term during demo. import tweepy from textblob import TextBlob # Un...
f6a261f2e65987322ee8a63c5e1fb28e75be036e
KubilayAkyildiz/veri-yapilari
/python/SiralamaAlgoritmalari/siralama_algoritmalari.py
1,602
3.53125
4
class SiralamaAlgoritmalari: def __init__(self): pass def _partition(self, array, low, high): # quick sort için pivot = array[high] i = low - 1 for j in range(low, high): if array[j] < pivot: i += 1 array[j], array[i] = array[i], arr...
6465df234a9b76ffe633276c5021227c842cdbfe
AYAN-AMBESH/learning-Python
/ex6.py
440
4.125
4
#Write a short Python function, minmax(data), that takes a sequence of #one or more numbers, and returns the smallest and largest numbers, in the #form of a tuple of length two. Do not use the built-in functions min or #max in implementing your solution. def minmax(data): data=(input("ENTER A:"),input("ENTER B:")) ...
13d69d2f3826f9a2a5c0554471c82ebc52a3ca80
AYAN-AMBESH/learning-Python
/ex20.py
295
4.25
4
# Write a Python program to get the difference between a given number and 17, # if the number is greater than 17 return double the absolute difference. def number(): x = 17 y = int(input("enter a number: ")) if y>17: return 2*abs(y-x) return (x-y) print(number())
981e91605ca7b3b9db2472038e09f32b8873c63a
uniquenikki/Decode-the-codon-python
/protein_translation.py
514
4.09375
4
S=input() myDict = {' Methionine': ['AUG'], 'Phenylalanine': ['UUU', 'UUC'], 'Leucine': ['UUA', 'UUG'], 'Serine': ['UCU', 'UCC', 'UCA','UCG ' ], 'Tyrosine': ['UAU', 'UAC'], 'Cysteine': ['UGU', 'UGC'], 'Tryptophan': ['UGG'], 'STOP': ['UAA', 'UAG', '...
5c92cacbdc6bea422c918e9986b59ddde24184c7
ryangzz/proyects-sphinx
/02ejemplo/source/sources/sumaLista.py
567
4.25
4
""" Suma de los elementos de una lista en python ============================================ En este modulo veras como podemos sumas los elementos que se encuentren dentro de una lista por medio de una funcion que recibe como parametro dicha lista """ def sumaLista(list): """ **Esta funcion recibe una lista y ...
3e5cf7e38150ab33b580249f6f019fa43ba62906
lekah/ML_course
/labs/ex05/template/least_squares.py
498
3.859375
4
# -*- coding: utf-8 -*- """Exercise 3. Least Square """ import numpy as np def least_squares(y, tx): """calculate the least squares.""" # *************************************************** # INSERT YOUR CODE HERE # least squares: TODO # returns mse, and optimal weights # *******************...
98c4493e4a4f926449a9b87b5e7fcc45b0dd63a9
neonexxa/ngram-nexxa
/nltksupport.py
210
3.796875
4
from nltk import ngrams sentence = 'this is a foo bar sentences and i want to ngramize it' n = 6 sixgrams = ngrams(sentence.split(), n) print(list(sixgrams)) # for grams in sixgrams: # print (grams)
3aeb18f6a0b08a8ae26e9feda585e523790a388b
lonelystag/code-kata
/len of int.py
73
3.8125
4
#to count the numbers in the given int input a=input() b=len(a) print(b)
33e17d1a74672408adbcf6802eb9265b0268f646
ruanramos/distributed-systems
/src/references/client.py
1,210
3.625
4
# servidor de echo: lado cliente import socket HOST = 'localhost' # maquina onde esta o servidor PORT = 9000 # porta que o servidor esta escutando def iniciaCliente(): '''Cria um socket de cliente e conecta-se ao servidor. Saida: socket criado''' # cria socket sock = socket.socket(socket.AF_INET, ...
1d91c0a599863dd370924bfebd547a508e84d020
andra23/Python-university_projects
/Car service/Domain/Transaction.py
2,704
3.59375
4
import datetime class Transaction(): """ Transaction business object. """ def __init__(self,id,idCar,idCard,sumaP,sumaM,date,hour,delete=None): ''' Creates a transaction. :param id: :param idCar: :param idCard: :param sumaP: :param sumaM: ...
5728f044dc85a2c65a3e4d559ff0ee3f727c5e3e
MiguelMR96/holberton-system_engineering-devops
/0x15-api/0-gather_data_from_an_API.py
1,376
3.609375
4
#!/usr/bin/python3 """ Using an example REST API extract some data for a given employee ID, returns information about his/her To-Do list progress """ from os import sys import requests if __name__ == "__main__": """ Gather data from API, request data filtered by id. Should give id when program runs ./0-ga...
75a7d15ea1a0aebc7bd02b233a55f3b18b1cf3e0
I-Dream-in-Code/CIS-210
/1/alphacode nonterminal.py
417
3.53125
4
CONSANANTS = "bcdfghjklmnpqrstvwyz" VOWELS = "aeiou" pincode =int( input("Enter PIN number ")) chunk_1 = pincode%100 new_pincode_1 = pincode//100 chunk_2 = new_pincode_1%100 consonant1 = CONSANANTS[chunk_1//5] vowel1 = VOWELS[chunk_1%5] consonant2 = CONSANANTS [chunk_2//5] vowel2 = VOWELS[chunk_2%5] pair1 = (conson...
90993c461337f276bb1578f763e83e3a1d54978f
emilioPonceAlvarado16/Automated-Word-document-with-python
/IOFunctions.py
358
3.609375
4
def file2list(filename): file=open(filename,encoding='UTF-8') str=file.read() lista=str.split('/') for element in lista: if element == "\n": lista.remove(element) elif element == "": lista.remove(element) elif element.isspace(): lista...
8865a2bee47cd9681cd3ff28efeb31860298db5f
terrylovesbird/budget
/modules/month.py
201
3.625
4
from enum import Enum # month enum class Month(Enum): JAN = 0 FEB = 1 MAR = 2 APR = 3 MAY = 4 JUN = 5 JUL = 6 AUG = 7 SEP = 8 OCT = 9 NOV = 10 DEC = 11
453a65a52552b8d8b0824f86423b33e8bb931047
JoshuaGeraghty-Smith/Poker
/player.py
674
3.890625
4
from dataclasses import dataclass, field from card import Hand, PokerHand from abc import ABC, abstractmethod @dataclass class Player(ABC): """ Abstract class for player entities, takes in an id and name on initialization, every player has a chip value and hand object. """ id: int name: str ...
9ba38bc14b58a35b596cf1079b1b22618ed2fa38
sbaxter95/Python-Programs
/ScoreRating.py
1,627
4.03125
4
def scores_to_rating(score_1, score_2, score_3, score_4, score_5): def convert_to_number(score): #Convert score to number converted_score = float(score) return converted_score def sum_of_middle_three(score_1, score_2, score_3, score_4, score_5): #Find the sum an...
052273cc85c8abcea2f9100d9c61ec2fdce42860
Prashant1806/PythonDataScience
/DataScience2.py
525
3.640625
4
import numpy as np import pandas as pd # Create a DataFrame dframe = pd.DataFrame({'Prashant': [23, 24, 22], 'Data': [10, 12, np.nan], 'Science': [0, np.nan, np.nan]}, columns = ['Prashant', 'Data', 'Science']) # Use fillna of complete Dataframe # value function will be applied on every ...
29ae65154da5ff15a442ab8eace2382e559a3e11
steaksauce-/MacAddy-Fixer
/macaddy-fixer.py
5,634
4.03125
4
#!/usr/bin/python3 # Converts scanned mac-addresses into formatted mac-addresses. import argparse parser = argparse.ArgumentParser(description="Converts a list of mac-addresses to mac-addresses with a different delimeter (or no delimeter). Default behavior is to convert alpha-numeric mac-addresses to colon delimete...
fc0bb6cba2a94251dee1f45c8a6cf8cc587267ac
CatherineFish/PythonDevelopment2021
/20210412_2/Interface.py
2,618
3.703125
4
""" Homework application interface. - Functions and classes have few parameters """ import tkinter as tk from Logic import Application class App(Application): """Main application class.""" def create_widgets(self): """All widgets of this application.""" super().create_widgets() valid...
e72ab63d144bbbb3001592d0455b1896e2a6728b
TerisseNicolas/SudokuSolver
/SudokuSolver/init_test.py
8,111
3.75
4
def fillDefaultMatrix(matrix): matrix[0,0]=6 matrix[0,1]=0 matrix[0,2]=0 matrix[0,3]=2 matrix[0,4]=1 matrix[0,5]=8 matrix[0,6]=7 matrix[0,7]=3 matrix[0,8]=9 matrix[1,0]=3 matrix[1,1]=9 matrix[1,2]=0 matrix[1,3]=0 ...
b71ec89bf0b0937d50e0eadca45200de9d838347
Angelica137/paying-off-debt
/scripts/p1answer.py
342
3.90625
4
balance = 42 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 month = 0 while month < 12: minMonthPmt = monthlyPaymentRate * balance monthUnpaidBal = balance - minMonthPmt newBal = monthUnpaidBal + (annualInterestRate/12)*monthUnpaidBal balance = round(newBal, 2) month += 1 print("Remaining balan...
402f484b738b2afeff1ddcff1e220eed6da723c2
j-enny/SimpleCGPA-GUI
/SimpleCGPA_GUI_App.py
7,790
4
4
from tkinter import * # simple result display # Beginning of the tkinter main window nextWin = Tk() nextWin.title("Result Sheet") nextWin.geometry("640x700") scroll = Scrollbar(nextWin) scroll.pack(side='right',fill=Y) SchInfolabel = Label(nextWin, text="Student Result Sheet", font=("Times New Roman", 22, "bold"),b...
0a439a410b559ce91c0728bc00ec872060c678fd
atavener68/intro_to_python
/dndmap.py
2,700
4.28125
4
""" map od territory with open spaces walls or floor tile/square end up grid of rows and columns player - orientation/direction ^>v< move_forward turn(left or right) """ game_map = [ [1, 1, 1, 1, 1, 1, 1, 1, ], [1, 0, 0, 0, 0, 0, 0, 1, ], [1, 0, 0, 0, 0, 0, 0, 1, ], [1, 0, 0, 0, 0, 0, 0, 1, ], [1,...
f9fb70900d1e845e5f66dac5e07355a02b417afa
atavener68/intro_to_python
/fileio1.py
286
3.765625
4
output_file = open("output1.txt", "w") # w write, a append, r for read output_file.write("\neven more stuff to write\n") output_file.close() input_file = open("output1.txt", "r") text_list = input_file.readlines() print(text_list) for line in text_list: print(line.strip())