blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
ea11c9d81638a2634be10338ccf880201265c417
yooq/PythonUp
/leetcode/461.py
366
3.859375
4
''' 两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。 给出两个整数 x 和 y,计算它们之间的汉明距离。 注意: 0 ≤ x, y < 231. 示例: 输入: x = 1, y = 4 输出: 2 解释: 1 (0 0 0 1) 4 (0 1 0 0) ''' x=4 y=2 print(bin(x)) print(bin(y)) print( bin(x ^ y)) #异或相同为0 不同为1
772eb991eaca35536c21c5f247afba3bbc6b52fd
yooq/PythonUp
/leetcode/0501.py
726
3.546875
4
''' 插入。给定两个32位的整数N与M,以及表示比特位置的i与j。 编写一种方法,将M插入N,使得M从N的第j位开始,到第i位结束。 假定从j位到i位足以容纳M,也即若M = 10 011,那么j和i之间至少可容纳5个位。 例如,不可能出现j = 3和i = 2的情况,因为第3位和第2位之间放不下M。 示例1: 输入:N = 1024(10000000000), M = 19(10011), i = 2, j = 6 输出:N = 1100(10001001100) 示例2: 输入: N = 0, M = 31(11111), i = 0, j = 4 输出:N = 31(11111) ''' class Solut...
46e52cbf24582eaea86e96065542d1915c205d20
sjb3/data_sci_project
/py3.8/stacks/convert_int_to_bin.py
285
3.828125
4
from stack_reverse import Stack def div_by_2(num): s = Stack() while num > 0: remainder = num % 2 s.push(remainder) num = num // 2 bi_num = '' while not s.is_empty(): bi_num += str(s.pop()) return bi_num print(div_by_2(242))
8653f9f8c28a55fafd6a3b908313614fe69eb1af
sjb3/data_sci_project
/py3.8/string_processing/check_perm.py
884
3.75
4
is_perm_1 = 'dog' is_perm_2 = 'god' not_perm_1 = 'not' not_perm_2 = 'top' # time complexity = O(n) # space complexity = O(n) def is_permmutation(str_1, str_2): str_1 = str_1.lower() str_2 = str_2.lower() if len(str_1) != len(str_2): return False # sorted way time complexity = O(n log n) ...
1ec1fee4b9bb2a0bac0d5852deff4a33b6ba5197
sjb3/data_sci_project
/py3.8/singlylinkedlist/llist_insertion.py
2,393
3.890625
4
''' array list -------------------------- insert/del O(n) O(1) access el O(1) O(n) contiguous Y N memory ''' class Node: # represents el def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.he...
a53415e06cf7305832f18c25a4317eac617986a2
aaronmorgenegg/cs5700
/assn3/shapes_python/shapes/image.py
1,259
3.53125
4
#!/usr/bin/env python3 """ Image Shape This class represents embedded image shapes that contain an image. Users of an image shape can also compute its area """ from shapes.image_cache import ImageCache from shapes.rectangle import Rectangle from shapes.shape_exception import ShapeException from shapes.validator impor...
d79db598266d0797e92d5d06aaad8703a6abe87b
aaronmorgenegg/cs5700
/assn1/shapes_python/shapes/circle.py
585
3.84375
4
#!/usr/bin/env python3 """ Circle This class represents circle objects that can be moved and scaled. Users of an circle can also compute its area and radius. """ from shapes.constants import PI from shapes.ellipse import Ellipse from shapes.validator import Validator class Circle(Ellipse): def __init__(self, *a...
eba72422829008ee357a34ff6f01322590f8382d
aaronmorgenegg/cs5700
/assn3/shapes_python/shapes/triangle.py
2,350
3.90625
4
#!/usr/bin/env python3 """ Triangle This class represents triangle objects that can be moved. Users of a triangle can also compute its area. """ import math from shapes.line import Line from shapes.point import Point from shapes.shape import Shape from shapes.shape_exception import ShapeException from shapes.valida...
8a2ebe17e4a5d565680efaa70130bf89bf97d6ef
aaronmorgenegg/cs5700
/assn4/sudoku/sudoku_solver/timer.py
881
3.765625
4
import timeit class Timer: def __init__(self): self.start_time = 0 @staticmethod def getCurrentTime(): return timeit.default_timer() def getStartTime(self): return self.start_time def startTimer(self): self.start_time = Timer.getCurrentTime() def stopTimer(s...
5e653857300e785e7c2755977af5951cbd0bc909
HeyMikeMarshall/GWARL-Data
/03-Python/2/Activities/01-Stu_QuickCheckup/Solved/quick_check_up.py
483
4.15625
4
# Print Hello User! print("Hello User!") # Take in User Input hru = input("How are you doing today?") # Respond Back with User Input print(f"I am glad to hear you are {hru}.") # Take in the User Age age = int(input("If you don't mind my asking, how old are you?")) # Respond Back with a statement based on age if ...
d8e26246147eeb15860e2946038dea1519814e13
truongpt/warm_up
/practice/python/study/linked_list.py
1,004
4.1875
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if self.head is None: self.head = new_node return ...
6c8a495846ccdfbcc67ad2b6f74c6e8f21666890
truongpt/warm_up
/practice/python/hash_table/group_anagrams.py
312
3.671875
4
""" - Problem: https://leetcode.com/problems/group-anagrams """ def groupAnagrams(strs): m = {} for s in strs: key = ''.join(sorted(s)) m[key] = m.get(key, []) + [s] return list(m.values()) if __name__ == "__main__": print(groupAnagrams(["eat","tea","tan","ate","nat","bat"]))
e49d28f27a04f774760002ff654aeda263e78b80
truongpt/warm_up
/practice/python/graph/two_sum_4.py
693
3.6875
4
""" - Problem: https://leetcode.com/problems/two-sum-iv-input-is-a-bst """ class TreeNode: def __init__(self, val = 0, left = None, right = None): self.val = val self.right = right self.left = left def dfs(root, s, k): if root is None: return False if root.val in s: ...
7454052943bdd0866af22156f9807ba300ebf26e
truongpt/warm_up
/practice/python/study/class_base.py
1,933
3.90625
4
from abc import ABC, abstractmethod # basic class MachineLearning: version = [] # class variable def __init__(self, s = "con cho con", u = "con meo", t = 1): self.suppervisor = s # instance variable self.unsuppervisor = u self.type = 2 # Inheritane class Vehicle: de...
ca9dc7a7cfbbda6686def0a6f6081a30fba4a846
truongpt/warm_up
/practice/python/queue_stack/valid_parentheses.py
736
3.90625
4
''' - Problem: https://leetcode.com/problems/valid-parentheses/ - Solution: - Using stack to check current character with previous character. - if conflict with rule valid parentheses -> return false. - if OK -> remove this pair. - Time and space complexity. - TC: O(n) - SC: O(n) ''' d...
636f23fd5d13656c56cee0a040257f3f3e1f0358
truongpt/warm_up
/practice/python/array/set_mismatch.py
1,257
3.78125
4
''' - Problem: https://leetcode.com/problems/set-mismatch/ - Solution 1: Using set to check duplicate and missing. - Time and space complexity. - TC: O(n) - SC: O(n) - Solution 2: - Using trick, change value nums to minus by scan value of nums -> set nums[ value - 1] *= -1 - During scan, if nums[v...
01925e132f5a1d1a98effa667f55d3b8de90efa8
abhiwalia15/practice-programs
/largest_num.py
193
4.09375
4
def largest_num(a,b,c): if (a>b) and (a>c): print("A IS THE LARGEST NUM",a) elif b>c and b>a: print("B IS THE LARGEST NUM",b) else: print("C IS THE LARGEST NUM",c) largest_num(5,4,3)
d4c5968e7381220b270cb9dbe29d00d71e7c9c01
abhiwalia15/practice-programs
/set_operations.py
354
3.828125
4
#python program to find perform different set operations . #display the two sets. E = {0,1,2,3,4,5,6,7,8,9,10} N = {2,4,6,8} #union of sets (U) print("UNION =",E | N) #intersection of sets (n) print("INTERSECTION =",E & N) #difference of sets (-) print("DIFFERENCE =",E - N) #SYMMETRIC DIFFERENCE OF SETS (/_\) prin...
70ffe83f919c23510c313d3dee15599bc1093b71
abhiwalia15/practice-programs
/prime_num.py
184
3.96875
4
def prime(n): count=0 for i in range(1,n+1,1): if n%i==0: count += 1 if (count==2): print("IT IS A PRIME NUMBER") else: print("NOT A PRIME NUMBER") prime(131)
33de70bb95f336872fccd00f1445e1d8e8bc14d1
abhiwalia15/practice-programs
/num_divisible_by_another_num.py
271
4.4375
4
# Python Program to find numbers divisible by thirteen from a list using anonymous function # Take a list of numbers my_list = [12, 65, 54, 39, 102, 339, 221,13] def num_divisible_by_num(n): for i in my_list: if (i%n == 0): print(i) num_divisible_by_num(13)
25af17ac429cf0d5a974f3199f5261e4ee79b45d
abhiwalia15/practice-programs
/HCF_m2.py
226
3.75
4
# Python program to find the H.C.F of two input number # define a function def hcf(a,b): if(a>b): small = b else: small = a while(small!=0): hcf = small small = big%small print("HCF = "+str(hcf)) hcf(69,122)
5826c6d384c286ff8eea9f74c0e2d27314caa6fb
andrewermel/curso-em-video
/37.py
230
3.875
4
#Escreva um programa que leia um numero inteiro qualquer e peça para o usuario escolher qual sera a base de conversão: #1 para binario # 2 para octal # 3 para hexadecimal #exercicio: num=int(input('digite um numero qualquer'))
c6b9288469fabe01525fa3e899da294079e2115f
andrewermel/curso-em-video
/chefao 45.py
1,249
3.890625
4
# criar um jogo de Joken po from random import randint itens=('pedra','papel','Tesoura') computador = randint(0,2) # print('O computador escolheu {}'.format(itens[computador])) print('''Suas opções [0] Pedra [1] Papel [2] Tesoura''') jogador =int(input('qual é a sua jogada?')) print('-='*40) print('O computador esc...
2d27e969a6c624849e413801edacf92a18b5b68d
andrewermel/curso-em-video
/chefao 50.py
376
3.859375
4
# desenvolva um programa que leia seis # numeros inteiros e mostre a soma # apenas daqueles que forem pares. # se o valor digitado for impar, # desconsidere. # exercicio soma = 0 cont = 0 for c in range(1,7): n=int(input('diga um numero:')) if n % 2==0: soma +=n cont +=1 print('voce informou {} ...
d74f64f71ca96b45315053e9dc379be4c6e2384b
andrewermel/curso-em-video
/chefao 37.py
676
4.25
4
#escreva um programa que leia um numero interio qualquer e peça para o usuario escolher qual sera a base de conversão: # 1 para binario # 2 para octal # 3 para hexadecimal # exercicio num=int(input('digite um numero inteiro:')) print('''Escolha uma das bases para conversão: [1] converter para BINARIO [2] converter p...
35635bf889330edb17cf4bd0b8c294e576465142
madsaken/population
/population.py
1,022
4.03125
4
# Lesa skráarnafn frá notanda # Lesið tiltekið ár frá notenda # Opna skrá # Meðhöndla skrá # prenta út Minimum: (population, state) # prenta út Maximum: (population, state) def read_filename(): name = input("Enter filename: ") return name def read_year(): while True: year = int(input("Enter year: ")) if year ...
ff787b06e4b2948315996a2f44ec9d9cfb553692
lunabird/MyPythonNote
/myweb/web10_split.py
987
3.640625
4
#-*- coding:utf-8 -*- # (3)re.split(pattern, string[, maxsplit]) # 按照能够匹配的子串将string分割后返回列表。maxsplit用于 # 指定最大分割次数,不指定将全部分割。我们通过下面的例子 # 感受一下。 import re # pattern = re.compile(r'\d+') # print re.split(pattern, 'one1two2three3four4') ### 输出 ### # ['one', 'two', 'three', 'four', ''] # (4)re.findall(pattern, string[, fla...
a3e3d2e39dd4d45b56394a7ee36bb574761a6263
sailskisurf23/sidepeices
/alt_let_cap.py
189
4.03125
4
test_str = "This is a test string" result = '' for i,char in enumerate(test_str): if i % 2 == 0: result += char.upper() else: result += char.lower() print(result)
837417ff10a136800d60313bca2657459e48b71b
sailskisurf23/sidepeices
/prime.py
556
4.28125
4
#Ask user for Inputs userinput1 = int(input("This program determines primality. Enter an integer greater than 0: ")) #Define function that returns divisors of a number def divisor(number): divisors = [] for x in range(1, (number+1)): if number % x == 0: divisors.append(x) return divisor...
f1f1f45df43dedd6a8bceb43e09e20c12e6ea443
sailskisurf23/sidepeices
/3door_sim.py
915
3.96875
4
#want to model simulation of 3 doors fallacy - Monty Hall problem import random as r def montysim(switch): doors = ['Door1','Door2','Door3'] winning_door = r.choice(doors) first_pick = r.choice(doors) dummy_door_poss = [e for e in doors if e not in [winning_door, first_pick]] dummy_door = r.choice...
bf34ef2231cd514deb40a267976b5b7ede184893
sailskisurf23/sidepeices
/factorial.py
337
4.21875
4
uservar = int(input("Enter an integer you would like to factorialize: ")) def factorialize(var1): """Returns the factorial of var1""" counter = 1 result = 1 while counter <= var1: result = result * counter counter = counter + 1 return result print(str(uservar) +"! = " + str(factori...
5e30f36955b95279a0e0c9cded56c35cf7d67184
sailskisurf23/sidepeices
/dice.py
2,879
4.34375
4
#1. Write a function that rolls two sets of dice to model players playing a game with dice. #It will accept two arguments, the number of dice to roll for the first player, and the number of dice to roll #for the second player. Then, the function will do the following: #* Model rolling the appropriate number of dice f...
9fa447c3fae1328014bd7775bd7688bb16b2a180
KSVarun/Coding-Challanges
/remove_consonents.py
825
4.1875
4
# Given a string s, remove all consonants and prints the string s that contains vowels only. # Input: The first line of input contains integer T denoting the number of test cases. For each test case, we input a string. # Output: For each test case, we get a string containing only vowels. If the string doesn't contain a...
a13cca02b4947744c1ff9c2bec82321dfb3ab2e8
KSVarun/Coding-Challanges
/peak_element.py
1,446
3.78125
4
# Given an array A of N integers. The task is to find a peak element in it. # An array element is peak if it is not smaller than its neighbours. For corner elements, we need to consider only one neighbour. # Note: There may be multiple peak element possible, in that case you may return any valid index. # Input Format...
1732396d3ea9cda7e3369fdb104b896bdac15bbf
KSVarun/Coding-Challanges
/index_extra_element.py
227
3.609375
4
t = int(input()) for i in range(0, t): n = int(input()) arr1 = list(map(int, input().split())) arr2 = list(map(int, input().split())) for j in range(0, n): if(arr1[j] not in arr2): print(j)
4465556b1b66fb50f8bf6f799ffcede337359475
aayushisharma26/if-else_Python
/possetive.py
445
4.0625
4
a=int(input("enter the number")) if a>0: print("it is possetive number") else: print("it is not possetive number") b=int(input("enter the number")) if b<0: print("it is negative number") else: print("it is not negative number") c=int(input("enter the number")) ...
b927871e518936cb3f5ec456e23f3742480db989
aayushisharma26/if-else_Python
/name.py
114
3.84375
4
user=input("enter the name") if ("a"in user): print("come for interview") else: print("not interview")
d4a5e2ff87967cd7d8fa164bf66e40becb13b6b1
aayushisharma26/if-else_Python
/second_highest_number.py
459
4.0625
4
a=int(input("enter the number")) b=int(input("enter the number")) c=int(input("enter the number")) if a>b<c: print("a is second highest number") elif a<b>c: print("a is second highest number") elif a>b<c: print("b is second highest number") elif a<b>c: print("b is second highest number") elif...
9d8358ca4e9e5d4cfcc4aaaeb90d67a60eb40984
nmema/algoritmos
/leetcode/001_two_sum.py
374
3.546875
4
''' https://leetcode.com/problems/two-sum/ time complexity -> O(n * log(n)) ''' class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: indices = {} for i in range(len(nums)): x = target - nums[i] if x in indices: return [i, indices[x]] ...
ce88654930ff3b00bebca522f7f4f2696ba95f5a
Mak2006/hacker-rank-projects
/30daysofcode/day6.py
868
3.875
4
# Given a number of strings, print the odd chars space even cars def candyprint(givenstrings): for i in range(0, len(givenstrings)): acandy = givenstrings[i] even = "" odd = "" for j in range(0, len(acandy)): if(j%2 ==0): even += acandy[j] els...
4f82e6ea7c02d2a81d5ad87a59ac26af7588dff7
p-alisson/BuscaExploracao
/ts/classes.py
2,282
3.578125
4
class Problema(object): def __init__(self, inicio, objetivo=None, acao=None): self.inicio = inicio self.objetivo = objetivo self.acao = acao def test_objetivo(self, estadoNo): return estadoNo == self.objetivo def acoes(self,estadoNo): return list(self.acao[estadoNo...
9137564c9eb591961b7642b62f662a17038b53fa
kaphleamrit2/radiation-dose
/analyse_feature_correlation.py
1,054
3.6875
4
# -*- coding: utf-8 -*- ''' Created on Fri Dec 7 13:34:34 2018 @author: Visa Suomi Turku University Hospital December 2018 @description: This function is used to analyse feature correlation with the target input: dataframe - Pandas dataframe of features and tar...
d1a9fa215047f2c8dab97c769cc68fc485094be6
DO6FP/streaming_software
/web_interface/web_interface.py
929
3.625
4
#!/usr/bin/python3 # this module contanis the gtk3+ graphical user interface, # which is displayed in the browser on the tablet # # read the following resources: # https://python-gtk-3-tutorial.readthedocs.io/en/latest/ # https://developer.gnome.org/pygtk/stable/ # https://developer.gnome.org/gtk3/stable/gtk-broadway.h...
2e48717f7c6492a2fbb5b7d05dfa681e9feeb439
ToWorkit/Python_base
/操作符/占位符.py
633
3.765625
4
# 字符串占位符 %s string # 整数占位符 %d digit # 浮点数占位符 %f float name = input('Name: ') age = input('Age: ') job = input('Job: ') salary = input('Salary: ') # 判断长得像不像数字 if salary.isdigit(): salary = int(salary) else: # print('mut input digit') exit('mut input digit') # 不满足条件则停止继续执行程序 # 占位符同样要求格式 msg = ''' ---...
35dce0bd9312f25968ff92c0c668ae46a1c2fcc8
ToWorkit/Python_base
/运算/打印三角形.py
177
3.703125
4
i = 7 while i > 0: flag = i while flag > 0: # 当前一行并列间隔符 end = '&'(符号可以自定义) print('*', end = '') flag -= 1 print() i -= 1
879904d1eb93a81fde6a938d5802df3fb36094ff
ToWorkit/Python_base
/错误处理/try.py
967
4.1875
4
try: print('try') # 注意差看区别 # r = 10 / 0 r = 10 / 2 print('result:', r) except ZeroDivisionError as e: print('except: ', e) finally: print('finally') print('END') print('-----------------------------') # 多个except捕获不同类型的错误 try: print('try') r = 10 / int('5') print('result:', r) except ValueError as ...
e9cd7907e6a9fcdfedd677b982af4b1bdd415ec2
ToWorkit/Python_base
/正则/re模块.py
762
3.6875
4
# 字符串 # 对应的正则表达式字符串会变为 'ABC\-000' s = 'ABC\\-000' print(s) # 使用python的 r 前缀,就避免转义的问题 # r 防止字符串转义 s2 = r'PL\-LP' print(s2) # 判断正则表达式是否匹配 import re re.match(r'\d{3}\-\d{3,8}$', '019-19823') # math() # 判断是否匹配 # 成功返回一个Match对象 # 失败返回None print(re.match(r'^\d{3}\s\d{3,8}$', '000 12345')) ''' test = '用户输入的字符串' if re.match(r...
a65642c0fcb735ff290002d810c5c7a2e0d2f97f
ToWorkit/Python_base
/面向对象高级/property练习.py
662
3.578125
4
class Screen(object): # 可操作 @property def width(self): return self._width # 设置 @width.setter def width(self, value): # 校验 if not isinstance(value, int): raise ValueError('width must interger') self._width = value @property def height(self): return self._height @height.set...
0a0633ee1446a7900a2454d26601fc21f28f8c02
ToWorkit/Python_base
/面向对象/实例属性和类属性.py
655
3.796875
4
class Student(object): def __init__(self, name): self.name = name s = Student('Bob') s.score = 90 print(s.name) print(s.score) # 本身绑定属性 class Su(object): name = 'student' # 创建实例 s = Su() # 打印name属性,s 实例并没有name属性,所以会继续往下查找class的name属性 print(s.name) # 打印类的name属性 print(Su.name) # 实例绑定name属性 s.name ='lp' # 实例属性优...
23bcfd3d09814b9437babe06c546fcd27ae50364
ToWorkit/Python_base
/操作符/生成器.py
173
4.03125
4
# 第一种 print([x * x for x in range(10)]) g = (x * x for x in range(10)) print(next(g)) # 通过next() 函数获得generator的下一个返回值 for n in g: print(n)
e4fe6df9f3ccb790c645f19d985175ecfae9e009
ToWorkit/Python_base
/面向对象/私有变量.py
349
3.671875
4
class Student(object): def __init__(self, name, score, age): self.__name = name self.__score = score self.age = age def print_score(self): print('%s成绩%s' %(self.__name, self.__score)) bart = Student('lp', 100, 25) bart.print_score() print(bart.age) bart.age = 26 print(bart.age) print(bart._Student...
1f0e4cb1d55c72b4effd49f9ed1dc98a6bcb2caf
jeevankumarr/ml-scratch
/src/linear/simple_linear_regression.py
4,659
4.1875
4
"""Simple Linear Regression relationship: Y = b_0 + b_1 * X Author: Jeevan Kumar R (jeevan.kr@gmail.com) References: Machine Learning Algorithms From Scratch - Jason Brownlee Dataset: https://www.math.muni.cz/~kolacek/docs/frvs/M7222/data/AutoInsurSweden.txt """ import random import numpy as np ...
0751bf27a74a4cae4f2cd58e84d008abc82ad880
chanhee-lee/WristWashAnalysis
/Grapher/util.py
2,911
3.875
4
from scipy.signal import butter, lfilter import numpy def vector_magnitude(data): """ function to calculate the magnitude of a vector Calculate the magnitude of the vector superposition of data (for example, acceleration) on x, y, and z axis Arguments: data: array of (x, y, z) tuples for a ve...
96428f70379cbea3ff44130a007b1e1afc32c5db
leemutai/google_opener
/main.py
675
3.515625
4
#importing web browser module import webbrowser #importing tkinter from tkinter import * #creating root root = Tk() #setting a GUI title root.title("webBrowser") #setting GUI geometry root.geometry("300*200") #function to open copyassignmet.com in browser def copyassignment(): webbrowser.open("www.copyassignment.co...
5340b922b39e0485d5a7ec7b780ec47253fe5dae
blakegreendev/nfl-wordcloud
/nfl.py
1,093
3.640625
4
from sportsreference.nfl.roster import Roster import matplotlib.pyplot as plt from wordcloud import WordCloud, STOPWORDS import numpy as np from PIL import Image import random #Create empty list to store players names players = [] # Pull down 49ers roster from sportsrefence API - Reference: https://sportsreference.re...
2b9016649ea71728fc6ae2286b0fffae0b1daf07
chum-ch/python
/python-self/Week/week17/ex1_add_new_col.py
278
3.890625
4
name = [ ["Ronan", "Ogor", 2], ["Jonathan", "Faucher", 90], ["chum", "yoeurn", 3], ["vann", "neom", 18] ] for index in range(len(name)): if name[index][2] >= 18: name[index].append("Major") else: name[index].append("Minor") print(name)
78b96e44bedee83ff38611b66d4756c190e64759
chum-ch/python
/python-self/event/01-randomCircles-startCode.py
686
4.09375
4
import tkinter as tk import random # Create an empty window root = tk.Tk() root.geometry("600x600") canvas = tk.Canvas(root) colors = ["red", "orange", "yellow", "green", "purple", "brown", "blue", "indigo", "violet"] def drawCircle(event): randomx = random.randrange(0, 600) randomy = random.randrange(0, 600...
e3e2df0357f3d129869f705f8e170e1ca898c76b
chum-ch/python
/test/t.py
751
3.578125
4
# import tkinter as tk # import random # root = tk.Tk() # root.geometry("600x600") # canvas = tk.Canvas(root) # def draw_oval(x, y, size) : # x1 = x - size # y1 = y - size # x2 = x + size # y2 = y + size # oval = canvas.create_oval(x1, y1, x2, y2, fill="red", tags="move_positon") # def onButton()...
42c03fc5010ec976cc7bcc821e4cf1021e3158a3
chum-ch/python
/python-self/challange.py
2,914
3.890625
4
BOARD_SIZE = 10 # print the grid with Balook inside def printBoard(captainPosition): boardString = "" for colIndex in range(BOARD_SIZE): for rowIndex in range(BOARD_SIZE): if(captainPosition[0] == rowIndex and captainPosition[1] == colIndex): boardString += " ★" ...
55d5154a84deb84d3151ac2062e1b97b3cfd02bd
chum-ch/python
/game/ex-game2.py
1,422
3.859375
4
import tkinter as tk import random root = tk.Tk() root.geometry("600x600") canvas = tk.Canvas(root) oval2 = "" ball_move_down = True move_xleftB_rightT = 5 move_yleftB_rightT = 5 # create a oval with the middle position def draw_a_oval(x, y, size): global oval2 x1 = x - size y1 = y - size x2 = x + siz...
41fdc2cfe99d8dea8ec57a5f89908c8772149d30
Zlstg/py
/廖雪峰基础知识/3.python基础/3-3.使用list和tuple.py
3,073
4.28125
4
# coding:utf-8 # list是Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。 classmates = ['Miss', 'xiaoming', 'xiaohong'] print(classmates) # 变量classmates就是一个list。 print('--- 用len()函数可以获得list元素的个数 ---') print(len(classmates)) # 用索引来访问list中每一个位置的元素,记得索引是从0开始的: print(classmates[0]) print(classmates[1]) print(classmates[2]...
7c7cb8847b299c28be1d746f9ac3d96a18632b64
Zlstg/py
/廖雪峰基础知识/5.高级特性/5-3,列表生成式.py
1,567
3.640625
4
# 要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list(range(1, 11))) # 生成[1x1, 2x2, 3x3, ..., 10x10] L = [] for x in range(1, 11): L.append(x * x) print(L) # 使用列表生成式 print([x * x for x in range(1, 11)]) # 列表生成式仅偶数的平方 print([x * x for x in range(1, 11) if x % 2 == 0]) # 两层循环,生成全排列 print([x + y for x in 'ABC' for y i...
14dc78a328ba07c7d615de2083528c2e7abe0c7d
eucalypto/bitesofpy
/90/southpark.py
1,133
3.53125
4
from collections import Counter, defaultdict import csv import requests CSV_URL = 'https://raw.githubusercontent.com/pybites/SouthParkData/master/by-season/Season-{}.csv' # noqa E501 def get_season_csv_file(season): """Receives a season int, and downloads loads in its corresponding CSV_URL""" with re...
1d68c716dd00ca4102a59b1d99f2c5cdb1279db7
eucalypto/bitesofpy
/96/wc.py
700
3.6875
4
def wc(file_): """Takes an absolute file path/name, calculates the number of lines/words/chars, and returns a string of these numbers + file, e.g.: 3 12 60 /tmp/somefile (both tabs and spaces are allowed as separator)""" with open(file_) as file: lines = file.readlines() charac...
f9b5d7c1d52e5a1a8a7020291fefc7c61d7a9373
eucalypto/bitesofpy
/19/simple_property.py
600
3.515625
4
from datetime import datetime, timedelta NOW = datetime.now() class Promo: def __init__(self, name: str, expires: datetime): self.name = name self.expires = expires @property def expired(self) -> bool: """Get the expired status.""" if datetime.now() <= self.expires: ...
bc81d27a92d0ff3dbcdfb4375b6e8c6c1e716886
eucalypto/bitesofpy
/54/poem.py
1,508
3.59375
4
from collections import deque INDENTS = 4 def print_hanging_indents(poem: str): lines = poem.strip().split("\n") lines = map(str.strip, lines) formatted_poem = "" is_first_line = True indent = " " * INDENTS for line in lines: if line == "": is_first_line = True ...
31ac183db90cde50b932b67c2d1bdf6b6da9aa6a
eucalypto/bitesofpy
/187/howold.py
734
3.6875
4
from dataclasses import dataclass from dateutil import parser from dateutil import relativedelta @dataclass class Actor: name: str born: str @dataclass class Movie: title: str release_date: str def get_age(actor: Actor, movie: Movie) -> str: """Calculates age of actor / actress when movie was ...
f8af4c7bc350f6299897c6eb7a4ce1803d14ba32
ncamposp/fibonacci
/test_fibonacci.py
458
3.609375
4
import unittest import fibonacci class TestFibonacci (unittest.TestCase): # def test_fibonacci(self): self.assertEqual(fibonacci.fibonacci(0), 0) self.assertEqual(fibonacci.fibonacci(1), 1) self.assertEqual(fibonacci.fibonacci(2), 1) self.assertEqual(fibonacci.fibonacci(3), 2) self.as...
93ade36aacf46c181b1c4c3a73d4031ea9ebd50b
hsawa0709/strategy
/physics.py
781
3.625
4
import numpy as np import entity class CollisionDetection(): def __init__(self, robot_num): self.robot_num = robot_num #self.robot = robot #self.robot = [0,0,0,0,0,0,0,0] def robot_collision_detect(self, robots): for i in range(self.robot_num): for j in range(self.r...
d6d27c63a7337d0f079899ab5ccf1dae8c4f18d0
SlimJed/CS50-Projects
/pset6/mario/mario.py
283
3.5
4
def main(n): assert n in range(1,24) for i in range(2,n+2): print (' '*(n+1-i), end='') print ('#'*i) if __name__ == '__main__': while True: lines = int(input('Height: ').strip()) if lines in range(1,24): break main(lines)
85f91445277b29a2b51800bf56013d937f14c997
ghyeon0/fxmark
/bin/set-cpus
8,803
3.53125
4
#!/usr/bin/env python2 import sys, os, optparse from cpuinfo import * FIELDS = ["processor", "socket", "coreid", "thread", "apicid", "node"] # Process arguments # set-cpus is really two programs rolled into one; instead of # hotplugging CPU's, it can just list them. The documentation we give # differs slightly bet...
847252b2b65da4adf71fedb141400e8f74d97e5e
remon/pythonCodes
/python_bacics_101/Arithemtic_operators_en.py
2,020
4.21875
4
# Examples on how to uses Python Arithmetic Operators ''' What is the operator in Python? Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand. for example: 2 + 3 = 5 Here, + is the operator that performs addition. 2 and...
fb6b67ad09585fe97647f5fc40bf1934a4e7dfd7
remon/pythonCodes
/Lists/List_Methods/append_en.py
1,291
4.75
5
#added by @Azharoo #Python 3 """ The append() method adds an item to the end of the list. The item can be numbers, strings, another list, dictionary etc. the append() method only modifies the original list. It doesn't return any value. """ #Example 1: Adding Element to a List my_list = ['python', 'codes', 1, 2, 3] ...
3d67d44f91508ecb5336490c5cb0fbd6e5621af2
remon/pythonCodes
/Modules/secreat-message.py
701
3.859375
4
from __future__ import print_function #This file contain examples for os module #What is os module? #is a module using for list files in folder, we can get name of current working directory #rename files , write on files import os def rename_files(): # (1) get file names from a folder file_list = os.listdir(r"C:\...
1a9fa90752b2629767100945f27c5bffa4a9807f
remon/pythonCodes
/Turtle/draw_rectangle_en.py
755
4.5625
5
#added by @Azharoo #Python 3 #draw a simple rectangle # Example - 1 import turtle t = turtle.Turtle() window = turtle.Screen() window.bgcolor("black") t.hideturtle() t.color("red") def slanted_rectangle(length,width): for steps in range(2): t.fd(width) t.left(90) t.fd(length) t....
0a78a10b44750efbf098df50ab885e38eb12058e
remon/pythonCodes
/Functions/python_exmple_fibonacci_en.py
641
4.375
4
#this file print out the fibonacci of the function input #importing numpy for execute math with lists import numpy as np #define the function that takes one input def fibonacci_cube(num): #define a list that contains 0 and 1 , because the fibonacci always starts with 0 and 1 lis = [0,1] #this for loop take...
6c568207157997c04d5aacba36d8dfdb911dd03b
remon/pythonCodes
/Lists/List_Methods/reverse_ar.py
1,918
4.90625
5
#added by @Azharoo #Python 3 """ The reverse() يعكس عناصر قائمة محددة. The reverse() لا تأخذ أي عوامل. The reverse() لا يعيد أي قيمة. يقوم فقط عكس العناصر وتحديث القائمة. """ #مثال 1 : Reverse a List # Operating System List os = ['Windows', 'macOS', 'Linux'] print('Original List:', os) # List Reverse os.reverse() ...
591ce87b8211499434dc4f19086d6a8eb042f843
remon/pythonCodes
/Functions/strip_en.py
618
4.25
4
#strip() returns a copy of the string #in which all chars have been stripped #from the beginning and the end of the string #lstrip() removes leading characters (Left-strip) #rstrip() removes trailing characters (Right-strip) #Syntax #str.strip([chars]); #Example 1 #print Python a high level str = "Python a high...
3e6fd260f9bede680f5095e25d108cbc6006f03a
remon/pythonCodes
/Lists/pop.py
503
3.9375
4
# الدالة pop() تقوم بحذف اخر عنصر بالقائمة # نستطيع ان نحدد العنصر المراد حذفه وذلك بتحديد اندكس العنصر بداخل القوسين #المثال الاول li = [2,3,4,5] li.pop() print li #[يطبع [2,3,4 # المثال الثاني li = [2,3,4,5] li.pop(2) print li #[يطبع [2,3,5 # الدالة pop لها قيمة ارجاع وهي العنصر المحذوف li = [2,3,4,5] pr...
57e7fdb1ff3591f58ec76cf85638980d3f5a6171
remon/pythonCodes
/Lists/comprehensions_en.py
1,012
4.5625
5
# Added by @ammarasmro # Comprehensions are very convenient one-liners that allow a user to from a # whole list or a dictionary easily # One of the biggest benefits for comprehensions is that they are faster than # a for-loop. As they allocate the necessary memory instead of appending an # element with each cycle an...
9dc25a0f6dee8bbf0a354f0fe26d91113402121a
CamMcLeod/Data-Wrangle-OSM
/Project Code/data - project.py
9,053
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.cElementTree as ET import pprint import re import codecs import json from collections import defaultdict """ This code wrangles the data and transform the shape of the data into the model decided in the class exercise. The output is a list of dictionaries...
aa3f18d2d26c103253f0df89c11c30c5bd9a754e
vdn-projects/omnilytics-challenge
/read_print_data.py
998
4.125
4
import os def is_float(obj): """ Check if object is float datatype or not Args: obj: input object in string Returns: True if it is float, else False """ try: float(obj) except ValueError: return False return True if __name__=="__main__": b...
d56f058136d3deed40a15968a860c86b12fd3b43
xriswhat/CSC111
/grammarextended/GrammarExtended.py
4,659
3.9375
4
# Assaignment 10 For Extra Credits # Chris Xiaoyue Tan # This home work uses recursion to generate more complex sentences from random import randint def ReadInDict( ): '''Reads in a list of words, one category per line The 0-th element of the list is the category name. The filename is hardwired to...
f7eea8ad156151c4db7e887dd1091e4476318b7e
quantombone/SimpleCV
/SimpleCV/examples/x-ray.py
1,602
3.5625
4
#!/usr/bin/python import time from SimpleCV import * from SimpleCV.Display import Display, pg display_width = 640 display_height = 480 display = Display(resolution = (display_width, display_height)) #create a new display to draw images on cam = Camera() #initialize the camera done = False # setup boolean to stop the...
0858e00dbefe600268bf106ce92459396828b6f8
laineyr19/MAGIC
/Week 3/text_based_adventure_game-2/game_02.py
317
4.15625
4
def main(): '''Getting your name''' play_name=(raw_input("What's your name? > ")) play_age=(raw_input("enter your age? >")) print ("hi"+" "+play_name) result="my name is {name} and my age is {age}".format (name=play_name, age=play_age) print(result) if __name__ == '__main__': main()
f160033666f606336d2784d1da9b425cbfeb9520
AkshayRamteke/KNN-Zoo-Dataset-Using-Python
/zoo.py
4,057
3.78125
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt zoo = pd.read_csv("E:\\Assignment\\13)KNN\\Zoo.csv") zoo.rename(columns = {"animal name":"animalname"},inplace =True) ############ EDA ########### ani = zoo["animalname"].value_counts() ### As we look at the data, #animal name is the...
8879a4742836a0a39067dcfece5e2f5a084bb668
bastic18/strip-me-card-game
/stripme.py
13,185
3.828125
4
# Creator: Garfield Grant # Creator: Horraine Mccalla # COMP1127 project # Main file for the project import sys import cards from random import randrange import adt_ def showGreeting(): # This function shows the main menu for the game print ("*******************************************...
3ec90389ef65f33a2edb0140c2bc5d295b9c652e
FrancescoScarlata/DecisionTreeClassifier
/Source/DecisionTree.py
10,545
3.75
4
from DecisionNode import DecisionNode from Leaf import Leaf from Question import Question from Node import Node class DecisionTree: ''' This is just the tree classifier and some objects this is just to have the infos put in a good way. ''' def __init__ (self, data, header, maxNodes): self.maxNodes=maxNodes ...
0cd4d8a6bb4d37a43c30a913de835cbe4f710a05
Millitesla/Retina_Python_Tools
/DensityRecoveryProfile_V2.py
13,041
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 11 14:06:37 2016 Version 1 Date: 11.09.2016 Description: 1.Project all points to zero point 2.Count density of points in x,y matrix that are within radius r @author: ruff tobias """ import appnope import matplotlib.pyplot as plt import pylab as p import os import pandas...
7264c06c4327d762d4f072a4c903cc6fd79cf3c4
krishnachouhan/calculator
/calculator/sum.py
1,200
4.25
4
# Sum Module def sum(a, b, verbose=0): ''' Writing this Sample doc. This is useful as when you type __doc(sum)__, this text is printed. hence its a good practice to use this. Here, - parameters are to be explained. - return values are to be explained. - finally, dependencies ar...
919e37cd71e09c73e071d1cae8c56bfe5e2387e7
genii01/coding_test
/Q_03_reoder-data-in-log-files.py
1,008
3.5625
4
## 준영 def reoderLogFiles(logs): letters, digits = [],[] for log in logs: if log.split()[1].isdigit(): digits.append(log) else: letters.append(log) # 2개의 키를 람다 표현식으로 정렬 letters.sort(key = lambda x : (x.split()[1:], x.split()[0])) return letters + digits inpu...
3e037daa81f5e6160a4b83904ccbcbab3b27a6c1
DonaldMurdock/Black-Box-Game
/BlackBoxGame.py
11,877
3.90625
4
#Donald Taylor #8/7/2020 #Implementation of the Black Box game. class BlackBoxGame: """Represents Black Box Game. Has data members for storing the gameboard, score of the player, number of atoms, a list of incorrect guesses, and a dictionary that stores each atom and whether or not it has been guessed. """...
3f3d54029cab0cae15d3b1fa50d0b25bda64d502
rishabmsaini/Python-Projects
/GUI/Text Editor/TextEditor.py
3,225
3.859375
4
from tkinter import * from tkinter import filedialog class TextEditor: clip=" " filename=" " def __init__(self,root): filename="Untitled.txt" self.t=Text(root, width=80, height=20, wrap=WORD) self.t.pack() #BASIC BODY:- self.menubar=Menu(root) #Creates a menubar ro...
4d338a0c1cb299afd1c881066acadfc18e2d74f1
himanshudiv/hackerrank_solutions
/text wrap.py
263
4.03125
4
import textwrap def wrap(string, max_width): '''text wrapping using text wrap module''' return textwrap.fill(string, max_width) if __name__=='__main__': string, max_width = raw_input(), int(raw_input()) result = wrap(strimg, max_width) print result
e78b1194d77ef724cd551a81dda893aac8488a6e
cherish62113/Python_practice
/Numpy-Day1.py
2,885
3.515625
4
#安裝 Numpy 終端機輸入 "pip install numpy" # 載入 Numpy 模組 設定別名 np import numpy as np #開啟文本 # 自訂變數 = np.genfromtxt("檔名.txt", delimiter=",", dtype="U75", skip_header=1) #delimiter=","表示每列的資料之間使用,做分隔符號 #dtype="U75"表示資料以字串方式置入(75為置入的字的個數) #skip_header=1 :表示從txt的第1列開始讀取(開頭為第零列) txt = np.genfromtxt("world_alcohol.txt", de...
b44a6421ed0a6f0cd5075d5b4072aaf46090bd28
Gnarlymath/tree_structures
/basic_binary_tree.py
2,132
3.984375
4
preorder_array = [] class TreeNode: def __init__(self, val): self.left = None self.right = None self.data = val def __str__(self): return str(self.left) + " " + str(self.right) + " " + str(self.data) #recursive binary tree #check if value is greater or less t...
60a15f880a910137d6c267daf14baad13a638fc3
abramova-alex/first
/Fourth.py
546
4.28125
4
#Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit and print out the converted temperature. celsius = raw_input('Print temperature in Celsius: ') celsius = float(celsius) fahrenheit = celsius * 9 / 5 + 32 print 'In Celsius', celsius, ' converting to', fahrenheit...
f3203d5e37d0fa3ddc315b0b648e76982e2fb2ed
agandhasiri/Python-OOP
/program 6 Class Ball/SimulationGraphics.py
8,072
3.578125
4
from cs1graphics import Canvas, Circle, Point import time import copy class BallWrapper(Circle): def __init__(self,x,y,vx,vy,radius=15): Circle.__init__(self) self._ball = Ball(x, y, vx, vy) self._radius = radius self.moveTo(self._ball.getPositionX(),self._ball.getP...
ee26f9872314401c7e376ac3018ef80dd5f23e58
agandhasiri/Python-OOP
/program 4 Contest problems/everywhere.py
996
4.15625
4
Tests = int(input()) # no of test cases len_list=[] # for length of each test case list with distinct names for v in range(Tests): # a loop for every test case n = int(input()) # no of work trips for each test case list = [] ...
1a8d4fdaf32d745f81f0089faf9287047b600c6e
wspang/musicPlatform
/ingest/reddit_ingest.py
2,235
3.578125
4
from api_methods import reddit_obj class Reddit: def __init__(self): # Create the Reddit object (read only) to use in API calls self.REDDIT = reddit_obj() return def get_posts(self, subreddit_name, post_count): # retrieve post titles from subreddits and return as a list t...