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
20099604968983eb02c4ec2b0f9c67600afcf002
anuragdogra2192/Data_structures_with_python3
/strings/integer_to_string.py
899
4.28125
4
""" Integer to string Built-in functions used in the code 1) ord() The ord() function returns an integer representing the Unicode character. ord('0') - 48 ord('1') - 49 : : ord('9') - 57 2) chr() Python chr() function takes integer argument and return the string representing a character at...
66ca2398e71e7faf0042e69596658d19d25a9409
anuragdogra2192/Data_structures_with_python3
/LargeAssociationItems.py
2,558
4.28125
4
""" My approach: DFS Question: In order to improve customer experience, Amazon has developed a system to provide recommendations to the customer regarding the item they can purchase. Based on historical customer purchase information, an item association can be defined as - If an item A is ordered by a customer, then ...
bc0d0b2cc4c375d1ad39868a51d91f965db0faa6
anuragdogra2192/Data_structures_with_python3
/queue/QueueFromStacks.py
758
3.78125
4
class MyQueue: def __init__(self): self.enq = [] self.deq = [] def push(self, x: int) -> None: self.enq.append(x) def pop(self) -> int: if not self.deq: while self.enq: self.deq.append(self.enq.pop()) return self.deq...
057936a9d73bf94e2ce3fab572082617614f5ee8
anuragdogra2192/Data_structures_with_python3
/arrays/PermutateArrayWithoutAdditionalStorage/Permute_the_element_of_an_array.py
1,517
3.9375
4
""" Permutate an array without additional storage Given: A = [a,b,c,d] Mapping a - 0 b - 1 c - 2 d - 3 c - 0 a - 2 perm = [2,0,1,3] == perm = [0,1,2,3] 0 1 2 3 b c a d 0 1 2 3 map 1 2 0 3 A = [b, c, a, d] 0 1 2 3 a b c d e ...
2e1a468b27e60fab379c6a2a0066e1c669422aab
anuragdogra2192/Data_structures_with_python3
/OptimizingBoxWeights.py
1,575
3.921875
4
''' Optimizing Box Weights: An Amazon Fulfillment Associate has a set of items that need to be packed into two boxes. Given an integer array of the item weights (arr) to be packed, divide the item weights into two subsets, A and B, for packing into the associated boxes, while respecting the following conditions: • Th...
4d5588bb7f64fd6ecb6d8848be244af5a8d221f1
ahdahddl/cytoscape
/csplugins/trunk/ucsd/rsaito/rs_Progs/rs_Python/rs_Python_Pack/tags/rs_Python_Pack090515/General_Packages/Usefuls/Excel_Col_Name.py
1,515
3.671875
4
#!/usr/bin/env python ALPHA = ("A","B","C","D","E", "F","G","H","I","J", "K","L","M","N","O", "P","Q","R","S","T", "U","V","W","X","Y", "Z") ALPHA0 = ("","A","B","C","D","E", "F","G","H","I","J", "K","L","M","N","O", "P","Q","R","S","T", ...
8727f10f0fcee19c9aa295e1069cc283c7dae453
ahdahddl/cytoscape
/csplugins/trunk/ucsd/rsaito/rs_Progs/rs_Python/rs_Python_Pack/trunk/General_Packages/Usefuls/Replace_by_dict.py
261
3.78125
4
#!/usr/bin/env python def replace_by_dict(s, d): ret = s ks = d.keys() ks.sort() for k in ks: ret = ret.replace(k, d[k]) return ret if __name__ == "__main__": print replace("ABCDEF", { "A": "1", "C":"3", "E": "5", "G": "7" })
c1905acffd40d6c31aaa19f640b4ef4daebedc59
ahdahddl/cytoscape
/csplugins/trunk/ucsd/rsaito/rs_Progs/rs_Python/rs_Python_Pack/trunk/Test_Packages/TestPy/iterator1.py
774
3.671875
4
#!/usr/bin/env python class Foo: def __init__(self): self.count = 0 def __iter__(self): return self def next(self): self.count += 1 if self.count > 5: raise StopIteration return self.count class ArrayTest: def __init__(self, ilist): self.ilis...
d491742d04ca948b413f5080fe8aa02a18adf331
ahdahddl/cytoscape
/csplugins/trunk/ucsd/rsaito/rs_Progs/rs_Python/rs_Python_Pack/trunk/Graph_Packages/Graph/IG1.py
1,416
3.578125
4
#!/usr/bin/env python """ Calculates interaction generality. """ from Graph1 import Graph import Node1 import Edge1 def IG_I(graph, node1, node2): interactors = list(set(graph.interactors(node1) + graph.interactors(node2))) # print interactors ig = 1 for node in interactors: if node is not no...
35249ca1225cbc69e8637b84349589399c67d068
ahdahddl/cytoscape
/csplugins/trunk/ucsd/rsaito/rs_Progs/rs_Python/rs_Python_Pack/tags/rs_Python_Pack080114/General_Packages/Usefuls/RangeList.py
736
3.78125
4
#!/usr/bin/env python class RangeList: def __init__(self, *range_list): self.range_list = range_list def check_overlap(self): """ ex: range_list = ((10, 20), (15, 21), (17, 30)) """ l_common = -10000000 r_common = 10000000 for range in self.range_list: ...
25f9da10af45308ca0ceafdd2d98f161a92f1bbf
ahdahddl/cytoscape
/csplugins/trunk/ucsd/rsaito/rs_Progs/rs_Python/rs_Python_Pack/tags/rs_Python_Pack080114/General_Packages/Usefuls/Counter.py
3,110
3.75
4
#!/usr/bin/env python # See also MultiDimDict class. class Count1: def __init__(self): self.counter = 0 def count_up(self): self.counter += 1 def add_count(self, val): self.counter += val def get_counter(self): return self.counter class Count2: def __init__(self): ...
b30a53d84be449ab0470a1f0dcab3dc909a4ee66
ahdahddl/cytoscape
/csplugins/trunk/ucsd/rsaito/rs_Progs/rs_Python/rs_Python_Pack/tags/rs_Python_Pack081007/General_Packages/XML/elementtree_practice1.py
642
3.640625
4
#!/usr/bin/env python import elementtree.ElementTree as ET # build a tree structure root = ET.Element("html") head = ET.SubElement(root, "head") title = ET.SubElement(head, "title") title.text = "Page Title" body = ET.SubElement(root, "body") body.set("bgcolor", "#ffffff") body.text = "Hello, World!" # wrap it i...
a17d75c373b0d4d29afe79844e746330a314d0e0
tianya1/python
/3.py
3,742
3.515625
4
#socket网络编程 见w3c课程 import socket import sys serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 9999 serversocket.bind((host, port)) serversocket.listen(5) while True: # 建立客户端连接 clientsocket,addr = serversocket.accept() print("连接地址: %s" % str(ad...
1bb0230e9ca9ae6404d40e7fd5a6091f4cbdb503
600rrchris/Python-control-flow-lab
/exercise-2.py
490
4.3125
4
# exercise-02 Length of Phrase # Write the code that: # 1. Prompts the user to enter a phrase: # Please enter a word or phrase: # 2. Print the following message: # - What you entered is xx characters long # 3. Return to step 1, unless the word 'quit' was entered. word = input('Enter "Please enter a word or ...
1a227101bb887a874d2088db2a8edae3b4ea9462
fengtianqi-GitHub/bj1910
/flask/1/code/myserver/test1.py
1,046
3.765625
4
# # d1 = {'a':10,'b':'hello'} # #get('键','默认值'),如果键不存在,不会报语法错; # print(d1.get('c','20')) # t1 = (1,2) # a,b = t1 # print(a,b) # import re # s1 = "hello1243rere" # pattern = r"123" # print(re.search(pattern,s1)) # def world(): # print("world") # def hello(): # print("hello") # # pf = hello # pf() # pf = world #...
d1060d81f5c7dd3af08be404565e66a7b743f815
patreilly/blackjack
/Game.py
2,895
3.765625
4
class Game: #Rules******************************************* #Blackjack starts with players making bets. #Dealer deals 2 cards to the players and two to himself (1 card face up, the other face down). #Blackjack card values: All cards count their face value in blackjack. Picture cards count as 10 and the ace can cou...
525fa36066c159ccd4a5f921f006ad71dbc47777
saurav-singh/CS260-DataStructures
/Assignment 3/floyd.py
1,718
4.375
4
#!usr/bin/env python # # Group project: Floyd's algorithm # Date: 03/13/2019 # # It should be noted that this implementation follows the one in the textbook """{Shortest Paths Program: shortest takes an nXn matric C of arc costs and produces nXn matrix A of lengths of shortst paths and an nXn matrix P giving a point i...
fe61f5c790fae2ca4a822f8923f93564ad416c29
ChefYeum/ChefYeumRandom
/archive/GoogleHashCode/qualification_round_2018/2018qual.py
732
3.75
4
from operator import itemgetter def distance(list): return abs(list[0]-list[2])+abs(list[1]-list[3]) if __name__ == "__main__": with open("a_example.in","r") as file: grid = [] for r in file.readlines(): grid.append(list(map(int,r.strip().split(' ')))) firstline = grid[0] ...
8edbc03db59844f2a04e40c913abbd4e3e560d0c
ChefYeum/ChefYeumRandom
/LeetCode/archive/860.py
717
4.0625
4
""" 860. Lemonade Change At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each custom...
61022b15e3dba74fbf9fa0213dd61cc70ad487d0
ChefYeum/ChefYeumRandom
/LeetCode/739.py
602
3.71875
4
from typing import List class Solution: def dailyTemperatures(self, T: List[int]) -> List[int]: def findFstWarmerPos(start): count = 1 for end in range(start+1,len(T)): if T[start] < T[end]: return count else: c...
177be93b8458d32c76a6997eb79ea536491fab33
dimDamyanov/Py-Fundamentals
/15. MORE EXCERCISE - Lists Advanced/05.py
2,185
3.78125
4
def format_start(): global maze for row in range(len(maze)): for col in range(len(maze[0])): if maze[row][col] == 'k': maze[row][col] = 1 def find_exits(): global maze exits = [] for row in range(len(maze)): for col in range(len(maze[row])): ...
dbbd0740cae3d79296d3e9eb36e01ee4ec1b303b
dimDamyanov/Py-Fundamentals
/19. EXERCISE - Dictionaries/02.py
270
3.859375
4
resource = {} line = input() while line != 'stop': quantity = int(input()) if line in resource: resource[line] += quantity else: resource[line] = quantity line = input() for key, value in resource.items(): print(f'{key} -> {value}')
b9e4da69c83f441cd3b5cf84559577e46bc652e2
dimDamyanov/Py-Fundamentals
/03. MORE EXCERCISE - Basic Syntax, Conditional Statements and Loops/05.py
367
3.78125
4
line = input() coffee = 0 while not line == 'END': if line.casefold() == 'coding' or line.casefold() == 'dog'\ or line.casefold() == 'cat' or line.casefold() == 'movie': if line.isupper(): coffee += 2 else: coffee += 1 line = input() if coffee > 5: print('...
f65d632cd638fd8fde602de7d5a398354f9c2807
dimDamyanov/Py-Fundamentals
/22. EXERCISE - Text Processing/04.py
100
3.6875
4
s = input() encrypted = [] for c in s: encrypted.append(chr(ord(c)+3)) print(''.join(encrypted))
7d52d970e8a6ff398aa99e553afb9b0afc0e1592
dimDamyanov/Py-Fundamentals
/02. EXCERCISE - Basic Syntax, Conditional Statements and Loops/03.py
280
4.15625
4
year = int(input()) if year == 88: print('Leo finally won the Oscar! Leo is happy') elif year == 86: print('Not even for Wolf of Wall Street?!') elif year != 86 and year < 88: print('When will you give Leo an Oscar?') elif year > 88: print('Leo got one already!')
f90262cfe5fa3543fd03cad3a16faa3760c053f0
dimDamyanov/Py-Fundamentals
/15. MORE EXCERCISE - Lists Advanced/03.py
402
3.828125
4
string = input() digits = [int(c) for c in string if c.isdigit()] non_digits = [c for c in string if not c.isdigit()] take = digits[::2] skip = digits[1::2] result = '' for td, sd in zip(take, skip): if td >= len(non_digits): result += ''.join(non_digits) else: result += ''.join(non_digits[:td]...
a1aeae43c77a7c699a1fecd468d0399c8c47cd4e
dimDamyanov/Py-Fundamentals
/05. EXCERCISE - Data Types and Variables/08.py
418
3.71875
4
size = int(input()) days = int(input()) coins = 0 for i in range(1, (days + 1)): if i % 10 == 0: size -= 2 if i % 15 == 0: size += 5 coins += 50 coins -= (2 * size) if i % 3 == 0: coins -= (3 * size) if i % 5 == 0: coins -= (2 * size) if i % 5 == 0: ...
addf730482b7c2df6a25e190effe4f91dc165639
dimDamyanov/Py-Fundamentals
/10. Functions/03.py
137
3.671875
4
input_string = input() n = int(input()) def repeat_string(string, rep): return string * rep print(repeat_string(input_string, n))
c0371e89375c352d37dbae102c6a252c9a5f7e28
dimDamyanov/Py-Fundamentals
/11. EXCERCISE - Functions/05.py
317
3.765625
4
data = list(map(int, input().split(', '))) def palindrome(nums: list): res = [] for num in nums: st = set() num_s = str(num) st.add(num_s) st.add(num_s[::-1]) res.append(True) if len(st) == 1 else res.append(False) return res print(*palindrome(data), sep='\n')
5323bc79bf9b40f585cb83a99c04f608bdf4ece1
jnguyen1991/Rosalind
/tree.py
1,484
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed May 23 15:48:10 2018 @author: jnguyen3 """ def parent_tree(n): #set up initial dict #each key represents a node, the value is its parent output = {k:1001 for k in range(1,n+1)} return output def tree(fpath): #goes through all edges, and picks one as its ...
5ab0115e9f7cafe7f38d194870d44295304c7275
FU11-M00N/Py_encryption
/2021-05-21/Diffie-Hellman.py
3,111
3.765625
4
import random # ============================================================================= # 소수 구하기 # ============================================================================= def is_prime(v): if v <2 : return False else: for a in range(2,v): if v % a ==0: re...
a92d226fe3884fcf0f785a8ecfbdaf2435121376
Jagermeister/CloversTilesHeartsPikes
/clovers_tiles_heart_spikes/cards.py
4,079
3.9375
4
""" A collection of cards and common utilities acting on them """ from functools import reduce from enum import Enum import random CARDS_IN_DECK_COUNT = 52 CARDS_IN_COLOR_COUNT = 13 DECK_BIT_MASK = (1 << CARDS_IN_DECK_COUNT) - 1 def bit_mask(index): return DECK_BIT_MASK - (1 << index) class Cards: """ Col...
17e3ffd4eaac11511e175582471aec8e8687489f
seungbok3240/Algorithm
/3613.py
922
3.5625
4
import sys import re s = sys.stdin.readline().rstrip() def printError(): print("Error!") sys.exit(0) if '_' in s: words = re.findall('[a-z]+', s) # c++ 대문자 유무 체크 if s != '_'.join(words): printError() tmp = s.split('_') result = tmp[0] for i in range(1, len(tmp)): tmp[i...
ce8c0e589b041e28a0d5ddcdb28ffe9cab62ef9b
seungbok3240/Algorithm
/1475.py
333
3.515625
4
from collections import defaultdict n = list(input()) int_dict = defaultdict(int) for i in n: if i == '6' or i == '9': int_dict['6'] += 1 else: int_dict[i] += 1 if int_dict['6'] % 2 == 0: int_dict['6'] = int_dict['6'] // 2 else: int_dict['6'] = int_dict['6'] // 2 + 1 print(max(int_di...
925e7f82b88b38f528e90cea00b09c421a6eed9d
ArseniyKD/RetroBulletHell
/GameOverScreen.py
5,682
3.859375
4
# Created by Arseniy Kouzmenkov 1542302 and Patrisha de Boon 1496979 import pygame import sys import os import shared import time import HighScoreTracking from text_to_screen import text_to_screen # the initialisation calls for pygame and the current screen along with the highs score tracking class. pygame.init() pyg...
398858f106a17ef8d036da226ad98c734f8733db
ArseniyKD/RetroBulletHell
/StartScreen.py
2,493
3.65625
4
# Created by Arseniy Kouzmenkov 1542302 and Patrisha de Boon 1496979 import pygame import sys import os import shared import time from text_to_screen import text_to_screen # the initialisation calls for pygame and the current screen. pygame.init() pygame.font.init() screen = pygame.display.set_mode((shared.width, sha...
db2968f291c70762d914f5a5c65137fa75e8a71a
Shiv015/python-learning
/8.py
310
3.953125
4
print 'Enter today\'s date in the formate dd/mm/yyyy: ' date = raw_input() dd,mm,yyyy = date.split('/') mm1 = ['01','03','05','07','08','10','12'] mm2 = ['04','06','09','11'] mm3 = ['02'] if (yyyy%400==0 and mm in mm1 and dd <=30): dd=int(dd)+1 print int(dd) + int(mm) + int(yyyy) else: print 'hi'
315c7b3cb27697eaf8701de087a9546ab286f5c1
MissPisces/python_GUI
/tkinter_04.py
585
3.875
4
# 组件布局place # 导入dkinter库 import tkinter # 创建主窗口对象 root = tkinter.Tk() # 设置窗口大小 root.minsize(500, 500) # 加入按钮组件1 btu1 = tkinter.Button(root, text='button1') # 摆放组件1 btu1.place(x=100, y=20) # 加入按钮组件2 btu2 = tkinter.Button(root, text='button2') # 摆放组件2 btu2.place(x=200, y=120, width=50, height=50) # 加入按钮组件3 btu2 = ...
41b0933e34e9d5193e5e257e34fe07b042754d03
MissPisces/python_GUI
/eventDemo_02.py
447
3.65625
4
# 事件绑定 键盘事件 import tkinter root = tkinter.Tk() root.geometry('500x500') # 定义变色函数 def changeR(eventobj): eventobj.widget['bg'] = 'red' def changeY(eventobj): eventobj.widget['bg'] = 'yellow' # 键盘事件绑定:按下r键 按下y键 ,注意区分大小写 root.bind('<Control-KeyPress-r>', changeR) root.bind('<Control-KeyPress-R>', changeR) r...
58e143dbe5668780ed69cd6eb2ea5200286fd53f
oguipcj/ListaDeExercicios
/ExerciciosListas/15.py
1,852
4
4
# 15. Faça um programa que leia um número indeterminado de valores, correspondentes a notas, encerrando a entrada # de dados quando for informado um valor igual a -1 (que não deve ser armazenado). nota_lida = 0 notas_lidas = [] while nota_lida != -1: nota_lida = float(input("Digite a nota ou -1 para encerrar: ")) ...
973a48bcf477b49c5d7352bda26d365134f81dca
oguipcj/ListaDeExercicios
/EstruturaSequencial/8.py
670
3.875
4
# 8. Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. # Calcule e mostre o total do seu salário no referido mês. valor_por_hora = float(input("Digite o quanto você ganha por hora: ")) quantidade_horas_trabalhadas = int(input("Digite o número de horas trabalhadas no mês: ...
158d766e760498e89c4aa53bed20298cfac613e3
oguipcj/ListaDeExercicios
/EstruturaSequencial/14.py
961
3.609375
4
# 14. João Papo-de-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de seu trabalho. # Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do estado de São Paulo (50 quilos) # deve pagar uma multa de R$ 4,00 por quilo excedente. João precisa qu...
acad35bb1e6f3f81a8b58084ccaa54b220f7b1ef
SSilvering/Python-Assignment-3
/src/src.py
13,395
4.53125
5
#===============================================================================# #---------------------------Python Assignment 3---------------------------------# # # # Student 1: Shai Hod - 304800402 ...
7f306d3d6e0f7fa61574c1bebfc38e1af8c058d0
TejsinghDhaosriya/python-practice
/jumpstart/conditional.py
181
4.21875
4
age = int(input("What is your age?")) if age>18: print("You can drive") elif age==18: print("We cannot decide you can drive or not") else : print("You cannot drive !")
d276e56a91a434bfac881f762b5d09e18599b4a8
TejsinghDhaosriya/python-practice
/set.py
223
3.59375
4
confusion = {} confusion[1] = 1 print(confusion) confusion['1'] = 2 print(confusion) confusion[1] += 1 print(confusion) sum = 0 for k in confusion: print("item are ",k) sum += confusion[k] print(sum) print (sum)
841c52c0b8d74828f6a30e8cc7c759e704fadde9
nmhoangg2000/session1
/ex2.py
112
4.125
4
r = float(input("What is the radius of the circle?")) S = r * 3.14 print("the area of the circle is" + str(S))
78f900448c6abe5f3f72c5e73a53a51676346f67
elkampu/Machine-Learning
/TilesBoard.py
6,781
3.671875
4
import copy import random from Tile import Tile class TilesBoard: def __init__ (self): self.tile1 = Tile(1, 0, 0, 2, 0) self.tile2 = Tile(2, 1, 0, 1, 0) self.tile3 = Tile(3, 2, 0, 0, 2) self.tile4 = Tile(4, 2, 1, 2, 1) self.tile5 = Tile(5, 2, 2, 2, 2) ...
5c2a7deae487170bdc0fa5b524847c577fa6b4d9
Serega6678/Python
/PythonCodeReview2-master/app/db_operations.py
1,073
3.6875
4
import sqlite3 class DatabaseHandler: def __init__(self, database_name): self.database_name = database_name def get_data(self, date): with sqlite3.connect(self.database_name + '.db') as conn: cur = conn.cursor() cur.execute('SELECT currency_rates.usd, currency_rates.ru...
0725be1066a074d73d764b67b8fe589b41b33cd7
rosewambui/NBO-Bootcamp16
/fizzbuzz.py
278
4.1875
4
"""function that checks the divisibility of 3, 5 or both""" """a number divisible by both 3 and 5 id a divisor 15, divisibility rule""" def fizz_buzz(num): if num%15==0: return "FizzBuzz" elif num%5==0: return "Buzz" elif (num%3==0): return "Fizz" else: return num
c7c0a272d6ba0eac9e5b8df3cfd3dba45db83a91
AFazzone/Python-Homework
/afazzone@bu.edu_hw_7_cmd_j.py
690
3.8125
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 2 13:26:25 2019 @author: alf11 """ str = """Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated""" def my_print (str, cursor): print(str[: cursor] + "^" + str[cursor :]) ...
8deb2e7e5c3e53f7769aec831a4a349621acc2ad
AFazzone/Python-Homework
/afazzone@bu.edu_hw_3_4_3.py
322
3.6875
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 10 20:50:53 2019 @author: alf11 """ a,b,c,d,e,f = eval(input("Enter a,b,c,d,e,f:")) if (a*d - b*c) == 0: print("The equation has no solution.") else: x = (e*d - b*f)/(a*d - b*c) y = (a*f - e*c)/(a*d - b*c) print("X is ", x, "and Y is", y)...
ac42344f6c84bdbe086c8ae55e918b19e5d1005a
AFazzone/Python-Homework
/afazzone@bu.edu_hw_10_6_5.py
381
3.890625
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 4 19:02:39 2019 @author: alf11 """ def displaySortedNumbers (x,y,z): x = [x,y,z] if x[0] > x[1]: x[0], x[1] = x[1], x[0] if x[0] > x[2]: x[0], x[2] = x[2], x[0] if x[1] > x[2]: x[1], x[2] = x[2], x[1] print("The...
5b88cdd33edcb0699629233d83617b73762c8105
AFazzone/Python-Homework
/afazzone@bu.edu_hw_7_extra_2.py
411
3.6875
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 2 14:43:12 2019 @author: alf11 """ str = """Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated""" def my_print (str, cursor): print(str[: cursor] + "^" + str[cursor :]) ...
08592b1c7b6938bc8c34dab4534dacad5b72ecb4
AlpinistPanda/newsdata
/news.py
1,901
3.5
4
#!/usr/bin/env python3 import psycopg2 db = psycopg2.connect(database="news") c = db.cursor() # Dont forget to run views.sql to create the views needed!! # QUESTION 1: What are the most popular three articles of all time? def question1(): query1 = '''SELECT title, views FROM articles ...
af9958bb4472c232176d09d165da46dab2c901b4
Rhushabh1/Handwritten-Digits-Classifier
/tf_basics.py
490
3.5625
4
import tensorflow as tf # we define the computational graph here # this all is happening in the backend of the program x1 = tf.constant(5) x2 = tf.constant(6) result = x1 * x2 # actually nothing is actually computed here # so it prints the tf object only print(result) # this is the interative session of the prog...
2699568119354b600426ed13fd39dbd6fd2c7ff6
L3onet/curso-python
/6.sqlite/dbDistanciaManhattan.py
2,792
3.9375
4
import sqlite3 from distanciaManhattan import * class dbDistanciaManhattan: __conexion = sqlite3.connect('dbDistanciaManhattan.db') def crearTabla(self): # Creamos el cursor cursor = self.__conexion.cursor() # Ahora crearemos una tabla de usuarios con nombres, edades y emails cursor.execute("CREATE TABLE I...
66d3d67a917e7453acf99d2de777677f90e43826
wingfai/Data_Structures_and_Algorithms
/recursion.py
413
3.578125
4
#!/usr/bin/env python # coding:utf-8 # Data Structures & Algorithms - recursion.py # 2018/10/18 15:13 __author__ = 'Wingfai Chow <chowwingfai@gmail.com>' def factorial(n: int): # n! = 1*2*3* ...* n! if n > 0: return n * factorial(n - 1) else: return 1 def fn(n: int): # 1 1 2 3 5 8 ...
6b596be7dbe7be8359e78e6bec3dba581d1762c7
mhorist/FunctionPractice
/FunkyPractice06.py
246
4.3125
4
# Write a Python program to reverse a string. def strRevers(charString): rstr = '' index = len(charString) while index > 0: rstr += charString[index - 1] index = index - 1 print(rstr) strRevers("abc def ghi jkl")
74b310c3a968d12caf330af00e6afa0f62cc44a0
junioraze/ml_sp_linear_regression
/linear_regression.py
921
3.921875
4
from statistics import mean import numpy as np import matplotlib.pyplot as plt # create values xs = np.array([1,2,3,4,5,6], dtype=np.float64) ys = np.array([5,4,6,5,6,7], dtype=np.float64) def best_fit_slop(xs, ys): ''' FUNCTION TO CALCULATE BEST FIT SLOP ''' m = ((mean(xs)*mean(ys)) - mean(xs*ys))/(mean(xs)...
8182b58aeb124fee4fbf42a16ff18a7790400fe4
Eisten1996/Curso-completo-de-Python-3
/Sección 6-Colecciones de datos/Conjuntos.py
261
3.8125
4
conjunto_colores = {"rojo", "verde", "azul"} print(conjunto_colores) for color in conjunto_colores: print(color) print(len(conjunto_colores)) conjunto_colores.add("negro") print(conjunto_colores) conjunto_colores.remove("verde") print(conjunto_colores)
27f643627e4835435b3a390f4b04594c22bc2b8c
Eisten1996/Curso-completo-de-Python-3
/Sección 12 - Ejercicios de bucles y condiciones/Ejercicio 3.py
445
3.6875
4
# 1. Crear una variable 'inicio' con el valor 1 # 2. Crear una variable 'fin' con el valor 6 # 3. Hacer un bucle while que muestre tantas filas como valores haya entre 'inicio' y 'fin' # 4. En cada interaccion del bucle mostrar el texto 'Esta es la fila' + numero de fila en la que esta inicio = 1 fin = 6 while (inici...
467ff5c86f9c3aff68f40885d941270473520a76
nobukatsu/stuff
/python/datetime_util.py
1,958
3.625
4
from datetime import datetime import os def get_datetime_from_date_suffix(file_name): root, ext = os.path.splitext(os.path.basename(file_name)) if has_yymmdd_suffix(root): # this check has to come first to avoid 170302 -> 1703/02/01 return datetime.strptime(root[-6:], "%y%m%d") elif has_yyyymm_su...
56d6310bbcf5e189c9217842550c88a8a79372a9
harshkumarkhatri/Hackerrank-Solutions
/Hackerrank-30-days-solutions/Day 2..py
466
3.875
4
#!/bin/python3 import math import os import random import re import sys # Complete the solve function below. def solve(meal_cost, tip_percent, tax_percent): x=meal_cost*(0.01*tip_percent) y=meal_cost*(0.01*tax_percent) totalcost=meal_cost+x+y print(round(totalcost)) if __name__ == '__main__...
799b7e0a24707104d797ec60da1143288f552c62
IsratIJK/URI-Problem-Solve
/2510.py
204
3.84375
4
T=int(input()) for i in range(T): a=input() length=len(a)#to get the length of a we can use len(string variable) if length >=0 and length <=25: print('Y') else: print('N')
24b54f6e7c047196a6581f0372594aeeab4eefa3
hirtiganto/The-Nature-of-Code-Examples-Python
/chp03_oscillation/NOC_3_10_PendulumExample/pendulum.py
3,183
4.25
4
# The Nature of Code # Daniel Shiffman # http://natureofcode.com # # Python port by Abhik Pal class Pendulum(object): """ A Simple Pendulum Class Includes functionality for user can click and drag the pendulum """ def __init__(self, origin, r): """ This constructor could be improve...
64555166020ef65bab4349759edc10320baa8082
hirtiganto/The-Nature-of-Code-Examples-Python
/chp03_oscillation/Exercise_3_11_AdditiveWave/Exercise_3_11_AdditiveWave.pyde
1,846
3.875
4
# The Nature of Code # Daniel Shiffman # http://natureofcode.com # # Python port by Abhik Pal # Additive Wave # Create a more complex wave by adding two waves together. # How far apart should each horizontal position be spaced xspacing = 8 # total # of waves to add together maxwaves = 5 theta = 0.0 # Height of wa...
26e1846cc727098af6b96df7eb450711b2b0d46d
hirtiganto/The-Nature-of-Code-Examples-Python
/chp03_oscillation/NOC_3_11_spring/spring.py
2,140
4.0625
4
# The Nature of Code # Chapter 3: Oscillation # Daniel Shiffman # # Python port by Abhik Pal class Spring(object): """ Class to describe an anchor point that can connect to "Bob" objects via a spring. Thank you: http://www.myphysicslab.com/spring2d.html """ def __init__(self, x, y, l): ...
d3a4bbad64ef8b5277d5659f3993957403a06271
hirtiganto/The-Nature-of-Code-Examples-Python
/introduction/SelfAvoidingWalk/walker.py
1,276
3.75
4
# Daniel Shiffman # The Nature of Code # http://www.shiffman.net/ # A random walker object! class Walker(object): def __init__(self): self.x = width / 2 self.y = height / 2 self.grid = [] for _ in range(width): self.grid.append([False] * height) def render(self): ...
3a11a1b7eea2abba7b0343017a893c06b0be2e82
hirtiganto/The-Nature-of-Code-Examples-Python
/chp04_systems/Exercise_4_04_asteroids/particle_system.py
757
3.609375
4
# The Nature of Code # Daniel Shiffman # http://natureofcode.com # # Python port by Abhik Pal from particle import Particle class ParticleSystem(object): """Simple Particle System A class to describe a group of Particles A list is used to manage the particles. """ def __init__(self): # Li...
928d3fa6bd92efa00a29f89c6a93cd017d254ec4
hirtiganto/The-Nature-of-Code-Examples-Python
/chp02_forces/Exercise_2_10_attractrepel/attractor.py
2,144
3.640625
4
# The Nature of Code # Daniel Shiffman # http://natureofcode.com # # Python port: Abhik Pal # A class for a draggable attractive body in our world class Attractor(object): def __init__(self): self.position = PVector(width/2, height/2) # Position self.mass = 10 # Mass, tied to size # h...
abb4cda42ae2be8a9138289ca89711c39ca45bdb
hirtiganto/The-Nature-of-Code-Examples-Python
/chp01_vectors/NOC_1_11_motion101_acceleration_array/NOC_1_11_motion101_acceleration_array.pyde
533
3.796875
4
# The Nature of Code # Daniel Shiffman # http://natureofcode.com # Demonstration of the basics of motion with vector. # A "Mover" object stores location, velocity, and acceleration as vectors # The motion is controlled by affecting the acceleration (in this case # towards the mouse) from mover import Mover moverCount...
71e93188146afa707ed1c9898b29f501451da991
vittascience/microbit-libraries
/game.py
1,591
3.53125
4
from microbit import display,sleep class GAME: def __init__(self): self.score=0 self.endGame=True self.startGame() def startGame(self): self.score=0 self.endGame=False display.clear() X=[2,2,2,2,3,4,4,4,3,1,0,0,0,1] Y=[0,1,2,4,4,3,2,1,0,0,1,2,3,4] for i in range(4): display...
3e343427e84750088ced3bded33681d72cb1446b
nishitabihani19/Python-and-Machine-Learning-Short-Codes
/func_add.py
869
3.6875
4
def addition(v1,v2): global sum v5=8 sum=v1+v2 print("a+b=",sum) write() return sum,v5 ''' def sub(): global sum sum=val1-val2 print("a-b=",sum) write() def mult(): global sum sum=val1*val2 print("a*b=",sum) write() def div(): global sum ...
55a0a87785683e6570074145bfdd6c6d3f9cc434
PrzemekBarczyk/arkanoid
/game_module/racket.py
1,819
3.53125
4
"""Moduł zawierający klase rakietki.""" import pygame from game_module import constants class Racket: """Klasa rakietki gracza: Porusza się w osi X sterowana przez gracza za pomocą myszy.""" def __init__(self): """Konstruktor inicjalizuje zmienne i tworzy powierzchnie piłki.""" self.w...
e73abad4edaf4f967fdb2bdb96285e3010506cc6
rajneesh05/Calculator-
/calculator.py
3,768
3.8125
4
from tkinter import* class Calculator: global operator global text_input def btnClick(self,numbers): self.operator=self.operator+str(numbers) self.text_input.set(self.operator) def clear(self): ## global operator ## global text_input self.text_input.set("...
f9f505ed02b844e1b868691f7001abbef51c3bd8
AlmogMaman/projectsToIDF
/Python/Boss Sniffer/Tools.py
583
4
4
def print_list(list): """ Prints the needed parameters for each packet. :param parameters_list: needed parameters, for each packet in a list. """ for element in list: print(element) print("\n\n") def print_live_packet(packet): """ Prints a packet in live time. :param packet: a packet. """ is_udp = U...
e6583be3c7c578cbd8dbaa3a0c9209829c77ed49
S010MON/docker-flask-mySQL
/app/entities/Dessert.py
302
3.640625
4
class Dessert: def __init__(self, dessert_id, name, cost): self.dessert_id = dessert_id self.name = name self.cost = cost def to_dict(self): return {"dessert_id": self.dessert_id, "name": self.name, "cost": round(self.cost, 2)}
43ef0d153e9104eaef11c247eed5b5c1827b040a
onaio/tally-ho
/tally_ho/libs/utils/numbers.py
464
3.734375
4
def rounded_safe_div_percent(numerator, denominator, precision=2, default=100): return round(100 * (numerator / denominator) if denominator else 100, 2) def parse_int(s): """ Parses a string to an integer and handles parse errors. Args: s (str): The string to parse. Returns: int: ...
f5cb729d404d18a695e16b715661accf7f632e96
adityarip/Tubes_Daspro
/F03_4_carigadget.py
2,562
3.625
4
def out(i,Gadget): #output untuk gadget print("ID : "+ str(Gadget[i][0])) print("Nama : "+ str(Gadget[i][1])) print("Deskripsi : "+ str(Gadget[i][2])) print("Jumlah : "+ str(Gadget[i][3])) print("Rarity : "+ str(Gadget[i][4])) print...
5353d0b73623ee93b0b6daec316ca0c7cef06a0a
ayatullah-ayat/cs50-course-activity
/course2-python/classes.py
587
3.84375
4
class Flight(): """docstring for Flight""" def __init__(self, capacity): self.capacity = capacity self.passengers = [] def add_passengers(self, name): if self.open_seats() == 0: return False self.passengers.append(name) return True def open_seats(self): return self.capacity - len(self.passengers) ...
2db7e00677625efb1119dab3fd48a6de2c3d1567
eflagg/dictionary-restaurant-ratings
/restaurant-ratings.py
1,861
4.40625
4
# your code goes here import random def alphabetize(filename): """Alphabetizes list of restaurants and ratings Takes text file and turns it into dictionary in order to print restaurant_name with its rating in alphabetical order """ username = raw_input("Hi, what's your name? ") print "Hi %s!"...
0dd69117cb20597cc16488e0b65cc35eed1683be
gmhaugen/python
/sortingalgorithms/bubblesort.py
418
4.0625
4
def main(): unsorted_list = [29, 54, 13, 23, 41, 20, 12,37, 38, 5, 7, 72, 39, 43, 64, 30, 71, 50, 45] sorted = False print("###BUBBLESORT###") print('Unsorted list:') print(unsorted_list) while sorted == False: for i in range(0, len(unsorted_list) - 1): current_number = uns...
a9c6667f25772f2ec474434aa9133866d6f0608b
Seiph59/presentation_python
/fichiers/listes.py
589
4.0625
4
# Création d'une liste ma_liste = [5, 6, 7] ma_liste2 = [1, 2, 3, 4] # Accès éléments print(ma_liste2[1]) # Ajout ma_liste.append(8) print(ma_liste) # [5, 6, 7, 8] # Insertion ma_liste.insert(4, 9) print(ma_liste) # Concatenation ma_liste2.extend(ma_liste) print(ma_liste2) # Suppression par index del ma_liste2[8] ...
063c98d5bbf5b35ab0dc8c95917f851820f898c3
harshal-shah16/Connect-Four
/connect_the_four_classes.py
15,935
3.859375
4
''' CS5001 - Spring 2020 Harshal Shah Project - Class Game Code ''' import turtle import time SQUARE_LEN = 50 CIRCLE_RADIUS = 20 TRIANGLE_SIDE = 20 class Game: """class: Game Attributes: rows, columns, red_filename, yellow_filename, x(x coordinate), y(y coordinate), red_score, y...
0182348d66c4898fb815b21cf542f28cef78a732
AstridLL/Natural-Language-Processing
/python_play1.py
2,046
3.796875
4
astring = "Hello world!" print(astring[3:8:2]) #(start:stop:step) #%% 1+1 #%% #%% print("hello") string = "hello there" print(string) import nltk #import tensorflow as tf # lidt ekstra code # lidt flere # ændring #import stanza #stanza.download("da") #stanza.download("en") # %% names = ["Pia", "Ina", "Rebecca...
ee17bb4675390e55f83dd430c5da1f5653c47c56
pennydew/ToxicFinal
/eda.py
1,771
3.5625
4
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns pd.set_option('display.max_columns', 500) data_train = pd.read_csv("resources/train.csv", low_memory=False) data_test = pd.read_csv("resources/test.csv", low_memory=False) data_test_labels = pd.read_csv("resources/test_labels.csv", low_memory=F...
565ec9ca59970f54aff5b241e4588c598e9be5bc
AmrHRAbdeen/Python
/COVID_19_Tracker.py
1,150
3.828125
4
############################################################### # This script is used to get specific content from Webpages... # @Author: Amr Abdeen # @Date: 23 March,2020 # COVID-19 CRISIS! ############################################################### import requests ### Beautiful Soup is a Python package for parsin...
d3f30f79bc57b3478e45eef6280f891682394a03
VVdovichev/Algoritms_Teaching
/Lesson_3/Task_5.py
543
3.890625
4
""" В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве. """ from random import random n = 10 my_list = [0] * n new_list = [] for i in range(n): my_list[i] = int((random() * 10) - 20) print(my_list) i = 0 index = -1 while i < n: if my_list[i] < 0 and index == ...
39a5053462e80a2ede595b1d639bec874e5a39b3
VVdovichev/Algoritms_Teaching
/Lesson_3/Task_9.py
626
3.796875
4
""" Найти максимальный элемент среди минимальных элементов столбцов матрицы. """ from random import random m_row = 5 m_str = 5 my_list = [] for i in range(m_str): new_list = [] for j in range(m_row): num = int(random() * 100) new_list.append(num) my_list.append(new_list) for i in my_list: ...
933cb40670046d95bfa03c327281a1f1b1663f53
VVdovichev/Algoritms_Teaching
/Lesson_3/Task_4.py
674
3.8125
4
""" Определить, какое число в массиве встречается чаще всего. """ from random import random n = 30 my_list = [0] * n new_list = [] for i in range(n): my_list[i] = int(random() * 100) print(my_list) print() num = my_list[0] max_quantity = 1 for i in range(n - 1): quantity = 1 for x in range(i + 1, n): ...
cc05850c98eed0509bf670814e371a149bd069c7
loveyouforever04/mike-test
/项目8.py
779
4.09375
4
# -*- coding: UTF-8 -*- # Filename : 05-if.py # author by : (学员lisa) # 目的: # 掌握使用 if 语句 #导入random(随机数)模块 import random print("\n----华丽分割线----") a=float(input("输入三角形第一边长 a=: ")) b=float(input("输入三角形第二边长 b=: ")) c=float(input("输入三角形第三边长 c=: ")) if (a+b>c)and(a+c>b)and(b+c>a): if(abs(a-b)>c)or(abs(a-c)>b)or(abs(b-c)...
f9668b8dd8c559e8a2338449fee23c5c60ad30da
ProjectOnePM/ProjectOneEjercicios
/Unidad 2 - IF/TP2_Ejer03.py
358
4.21875
4
print "-Calculo ascendente de 3 numeros-" N1=input("ingrese 1 numero") N2=input("ingrese 1 numero") N3=input("ingrese 1 numero") if (N1<N2<N3): print N1,"<",N2,"<",N3 elif(N1<N3<N2): print N1,"<",N3,"<",N2 elif(N2<N1<N3): print N2,"<",N1,"<",N3 elif(N2<N3<N1): print N2,"<",N3,"<",N1 elif(N3<N1<N2): print N3,"<",N1...
77cf807f550fffd13eeb8b7452e445ad33954412
SwaySway/pylabs
/SalesReceipt.py
305
3.5
4
#Josue Ruiz Lab 3 Part 2 def salesRecieptPrint(*cost, tax=0.08): sum=0 for i in cost: sum = sum + i return sum + (sum * tax) print("%2f" % salesRecieptPrint(80, 125, 45.5)) print("%2f" % salesRecieptPrint(95, tax=.105)) print("%2f" % salesRecieptPrint(12, 5.5, 6.5, 7.5, 9.0, tax=.07))
5b13a1cba09a26f97162196028e0bf52a63e0195
khk37601/Data-Structure
/Search/Quicksort.py
667
3.671875
4
# -*- coding: utf-8 -*- """ 정렬 알고리즘 중 가장 빠른 성능을 가지고 있는 알고리즘 입니다. 최선 : O(n log n)시간 복잡도를 가지고 있습니다. 최악 O(n^2) 복잡도 발생 """ def quick_sort(arr): # 정렬할게 없는경우. if len(arr) <= 1: return arr # 기준점 pivot = arr[0] less = [element for element in arr[1:] if pivot > el...
9ac65424b51c1fcdbd8749fbe375b7ca3dcd80e7
take1014/data-structures-and-algorithms
/003_Problems vs. Algorithms/problem_3.py
2,240
3.796875
4
def sort_a_little_bit(items, begin_index, end_index): left_index = begin_index pivot_index = end_index pivot_value = items[pivot_index] while (pivot_index != left_index): item = items[left_index] if item <= pivot_value: left_index += 1 continue items[l...
cc4760ce06911c819e85c5d2b5ea941de649f0d4
princecoker/codelagos-Python-Class-Assignment-1.0
/out of school assignment 2.py
801
4.3125
4
#this calculator tells what year you will be 100 years #algorithm #get name and age #calculate birthyear #add 100 to year of birth #display year in 100 years time name = str(input('what is your name: ')) age = int(input('How old are you: ')) birthyear = 2018 - age futuredate = int(birthyear + 100) print (na...
d676e468f9a31b04544c71ded020052f6f750f4a
KissMyLady/Flask_ihome
/ihome/Test/map_use.py
372
3.84375
4
# 文件名: Flask_Project_Code -> map_use # 创建时间: 2020/6/8 8:20 li1 = [1, 2, 3, 4, 5, 6] li2 = [2, 4, 5, 6, 7, 9] def add_self(num1, num2): return num1 + num2 def add_func(x): return x + x map_d = map(add_self, li1, li2) #for i in map(add_func, li1): #print(i) for i in map_d: print(i) # print(list(map_d)) ''' 2...
f3b4d90f47134e1524392e56559f38225421f9b8
levit123/Basic-Python-Projects
/Phonebook/phonebook_func.py
10,306
3.953125
4
import os from tkinter import * import tkinter as tk import sqlite3 #imports the code from the other Python files related to this project import phonebook_main import phonebook_gui def center_window(self, w, h): screen_width = self.master.winfo_screenwidth() screen_height = self.master.winfo_screenheight() ...
22e2f15b5ad6e3712a79dbcbbfe0e1bfe9168dda
kaidee/kaidee
/python/sqlitetest.py
1,126
4.03125
4
# import sqlite3 # conn = sqlite3.connect('DB\\userDB.db') # conn.execute("create table if not exists address(id integer primary key autoincrement,name varchar(128),address varchar(128))") # # conn.execute("insert into address(name,address)values('Susan','shenzhen')") # # conn.execute("insert into address") # # conn.ex...
68c3dc93f1d3a0e111c85a8892271d96958fc77b
Maxssto/git_lesson
/random_sort.py
311
3.75
4
from random import randint numbers = int(input("Сколько элементов в списке: ")) lst = [] for num in range(numbers): lst.append(randint(1, 100)) lst_sorted = sorted(lst) print("Рандомный список:", lst) print("Отсортированный список:", lst_sorted)