blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
05ae7d581656df28f4e9e3da269902e5cf61ed2e
sakamoto024/python-99
/P41/main.py
964
3.640625
4
import sys sys.path.append('../') from P40.main import goldbach def goldbach_list(lower_num,upper_num,limit_num = 0): even_list= [] limit_list = [] #偶数リスト作成 for i in range(lower_num,upper_num+1): if i % 2 == 0 and i > 2:#2よりも小さいものははじく even_list.append([i]) count = 0 #以下li...
de9cfc4b2fb268dcb1c4868c9879cc47f45d8789
sakamoto024/python-99
/P12/main.py
169
3.53125
4
def decode(a): b = [] for i in a: if type(i) is list: b += [i[1]] * i[0] elif type(i) is int: b.append(i) return b
d2575475cdad148b14112ea20bcd0833d7798a13
sakamoto024/python-99
/P46/main.py
846
3.578125
4
def AND(a,b): return a and b def OR(a,b): return a or b def NAND(a,b): return not a or not b def NOR(a,b): return not a and not b def XOR(a,b): return a != b def IMP(a,b): return a == b or not a def EQ(a,b): return a == b def table(lamb): lamb2 = lamb table = [] #Tr...
a24d1de57074fc1cf15d7bda28232cdaa35f28a0
CoderNight/tampa-coder-night-march-2017
/008/lcd.py
1,912
3.546875
4
#!/usr/bin/env python3 class Character: def __init__(self, c, mapping, drawn): self.c = c self.mapping = mapping self.drawn = drawn self.width = len(drawn[0])//len(mapping) self.index = mapping.index(c) def _get_line(self, n): return self.drawn[n][self.index * s...
e0b5713974cc470826e10d4c473736db0e1fcaa0
mackenna95/bme590hrm
/read_csv.py
1,204
3.59375
4
import csv import logging from numpy import genfromtxt class ReadCsv: """This is a ReadCsv class. __init__ sets the attributes Attributes: data (ndarray): Csv Values in single array Arguments: fname (str): file name of csv """ def __init__(self, fname): logging.basi...
ddfe02ef6b1b94d18a3592f1aa2f26d20195c80f
qian99/leetcode-question
/easy/25. Reverse Nodes in k-Group.py
1,063
3.703125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ result =...
8670f28d9b4004212ef50db33b7da1413aa70bd4
qian99/leetcode-question
/new/57. Insert Interval.py
1,219
3.765625
4
# Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval...
575a9557babace14bc8efef993995c45d526be42
andres-sumihe/kattis
/beavergnaw.py
167
3.5
4
from math import pi while True: D, V = [int(i) for i in input().split(' ')] if D == 0 and V == 0:break print(((((-6) * V) / pi) + (D * D * D)) ** (1 / 3))
f41e50ff7d62081cfa6a1b6680230f61d8ee1c0f
andres-sumihe/kattis
/abc.py
317
3.703125
4
number = [int(i) for i in input().split(" ")] number.sort() index = [] for i in input(): if i == 'A': index.append(number[0]) if i == 'B': index.append(number[1]) if i == 'C': index.append(number[2]) for i in range(len(index)): print(index[i] if i ==-1 else index[i], end=" ")
4edc4b95d78043c86703c5dfb1d0ba499e787601
PetrTolstov/Python
/Delite.py
4,480
3.75
4
class Homo(): def __init__(pl='на планете Земля'): print("Homo - это род семейства гоминидов отряда приматов, живущих {0}".format(pl)) def Sapiens(): l = '170 см' pl = 'на Земле, кроме Америки' print("Homo sapiens - человек разумный, живущих {0}, со средним ростом {1}".fo...
1206bf2795b6e89956a7857bba9df9841cf1d65e
LiFulian/LearnPython
/02.多任务/使用互斥锁解决资源竞争的问题.py
1,239
3.921875
4
import threading import time # 可能会出现死锁的情况,(定时解锁) # 定义一个全局变量 g_num = 0 def test1(num): global g_num # 上锁, 如果之前没有被上锁,那么此时会上锁成功 # 如果需要的锁已经被使用,此时会堵塞在这里,直到这个锁被打开 # 用锁方式1 mutex.acquire() for i in range(num): g_num += 1 mutex.release() # 解锁 # # 用锁方式2(频繁解锁,相当耗时) # for i in rang...
d63cd4f39cc8667cc6ac6cb926c591414784368e
LiFulian/LearnPython
/01.网络编程/tcp下载客户端.py
1,039
3.6875
4
import socket def main(): # 1. 创建tcp的套接字 tcp_scoket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 2.链接服务器 server_ip = input("请输入要连接的服务器的ip:") server_port = int(input("请输入要链接的服务器的port:")) server_addr = (server_ip, server_port) tcp_scoket.connect(server_addr) while True: ...
8ce457e3d773ade5db9353d9a3e063e7b5e012ec
LiFulian/LearnPython
/01.网络编程/tcp-client.py
670
3.546875
4
import socket def main(): # 1. 创建tcp的套接字 tcp_scoket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 2.链接服务器 server_ip = input("请输入要连接的服务器的ip:") server_port = int(input("请输入要链接的服务器的port:")) server_addr = (server_ip, server_port) tcp_scoket.connect(server_addr) while True: ...
b1e569d51e00eb3acc58d1d176110a49dbd6db59
mengyiliangcheng/python_learning
/sstring.py
646
3.671875
4
#!/usr/bin/env python #print "hello \n world" import string import hello #path = 'c:\share\test\new' #print path path1 = r'c:\share\test\new' #close transferred meaning print path1 """ s = raw_input('input a string:\n') letters = 0 space = 0 numbers = 0 others = 0 for c in s: if c.isalpha(): letters += 1...
795da49b81d706afb457009b0974d31472d0d1e8
magorbalassy/hackerrank
/pangrams.py
197
3.90625
4
s = input().upper() uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ' count=0 for i in range(len(uppercase)): if uppercase[i] in s : count+=1 if count==26 : print("pangram") else : print("not pangram")
e00c53b401787b92e352c5a3d763ea357d7321ff
michaelb/point-clustering
/geo/quadrillage_dense.py
2,023
3.75
4
""" Module implémentant une classe de quadrillage On découpe le plan en des carrés, et on place les points dans le quadrillage correspondant """ from itertools import product from math import ceil, floor, sqrt from geo.point import Point from geo.case_dense import Case from collections import defaultdict class Quadr...
e6402c9d4bf07ed87a4d861c29601155f86eae26
marcsans/cnn-physics-perception
/src/learn_pendulum_parameter.py
5,034
4.21875
4
# coding: utf8 """ function used to learn the pendulum parameters from the angle sequence """ from numpy import sin, cos, abs import numpy as np import matplotlib.pyplot as plt import scipy.integrate as integrate import matplotlib.animation as animation import pendulum def compute_F(th_0, th_1, th_2, l, n_dt=1): ...
4391b9b6e8f3081c4f771a7bedc5495c9beb6ed9
julian-lundquist/cryptography-practice
/DiffieHellman.py
969
3.6875
4
# prime number generator (DiffieHellman) import math import random def is_prime(p): for i in range(2, math.isqrt(p)): if p % i == 0: return False return True def get_prime(size): while True: p = random.randrange(size, 2*size) if is_prime(p): return p def is...
993b8aa99fda84d7f259090cded460efba2f65c8
decentfox/TAPL
/tapl/arith/support.py
714
4.0625
4
class FileInfo: def __repr__(self): return '<Unknown file and line>:' class Info(FileInfo): """ An element of the type info represents a "file position": a file name, line number, and character position within the line. Used for printing error messages. """ def __init__(self, file...
8f1131318024549d5841d8b217779286bd5180ce
MarnieAuld/CP1404
/prac_04/lottery_ticket_generator.py
1,010
4.25
4
""" import random user input for number of quick picks, while loop for error checking < 0 create empty list (quickpick) append random number to quickpick list, check for number in list already (while number in quickpick) quickpick.sort() print number of quick picks in blocks of 6 NUMBERS, MINIMUM_NUMBER = 1, MAXIMUM_NU...
8d2af9ffb0340090669639f0faabf8c82c58ff5f
MarnieAuld/CP1404
/prac_10/flask_temperature_converter.py
1,136
3.78125
4
from flask import Flask app = Flask(__name__) def celsius_to_fahrenheit(celsius): fahrenheit = celsius * 9 / 5 + 32 return "{:.2f}".format(fahrenheit) def fahrenheit_to_celsius(fahrenheit): celsius = 5 / 9 * (fahrenheit - 32) return "{:.2f}".format(celsius) @app.route('/') def homepage(): ret...
116a75af6daf6c1a469f248993530ca4a567207f
kexin-yang/Sprinkle
/BubbleClass.py
10,445
3.875
4
import random import speech_recognition as sr import hearWords class Bubble(): # define bubble def __init__(self,cx,cy,r,color,direction,word): # a bubble has a position, size, color and a word in it self.cx = cx self.cy = cy self.r = r self.color = color self.dir...
8c53db3d413f8cbc505f040196bba650fd486b4e
srisridar/SphoorthiFreeClasses2020
/formattingWorkOut.py
2,425
3.921875
4
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> " his name is %s"%("sreedhar") ' his name is sreedhar' >>> " his name is %s and he is %d years old"%("sreedhar",15) ' his name is sreedhar a...
03ce4592ce9e791008bac4abd372a2d1a1b3c424
neelanqj/python_stack
/python_OOP/animal/animal.py
990
3.875
4
class Animal(object): def __init__(self, name, health): self.name = name self.health = health def walk(self): self.health = self.health - 1 return self def run(self): self.health = self.health - 5 return self def display_health(self): print str(self.health...
44757b6674dda64485babff0eda5286dfa556ddf
William0617/python_study
/process_thread/thread/thread_creation01.py
571
3.75
4
# _*_ coding:utf-8 _*_ # Author: william.sun # Time: 2019-05-12 15:06 # File: thread_creation01.py # IDE: PyCharm from threading import Thread import time # 使用thread子类创建线程 class SubThread(Thread): def run(self): for i in range(3): time.sleep(1) msg = 'subthread' + self.name + ' exe...
2c9ca94191e6fe4db5967ea1a52be2da589c8fd6
William0617/python_study
/helloWorld.py
82
3.71875
4
print('hello world') num = [1, 2, 3, 4, 5, 6, 7, 8, 0] # print(reversed(num))
273a5a06ab62b8d2a4dbe5f9ea388181b6ab9edc
lc-silverio/Python-Password-Generator
/Password.py
543
3.59375
4
import random # Character Pool lower = "abcdefghijklmnopqrstuvwxyz" upper = "ABCDEFGHIJKLMNOPQRTUVWXYZ" numbers = "0123456789" symbols = "[]{}()*;/,_-@!?=$#%&<>|" # Input length = input("Insert a whole positive number: ") length = int(float(length)) while length < 0: print("Valor inserido não é ma...
407fe22b71d607d2aa86029fa83c99f6e1ae3dae
VigneshHariharan/Coding_Problems
/simpleparanthesis.py
476
3.546875
4
s="}{(([])[])[]}[]}" def isBalanced(s): dict = { "}" : "{", ")" : "(", "]" : "[" } opn = "{[(" close = "]})" temp = [] for i in s: if i in opn: temp.append(i) elif i in close: if len(temp) == 0 or dict[i] != temp[l...
9fb4d4a31c08632a17805f99d75f92151f2e5d59
BillDoors23/practicepython.org-exercise
/String_list.py
508
3.875
4
input = input("Input a palindrome words: ") var = [] for i in input: var.append(i) if var == var[::-1]: #"".join() make [a, b, c] to abc print(input.upper() + " is palindrome!\n") print("\tINPUT") print("".join(var)) print("\tREVERSED") ...
5b9f1eb90e75ae81745fdfb3d58f14f8e3568c8e
anapschuch/CES-22-Lista-1
/q5.py
868
3.984375
4
import sys def count_until_sam(list): """Returns how many words occur in list up to and including the first occurrence of 'sam'""" count = 0 for item in list: count = count + 1 if item == 'sam': return count return count def test(did_pass): """Ṕrint...
f46fcfa57bceafc42dd285850b56c8db7e0abbd4
ssavann/Py-fondamentaux
/cast.py
764
4
4
''' Modifier le type d'une variable (cast) = changer son type int nombre entier str chaine de caractères float nombre flottant bool vrai ou faux ''' nb = input("Nombre ? ") #malheureusement son type sera un "string" et non un nombre, je ne peux donc additionner les mots avec des chiffres #print(nb + 5) print(type...
d75c689ac3e22440ce28de3df9c97252df2001fc
ssavann/Py-fondamentaux
/operateurs_logique.py
1,164
3.984375
4
''' Opérateurs logique not n'est pas and et logique or ou logique ''' homme = False #homme = True if homme==True: print("Bonjour monsieur!") #cette version fonctinne aussi: ça sous-entend que homme est toujours "True" if homme: print("Bonjour monsieur!") #si la valeur était fausse if homme==False: pri...
0fa4e6f73c8e27853c1837ff2322e7029b87bd82
Panda4817/Snake-AI
/AI_snake.py
5,091
3.796875
4
import numpy as np # Global variables to find path depending on board size # Scale board size down to find a new path # Therefore 80x100 would be scaled down to 4x5 board height = 80 width = 100 # A class created to find hamiltonian paths in small boards # Those paths can be scaled up to bigger board with the same r...
0488fcd878d1157b02630dd7bcf16352a52d615a
michielkauwatjoe/V2_
/MoveMe/MultiPillow/GUI/gradients.py
9,388
3.65625
4
#Copyright 2006 DR0ID <dr0id@bluewin.ch> http://mypage.bluewin.ch/DR0ID # # # """ Allow to draw some gradients relatively easy. """ __author__ = "$Author: DR0ID $" __version__= "$Revision: 18 $" __date__ = "$Date: 2006-10-03 14:01:03 +0200 (Di, 03 Okt 2006) $" import pygame import math def gradient(surface, ...
880fd98f7dcc70ae88bf62de8f210c10f12c17c7
michielkauwatjoe/V2_
/MoveMe/MultiPillow/Room.py
10,018
3.578125
4
''' Group is the class that will control a single group ''' from StateMachine import * from Pillow import * import random import pygame ''' ''' class Group(StateMachine): def __init__(self, id=0): self.id = id self.pillows = {} self.color = (250,250,250) self.nextUpdateTime ...
ba97995bbb784c35819e1eb49478543012fa7d81
nanweiqing/pythontest
/730job.py
608
3.5
4
def fight(): # 我的血条 my_hp = 1000 # 敌人的血条 your_hp = 1000 # 我的攻击力 my_power = 80 # 敌人的攻击力 your_power = 60 while True: # 我剩余血条 等于 我的之前血条 减去 敌人的一次攻击 my_hp = my_hp - your_power # 敌人剩余血条 等于 敌人的之前血条 减去 我的一次攻击 your_hp = your_hp - my_power if my_hp <= 0...
970fc09d6a707762d6fef5302f5d162b598b4cfc
F1uxCapacitor/aoc2018
/day2_part1.py
703
3.78125
4
from collections import Counter from functools import partial import pandas as pd def num_chars_in_seq(seq, num): counter = Counter(seq) unique_character_counts = set(counter.values()) if num in unique_character_counts: return True else: return False has_two = partial(num_chars...
ac49a8b2772d683a18529e29f62e58cb30d6802e
ggiraldo/asteroids-py
/asteroids/vector.py
1,034
3.828125
4
# Asteroids Game # 2D vector class and related functions from random import random as rnd from math import sin, cos class Vector(): """ 2D vector """ def __init__(self, x = 0, y = 0): """ Class constructor """ self.x = x self.y = y def mag(self): """ Vector magnitude """ ...
346e66470ee0eaada3aeda5b42abfdc7d5f0ef7c
EvalImperialforces/CMEECourseWork
/Week2/Code/dictionary.py
1,057
3.578125
4
#!/usr/bin/env python3 """ Populate dictionary from taxa list to match species to order names. """ __author__= 'Eva Linehan (eva.linehan18@imperial.ac.uk)' __version__ = 0.01 __date__ = 'Oct 2018' __licence__ = 'Inclass practical' taxa = [ ('Myotis lucifugus','Chiroptera'), ('Gerbillus henleyi','Rodentia',),...
47903ddef14ada1df2d3933b888332928c63a566
EvalImperialforces/CMEECourseWork
/Week2/Code/align_seqs_fasta.py
3,084
3.6875
4
#!usr/bin/env python3 """ Aligning DNA sequences from any .fasta file, assigning a score based on the start position and number of base matches. """ __author__= 'Eva Linehan (eva.linehan18@imperial.ac.uk)' __version__ = 0.01 __date__ = 'Dec 2018' __licence__ = 'Extra credit practical exercise' import sys # If no ...
b74799d19e90136a1e431e26ff9147e9d30c6dc5
JachiOnuoha/Homework-Study-Helper
/formulapp.py
2,077
3.765625
4
# Homework help websites import Tkinter as tk import ttk import webbrowser import tkFont # Homework help main window design def mainapp(): form = tk.Tk() form.title("Raptorapp") form.geometry("300x320") form.config(background='black') form.resizable(False, False) Label = ttk.La...
ad0de191a1d516c940ce914d402d94d31f2bcd2f
bmallia/solid-principles
/SOLID/open_close.py
717
3.96875
4
''' A principal idéia é que a classe mãe deve ser genérica e abstrata para ser estendida e reaproveitada por classes filhar. Esse prinício rege que a classe mãe não deve ser alterada No PYthon, podemos fazer uma operação conhecida como Monkey-Patching. Uma classe em Python é mutável e uma método é ape...
e7256f2de742ad0a36993dbfc95ca6e08a83e0f1
GioMoreira/sisteminha
/funcionalidades/__init__.py
1,059
3.59375
4
def arquivo_existe(nome): try: a = open(nome, 'rt') a.close() except FileNotFoundError: return False else: return True def criar_arquivo(nome): try: a = open(nome, 'wt+') a.close() except Exception: print('\033[1;31mErro ao criar arquivo.\033...
de288cfd5bbea0eb8ef027d0b4f43daf396bb93c
rosscornwell/210CT-Coursework
/Task7.py
551
4.34375
4
def is_prime(N, a=3): if N == 2: prime = True elif N <= 1 or N % 2 == 0: prime = False elif a * a > N: prime = True elif N % a == 0: prime = False else: return is_prime(N,a+2) return prime print("This program checks if inputted number is prime") while True: #Error catching for st...
f19cbc680f8271c706a32fda205173e1e22d4232
davidlukac/codekata-python
/codewars/needle_in_haystack.py
1,342
3.84375
4
# A Needle in the Haystack # https://www.codewars.com/kata/56676e8fabd2d1ff3000000c def find_needle(haystack: list) -> str: return 'found the needle at position %d' % haystack.index('needle') def find_needle_5(haystack: list) -> str: return (lambda idx: { idx: 'found the needle at position %s' % idx...
994e329bba15eb16ac3c2128926cd06c8ac09d4f
crhan/python_talk_2020
/src/20_iredis.py
1,452
3.59375
4
#%% import re sperator = re.compile(r"\s") def strip_quote_args(s): """ Given string s, split it into args.(Like bash paring) Handle with all quote cases. Raise ``InvalidArguments`` if quotes not match :return: args list. """ word = [] in_quote = None pre_back_slash = False ...
74f27511a7bf9c1c099a47c6aa4df49847c2e8f9
crazy2k/algorithms
/excercises/bipartite.py
1,046
3.53125
4
from collections import deque from graph import Graph, Vertex WHITE = 0 GRAY = 1 BLACK = 2 INFINITY = 9999 def is_bipartite(g): s = g.vertices[0] for u in g.vertices: u.color = WHITE u.d = INFINITY u.pred = None s.color = GRAY s.d = 0 s.bset = 0 s.pred = None q ...
39258821676b97b7deb39f11b69d15390fe192ee
crazy2k/algorithms
/misc/reverse-words.py
1,068
3.71875
4
import unittest def reverse_sublist(l, start, end): # [abc def] for i in range((end - start + 1) // 2): l[start + i], l[end - i] = l[end - i], l[start + i] def reverse_words_in_list(l): start = None for i in range(len(l)): if l[i] != ' ' and start is None: start = i ...
b09b9a03a1d102399ff893a5501ce2f0b1956a2c
crazy2k/algorithms
/excercises/c1e2.py
330
3.859375
4
# Since strings in Python are immutable, and the excercises says the # string is a C-String, I assume the input is a list of characters. # Also, I take advantage of this to do the reverse in-place. # Always O(n). def reverse(l): for i in range((len(l) - 1)/2): j = (len(l) - 1) - 1 - i l[i], l[j] = l...
e769e900b6fdb1dc1b504fd0cc34886e851225ea
crazy2k/algorithms
/excercises/btree.py
1,209
4
4
class BinaryTreeNode: def __init__(self, item): self.left = None self.right = None self.item = item def traverse_inorder(root, func): if root.left: traverse_inorder(root.left, func) func(root.item) if root.right: traverse_inorder(root.right, func) def traverse_p...
5fdf13613154bae87a0fbe47bfa766acced63a45
crazy2k/algorithms
/hackerrank/2d_array_ds.py
831
3.6875
4
#!/bin/python3 import os # Complete the hourglassSum function below. def sum_hourglass(arr, i, j): values = [arr[i][j], arr[i][j + 1], arr[i][j + 2], arr[i + 1][j + 1], arr[i + 2][j], arr[i + 2][j + 1], arr[i + 2][j + 2]] return sum(values) def hourglassSum(arr): max_sum = No...
d00664ff3241068a004f4c2e5bc6d2db1b4ff346
crazy2k/algorithms
/sorting/bubblesort.py
163
3.6875
4
def bubblesort(l): for x in range(len(l)): for i in range(len(l) - 1): if l[i] > l[i + 1]: l[i], l[i + 1] = l[i + 1], l[i]
c29273ad26562d2bb6b44f0e20ba762b0ba764ec
AlphaMikeFoxtrot/pythonProjectEuler16-
/problem_25.py
221
3.671875
4
fib = 1 first = 1 second = 1 third = 1 _list = [1, 1] while len(str(fib)) != 1000: third = first + second first = second second = third fib = third _list.append(fib) third = 0 print(len(_list))
0e43b5d31501211307f9c7664180045b8fc74525
herereadthis/lutra
/tutorial_notes/core_electronics/2.1_python_intro.py
196
4.3125
4
"""Introduce Python: how to print.""" print('hello world!') string1 = 'foo' string2 = 'bar' # method 1 print('{0} {1}!' .format(string1, string2)) # method 2 print('%s %s' % (string1, string2))
ddb3bee22d2ce6aafc783090828328620ed1f076
herereadthis/lutra
/objectives/PIR_motion_sensor/demo.py
490
3.578125
4
"""Use a passive infrared motion sensor (PIR) to detect movement.""" from gpiozero import MotionSensor, LED led = LED(17) pir = MotionSensor(24) def main(): """Demo the PIR motion sensor.""" try: while True: pir.wait_for_motion() led.on() print("You moved") ...
4ba8e1f9e344a9275424488c0233c4381b4ceeae
herereadthis/lutra
/objectives/gpiozero/led.py
1,004
4.21875
4
"""Control the lighting of an LED using the GPIO pins.""" # https://learning.raspberrypi.org/en/projects/physical-computing # GPIO zero is a Python library which provides a interface to GPIO components # Use to get LED class from gpiozero import LED from time import sleep # attach jumper lead from GPIO pin 17, then ...
fb62ea9eabd284cf3810bae72cc7e77352b23c89
dianalow/RiceFOC
/01_InteractivePythonProgramming/stopwatch.py
1,957
3.640625
4
# Written by : Diana Low # Last updated : 18 April 2014 # Coding assignment for Rice University's # Interactive Python Programming course # Game : "Stopwatch" # Run on codeskulptor.org import simplegui import time import math # define global variables points = 0 clicks = 0 width = 300 height = 200 position = [width...
9f59856a08191d7712f71ecf51a274297528efba
Nezgun/Exploring-Bees
/mainFunctions.py
2,195
3.578125
4
from WorldGen.World import World def displayOverview(size, numOfWorlds): print("Initalization Overview") print(size + " size selected.") print(str(numOfWorlds) + " worlds will be generated.") def sizeSelection(size): if size == "small": return 100 elif size == "medium": return 1000...
ab5b40908d8d19a8c6f78f6a121f7b172b84fee5
luiscruzn/python_exercises
/exercises/inegi_03/inegi_vivienda2_3.py
2,639
3.71875
4
import pandas as pd import plotly.express as px # Import data from CSV file, we apply a filter for only gather information from specific columns data = pd.read_csv("/home/luis/proyectos/python/python_exercises/resources/inegi2010/conjunto_de_datos/iter_00_cpv2010.csv", usecols=["nom_ent", "entidad",...
2d430d05c19e6f41a941af9aa3065caf98f3cacf
luzumi/Adressbuch.py
/AdressbuchPY_e/AdressbuchPY_e/Telefonbuch.py
2,697
3.75
4
""" Klasse Telefonbuch addNummer(nummer)^^ getNummer(vorname, name)^^ deleteNummer(nummer) getKontaktliste() """ import sqlite3 #'modul zum Ansprechen der SQLite-Datenbank' class Telefonbuch: """Constructor zur Vorbereitung des Datenzugriffs""" def __init__(self): #übernim...
20071a235a96e3fb4f9db1e574b5735cf851a926
emilylakic/cs110
/lab7/lab7.py
982
3.9375
4
import listoperations import string user = input("Enter a word: ") useThese = string.ascii_letters myList = [] def countAll(): #for i in range(0, len(user)): for i in range(0,1): for x in range(0,26): myList.append(user.count(useThese[x])+user.count(useThese[x+26])) print(myList) def ma...
63fdd2fbf5328086bcb86ad24881f3cb86fad986
emilylakic/cs110
/lab6/lab6.py
1,530
3.953125
4
import turtle def seq3np1(n): #starts with n and goes until it reaches n=1 """Print the 3n+1 sequence from n, terminating when it reaches 1.""" count = 0 while n!=1: count += 1 if n % 2 == 0: n = n // 2 else: n = n * 3 + 1 return count def graphIterations...
30996d4be14191062e9441d8454ae42d448830b8
xjohnwu/python_features
/leetcode/April-30DayChallenge/1_6GroupAnagrams.py
606
4.25
4
""" Group Anagrams Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of your output does not matter. """ from typing import List class Solutio...
216aa394aa0e5d8ef9febe71abd63d082bd96bc1
xjohnwu/python_features
/tests/decorators/test_class_decorator.py
753
3.6875
4
from functools import wraps def decorate_all_functions(function_decorator): def decorator(cls): for name, obj in vars(cls).items(): if callable(obj): setattr(cls, name, function_decorator(obj)) return cls return decorator def print_on_call(func): @wraps(func)...
01d20ad19bb1ac11355b279a4a9dabcdb00a9e30
pjh0347/algorithm
/binarysearch.py
709
4.09375
4
# coding: utf8 ''' Binary Search time complexity : O(log n) ''' import time import bisect def binarySearchForLoop(alist, x): begin = 0 end = len(alist) - 1 found = False pos = None while ( begin <= end ) and ( not found ): mid = ( begin + end ) // 2 if alist[mid] == x: found = True pos = mid else...
db846d8aa427b277508c8ca52e78e35fa5fffb25
Ryan-Wisniewski/Sorting
/src/iterative_sorting/iterative_sorting.py
1,439
4.25
4
# TO-DO: Complete the selection_sort() function below ####### Steps to sort ## 1 Check first index ## 2 in the array and find the lowest value ## 3 change (swap) the index of the lowest value to the current index ## 4 Increase the current index ++ and repeat while len(arr) == true def...
7b7b78a3ad728e41dc51fe67e8fda4d5c63e8d77
Squidtoon99/Code-Wars
/WillYouMakeIt.py
560
4.125
4
_input = input() Hours, Miles, Speed = _input.split() Hours, Miles, Speed = int(Hours), int(Miles), int(Speed) #Miles is Miles to travel #Hours is hours until code wars starts #Speed is mph #Read 3 integers on one line separated by spaces "H M S", # representing the Hours until CodeWars starts, the miles you need to t...
de84ac4dead2fc498b1590cc68d247d9ec620234
mikanyman/hindi2
/awareness_1.py
1,619
3.875
4
# -*- coding: utf-8 -*- # Handles single line vowels = ['a','e','i','o','u','y'] consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q', 'r','s','t','v','w','x','z'] content = "abcde fghi jklm nopq rstuv wxyz" word_counter = 0 word_buffer = "" word_store = "" word_pattern = "" for num, name in enumerate(...
865358d7daff65411f1a5ac18d70fce1a9201053
sethau/Short_Programs
/Hackerrank/Bidding.py
1,435
3.53125
4
#!/bin/python #author: Seth Denney #date: 1/2013 #Bidding For Scotch on Hackerrank.com # #Simple concept implementation #game passes in only: #player id {1|2} #scotch position {0,10} #lists of each player's previous bids def calculate_bid(player, pos, first_moves, second_moves): #current money must be calculated from...
73b0466972052d3dc4de21f74775dbae28df950c
sethau/Short_Programs
/Academic/Principles of Programming Languages/InsertionSort.py
446
3.5625
4
#! usr/bin/env python #Seth Denney Homework 1 import sys print 'Enter the integers: ' read = sys.stdin.readline() array = read.split() int_array = [int(s) for s in array] n = len(int_array) print 'n = ', n print int_array print 'Sorting...' for i in range(1, len(int_array)): j = i - 1 key = int_array[i] while (...
e0c0f6a84b8a6d0ac839c9645934019575d95f33
sethau/Short_Programs
/Practice/RomanNumerals.py
891
3.84375
4
#This program evaluates a roman numeral string stored in 'numeral' hierarchy = ['I', 'V', 'X', 'L', 'C', 'D', 'M'] values = [ 1, 5, 10, 50, 100, 500, 1000] def lessThan(a, b): if indexOf(hierarchy, a) < indexOf(hierarchy, b): return True return False def indexOf(l, x): i = 0 while ...
d16ef364cf6106a88a1b28a9a96bdae89166f80c
skafev/Python_basics
/Seventh_week_exersice/03Sum_prime_non_prime.py
447
4.375
4
number = input() not_prime = 0 prime = 0 while number != "stop": number = int(number) if number < 0: print("Number is negative.") elif number > 3: if number % 2 == 0 or number % 3 == 0: not_prime += number else: prime += number else: prime += num...
916215baf51da4f4fb07dcbb699a170e85f5f0e7
skafev/Python_basics
/FIfth_week/02Number_N-1.py
69
3.65625
4
number = int(input()) for num in range(number, 0, -1): print(num)
08f07bb6babcdaa140534f222acf0de7316e4262
skafev/Python_basics
/Fourth_week_exersice/10Volleyball.py
379
3.703125
4
import math year = input() holiday = int(input()) weekends = int(input()) weekends_to_play = (48 - weekends) * 0.75 holiday_can_play = holiday * 2/3 playing_volleyball = weekends_to_play + weekends + holiday_can_play if year == "leap": playing_volleyball += playing_volleyball * 0.15 print(math.floor(playing_v...
de1ff82ba8f570ba711a21c155c6c79171a6879d
skafev/Python_basics
/Seventh_week/07Cinema_ticket.py
996
3.859375
4
movie = input() standard_billet = 0 kid_billet = 0 student_billet = 0 while movie != "Finish": free_space = int(input()) space = 0 while free_space > space: type_of_billets = input() if type_of_billets == "standard": standard_billet += 1 space += 1 elif type...
a2a7bc2d12a48428996e95cb69edfd9e5e579c73
skafev/Python_basics
/Exam_basic_modul/01Supplies_for_school.py
263
3.734375
4
pens = int(input()) * 5.8 markers = int(input()) * 7.2 cleaner = float(input()) * 1.2 percent_discount = int(input()) all_supply_price = pens + markers + cleaner discount = all_supply_price - ((all_supply_price * percent_discount) / 100) print(f"{discount:.3f}")
0ab17de41499cfda69e45eab363f8c16a2e8668c
skafev/Python_basics
/Fourth_week_exersice/02Cinema.py
289
3.609375
4
text = input() rows = int(input()) columns = int(input()) price = 0 full_cinema = rows * columns income = 0 if text == "Premiere": price += 12 elif text == "Normal": price += 7.5 elif text == "Discount": price += 5 income = price * full_cinema print(f"{income:.2f} leva")
2bf491598d8877141b26d1c5915f54eebb5e9a13
skafev/Python_basics
/Third_week_exersice/01Sum_seconds.py
268
3.75
4
athlete_a = int(input()) athlete_b = int(input()) athlete_c = int(input()) total_time = athlete_a + athlete_b + athlete_c minutes = total_time // 60 seconds = total_time % 60 if seconds < 10: print(f"{minutes}:0{seconds}") else: print(f"{minutes}:{seconds}")
088c6b3c49e027c7cdd662dcc9f19a5b254010ab
skafev/Python_basics
/Exam_basic_modul/06Tournament_for_christmas.py
922
3.65625
4
days = int(input()) money = 0 all_money = 0 won_games = 0 lose_games = 0 days_win = 0 days_lose = 0 for day in range(1, days + 1): money = 0 won_games = 0 lose_games = 0 command = input() while command != "Finish": game = command result = input() if result == "win": ...
4c1fba3060206e4ef6a9677c708fa4aae22b0398
mykreeve/advent-of-code-2018
/day09.py
1,258
3.546875
4
players=459 max_marble_no=7179000 player_scores={} current_player=1 marble_no=1 circle=[0] current_position=0 def add_player_score(player, score): if player in player_scores: player_scores[player] += score else: player_scores[player] = score while marble_no<max_marble_no: if marble_no%23==...
cc6ec11a8477c5c8f20f6160b060d0b140628399
T-R0D/JustForFun
/adventofcode/Day16/aunt_sue.py
1,877
3.5
4
def main(): sue_data = [] with open('input.txt') as input_file: for line in input_file: parts = line.strip().replace(':', '').replace(',', '').split(' ') sue_dict = {'n': int(parts[1])} for i in range(2, len(parts), 2): sue_dict[parts[i]] ...
9a4b74a1472037d4177324695ecdfc9c2583037b
T-R0D/JustForFun
/adventofcode/Day22/wizard_simulator_20xx.py
7,445
3.546875
4
import copy class GameState(object): def __init__(self, player, boss): self.turn = 0 self.mana_used = 0 self.player = copy.deepcopy(player) self.boss = copy.deepcopy(boss) self.shield_effect = 0 self.poison_effect = 0 self.recharge_effect = 0 self.hi...
74f87c01f62aa8f401e03d53ef1537eac412806c
jalcoriza/pylearning
/lean-python-examples/Python3/primes.py
486
3.78125
4
#!/usr/bin/env python3 # # Copyright (c) 2014 Paul Gerrard # This program is free software. # license: GNU General Public License version 3 # # This code is an example from `Lean Python`: http://leanpy.com/ # i=2 nprimes=1 primes=[2] print(nprimes,i, 'prime') while nprimes<100: prime=True for j in primes: ...
08a8bbe19b69f2b79e9d64a942d1578ac6229d75
jalcoriza/pylearning
/lean-python-examples/Python3/dbcreate.py
1,624
3.859375
4
#!/usr/bin/env python3 # # Copyright (c) 2014 Paul Gerrard # This program is free software. # license: GNU General Public License version 3 # # This code is an example from `Lean Python`: http://leanpy.com/ # import os import sqlite3 db_filename='mydatabase.db' # # if DB exists - delete it # exist...
34ce2a6a5e44e30ddd0c8ae0538c6497e56c6935
divyamamgai/UdacityProjectMovieTrailerWebsite
/fresh_tomatoes.py
1,856
3.609375
4
import webbrowser import os # A utility function to retrieve file contents. def file_get_contents(file_path): file = open(file_path) file_contents = file.read() file.close() return file_contents # A utility function to create HTML content of the movie_container section of the page. def create_movie_...
a496b1986a57b8ec5f25e6d1e8e1ec8fb2a6e801
ankutalev/tooiTasks
/task5.py
2,067
3.71875
4
import unittest import numpy as np import re def simple_adder(a, b): return a + b def insert_if_not_in_dict(dict, key, value): if key in dict: return False else: dict[key] = value return True my_dict = {"1": 1, "2": 2} def random_list(size): return np.random.randint(10, s...
6a117c5c0a9b0fbe11e539991fb087075b3944f8
gf2crypto/blincodes
/blincodes/vector.py
15,096
3.65625
4
"""Module for working with vectors over GF(2).""" class Vector(): """Binary vector abstraction.""" def __init__(self, value=None, length=None): """Create new vector of size. :param: int `value` - integer representation of bit vector :param: int `length` - length of the vector ...
03f484e4f3afb37356a328ebc3abc8f4e73af8e5
Jmbac0n/Cryptography
/Encrypt_Decrypt_File_Tutorial.py
1,192
4.03125
4
from cryptography.fernet import Fernet def write_key(): # Generates key to file key = Fernet.generate_key() with open("key2.key", "wb") as key_file: key_file.write(key) def load_key(): # Loads the key from the current dirct name 'key.key' return open("key2.key", "rb").r...
7be2422e7aea52a1cc2c44dacb2deaae49738025
Akhil-Raj/SIH2019-SharedRooftopRainwaterHarvesting
/Reservoir Optimization/YAS_Cost_analysis.py
2,645
3.625
4
# coding: utf-8 # In[302]: import math def findDcurr(nd, nft, F): Dcurr = nd * nft * F def YASRec(Vprev, Qcurr, Dcurr, A, R, Rcurr, S, nd, nft, F): vprev = Vprev / (A * R) qcurr = Qcurr / (A * R) #dcurr = findDcurr(nd, nft, F) / (A * R) dcurr = nd * nft * F / (A * R) s = S / (A * R) ...
7353b60a399a7489f3fad78c75d10deebb65a403
jkusita/rename-dates
/rename-dates-myself.py
1,844
3.609375
4
# rename-dates.py - Renames filenames with American MM-DD-YYYY date format to European DD-MM-YYYY. import shutil, os, re # Directory of the folder containing the files. directory_path = ("/Users/ramteechua/Desktop/rename-dates-folder") # Creates a regex that matches files with the American date format. date_pattern ...
450a1ca772177a9d97186f7a083c063518420426
RUANHAOANDROID/python-spider-learn
/chapter/_2/example2-6.py
124
3.625
4
import re # 任意匹配元字符 exam = "codingke..." str1 = "aaa66codingke666666" ret = re.search(exam, str1) print(ret)
4d73d1c6b4603b335b788c76023145d1b53a42a9
andrestamayo/2017sum_era2_kol1
/kol1.py
397
3.65625
4
class Matrix: def __init__(self, first, second, third, fourth): self.f= first; self.s= second; self.t= third; self.fo=fourth; @staticmethod def add(matriz): one=self.f+matriz.f; two=self.s+matriz.s; three=self.t+matriz.t; four=self.fo+matriz.fo; return Matrix(one,two,three,four); matrix_1 = Matr...
dc52b416b9a414acf42d1f926ec38205757d2b75
JordanArya/Libary_registration
/modul/user.py
2,212
3.828125
4
import time def Add_book(genre_choice): books = input('what title of book do you want to input : ') print(genre_choice) genre = input("what genre of book it's ") return books,genre def view_member(msg,member): print(msg) opsi = input("what menu do you want to choice : ") if opsi == '1': for every_name in memb...
2e0c24605127fda3856cff34e9bf09d7c9d128a1
alexoreiro/Python
/odd_numbers.py
116
3.890625
4
#!/usr/bin/python3 # use a list from 0 to 21 for i in range(0, 21): if (i % 2 != 0): print("i = ", i)
9d6300169a8c2c8e90cae1c77400fa52ed08fbaf
alexoreiro/Python
/factorial_recursion.py
252
4.375
4
#!/usr/bin/python3 factorial = input("Enter the number to factorize: ") def factorial(num): if num <= 1: return 1 else: result = num * factorial(num -1) return result fact = result print("This is the result", fact)
51929e41631845a2c8946ed75d57b5d0205204bf
Cypher-codex/Python
/color.py
1,234
4.15625
4
#!/usr/bin/python # This one colors the background as well. # Simple button demo. from tkinter import Button from Tk import * # A better way is to create our fancy button by extending the Button class. class ColorRotButton(Button): # Brighten a color by hex 101010 and return the modified color. def brighte...
4b03264284a2d1efd9b78c7b004222aaf178502d
huiwq1990/ReinforcementLearning
/brl/PriorityQueue.py
1,432
3.96875
4
import heapq class UniquePriorityQueue(object): """ implement the min queue, assuming that each item is unique""" def __init__(self, L = []): """ initialize the priority queue with some (priority, value) pairs """ # copy the list values self.queue = L[:] heapq.heapify(self.queue...
6f71f77e07b48c7a51807af89ae0c3187f5e912e
it31415/machine_learning
/hold_out.py
698
3.53125
4
# coding: utf-8 # コードの実行に必要なモジュールを読み込みます。 from sklearn import datasets from sklearn.model_selection import train_test_split # 「IRIS」というデータセットを読み込みます。 iris = datasets.load_iris() X = iris.data y = iris.target # 「X_train, X_test, y_train, y_test」にデータを格納します。 X_train, X_test, y_train, y_test = train_test_split(X, y, test...
db0d4b2a158b1ba929d91ba9c528b53a35e678d1
CMSTrackerDPG/certifier
/certifier/utilities/utilities.py
278
3.734375
4
def extract_numbers_from_list(list_of_elements): return [int(i) for i in list_of_elements if type(i) == int or i.isdigit()] def uniquely_sorted(list_of_elements): new_list = list(set(extract_numbers_from_list(list_of_elements))) new_list.sort() return new_list
b60de5e9f9cc80f3b0fb3f94f09de8c564525da7
danilobarros18/aulas
/web-django/exemplos/aula-2/aulatwo.py
339
3.890625
4
""" Minha primeira lib em python """ def fibonacci(n): """ fibonacci(int n) -> serie de fib """ a ,b = 0, 1 try: for i in range(n): yield b a,b = b, a+b except: print("Erro") if __name__ == '__main__': fib = fibonacci for el in fib(100):...