blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b64650fd3958d473266bb0313461ec86072aa838
eechooo/letcode
/49.group-anagrams.150744118.ac.py
1,067
3.875
4
# # [49] Group Anagrams # # https://leetcode.com/problems/group-anagrams/description/ # # algorithms # Medium (38.94%) # Total Accepted: 201.1K # Total Submissions: 516.4K # Testcase Example: '["eat","tea","tan","ate","nat","bat"]' # # Given an array of strings, group anagrams together. # # Example: # # # Input:...
4336da1b0731cdbce394a011ab44d69a2df0aef4
INNOMIGHT/searching-and-sorting
/Searching/BinarySearch.py
473
3.984375
4
def binary_search(arr, val): left_pointer = 0 right_pointer = len(arr) - 1 found = False while left_pointer <= right_pointer and not found: mid = (left_pointer+right_pointer)//2 if arr[mid] == val: found = True else: if mid > val: right_p...
5f9f4606f62ca87eedcc621960fa83109dbbdc47
AnjolaTope/Automate_Spotify
/spotify_client.py
1,749
3.84375
4
import requests from urllib.parse import urlparse import urllib.parse class SpotifyClient(object): def __init__(self, api_token): #this token is used to issue a request self.api_token = api_token def search_song(self, artist, track): #this is used to get the url of the string ...
e0fafcd6a19f2421b22dcccc8a8ea243d3571b8a
KevenGe/LeetCode-Solutions
/problemset/1996. 游戏中弱角色的数量/solution.py
1,017
3.578125
4
# 1996. 游戏中弱角色的数量 # https://leetcode-cn.com/problems/the-number-of-weak-characters-in-the-game/ from typing import List from functools import cmp_to_key class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: def cmp(a, b): if a[0] != b[0]: return...
9e53f2613812d24c3a0613c936b58a179944fe3a
melodypei/Python
/printTable.py
669
3.734375
4
#! python3 # -*- coding: UTF-8 -*- tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printTable(tableData): colWidths = [0] * len(tableData) for i in range(len(tableData)): colWidths[i] = max(len(item) ...
4dcb455d91798b00c87bc33b61dced64357270cf
sneggoroddd/GlobalProekt
/Loops/RPC.py
2,156
4.15625
4
'''Реализуйте серию из n игр "Камень, ножницы, бумага" с компьютером. В результате выведите статистику: сколько игр выиграл пользователь, сколько раз каждого вида ходов было выбрано. Дополните игру анализом компьютера ваших ходов и выбор наиболее подходящего против вас хода.''' import random def moveUser(start, end, ...
de46a2956ff6276ca0a3dda96b1f2c40067ad555
krajcovic/HelloPython
/kapitoly/kap5.py
1,428
4
4
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'krajcovic' import math import doctest def countdown(n): while n > 0: print(n) n = n-1 print("Pal!") def sequence(n): while n != 1: # print(n, end=", ") print(n) if n % 2 == 0: # n is even n ...
b6bc0df6dbc129be7b6f858b1b28ca59706989b3
shangguanouba/python
/python/练习/if嵌套-火车站安检.py
530
3.734375
4
# 定义布尔型变量 has_ticket表示是否有车票 has_ticket = True # 定义整型变量 knife_length表示刀的长度 单位:厘米 knife_length = int(40) # 首先判断是否有车票 if has_ticket: print("车票检查通过,请进行安检") # 安检检查刀的长度,超过20厘米不允许进站 if knife_length<=20: print("请进站") else: print("您携带的道具长%d厘米,不允许进站" % knife_length) else:print("请先购买车票") # 如果没有车票不许...
302a54ab7c6ceaa017bd13f276889b0fcb5e219d
junteudjio/algorithms_in_python
/algorithms_in_python/_12_sorting_and_selection/examples/merge_sort_bottom_up.py
1,162
3.796875
4
__author__ = 'Junior Teudjio' def merge_sort_BU(l): def _sort(l, start, middle, end): end = min(len(l), end) #update end since it may be greater than the real size of l #copy the arrays and start modifying l aux1 = l[start:middle] aux2 = l[middle:end] i = j = 0 k ...
65f93cc94dfe9874ec0cac2fa8b67f700a5f1195
Rocosso/INPALPE
/ADT.py
431
3.59375
4
class MyStack: contador = 0 def __init__ (self, list): self.data = list def pop(): self.data = self.data[:-1] self.contador-= 1 def push(ele): self.data.append(ele) self.contador+= 1 def top(): length = len(self.data) -1 return self.data[len] def isEmpty(): return self.contador <= 0 def find(el...
d35ed2be3a39d90979c76db78da670b2a4daf5c2
ejolie/problem-solving
/LeetCode/src/com/ejolie/problems/medium/lc_11.py
1,080
3.640625
4
from typing import List """ 11. Container With Most Water - 0 <= i < j <= len(height) - 1 일때, area = min(height[i], height[j]) * (j - i) [Idea / Proof] cf. https://leetcode.com/problems/container-with-most-water/discuss/6100/Simple-and-clear-proofexplanation 1. The widest container: j - i를 max 값으로, 즉 i = 0 && j = ...
9993fdc731cc711348773a339bf5b579ff543571
chaitanyav/python_practice
/selection_sort.py
1,259
4
4
import random import time def minimum_index(numbers, lindex, n): min_index = None for index in xrange(lindex, n): if min_index is None: min_index = index else: if numbers[min_index] > numbers[index]: min_index = index return min_index def selection_...
cde7faf04972265b57320e719e76661d5b3226ea
ReijiMaigo/pyhanz
/python_work/input/favourite_number.py
281
3.703125
4
import json number = raw_input('What is your favourite number? ') filename = 'number.txt' #Store to file with open(filename, 'w') as file_object: json.dump(str(number), file_object) #Read from file with open(filename, 'r') as file_object: print(json.load(file_object))
df0d24444059c1d6d39efb9e3abf2af3bfc94213
Darkcacht/Letni
/funcion5.py
458
3.71875
4
#! /usr/bin/python #! coding: utf-8 import os clear = lambda: os.system('clear') clear() def ordenar(x, y): pares = sorted(x) impares = sorted(y) print pares print impares def lista(): num = 0 pares = [] impares = [] while num != "": num = raw_input("Ingrese un número: ") if num != "": if int(nu...
cebc79c842efbd16f788d541d8eaf8378bacaa50
christinabranson/hackerrank-python
/ProblemSolving/Arrays/ArraysDS/ArraysDS.py
497
3.703125
4
#!/bin/python3 import math import os import random import re import sys # Complete the reverseArray function below. def reverseArray(a): return a[::-1] if __name__ == '__main__': fptr = open(os.getenv('OUTPUT_PATH', 'ArraysDS.txt'), 'w') #arr_count = int(input()) #arr = list(map(int, input().rstrip...
a358ea1872072e47d4dced8b8edcbf1b460d68da
simpanID/python
/Part 01/belanja.py
937
3.703125
4
dompet = 20 # ini adalah isi dompet kamu barang = { 'samsung' : 4, 'apple' : 6, 'xiomi' : 2, } for barang_key in barang : print('--------------------------') print('Anda Mempunyai Dompet '+str(dompet)+' Dollar') print(barang_key+' seharga '+str(barang[barang_key]) +' dollar') jumlah_beli =...
535f274474e3b90e8478251438f0c114c0e76e23
sergiogbrox/guppe
/Seção 4/exercicio38.py
463
3.9375
4
""" 38- Leia o salário de um funcionário. Calcule e imprima o valor do novo salário, sabendo que ele recebeu um aumento de 25%. """ print(f'\nDigite o valor de seu salário para ser calculado seu aumento de 25%:') salario = input('R$') try: salario = float(salario) print(f'\nSeu novo salário é de...
6dfbea7c3b90219f08289a2b9ce3a9a000be5a1a
xiaojun2017/PythonLearn
/class/oop_subclass.py
930
3.75
4
# coding=UTF-8 class SchoolMember: def __init__(self, name, age): self.name = name self.age = age def tell(self): print("Tell, {} {}".format(self.name, self.age)) class Teacher(SchoolMember): def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) ...
7aa13f83fb7072c2692286c1c86ccf95d680b864
vincenttuan/Python0709
/d02/Hello10.py
133
3.5625
4
# 字串格式化 color = '紅色' name = '蘋果' #fruit = color + '的' + name fruit = '{0}的{1}'.format(color, name) print(fruit)
6a29c35a4e7387257700bd8bcfb67f5086128d88
ChangXiaodong/Leetcode-solutions
/Coding interviews/56.entry_node_in_list_loop.py
453
3.609375
4
def entry_node(node): if not node: return p1 = node p2 = node while p1.val != p2.val: p1 = p1.next p2 = p2.next.next cur_val = p1.val loop_count = 0 p1 = p1.next while p1.val != cur_val: p1 = p1.next loop_count += 1 p1 = node p2 = node ...
399df8bf37f70766e7a8153f0d701b1459f8226c
jaecheolkim99/CodingPlayground
/LeetCode/Increase Order Search Tree.py
1,755
3.609375
4
""" [BEST] class Solution(object): def increasingBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ res = self.inOrder(root) if not res: return dummy = TreeNode(-1) cur = dummy for node in res: node.left = ...
cbca7f7bd5a7cf486d615e5d20d59ecf08a27e2b
Machin-Learning/Exercises
/sqroot.py
89
3.59375
4
def sqrt(num): res = num**(1/2) return round(res,3) print(sqrt(11)) print(sqrt(4))
e56c19c6bf2cd083b444381a7e25d7580f5d2987
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/7027f36df5b24850a9f5b3fa96e9953c.py
341
3.734375
4
# # Skeleton file for the Python "Bob" exercise. # def hey(phrase): return ['Whatever.', 'Whoa, chill out!', 'Sure.', 'Fine. Be that way!'][ sum(((phrase.strip() == ''),)) * 3 or sum((any(c.isalpha() for c in phrase) and not any( c.islower() for c in phrase),)) or sum((phrase.e...
9c63f8d6b51696042b00f87fe0c1d24537826eef
Techsrijan/techpython
/factorialofanynumber.py
182
3.96875
4
n=int(input("Enter the no fo which u want factorial")) ''' f=1 while n>=1: print(n) f=f*n n=n-1 print(f) ''' i=1 f=1 while i<=n: print(i) f=f*i i=i+1 print(f)
c0d5ff106e7f0dd6e564d89fa80c4a3221635faf
S-Vel/day-8
/Q 07.py
204
3.984375
4
# program to sum three values and divide it by value given by user a = 65 b = 265 c = 354 sum = a+c+b ins= int(input("enter number here to divide the sum:\n")) print("question no.7 output:\n",sum/ins)
706463dca11622644dde7d3e34625fde76cc4d50
gsasaki23/cd_algo_party
/w3d3.py
1,549
4.125
4
''' String: Is Palindrome Create a function that returns a boolean whether the string is a strict palindrome. - palindrome = string that is same forwards and backwards Input: "a x a" or "racecar" Output: return true Input: "Dud" or "oho!" Output: return false . Do not ignore spaces, punctuation and ...
0b4c84dbcb5b45db7d912b8e95279e887ddddbef
codeBeefFly/bxg_python_basic
/Day08/06.手机案例.py
1,617
4
4
''' 手机电量默认是100 打游戏每次消耗电量10 听歌每次消耗电量5 打电话每次消耗电量4 接电话每次消耗电量3 充电可以为手机补充电量 ''' class Phone: def __init__(self): # 手机电量默认是100 self.battery = 100 # 打游戏每次消耗电量10 def playGame(self): if self.battery<10: print('电量不足,请充电') return self.battery -= 10 # ...
c739251ffbfa41e03cee6b1ac732ddc4da64891b
linshaoyong/leetcode
/python/recursion/0022_generate_parentheses.py
673
3.53125
4
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ res = [] self.generate('', n, n, res) return res def generate(self, v, left, right, res): if left == 0: res.append(v + ')' * right) ...
7436a6d36ebf8f770f13d1a70a5dcfb8dfce7e55
ysoftman/test_code
/python/numpy_array_reshape.py
922
3.546875
4
# -*- coding: utf-8 -*- # author: ysoftman # python version : 3.x # desc : numpy 테스트 # pip install np import numpy as np def reshape_array(): # 64x64x3 의 3차원 배열을 만든다. arr = np.zeros((64, 64, 3)) print("arr.shape:", arr.shape) # 4096x3 의 2차원 배열로 변경 newarr1 = arr.reshape(64 * 64, 3) print("arr ...
8d438c71959d3fd16bffc44490bdfea783fcf61d
vassmate/Learn_Python_THW
/mystuff/ex3.py
1,312
4.8125
5
# http://learnpythonthehardway.org/book/ex3.html # This will print out: "I will count my chickens:". print "I will count my chikens:" # This will print out how much Hens we have. print "Hens", 25.0 + 30.0 / 6.0 # This will print out how much roosters we have. print "Roosters", 100.0 - 25.0 * 3.0 % 4.0 # This will pr...
238354fb7202b459341aaca35226b2611d664ece
mrocha98/ed-ads
/python-zip/Fibonacci Recursivo Ineficiente.py
146
3.53125
4
def fib(n): print (f'fib({n})') if n <= 2: return 1 return fib(n-1) + fib(n-2) print (fib(10)) #dá para calcular fib(100) nesta palestra?
9ff25e08f4a7ef1c740a36b10d17957dee9300fc
pwdemars/projecteuler
/josh/Problems/69c.py
814
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 14 14:29:22 2017 @author: joshuajacob """ import numpy def primes_list(n): x = numpy.ones(n, dtype = numpy.bool) for i in range(2,int(n**0.5)+1): if (i-1)%6 == 0 or (i+1)%6 == 0 or i == 2 or i == 3 and i<n+1: x[2*i-1::i...
b2e612da406831d7fa6820ad503d0d9f8dab1759
wildmask01/algorithms
/python_feature/singleton.py
491
3.53125
4
class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance class MyClass(Singleton): a = 1 import gc if __name__ == '__main__': one = MyClass() ...
88d633866297db8c9bb80d0699a88a1e696a122f
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/meetup/1ad1f993297643978c7c649e84c6e728.py
716
4.03125
4
from calendar import monthrange from datetime import date weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] weeks = {'1st':0, '2nd':1, '3rd':2, '4th':3, 'last':-1} def meetup_day(year, month, day, week): """Return the desired date based on the nth weekday of the spec...
f2799846c16dfc6645d9d387c5b9c60e5f95c145
ikaros274556330/my_code
/python_1000phone/语言基础/day18-练习和网络编程/code/01-扑克作业.py
2,311
3.890625
4
"""__author__=吴佩隆""" # 如果一个类继承enum模块中的Enum类,那么这个就是枚举 from enum import Enum from random import * class PokerNum(Enum): J = (11, 'J') Q = (12, 'Q') K = (13, 'K') A = (14, 'A') Two = (15, '2') Three = (3, '3') Four = (4, '4') Five = (5, '5') Six = (6, '6') Seven = (7, '7') Ei...
051de7504b9cbd197791a75e938feda64c729b66
pakpake/licence-informatique
/2nd-year/structures-de-donnees-algos-python/tp11/pakpake-tp11-2.py
6,217
3.9375
4
class ArbrePrefixe() : """ Arbre prefixe contenant des mots ayant la meme premiere lettre """ def __init__ (self,lettre,derniere=False,fils=[]): """ Initialise l’arbre ; Entree : la lettre prefixe de l’arbre """ # pour construire des arbres simples, on a rajouté les parametres # derniere...
40a20666748f306e2dbb0e4391e29d5f961671e3
jaredledvina/adventofcode2020
/day4/day4.py
3,238
3.78125
4
#!/usr/bin/env python3 def read_input(): with open('input.txt') as f: puzzle_input = f.read().splitlines() return puzzle_input def eval_passport(passport): required = [ 'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] for attr in required: ...
567848b638d6d8694afb6c3089caa079145dd740
loganyu/leetcode
/problems/404_sum_of_left_leaves.py
1,447
4.0625
4
''' Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): ...
1d1f7f085defc8ba9fc9c58f067dab131e1cf9de
jonjhallett/covid-19
/prob.py
1,208
3.625
4
#!/bin/python3 -tt import math deaths_in_uk = 5000 population_of_uk = 66400000 fatality_rate = 0.009 doubling_rate_in_days = 17 average_time_to_death_in_days = 17.3 def main(): for number_of_people in [3, 4, 6, 10, 20, 30, 350, 700, 1400, 3500, 35000]: probability = probability_of_at_least_one_case(num...
49c277c5d22470743aae14990f4604054e23c273
MEENUVIJAYAN/python
/python lab 6/max.py
275
4.0625
4
#Python program to get a maximum and mininum value in a dictionary a = {'x':500, 'y':5874, 'z': 560} maximum = max(a.keys(), key=(lambda k: a[k])) minimum = min(a.keys(), key=(lambda k: a[k])) print('Maximum Value: ',a[maximum]) print('Minimum Value: ',a[minimum])
ae43de603a4409f047712e81fa0bc573e10ec236
Aguirre718/File_Handling
/main.py
421
3.96875
4
# -*- coding: utf-8 -*- def main(): print(' Search a word in .txt file ') word = str(input('Enter the word to be searched: ')) find_word(word) def find_word(word): counter = 0 with open('texto.txt') as f: for line in f: counter += line.count(word) print('The word {}...
c436bab80c65d630d6d77cf799cdcd71b38d7fa7
droptablestar/capitalize_mapreduce
/model-mapper.py
1,250
3.640625
4
#!/usr/bin/python import sys # this will be our features dictionary features = {} LOWER = 1 UPPER = 0 for line in sys.stdin: line = line.strip('\n').split() for word in line: isLower = word.islower() length = len(word) # break the work into features depending on its length if ...
d855213751d1e3838c886440c8c39820107cf2a8
sriley86/Python-4th
/Python Chapter 3 February Days.py
485
4.25
4
# Chapter 3 Exercise 16 February Days # This program Asks the User to Enter a Year, Display the Number of Days # in February of that Year. # Input year = int(input('Enter a year: ')) # Process and Output # Is the Year Divisible by 100 and 400 # (year % 100) == 0 and if (year % 400) == 0: print(' In February', ...
3528abd7a48e6ef9451cbc0c24cd8c0a1fa18e3f
lubisarieff/example-qiskit
/full-adder/test_full_adder.py
1,128
3.5625
4
""" Author : Arief Muhammad Lubis Created on 11 Apr 2020 Code for adder two number using quantum computing """ from FullAdder import FullAdder def main(): # Before you can use the jobs API, you need to set up an access token. # Log in to the Quantum Experience. Under "Account", generate a personal ...
7a165c4d007d1ba99dc4024e658e26bcc7dbee5d
hector81/Aprendiendo_Python
/Listas/Ordenacion_listas.py
729
4.40625
4
''' ORDENACIÓN DE LISTAS ''' x = [8, 2, 3, 7, 5, 3, 7, 3, 1] print(x) print(f"1. El mayor número de la lista ") print(f"{max(x)}") print(f"2. El menor número de la lista ") print(f"{min(x)}") print(f"3. Los tres mayores números de la lista ") lista = sorted(x, reverse=True) print(lista[0:3]) print(f...
e9a2cf22c1d95574d2c838cc9d63feb8fa46c261
anshikasangwan/pythonBasics
/databaseSQL(retriving).py
628
4
4
#import sqlite3 #MySchool=sqlite3.connect('schooltest.db') #sql="SELECT * from student;" #curschool=MySchool.cursor() #curschool.execute(sql) #while True: # record=curschool.fetchone() #fetches the next available record from the result set # if record==None: # break # print (re...
ebd473eec700b4c073efcd1464cc61095e2e70fc
osheen77/python_7
/chapter_8.py
5,276
3.625
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 3 14:41:47 2020 @author: Osheen """ print("Exercise 8.1") def display_message(): # deffining message print("\nI am learning chapter 8") ##################################################### display_message() print("\nExercise 8.2") def fav_book(book): print("The n...
b4052e36121053547f8b0aceb9923b84d786814e
red-sap/cloud1907
/03.tuple_struct/example01.py
1,120
3.9375
4
# 如何间接更改元组中的元素 list01 = [1, 2, 3, 4, 5] # tuple01 = (1, 2, 3, 4, list01) tuple01 = (1, 2, 3, 4, [1, 2, 3, 4, 5]) # print(type(tuple01)) tuple01[-1][3] = 'c' print(tuple01) # 元组中的方法 # index, count # 元组中是支持索引, 可以支持元素的查找, 也可以支持遍历元组 t01 = (1, 2, 3, 4, 5) print(t01[1:3]) for i in range(len(t01)): if t01[i] % 2 == 0: ...
bfa0aefa191449b58f4c5d123745eb0681c3ddab
waverim/leetcode
/python/populating-next-right-pointers-in-each-node.py
1,441
4.0625
4
""" 层序遍历,首先暂存节点的左子节点 若该节点有左右子树,左->右,没有既是叶子节点 判断右子节点是否还可以连接更右的节点: 如果该右子节点的父节点的next不为空,则表示可以连接, 即链接该右子节点的父节点的next节点的左子节点 这样上一层联通之后,下一层可循环解决 """ # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None ...
dc7ccb39cf0cdf69e9500858b900f47f20a00bcf
villarrealp/sudokuD
/Code/BacktrackingAlgorithm.py
6,924
3.78125
4
""" Author: Miguel Haruki Yamaguchi Date created: 10/13/2009 Description: Sudoku Puzzle Solver Modified: 07/08/2013 by Pilar Villarreal Comments: Use bactracking algorithm from the original file SudokuSolver.py, the code was adapted for the fin...
d48fcba372b9f95c37ec6b48409c0c491a94767b
nopedawn/python-repository
/pythonbasic/for-loop,else,range,break.py
224
3.9375
4
# variable angka = 8 # for-loop, else, range, break for urutanAngka in range(0,10): print(urutanAngka) if urutanAngka is angka: print('angka', angka, 'ada lur') break else: print('angka', angka, 'tidak ada lur')
8ff86507dc94de484d216b158cb7ec48580a566d
Qieclipkh/study-python
/study/study07/study07.py
3,390
4.09375
4
#更加抽象 #多态 #参数是支持加法的对象,都可以使用operater模块的add方法 import operator print(operator.add(1,2)) print(operator.add('changle','le')) #封装 #继承 #创建自己的类,参考study07_002 #特性、函数和方法 class Class: def method(self): print('I hava a self') def function(): print('I don\'t...') instance =Class() instance.method() instance.meth...
3e32907a1fe09758b54090abdfc96c9d86c18f8a
yaoayaoflora/gogoyao
/DataStructuresAlgorithms/grokking-the-coding-interview-patterns-for-coding-questions/2_Two_Pointers/2_1.py
747
4.09375
4
# Given an array of sorted numbers and a target sum, find a pair in the array whose sum is # equal to the given target. # Write a function to return the indices of the two numbers (i.e. the pair) such that they add up to # the given target. def pair_with_targetsum(arr, targetSum): left = 0 right = len(arr) -...
093026b2b7541c7c7cf1a633a35edeab4add8d47
nguyenthanhvu240/DataAnalyst
/DA-With-W3school-Course/Matplotlib/pieCharts.py
357
3.71875
4
import matplotlib.pyplot as plt import numpy as np y = np.array([10,10,30,50]) #counterclockwise : nguoc chieu kim dong ho mylabel = [1,2,'three','four'] plt.pie(y,labels=mylabel) plt.show() plt.pie(y,labels=mylabel,startangle=90) #truc toa do plt.show() plt.pie(y,labels=mylabel,explode=[0.2,0,0.6,0],shadow=True) p...
6a853330747fd4e8ec35d3a4f0fc8b5d6028f91d
szabgab/slides
/python/examples/basics/if.py
220
3.6875
4
def main(): expected_answer = "42" inp = input('What is the answer? ') if inp == expected_answer: print("Welcome to the cabal!") print("Still here") print("This always happens") main()
1929408e029c64f5922f0c7708003c7d96066609
nian-mejia/Python-Poo-Algorithmost
/others/verificar_parentesis.py
1,153
3.53125
4
def parejas(str_pareja): list_simbols = ["()",r"{}", "[]"] if str_pareja in list_simbols: return True else: return False global b1 b1 = 0 def clean(simbols): if len(simbols) > 1: if parejas(simbols[-2:]) == True: simbols = simbols.replace(simbols[-2:], "") ...
32631887d5ca544b68f3e7efb78012dda3ceb175
flowbish/my_scripts
/calcprimesbelow
384
3.671875
4
#!/usr/bin/env python # # Calculate the prime below a number import sys max_num = 1 if len(sys.argv) > 1: max_num = int(sys.argv[1]) nums = range(2,max_num+1) i = 0 while i < len(nums): length = len(nums) nums = [nums[i]] + [n for n in nums if not n % nums[i] == 0] if len(nums) == length: b...
123b2dfb4054cd37e1afb8e37b13b1c490737ba5
frerich/aoc2020
/day3.py
1,011
3.640625
4
def parse(fn): with open(fn) as f: lines = [line.rstrip() for line in f] width = len(lines[0]) height = len(lines) trees = set() for y, line in enumerate(lines): for x, char in enumerate(line): if char == '#': trees.add((x, y))...
70f071476e6e49efc8810021f824a1cce6719459
moheshwar/Pythonprojects
/Generate Order Summary.py
7,022
3.75
4
''' Created on Oct 2, 2019 @author: Moheshwar Palani ''' ''' The program generates an time wise order summary for a coffee shop This includes text processing and calculations ''' import orderlog ORDERS = orderlog.orderlst OPEN=360 #Store opening time in minutes CLOSE=1440 #Store closing time in minutes...
122d184ca3a5d7a1f6b5f633c6bb15ede2c4ebcf
mmankt2/CodingDojo
/Python/python_fundamentals/insertion_sort.py
378
3.96875
4
#! /usr/local/bin/python3.7 def insertion_sort(myList): for i in range(1,len(myList)): j = i -1 minIndex = j while j >= 0: if myList[i] < myList[j]: minIndex = j j -= 1 if myList[minIndex]>myList[i]: temp = myList[i] myList.pop(i) myList.insert(minIndex,temp) r...
13432547497cb9305225958e16068dc8d5614740
shiqi0128/My_scripts
/test/practise/ten/test_02.py
1,719
4.0625
4
# 10-06加法运算 # print("Please write down two numbers, we'll add them.") # print("Please enter 'q' to quit!") # while True: # try: # first_number = int(input("First number: ")) # except ValueError: # pass # else: # if first_number == 'q': # break # try: # secon...
44522519863ce9762e1bc0ffed67480cff674160
ashisharma23/Udacity-Data-Analyst-Nanodegree
/Working with MongoDB/processing.py
5,826
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ In this problem set you work with another type of infobox data, audit it, clean it, come up with a data model, insert it into MongoDB and then run some queries against your database. The set contains data about Arachnid class animals. Your task in this exercise...
8a463adc2d12701e7079fbebd67f68e40d9ac730
TCmatj/learnpython
/10-1_python_study.py
405
3.5625
4
# TC 2020/10/9/22:20 filename = 'C:\\Users\\Administrator\\Desktop\\learnpython\\python_study.txt' with open(filename) as file_object: contents = file_object.read() print(contents) with open(filename) as file_object: for line in file_object: print(line.rstrip()) with open(filename) as file_object: ...
f85f0fe620193079da59d4568ee330f8ef112214
SNU-sunday/Raspi_lab
/led/led.py
1,361
3.5
4
from __future__ import print_function, division from RPi import GPIO import time LEDpin = 20 def setup(LEDpin): GPIO.setmode(GPIO.BCM) GPIO.setup(LEDpin, GPIO.OUT, initial=GPIO.HIGH) print('Setting the GPIO modes to BCM Numbering') print('The number of BCM pin is: %i'%LEDpin) def on(LEDpin): ...
0c63555f5959ecb4e548a39513fdb19611b93464
pnovotnyq/python_exercises
/07_RPS.py
2,223
3.921875
4
#! /usr/bin/env python3 ''' Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the wp, and ask if the players want to start a new game) Remember the rules: Rock beats scissors Scissors beats paper Paper beats rock ...
626c6d2d28a77056ec731bb6d6d91683147423f8
MiroVatov/Python-SoftUni
/PYTHON OOP/Previous Exams/Python OOP - Exam Preparation - 2 April 2020/skeleton/tests/test_trap_card.py
1,282
3.875
4
import unittest from project.card.trap_card import TrapCard class TestMagicCard(unittest.TestCase): def setUp(self): self.trap_card = TrapCard("Pinokio") def test_trap_card__init__(self): self.assertEqual(self.trap_card.name, "Pinokio") self.assertEqual(self.trap_card.damage_points,...
37f0bdea9388286ee8a1ac0ec3f7b6e4578749e2
st362515241004/menny
/Exercise8_nattaphat_b.py
1,208
3.59375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: #นาย ณัฐภัทร บุญรอด 362515241004 EE36241N Username=input("Username :") Password=input("Password :") if Username=="ntp" and Password=="0918": print("Welcome to mennybar Shop.") print("-------------------Menu-------------------") print("Welcome to mennybar Sho...
01bda1414e0001d9f6d44b6ad81dce5db4147715
AdamZhouSE/pythonHomework
/Code/CodeRecords/2730/60623/284735.py
269
3.71875
4
a=int(input()) t=[] tL=[] for i in range(a): b=input() l=input().split() t.append(b) tL.append(l) if tL==[['40', '50', '60'], ['4', '5']]: print(1) print(1) elif tL==[['40', '50', '70'], ['2', '5']]: print(0) print(0) else: print(tL)
0d116aad80c9626b1e1575a71605b1177e7daf57
jsw95/deep-rl-ai
/src/utils.py
264
3.59375
4
import numpy as np def board_to_array(board): """Transforms the 0s and Xs to numpy array of -1, 1, 0""" mapper = { "X": 1, "O": -1, " ": 0 } board_array = np.array([mapper[sq] for sq in board]) return board_array
3c5a47a5adef6b1cd948d6dd601a3262aaf1bdef
sheen4n/python-course
/4-mutable_immutable.py
261
3.8125
4
x = 1 print(id(x)) # print address of location # Primitive types such as int, string is immutable x = x + 1 print(id(x)) # new reference of x because integers are immutable x = [1, 2, 3] print(id(x)) # notice that lists are mutable x.append(4) print(id(x))
f5f7032150e8eb219f3271e7621cb638f86215a1
serleo86/Learning_Python
/3/3.1.8.py
142
3.859375
4
x=float(input()) def f(x): if x<=-2: s=1-(x+2)**2 elif x>2: s=(x-2)**2 +1 else: s=-x/2 return s f(x)
306f030b69423ffdcea0930b493a5f8aecadc2ab
asiemz/cmpt120siemionkowicz
/project/logic_gates.py
530
3.5625
4
#logic_gates.py def and_g(a,b): if a==1 and b==1: return 1 else: return 0 def or_g(a,b): if a==1 or b==1: return 1 else: return 0 def not_g(a,b): if a==0: return 1 elif a==1: return 0 #above are the three basic functions def nand_g(a,b)...
4918447991c4fc393d83d0a13d82e0ab9647d516
pmontesd/katando_python
/20180929/03_roman_validator/roman_validator.py
584
3.53125
4
def roman_validator(roman_number): digit_valid_reps = { "I": 3, "V": 1, "X": 3, "L": 1, "C": 3, "D": 1, "M": 3 } not_valid = ["IL", "ID", "IM", "XD", "XM", "VX", "VL", "VC", "VD", "VM", "LC", "LD...
05ea99b0303e0079ad97ac64eccd0651a4436b7f
DarthSidM/repo1
/sum of squares.py
89
3.953125
4
sum=0 n=int(input("enter value:")) for i in range(1,n+1): sum=sum+i**2 print(sum)
d7a7de9385e68e0b4bdca87411f5d85b75b57355
iholliday/-objective1-iholliday
/Characters.py
234
3.890625
4
#characters #subroutine to output text def char(): digits = '0123456789' characters = 'abcdABCD@#!£' print('The digits are:', digits, ' \nThe characters are:', characters, ' \nThe alphanumerics are:', digits, characters) char()
6d91a3f9f8bf1d34c80d4b13d0997aa8763e7780
matey97/Programacion
/Boletín2/Ejercicio29.py
290
3.90625
4
''' Created on 15 de oct. de 2015 @author: al341802-Miguel Matey Sanz ''' n=float(input('Introduce un número: ')) minimo=n fin=1 while fin==1: a=float(input('Introduce un otro número:')) if a<0: fin=0 elif a<minimo : minimo=a print('Mínimo: ',minimo)
0ca12599d692b0f7a46966c6603f5b78334df63f
XxTyaftioNxX/LyricalBot
/graph.py
1,684
3.5625
4
#Markov Chain Representation import random #define the graph in terms of vertices class Vertex: def __init__(self, value): self.value = value self.adjacent = {} #nodes that have edge to this vertex self.neighbours = [] self.neighbour_weights = [] def add_edge_to(self, vert...
cd73272ff7aea26f09bcb79fae88f883ec185e5b
itsbhm/python
/03_Operators.py
423
3.859375
4
# Arithmetic Operators and Strings age1 = 10 age2 = 18 sum = age1 + age2 sub = age2 - age1 mul = age1 * age2 div = age2 / age1 mod = age2 % age1 print(sum) print(sub) print(mul) print(div) print(mod) firstName = "ITSBHM" lastName = "Group" fullName = firstName + " " + lastName print(fullName) print("Hi" * 10) s...
c0556765191e7d7e49ad7f34b79770933d9e98c0
iguess1220/py
/0918/lambda.py
368
4.15625
4
# 匿名函数 # a = lambda x,y: x+y # print(a(1,2)) # #定义匿名函数并直接调用 # result =(lambda x,y: x*y)(1,2) # print(result) # 传入可变参数, 返回列表生成式,直接调用取值 result = (lambda *x: [i*i for i in x ])(1,2,3,4) print(result) # 解包赋值 a,b,c = (lambda *x: [i*i for i in x ])(2,4,6) print(a) print(b) print(c)
350aa8045b4a21b5f782bb654899595d429a8df7
thakuli/rally_team6
/avarage.py
618
3.640625
4
MAX_ITEMS=5 class Average: def __init__(self): self.nums = [] def add(self, num): self.nums.append(num) if len(self.nums) == MAX_ITEMS: self.nums.pop(0) def average(self): return reduce(lambda x,y: x+y, self.nums)/len(self.nums) def testi(): avg ...
44fb39c771837a4c748c909348c1670b2c71731e
luizhmfonseca/Estudos-Python
/EXERCÍCIOS - meus códigos/EX18.py
162
3.890625
4
import math ángulo = float(input('Digite um angulo: ')) seno = math.sin(math.radians(ángulo)) print('O angulo e {:.2f} e o seno e {:.2f}'.format(ángulo, seno))
2e159615613320a65c109314475c74606f78858a
Synaxis/py
/ww3/tuples.py
1,143
4.5
4
#negative indexing #negative indexing means beggining from the end thistuple = ("apple", "banana", "cherry") print(thistuple[-1]) #Change Tuple Values """once a tuple is created , you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But you can convert the tuple into a list , an...
2bfaba613fd07f917856439b2d4d794722b21590
daniel-reich/ubiquitous-fiesta
/FPNLQWdiShE7HsFki_1.py
1,893
3.5
4
from math import sin, pi inner_edge = [i * 2 * sin(pi / 8) for i in range(5)] grid = "ABCDEFGH" ​ def spider_vs_fly(spider, fly): s_radial, s_radius = spider[0], int(spider[1]) f_radial, f_radius = fly[0], int(fly[1]) s_idx = grid.index(s_radial) clockwise = 0 while grid[(s_idx + clockwise) % 8] !=...
b747001979b68a34e19c88042f1631b7c1091503
djmatt/adventofcode
/2017/day03/aoc2017d03p2.py
1,497
4.0625
4
from itertools import islice def spiralgen(): ''' Infinite spiral generator ''' loc = (0, 0) yield loc ring = 1 while True: # move right for the next ring loc = (loc[0]+1, loc[1]) yield loc # move up right side for _ in range((ring * 2)-1): ...
de8f0b3d5c375466a0ce42a6d7f55cd928c9bbbb
Dissssy/AdventOfCode2020
/01/2/code.py
1,072
3.828125
4
import time start_time = time.time() #open the file and parse it into a list of strings on newlines text_file = open("input.txt", "r") lines = text_file.read().split('\n') #every input text file has an empty newline at the end, delete it lines.pop(-1) #convert every string in the list to an int for i in range(0, len(...
deb9718bfcbf3b60891dd88d7c7b07e4f8cb7d4a
twopiharris/230-Examples
/python/basic3/inventory.py
851
3.890625
4
""" inventory.py Demonstrates lists 4/20/06 """ inventory = [ "toothbrush", "suit of armor", "latte espresso", "crochet hook", "bone saw", "towel"] print("I packed these things for my adventure:") print(inventory) print print("I love my {} and my {}".format(inventory[2...
48b99c8213ba9bd73aba5f2c9ff17a622e9d1162
MrFan313/write_code01
/w_字符串大小写转化.py
204
3.5
4
#coding = utf-8 ''' 标题 @name: @function: @author: Mr.Fan @date:2021-- ''' str = 'hello world' str2 = 'HELLO' #大写.spper s = str.upper() #小写 s2 = str2.lower() print(s,s2)
5f7ab053e0ddd1a1e41056b8c4f2ba14c442efef
Mariama2006/holbertonschool-higher_level_programming
/0x0A-python-inheritance/8-rectangle.py
538
3.640625
4
#!/usr/bin/python3 """class Rectangle """ BaseGeometry = __import__("7-base_geometry").BaseGeometry class Rectangle(BaseGeometry): """Rectangle inheirit from geometry """ def __init__(self, width, height): """instance Arguments: width {int} -- [width fo rectangle] ...
f504db7524ed4f91ecf39be62d36d4bdd51c46f4
daniel-reich/turbo-robot
/TamJueJxoWNctcQoD_23.py
447
4.21875
4
""" Write a function that returns `True` if both numbers are: * Smaller than `0`, OR ... * Greater than `0`, OR ... * Exactly `0` Otherwise, return `False`. ### Examples both(6, 2) ➞ True both(0, 0) ➞ True both(-1, 2) ➞ False both(0, 2) ➞ False ### Notes Inputs will always ...
9baad5039d1b364d5cca82ef4c74b80b8f984b9e
Drobyazko/python-laboratory
/laboratory 5/Task 5.1.py
281
3.859375
4
n = 0 while n!=1: print("Enter list") list=input().split(' ') result = [] for element in list: for part in element: result.append(part) print(result) print("Enter 0 if you want to continue and 1 if you want to stop") n = int(input())
b9a3751f5dca4589ad71f529a5a0f1527a10ba09
halsa011/Python_Class
/lists1.py
310
3.765625
4
fname = raw_input("Enter file name: ") fh = open(fname) lst = list() words=list() delete_list=list() for line in fh: lst=line.split() words.extend(lst) words.sort() for i in range(len(words)-1): if words[i]== words[i+1]: delete_list.append(words[i]) for i in delete_list: words.remove(i) print words
ccb1fd9d1e3b70fd97b153ad54a7bb40837582ab
TylerBromley/fullstack_python_codeguild
/lab15-number-to-phrase_v2.py
2,218
3.921875
4
# lab15-number-to-phrase.py # convert a given number to its english representation. tens_dict = {0: "", 1: "teen", 2: "twenty", 3: "thirty", 4: "forty", 5: "fifty", 6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety"} ones_dict = {0: "", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven...
5f8200aaa58f1e514c8c851c26298df112f00256
praneesh12/Data-Structures-Algorithms
/Algorithms/search_and_recursion/binary_serach.py
780
3.53125
4
#binary_serach.py Iterative Version import logging logger = logging.getLogger(__name__) def binary_search_iterative(input_array, value): try: low_index = 0 high_index = len(input_array) - 1 while low_index <= high_index: middle_index = (low_index + high_index)//2 # rounds off to lower middl...
625b8fe76200201c5a8779fa533ef52452919853
nsuryateja/python
/vowelFinder.py
494
3.828125
4
string = 'the fragrance of flowers spreads only in the direction of the wind' lis = string.split() print(lis) vowel = 0 num = [] for i in range(len(lis)): k = lis[i] for r in k: if (r== 'a' or r== 'e' or r== 'i' or r== 'o' or r== 'u' ): vowel = vowel +1 num.append(vowel) vowel = 0 p...
2947e1c606d5dae95dbf724bfd6b2ed5a982bc1f
mzb2599/python
/set/s2.py
259
3.546875
4
#12-1-2020 squares = {1, 4, 9, 16} print(squares) print(4 in squares) print(9 in squares) # set = squares - set(16) print(squares) # squares = squares + 16 # i=5 # for i in range(10): # squares = squares + (i ** 2) # i=i+1 # print(squares)
d129f3645f92e56e93bb0e437f04d80de1aab7b7
kushalmae/test
/hello.py
156
4.15625
4
## test23 print("hello") print("Kushalisawesome") kushal = "hi" + "Kushal" KingName = input("What is Your Name?") print("Name of the King is" + KingName)
7853a792dbf8c09ec92c9b3e64ab56a7273285d5
Grug16/CS112-Spring2012
/hw07/search.py
1,302
4.0625
4
#!/usr/bin/env python """ Binary Search This was supposed to be a binary search algorithm but it isn't working... I used the Iterative implementation from here: http://en.wikipedia.org/wiki/Binary_search_algorithm """ from hwtools import input_nums nums=input_nums() nums = sorted(nums) #the Sorted function doesn'...
8d88226b86443c87667c9f6476dc97b887b0af35
danielnilssoncole/pythonPractice
/regex_practice.py
780
4.3125
4
import re #? 1 or 0 times #* 0 or more times #+ 1 or more times #[] indicates a set of chars #[^ab] inverts the set === every char except 'a' or 'b' def find_word(phrase, substr): match = re.search(re.escape(substr) + r'\w*', phrase) if match: print('found: {0}'.format(match.group())) else: ...
b04db7779cf8c738dbe83aa950b4353da1004f84
tori62/web-caesar
/caesar.py
464
4.0625
4
from helpers import alphabet_position, rotate_character def rotate_string(text,rot): new_string = '' for char in text: if char == ' ': new_string = new_string + ' ' else: new_string = new_string + rotate_character(char,rot) return new_string def main(): message ...
e29b9b36a1351c07b1c5055061b01914aadf7488
andreabassi78/BiophotonicsLectures
/FourierTransforms/FTexamplesMAIN.py
2,277
3.671875
4
''' Created on 2 ago 2019 Shows examples of calculation of 2D Fourier Transform @author: Andrea Bassi, Politecnico di Milano Lecture on 2D Fourier Transforms and filtering Optical Microscopy Course (Biophotonics) ''' import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from numpy.fft import ff...