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 |
|---|---|---|---|---|---|---|
ce11c977e4b9ac7bb46c1bac3643988677435145 | whhxp/polygon_triangulation | /lib/uniform_fill.py | 461 | 3.921875 | 4 |
from random import random as r
def uniform_fill_tri(x,y,z,n):
'''Uniform-randomly fill a triangle (x,y,z) with n points'''
a, b = y-x, z-x
points = []
for i in range(n):
r0, r1 = r(), r()
if r0 + r1 > 1:
# this point would land *outside* triangle, so we
# ref... |
fdb13ce90add62a8da6e6e084d2b359d03aeb897 | AkThao/PySnake | /main.py | 6,448 | 3.859375 | 4 | #!/usr/bin/env python3
import pygame as pg
from random import randint
# Define window parameters
BLOCK_SIZE = 20 # Size of single block
WIN_SIZE = 500 # Width and height of window
UPDATE_FRAMES = 4 # How often to update snake position, controls game speed
class Head():
blue = (0, 0, 255) # Colour of snake
... |
f5dd8aa645284fcad07f66022e1e7e4d7f0274f5 | poal023/ACMTemplateRepo | /main.py | 196 | 4.25 | 4 | class Dice():
"""
TO DO:
ADD IN A DICE CLASS
"""
numSides = int(input("Enter the number of sides on a die!"))
print("Your dice has " + str(numSides) + " sides!")
|
a01679450bdc2b9189ae6be1a0242281469452fc | Dustin461/projects | /various/iap_8_fileops.py | 6,563 | 4.03125 | 4 | #!/usr/bin/env python2
# *-* coding: utf-8 *-*
"Interactive Python Part 8: File Operations"
def withfor():
qbfile = open("lib/qbdata.txt","r")
for line in qbfile:
values = line.split()
print 'QB ', values[0], values[1], 'had a rating of ', values[10]
qbfile.close()
def withwhile():
in... |
f5533b821ffcc74a2530a56749a7a169f51c1d43 | Dustin461/projects | /various/iap_11_oop.py | 6,438 | 4.53125 | 5 | #!/usr/bin/env python2
# *-* coding: utf-8 *-*
"Interactive Python Part 11: OOP"
from __future__ import division
import turtle
from math import sqrt
class Point(object):
" Point class for representing and manipulation cartesian coordinates"
def __init__(self, x=0, y=0):
self.x = x
self.y... |
205f48302a6acf6fe8177a3dbfaa2ae04971b122 | Dustin461/projects | /games/connectfour.py | 2,503 | 3.640625 | 4 | #!/usr/bin/env python2
# Overhaul, still missing the logic though
from random import randint
class Board(object):
def __init__(self, width, height, player_char, npc_char, first_turn):
self.width = width
self.height = height
self.data = ["_" for x in range(width) for y in range(height)]
... |
bb984eb7c1ecb5e4d1407baa9e8599209ff05f3b | xASiDx/other-side | /input_validation.py | 794 | 4.25 | 4 | '''Input validation module
Contains some functions that validate user input'''
def int_input_validation(message, low_limit=1, high_limit=65536, error_message="Incorrect input!"):
'''User input validation
The function checks if user input meets set requirements'''
user_input = 0
#we ask user to e... |
6d24c723ddb4d0f91e134561f615bd78feb85c34 | 123xiaoming/Test | /学生管理系统.py | 1,238 | 4.0625 | 4 | student_list = ["1","2","3","4"]
flag = 1
# 运行时显示操作界面
def show():
print("1代表添加学生")
print("2代表删除学生")
print("3代表查询某个学生")
print("4代表修改某个学生")
print("5代表显示所有学生信息")
print("6代表退出")
print("请输入对应的指令:",end=" ")
# 主函数
while flag:
show()
cmd = input()
if cmd == "1":
... |
1b49965e1ec10b6beece28533844d808af1bf9d5 | 715687545/get_filename_and_copy | /get_filename_and_copy.py | 2,699 | 3.765625 | 4 | import os
import shutil
"""
在目标文件夹中提取含有某字符串命名的文件夹下所有文件
"""
def FindAndCopy(filepath,str1,pathnew,count=1000): #count 表示要提取的相关文件夹的数量,默认1000
file1list=os.walk(filepath) #遍历filepath下的所有文件路径,将其写入file1list
count0=0 #文件夹数量计数
for... |
5d3fc7ea31b77e9f838685c49cf149f5a5d98ccf | karanalang/technology | /python_examples/Py_UpdatingListOfLists.py | 300 | 3.515625 | 4 | listOfLists = [[] for i in range(10)]
print(" lisOfLists - ", listOfLists)
print(" lenOfLists -> ", len(listOfLists))
listOfLists[0].append(1)
print(" lenOfLists, after update -> ", listOfLists)
arr1 = [-1 for i in range(10)]
print(" arr1 -> ", arr1, " arr1[idx not in array] -> ", arr1[100])
|
ccbe5125470f650707436e4490f8dceb07d7056b | karanalang/technology | /leetcode_subsets_combinations_parmutations_subsequence/FindAllCombinations.py | 658 | 4 | 4 | # https://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/
class FindAllCombinations:
def allCombinations_iterative(self, nums):
res = []
for i in range(len(nums)):
for j in range(i, len(nums)+1):
print(" i -> ", i, " j ->... |
8cb695a1c54c6c98ea134ff1a365a854389f01c3 | karanalang/technology | /python_examples/Py_SortedList.py | 494 | 3.65625 | 4 | # SortedList ->
# http://www.grantjenks.com/docs/sortedcontainers/implementation.html
# http://www.grantjenks.com/docs/sortedcontainers/index.html
from sortedcontainers import SortedList, SortedDict
sl = SortedList(['a','z','b','d','p','q','r'])
print(" sl -> ", sl, " sl[-2:] -> ", sl[-2:])
sl.pop(0)
print(" after p... |
4996d51a0d79f44c1ed2abf236c1bcf8789bb18a | karanalang/technology | /python_examples/py_bisect.py | 1,332 | 4.15625 | 4 | # https://docs.python.org/3/library/bisect.html
# https://www.tutorialspoint.com/bisect-array-bisection-algorithm-in-python
import bisect
# data = [1, 2, 3,4 ]
#
# idx = bisect.bisect(data, 2)
# print(" bisect.bisect(data, 2) i.e. get the idx to the RIGHT of the elem 2 -> ", idx)
#
# data.insert(idx, 100)
#
# print(... |
5272e63f67b24393a835968cac1a70fef631c676 | karanalang/technology | /python_examples/Py_ascii_uppercase.py | 331 | 4 | 4 | # https://www.geeksforgeeks.org/python-string-ascii_uppercase/
import string
uppercaseLetters = string.ascii_uppercase
print(" uppercaseLetters -> ", uppercaseLetters)
lowercase = string.ascii_lowercase
print(" lowercase letters -> ", lowercase)
asciiLetters = string.ascii_letters
print(" asciiLetters -> ", asciiLe... |
daa4dcbabeafa1eaa1de41eb195470d3d2749be5 | karanalang/technology | /python_examples/Py_create_2dArray.py | 469 | 3.5625 | 4 | class Array2D:
def print2DArray(self, row:int, col:int):
arr2d = [[0]*row]*col
print(arr2d)
arr2d_1 = [[0 for i in range(row)] for j in range(col)]
print(arr2d_1)
for i in range(len(arr2d)):
arr2d[i][i] = 1
print(" arr2d, set i==j to 1", arr2d)
... |
33c1937b0d95274845c6a217d575c5f39353da45 | karanalang/technology | /python_examples/Py_checkNumberOrCharacter.py | 148 | 3.671875 | 4 | s = "a1b2"
for i in range(len(s)):
print(s[i], " isdigit() -> ", s[i].isdigit(), " isnumeric -> ", s.isnumeric(), " isalpha -> ",s.isalpha()) |
140841edd419ed42b16027c215524f46d7bace61 | karanalang/technology | /python_examples/Py_doubleSizeOfArray.py | 101 | 3.671875 | 4 | l = [-1 for i in range(5)]
print(l)
l.extend([-1 for i in range(5)])
print(" after extending ", l) |
5453b1a6496d74e666b87ba12f6f1b29c97d6fdf | karanalang/technology | /python_examples/Py_usingCounter.py | 136 | 3.546875 | 4 | from collections import Counter
s = "aabbaaccccdef"
c1 = Counter(s)
print(c1)
d = {'a':2, 'b':3}
c2 = Counter(d)
print(" c2 -> ", c2)
|
ff560ef34931034c07567e9f21bee4af9a9b7fd6 | karanalang/technology | /python_examples/bitwise/bitwise_CountSetBitsInteger.py | 701 | 3.921875 | 4 | # https://www.geeksforgeeks.org/count-set-bits-in-an-integer/
n = 21
def countSetBits(n):
cnt = 0
while n>0:
cnt += (n & 1)
n = n >> 1
return cnt
setBits_iterative = countSetBits(n)
print(" setBits -> ", setBits_iterative)
def countSetBits_rec(n):
if n==0:
return 0
... |
c276d6f87149f8a9f724e58ad95ba1a1f80296b5 | karanalang/technology | /python_examples/Python_eval.py | 1,472 | 4.21875 | 4 | from math import *
# https://www.geeksforgeeks.org/eval-in-python/
class Python_eval:
def usingEval(self, str):
res = eval(str)
print(" res -> ", res)
def secret_function(self):
return "Secret key is 1234"
def function_creator(self):
expr = input("Enter function in terms... |
63b9a7894678d33d0833d6aff84e85e3bfe2acf9 | karanalang/technology | /python_examples/Py_AddLists.py | 544 | 3.9375 | 4 |
# afterAppend = l1.append(l2)
# print(" afterApopend -> ", afterAppend)
l1 = [1, 2, 3]
l2 = [2, 6, 7]
res = [1]
res.append(l1)
res.append(l2)
print(" res -> ", res)
print("l1.extend(l2) -> ", l1.extend(l2))
print(" l1 + l2 -> ", l1+l2)
print(type(res.append(l1)))
print(l1.extend(l2))
all = [1,2,5,7]
idx = 1
left1... |
5c51d56bc746abfb349aafdc7a78a5caa4458a90 | karanalang/technology | /python_examples/Python_Dictionary.py | 2,710 | 3.625 | 4 | from collections import defaultdict, OrderedDict
from typing import List
class Python_Dictionary:
def usingDefaultDict(self, l:List):
dd_defautInt = defaultdict(int)
for k,v in l:
dd_defautInt[k] = v
print(" defaultDict, default int -> ",dd_defautInt)
print(" trying ... |
b5575fa6cea7ba8fa0805b657a39438f83c5d774 | karanalang/technology | /python_examples/Python_IndexOfItemInList.py | 435 | 3.640625 | 4 | from typing import List
class Py_IndexOfItemInList:
def getIndexInList(self, nums:List[int], elem):
# indexOfElem = nums.index(elem)
# print(" index is -> ", indexOfElem)
indexes = [idx for idx, num in enumerate(nums) if num == elem]
lenArr = indexes[1]-indexes[0]+1
print(... |
8ef61ef4611ab539d01188336573480926f81413 | karanalang/technology | /python_examples/CheckIfPalindrome.py | 252 | 3.859375 | 4 | class CheckPalindrome:
def isPalindrome(self, s):
s = s.lower().replace(' ','')
return s == s[::-1]
p = CheckPalindrome()
s1 = 'A Santa Lived As a Devil At NASA'
print(s1)
print(' check if palindrome -> ', p.isPalindrome(s1))
|
c18d6f0cf84c5924093a0967bfc0229d1ebe75a2 | joaopnramos/Python | /AP_P02.py | 900 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#Exercicio 10
ds=input('Hoje qual é o dia da semana?')
print(ds)
type(ds)
numint=int(input('Que temperatura vai estar hoje?'))
print (numint)
type(numint)
numfloat=float(input('Qual é a od do Porto?'))
print(numfloat)
type(numfloat)
print... |
07cc29dd8d9bb35718df9c8b77edd82a604a23ac | sean830314/python-note | /Multiprocessing/mutiprocessing_share_instance.py | 820 | 3.515625 | 4 | from multiprocessing import Process,Value,Lock
from multiprocessing.managers import BaseManager
class Employee(object):
def __init__(self,name,salary):
self.name=name
self.salary=Value('i',salary)
def increase(self):
self.salary.value+=100
def getPay(self):
return self.name+'... |
04393206b7b54166cccd3defd8aa88d1f6b9cd06 | sean830314/python-note | /Design_Patterns/Behavioral_Design_Patterns/Observer/Observer_test.py | 1,967 | 3.703125 | 4 |
from abc import ABC, abstractmethod
class Observer(ABC):
@abstractmethod
def update(self,absence:str, designee:str):
pass
class ObserverPbx(Observer):
def update(self,absence:str, designee:str):
print("[PBX] 已指定轉接{0}的來電給{1}!".format(absence, designee))
class ObserverMailServer(Observe... |
9b7632bc5e8e0ec4d1b35f2412bb68317949d0f2 | sean830314/python-note | /Object_Oriented_Programming/property.py | 625 | 3.9375 | 4 | class Article:
def __init__(self, aid, title):
self.__aid = aid
self.__title = title
@property
def aid(self):
return self.__aid
@aid.setter
def aid(self, aid):
self.__aid = aid
@property
def title(self):
return self.__title
@title.setter
de... |
4671896cad5db4706f84ec9812ad1e6a4d30f47c | swrko/zaloha_pi_dallas | /zaloha/iotest.py | 296 | 3.578125 | 4 | <p>import RPi.GPIO as GPIO
# Use GPIO numbers not pin numbers
GPIO.setmode(GPIO.BCM)
# set up the GPIO channels - one input and one output
GPIO.setup(7, GPIO.IN)
GPIO.setup(8, GPIO.OUT)
# input from GPIO7
input_value = GPIO.input(7)
# output to GPIO8
GPIO.output(8, True)</p> |
3015e2c025dff7d3928b8a5da1138415f9173ddc | TheMoralEconomist/Ergodic_Economics | /ergodic-coin-toss.py | 1,572 | 3.625 | 4 | import numpy as np
import matplotlib.pyplot as plt
#Source
#https://ergodicityeconomics.files.wordpress.com/2018/06/ergodicity_economics.pdf
#Coin Toss Outcomes
rOfT = [.6, 1.5]
#if 0 multiply wealth by .6, if 1 multiply wealth by 1.5
def coinTossFunction(wealth):
coinToss = np.random.random_integers(0,1)
if... |
970a0d258eba45c8c033d65b712b013757d45a92 | dspolyar/Main | /Library_DigitClock.py | 1,618 | 4 | 4 | """
SOURCES:
DEFINITION:
Creates an outer product possibility space given a number of differnt events accross differnt dimensions
ARGS:
DigitMaximums
Type: Python List of Python Ints
Description:
Contains a list of the number of possibilities within each dimension - 1.
... |
a40065140b19d0757b173778b6705cac42a68f6e | Longerhaha/ml-udacity | /decision_tree/dt_author_id.py | 2,540 | 3.515625 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 3 (decision tree) mini-project.
Use a Decision Tree to identify emails from the Enron corpus by author:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess im... |
d1b96befe19a904a259d9507e72ec9303e1f34f7 | chibui191/cs50ai_week_0 | /tictactoe/tictactoe.py | 4,307 | 4.03125 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who h... |
6b998a1946eb923972f2bf8650d5c7a2482825cb | polyjason/algorithm | /min_max_recursive.py | 574 | 4.0625 | 4 | #Write a short recursive Python function that finds the minimum and maximum values in a sequence without using any loops
def minmax(data):
def minmax(data,left,right):
if left >= right - 1:
return min(data[left],data[right]),max(data[left],data[right])
else:
mid = (left+right... |
d7d2edc4cd2ad0d8c13eb8269a53b4a3f4d0a353 | nathangreene3/Dynamics-Chaos | /LangtonsAnt.py | 3,110 | 3.734375 | 4 | # LangtonsAnt.py
# Nathan Greene
# Summer 2018
#
# This script simulates Langton's ant.
#
# Source: https://www.futilitycloset.com/2014/04/06/langtons-ant/
import random
import sys
import time
def main():
LA = LangtonsAnt(10, "empty")
LA.run(iters=10000, sleeptime=0.2)
class LangtonsAnt:
"""
Langton's ant cons... |
5ba3519734e7ef4cf870442f2053039a1edaf6a6 | KApilBD/MachineLearning_Python | /Regression/MLR/NonLinearRegression.py | 2,776 | 3.859375 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
%matplotlib inline
# download the Dataset from below link using !wget
!wget -O FuelConsumption.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv
#Crea... |
47b2196333f4303850754e9e6cc4a2dcfcb98455 | arazkov/python_code | /untitled/greate_solutions.py | 604 | 3.734375 | 4 | #Solution №1
n = int(input())
d = {
n == 10: 'A+\nExcellent',
n == 9: 'A\nVery good',
n == 8: 'A-\nVery good',
n == 7: 'B+\nGood',
n == 6: 'B-\nGood',
n == 5: 'C+\nSatisfactory',
n == 4: 'C-\nSatisfactory',
n == 3: 'F\nFail\nGO TO ПЕРЕСДАЧА!',
n == 2: 'F\nFail\nGO TO ПЕРЕСДАЧА!',
... |
a5b7162c9e48e457f0ec5f9d2185d971fe44e53d | FelixJ20000/Quiz1 | /code/intro.py | 188 | 3.953125 | 4 | def greet():
name = input("First name: ")
print("Hello",name.capitalize()+", welcome to the train quiz.")
print("Answer questions with the number given.")
return name.capitalize()
|
07ad46ae7ae83e6ee0cb91d4ad0dcfb551820499 | Dedicationist/TICT-V1-PROG-15 | /Perkovic Exercises/Perkovic Exercise 4.23.py | 247 | 3.53125 | 4 | def gemiddelde(zin):
ListZin = zin.split(' ')
lst = []
for woorden in ListZin:
lst.append(len(woorden))
return sum(lst) / len(lst)
NeedAverage = input('Enter a sentence: ')
average = gemiddelde(NeedAverage)
print(average)
|
a7a307ee25a654563f71e01d6331a3cb8e0c91f8 | Dedicationist/TICT-V1-PROG-15 | /Perkovic Exercises/Perkovic Exercise 3.21.py | 99 | 3.71875 | 4 | lst = [2, 3, 4, 5, 6, 7, 8, 9]
for numbers in lst:
if numbers % 2 == 0:
print(numbers)
|
d22ef7d17e2fd5caef05bcb5c689e258d7191b58 | Dedicationist/TICT-V1-PROG-15 | /Perkovic Exercises/Perkovic Exercise 6.16.py | 207 | 3.75 | 4 | mult3 = set()
mult5 = set()
mult7 = set()
som3 = 0
som5 = 0
som7 = 0
for i in range(100):
som3 += 3
mult3.add(som3)
som3 += 5
mult3.add(som5)
som3 += 7
mult3.add(som7)
print(mult3)
|
1e739d3729378d53446491be58c385aafa635a00 | Dedicationist/TICT-V1-PROG-15 | /Opdrachten in de les/Les06/Exercise 6_3.py | 166 | 3.546875 | 4 | zin = input('Geef een zin om het acroniem te generen: ')
woorden = zin.split()
acroniem = ''
for woord in woorden:
acroniem = acroniem + woord[0]
print(acroniem)
|
7a9582977586a320573c201eba85f02a7d233ac0 | Dedicationist/TICT-V1-PROG-15 | /Opdrachten in de les/Les03/Exercise 3_6.py | 320 | 3.53125 | 4 | getallenrij = [2, 4, 5, 8, 10, 9, 7]
zoekgetal = eval (input('Welk getal wil je zoeken?'))
gevonden = False
for getal in getallenrij:
if getal == zoekgetal:
gevonden = True
if gevonden == True:
print ('Het zoekgetal zit in de getallenrij.')
else:
print ('Het zoekgetal zit niet in de getallenrij.')
|
b1311dbebf361a0399ac3c2a20f959629bbe1d02 | Dedicationist/TICT-V1-PROG-15 | /Perkovic Exercises/Perkovic Exercise 3.33.py | 135 | 3.609375 | 4 | def reverse_string(abc):
omgedraaid= abc[2] + abc[1] + abc[0]
return(omgedraaid)
random = 'def'
print(reverse_string(random))
|
a98e2a9e7e0a63e5ca611ce43d60a4ed261af663 | Dedicationist/TICT-V1-PROG-15 | /Perkovic Exercises/Perkovic Exercise 5.16.py | 277 | 3.90625 | 4 | def indexes(string, letter):
lst= []
for i in range(0, len(string)):
if string[i] == letter:
lst.append(i)
return lst
string = input('Voer een woord in: ')
letter = input('Voer een letter in: ')
uitvoer = indexes(string, letter)
print(uitvoer)
|
fa626219d0daf82c972832550e95361e1055640e | Dedicationist/TICT-V1-PROG-15 | /Perkovic Exercises/Perkovic Exercise 3.18.py | 149 | 4.125 | 4 | a = 3
b = 4
c = 5
if a < b:
print ('OK')
if c < b:
print ('OK')
if a + b == c:
print ('OK')
if a**2 + b**2 == c**2:
print ('OK')
|
f6003908f02c7d3576b18593e93abce6097af72c | Dedicationist/TICT-V1-PROG-15 | /Perkovic Exercises/Perkovic Exercise 5.21.py | 178 | 3.6875 | 4 | def pair(lst1, lst2, n):
for numbers in lst1:
if n - numbers in lst2:
print('{} {}'.format(numbers, n - numbers))
pair([8, 10, 6, 9], [8, 7, 9, 12], 18)
|
7225f3aa50b4ca404b8e9c9a7e43cec10d9d3a5d | shekorla/Scripting-Random | /python/coffee project.py | 3,012 | 3.828125 | 4 | class coffeeMachine:
totalRec=int
def totalCash(num):
coffeeMachine.totalRec=coffeeMachine.totalRec+num
return coffeeMachine.totalRec
def one_action(true):
print(" ")
print("PRODUCT LIST: all 35 cents, except bouillon(25 cents)\n1=black, 2=white, 3=sweet, 4=white & sweet, 5=bouillon \nSample comma... |
2aa16f8c7367ab45245e8e339593a73e8701ff92 | iandennismiller/gthnk | /src/gthnk/model/journal.py | 4,025 | 3.734375 | 4 | import re
from .day import Day
class Journal:
"""
Represents a full journal.
"""
def __init__(self, gthnk=None):
self.days = {}
self.gthnk = gthnk
def create_day(self, datestamp:str):
"Create a new day in the journal"
new_day = Day(journal=self, datestamp=datesta... |
c1813b41f04a1bf40e2b2b2932b252ac12e5bb7e | IvanZ123/Parallel_Convex_Hull | /co.py | 3,507 | 3.75 | 4 | import math
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def orientation(p,q,r):
val=((q.y-p.y)*(r.x-q.x))-((q.x-p.x)*(r.y-q.y))
#checking by the slopes for orientation
if val==0:
return 0 #coloiner points... |
d0219bd6ffe2d00bba2581b72b852b858c8c1a07 | QARancher/file_parser | /search/utils.py | 710 | 4.1875 | 4 | import re
from search.exceptions import SearchException
def search(pattern,
searched_line):
"""
method to search for string or regex in another string.
:param pattern: the pattern to search for
:param searched_line: string line as it pass from the file parser
:return: matched object of... |
74e87bf28436a832be8814386285a711b627dab9 | ohaz/adventofcode2017 | /day11/day11.py | 2,179 | 4.25 | 4 | import collections
# As a pen&paper player, hex grids are nothing new
# They can be handled like a 3D coordinate system with cubes in it
# When looking at the cubes from the "pointy" side and removing cubes until you have a
# plane (with pointy ends), each "cube" in that plane can be flattened to a hexagon
# This mean... |
b89513646363816999bafb7732910d53eafca2e2 | WithSJ/Computer-Graphics-Algoritms | /Line/DDA/main.py | 907 | 3.859375 | 4 | from graphics import *
from time import sleep
win = GraphWin(title="DDA algo",width=500,height=500)
def line(x1,y1,x2,y2):
#calculate change in x and y
dx = x2-x1
dy = y2-y1
#steps is equal to greater change
steps = abs(dx) if abs(dx)>abs(dy) else abs(dy)
# how much should incress value... |
9dde86e0bff49be42e84a81837c4ce674393eaaf | dennis-omoding3/firstPython | /dictionary.py | 456 | 3.90625 | 4 | personal=["dennis omodin","eldoret",24,False,"kenyan"]
#a dictionary is a data structure that holds key and value
a=0#int
b=0.0#float
c="" #str
d=[]#list
e=() #tuple
f={} #dictionary
print(type(f))
personal={"name":"dennis omoding","location":"eldoret","age":24,"is_short":False}
print(personal)
#access using the ke... |
9e9f9151efbe59c7e0100048c3d46f7d8786bba5 | dennis-omoding3/firstPython | /task.py | 630 | 4.15625 | 4 | taskList=[23,"jane",["lesson 23",560,{"currency":"kes"}],987,(76,"john")]
# 1. determine the type of var in task list using an inbuilt function
print(type(taskList))
# 2.print kes
print(taskList[2][2]["currency"])
# 3.print 560
print(taskList[2][1])
# 4. use a function to determine the length of taskList
print(len(ta... |
29b25d018193bcfb8821221fb8c689d27f90533d | coding-black/python-wikipedia-tool | /main.py | 1,158 | 3.8125 | 4 | import wikipedia
global title, url, content, find, result
find = input('\nEnter the thing of which you need wikipedia :- ')
result = wikipedia.page(f'{find}')
print('\n\n')
print(result.title)
print('\n')
print(result.url)
print('\n')
print(result.content)
print('\n')
title = result.title
url =... |
7fd73df6ab94d6443e78636bad0c7e1af2ef124a | RrennM/python_bc_mileage_converter | /mileage_converter.py | 317 | 4.0625 | 4 | print("How many kilometers did you cycle today?")
kms = input()
mile = float(kms) * 0.621371
# kms = str(kms)
# mile = str(mile)
# print("Okay, you said " + kms + " kilometers. That's about " + mile + " miles!")
round_mile = round(mile, 2)
print(f"Okay, you said {kms} kilometers. That's about {round_mile} miles!") |
6913850c0448471f30edbe7d0ed8dd492300b051 | Venkateshkatta07/DSA_python | /BubbleSort.py | 638 | 4.09375 | 4 | '''
Created on 23-Feb-2021
@author: Venky 07
'''
def swap_elements(array,index_1,index_2):
temp=array[index_1]
array[index_1]=array[index_2]
array[index_2]=temp
def bubble_sort(array):
for i in range(0,len(array)):
sorted_flag=False
for j in range(len(array)-1-i)... |
954315ccb1c7f400b853b834a9bfed66d58d81ba | felikemath/python-AI | /randomexperssion.py | 600 | 3.515625 | 4 | import time
def regularexpression(string):
new = ''
ans = []
for i in string:
if i.isalpha():
new += i
else:
new += ' '
newlist = new.split(' ')
final = list(filter(None, newlist))
for item in final:
loweritem = item.lower()
if loweritem.sta... |
915cd90fd4cb8778339476625c960e6624ea491f | Enokisan/ZipDatabase | /ken_alldl.py | 1,093 | 3.625 | 4 | import zipfile
import urllib.error
import urllib.request
import os
# 指定URL(第1引数)からファイルを取得して、指定パス(第2引数)に保存する
def file_download_unzip():
url = "https://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip"
data_dir_path = "./"
save_path = data_dir_path + "download.zip"
try:
"""
if os.... |
d287a30dd3120dba550b33529f282a86db28ce50 | Danielmagox/MontyHallSimulation | /MontyHall.py | 1,647 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Monty Hall problem
# In[11]:
import random
# In[12]:
NUMBER_OF_SIMULATIONS = 1000000
DOORS = [1,0,0]
# In[13]:
def shuffle_doors(doors):
random.shuffle(doors)
return doors
# In[14]:
def random_between(minimum=0,maximum=3):
return random.randrange(min... |
cc4516c88c52e6e6047f568d4e4e71460a999f1a | niloo9876/RoboCop | /src/script/python scripts/motor/mingMap.py | 17,053 | 3.734375 | 4 | """
This is the program that will connect the arduino on the car with the server
It has some requirements:
Author: Ming-han Ko, Yiyi Yan
1. The server has to follow the request format from http://griin.today/
2. The arduino has to follow the protocol in order to communicate with this program
It has to connect via o... |
231dad4c0f4f01b772e2d5532108916546a9cb8d | niloo9876/RoboCop | /src/Mapping/Map2.py | 5,112 | 3.546875 | 4 | import math
#Current Coordinates of the robot.
# Angle is kept between 180 and -180
Current_Coord = {'x': 0, 'y': 0, 'ang': 90}
#global used by functions
prevDistance = 0
outerParameter = []
patrolPath = []
#State of the Robot
mode = ["Mapping", "Manual", "Patrol"];
currentMode = "Manual";
# Class created for a li... |
6e6589f5c119a3aa6a630b166cce0d9d9fd8333c | cjgv1809/Codigos-iniciales | /Palabras_con_mas_caracteres.py | 338 | 3.578125 | 4 | def mas_caracteres(palabras):
pos=0
for x in range (1,len(palabras)):
if len(palabras[x])>len(palabras[pos]):
pos = x
return palabras[pos]
#Bloque Principal
palabras=["enero","febrero","marzo","abril","mayo","junio"]
print(palabras)
print("La palabra con más caracteres es:",mas_cara... |
c777cd86a459176be8a7e750216e2a91572ad2c1 | tonussi/freezing-dubstep | /pratica-04/randlist.py | 655 | 3.625 | 4 | # encoding:utf-8
import random
def main():
rl = RandList(1, 2000)
rl.gen_random_list()
rl.print_block_list()
class RandList(object):
def __init__(self, first, second):
self.first = first
self.second = second
self.populacao = []
def gen_random_list(self):
self.pop... |
fa58199fe0dde4e71b310771e3d12657df58dd26 | ElBell/Quiz1 | /quiz1/src/Test/test_StringUtilities.py | 1,585 | 3.59375 | 4 | from unittest import TestCase
from StringUtilities import StringUtilities
class TestMathUtilites(TestCase):
def setUp(self):
self.test_string_utilities: StringUtilities = StringUtilities()
def test_return_string(self):
expected: str = "Something"
actual: str = self.test_string_utiliti... |
0174dddee06ba5f49896eadfb5c94aad21834951 | EliiseS/Playground | /python101/models/student.py | 296 | 3.546875 | 4 | class Student():
school_name = "Sprinfield Elem"
def __init__(self, name: str, id: str = "1"):
self.name: str = name
self.student_id: str = id
def __str__(self):
return "Student " + self.name
def get_name_capitalized(self):
return self.name.capitalize()
|
1b828b49dfbf3636977b2dcb88d391e692e40e50 | vkaushik189/ltcode_solutions | /1108DefangingAnIP.py | 392 | 3.609375 | 4 | class Solution:
def defangIPaddr(self, address: str) -> str:
"""
new_address = address.replace(".", "[.]")
return new_address
"""
new_message = ''
for char in address:
if char != '.':
new_message = new_message + char
else:
... |
e43371e6543a71c6484f950e8eb17b4c961a2c6c | phamd1989/Pacman_AI_Search | /test.py | 255 | 3.5 | 4 |
a = ((2,3), (False, False, False, False))
##def test(a):
## sum = 0
## for i in a[1]:
## if i == False:
## sum += 1
## return sum==4
##
##print test(a)
##print a
b = []
b.append(a[1])
print b
print b[0][0]
|
b54da5092a123400827a586ded8da1aae3ee6397 | Aryan-Naveen/Naveen_Sneed_SNEL | /make_file_of_first_char_in_each_file.py | 499 | 3.703125 | 4 |
# open the file
def file_num_to_hex(dec):
num=hex(dec)[2:]
num_zero = 4-len(num)
return num_zero * "0" + num
def generate_file(i):
file_name = "file_" + i +".txt"
#print("folder_of_files/" + file_name)
with open ("text_files/" + file_name, 'r') as f:
return f.read()
... |
57cb03934fe2d8dfca737bec0031dc63dede0100 | woai77htz/test1 | /house.py | 729 | 3.703125 | 4 | """
class 类名:
多个类属性...
多个类方法...
"""
class House:
# 静态属性 -> 类变量,在类之中,方法之外定义
door = "red"
floor = "white"
# 动态方法
def sleep(self):
bed = "席梦思"
print("在房子里面睡觉")
def cook(self):
print("在房子里面做饭")
if __name__ == '__main__':
# 实例化
north_house = House()
ch... |
11906e74d90c402f7d5fdfe341c1f757976c18ed | jiningzhao/Scrapy | /pacongjichu/server.py | 1,008 | 3.53125 | 4 | from socket import *
# 创建socket
tcpSerSocket = socket(AF_INET, SOCK_STREAM)
# 绑定本地信息
address = ('', 8080)
tcpSerSocket.bind(address)
# 使⽤socket创建的套接字默认的属性是主动的,使⽤listen将其变为被动的,这样就可以接
tcpSerSocket.listen(5)
while True:
# 如果有新的客户端来链接服务器,那么就产⽣⼀个信⼼的套接字专⻔为这个客户端服务器
# # newSocket⽤来为这个客户端服务
# # tcpSerSocket就可以省... |
7f5c5f68d605093f88cfa7fc024b41b7281c7f3a | desmondmcconnell/Flask_Test | /app.py | 1,061 | 3.734375 | 4 | from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return '<h1>Enter /c/(number to convert) or /f/(number to convert) into the URL bar</h1>'
@app.route('/f')
@app.route('/f/<degrees>')
def f(degrees="0"):
return convert(degrees, "f")
@app.route('/c')
@app.route('/c/<degrees>... |
6ac581ae0842787a92b863397f609236eb09d0fd | nurSaadat/pythonLearning | /talking_robot.py | 856 | 4.40625 | 4 | # В институте биоинформатики по офису передвигается робот.
# Недавно студенты из группы программистов написали для него программу,
# по которой робот, когда заходит в комнату, считает количество программистов в ней
# и произносит его вслух: "n программистов".
x = int(input())
c = x % 100
d = x % 10
if 0 <= x <= 1000... |
d6c0888b67e5736683a8dc92f86ff20f63f9c8f5 | fancy84machine/Python | /Projects/Supervised Learning/Gapminder+Regression.py | 6,667 | 3.5 | 4 |
# coding: utf-8
# In[58]:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# In[ ]:
# In[59]:
df = pd.read_csv ('gm_2008_region.csv')
df.drop ('Region', axis = 1, inplace = True)
df.head()
# In[60]:
df.info()
# In[61]:
df.describe()
... |
bca6efc74a134d2864a0247814900b1ab72ac8fc | fancy84machine/Python | /Projects/Cleaning Data in Python/Building+Application+Value+Counts.py | 702 | 3.71875 | 4 |
# coding: utf-8
# In[21]:
# Import pandas
import pandas as pd
import matplotlib.pyplot as plt
# Read the file into a DataFrame: df
df = pd.read_csv ('dob_job_application_filings_subset.csv')
# Print the head of df
print(df.head())
# Print the tail of df
print(df.tail())
# Print the shape of df
print(df.shape)
... |
b20bce03cb87bbfeaa79fc1316a0e7a620847796 | AngishBhandwalkar/python-class-work | /arm.py | 196 | 3.765625 | 4 | #Angish bhandwalkar 11810766 M03
x=int(input())
a=x
sum=0
while a>0:
n=a%10
sum=sum+n**3
a=a//10
print(sum)
if sum==x:
print("it is a arm")
else :
print("it is not a arm")
|
db99cae1f44fa69341f702de79e9c0ed8662e537 | nazrul-avash/Algorithms-with-Python | /QuickSort.py | 992 | 4.0625 | 4 | def quick_sort(values):
if len(values)< 2:
return values
else:
pivot = values[0]
smaller = [x for x in values[1:] if x <= pivot]
larger = [x for x in values[1:] if x> pivot]
return quick_sort(smaller)+[pivot]+quick_sort(larger)
return values
def make_partition(values):
pivot = values[0]
pivot_index =0
... |
972c6355cba0d23f293664ba6ba6e8ded8a9fc33 | zhijunsheng/tictactoe-py | /algorithms/maps/occurrences.py | 1,088 | 3.921875 | 4 | import unittest
def max_word_count(file_name):
freq = {}
for piece in open(file_name).read().lower().split():
# only consider alphabetic character within this piece
word = ''.join(c for c in piece if c.isalpha())
if word: # require at least one alphabetic character
freq[w... |
7c4915ce1073e410c6ef32b2f0be10397a8d1374 | zhijunsheng/tictactoe-py | /algorithms/linked_lists/doubly_linked_lists.py | 14,479 | 3.578125 | 4 | import unittest
class Empty(Exception):
pass
class _DoublyLinkedBase(object):
"""A base class providing a doubly linked list representation."""
class _Node:
"""Lightweight, nonpublic class for storing a doubly linked node."""
__slots__ = '_element', '_prev', '_next' # streamline memory... |
0118e31885404c5e9222b7d454be9d2311af8041 | fiorezhang/Sudoku | /sudoku_generator.py | 5,398 | 4.0625 | 4 | #sudoku_generator
#copyright: fiorezhang@sina.com
import numpy as np
#calculate the remainder for x in range: 1~y
def remainder(x, y):
return (x-1)%y+1
''' #comment out the original matrix generator as generate in a function
#define the size of matrix
SIZE = 3
m_basic = np.zeros((SIZE * SIZE, SIZE * S... |
8f928cb830a1af09065c158d26d96331a0a77685 | Yurrili/PyMeno | /CORE/algh.py | 10,280 | 3.71875 | 4 | """
In this file we have function to split lyrics of songs with user's library
into dicts and looks for other similarly songs
"""
from collections import Counter
from PyLyrics import PyLyrics
import pickle
import math
import random
class FindMusic(object):
"""
FindMusic class is looking for simila... |
6981f9e5e3edf77f02db8d7c72e6d0c38a708801 | Kellswork/Intro-Python-II | /src/adv.py | 3,463 | 3.5625 | 4 | from room import Room
from player import Player
from item import Item
# Declare all the rooms
from src.item import Item
room = {
'outside': Room("Outside Cave Entrance",
"North of you, the cave mount beckons"),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages ... |
a99b2447674fe77854760c81a4cac517faee4358 | subhashgowda/Python | /Python_basic_pgms/Codechef_Fitness.py | 67 | 3.671875 | 4 | for _ in range(int(input())):
a=(int(input())*2)*5
print(a) |
06f1c28e382b521d94df85052d271129dc8cf077 | Obdam/AdventOfCode | /2020/day6.py | 931 | 3.625 | 4 | # Parse answer data as list objects, so you get a list with answers per group.
def parseData():
answerGroups = []
with open('/mnt/d/Code/AdventOfCode2020/2020/day6input.txt', 'r') as file:
lines = file.read().split("\n\n")
# Assumption: it does not matter how big a group is (a person in a g... |
47d5f499417462a03be0360ff9a1f2fe9d5ebf43 | YaseenAlMufti/BlackJack | /Resources/ChipsandBets_module.py | 1,227 | 3.859375 | 4 |
class ChipsAndBets:
def __init__(self, balance=100, bet=0):
self.balance = balance
self.bet = bet
self.balance_statement()
def place_bet(self, placed_bet):
# sets the bet
self.bet = placed_bet
print("Bet Placed!")
def win_bet(self):
# adds the winn... |
61d56c6645623e847f7a8e106c0a763bda90232c | lwjNN/leetcode-python | /Python/jichu/test2.py | 243 | 3.828125 | 4 | '''
测试条件判断
'''
# age = int(input("请输入你的年龄:"))
# if age >= 18:
# print("已成年")
# else:
# print("未成年")
age = int(input("请输入你的数字龄:"))
if age:
print("非0")
else:
print("0")
|
507c40a27389a4928259bcb503f6143683ec09c3 | lwjNN/leetcode-python | /Python/leetcode/everyday/Solution_328.py | 563 | 3.765625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
cur = head
last = head.ne... |
5f4447bc9fc11dae8bd52e7d8cb374fa3daace14 | lwjNN/leetcode-python | /Python/leetcode/start/Solution_02.py | 1,301 | 3.53125 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
"""
常规想法:将每个链表转为数字,求和。再把结果生成新的链表
"""
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
resNode = ListNode(-1, None)
tmp = resNode
def getNu... |
4d647b6c3147dec57dd0ab525c5bc97b94f9e459 | lwjNN/leetcode-python | /Python/sword2offer/Offer11.py | 1,044 | 4.4375 | 4 | """
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
示例 1:
输入:[3,4,5,1,2]
输出:1
示例 2:
输入:[2,2,2,0,1]
输出:0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing imp... |
ca54d6e3869c95b782ff486e6e9dbd40b3e1d96a | lwjNN/leetcode-python | /Python/leetcode/greed/Solution_1403.py | 1,523 | 4.03125 | 4 | from typing import List
"""
给你一个数组 nums,请你从中抽取一个子序列,满足该子序列的元素之和 严格 大于未包含在该子序列中的各元素之和。
如果存在多个解决方案,只需返回 长度最小 的子序列。如果仍然有多个解决方案,则返回 元素之和最大 的子序列。
与子数组不同的地方在于,「数组的子序列」不强调元素在原数组中的连续性,也就是说,它可以通过从数组中分离一些(也可能不分离)元素得到。
注意,题目数据保证满足所有约束条件的解决方案是 唯一 的。同时,返回的答案应当按 非递增顺序 排列。
示例 1:
输入:nums = [4,3,10,9,8]
输出:[10,9]
解释:子序列 [10,9] 和 [10... |
4998cb67572aba9cd8dea5fa85c4a104d03e76d8 | lwjNN/leetcode-python | /Python/demo/Test.py | 183 | 3.828125 | 4 | # nums = [2, 7, 11, 15]
# for i in range(len(nums) - 1):
# print("i = %d" %i)
# for j in range (i + 1, len(nums)):
# print("j = %d" %j)
l = [1,2,3]
print(reversed(l)) |
1e031c16f5d7f863622621f523a9fa392ab28a84 | lwjNN/leetcode-python | /Python/sword2offer/Offer10_1.py | 911 | 3.78125 | 4 | """
写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:1
示例 2:
输入:n = 5
输出:5
提示:
0 <= n <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/prob... |
87e090b176e8b2edb4e43b055dba0891242e1148 | SaretMagnoslove/Python_3_Basics_Tutorial_Series-Sentdex | /Lesson32_tkinter_2.py | 556 | 3.71875 | 4 | from tkinter import *
# now for creating the window
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
# initializing the window
self.master.title ('GUI') #adding title
... |
ea53fb163337a49762314dbc38f2788a74846343 | SaretMagnoslove/Python_3_Basics_Tutorial_Series-Sentdex | /Lesson24_multiline_print.py | 666 | 4.5 | 4 | # The idea of multi-line printing in Python is to be able to easily print
# across multiple lines, while only using 1 print function, while also printing
# out exactly what you intend. Sometimes, when making something like a text-based
# graphical user interface, it can be quite tedious and challenging to make every... |
b6ba5f426a5b27961cc7b6f128f24f2406bb6cd4 | SaretMagnoslove/Python_3_Basics_Tutorial_Series-Sentdex | /Lesson01_printing_strings.py | 824 | 4.0625 | 4 | # We're printing out a string.
# Notice that the quotes are single quotes.
# You can use single quotes or double quotes, but they need to be used together.
print('Single Quotes')
print("double quotes")
# You cannot use the "+" to join strings with ints or floats, you must use the ",".
print('can do this',5)
print('ca... |
e87e337024202ddedbce3a3a509813b7457cffc0 | SaretMagnoslove/Python_3_Basics_Tutorial_Series-Sentdex | /Lesson11_functions_parameters_defults.py | 652 | 3.96875 | 4 | # When using defaults, any parameters with defaults should be the last ones listed in the
# function's parameters.
# Something like:
def simple(num1, num2=5):
pass
# This is just a simple definition of a function,
# with num1 not being pre-defined (not given a default),
# and num2 being given a default.
def basi... |
1d3f279e8da993449241071093c7706d5e368b0e | SaretMagnoslove/Python_3_Basics_Tutorial_Series-Sentdex | /Lesson15_reading_file.py | 336 | 3.671875 | 4 | # similar syntax as you've seen, 'r' for read. You can just throw a .read() at
# the end, and you get:
readMe = open('litanyAginstFear.txt','r').read()
print('Reading all text:\n', readMe)
# this will instead read the file into a python list.
readMe = open('litanyAginstFear.txt','r').readlines()
print('Reading into a ... |
b89f65950e397b384ad0e52fad5453356da92ec6 | AarnavKashyap/project-c100 | /project-c100.py | 679 | 3.625 | 4 | class Atm(object):
def __init__(self, balance, cash_withdrawl):
self.balance = balance
self.cash_withdrawl = cash_withdrawl
self.remaining_balance = balance - cash_withdrawl
def print__balance(self):
print("Balance in your account is ₹ " + str(self.balance))
de... |
d64cc84dce82c636bed17c1bdf2b4594cbc61bb7 | brenokcc/capacitacao | /project201/goal02.py | 702 | 3.875 | 4 | from project201.goal01 import Polygon
class Polygons:
def __init__(self, m, r):
if m < 3:
raise ValueError('m must be greater than 3')
self._m = m
self._r = r
self._polygons = [Polygon(i, r) for i in range(3, m + 1)]
def __len__(self):
return self._m - 2
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.