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 |
|---|---|---|---|---|---|---|
b2d0c98991b224d46a59cfc79763fa386aa339dd | codeaid-dev/Python_practice | /Practice_object/space.py | 918 | 3.578125 | 4 | import tkinter
import random
class Circle:
def __init__(self):
self.x = random.randint(0, 600)
self.y = random.randint(0, 400)
self.speed = random.randint(1,6)
self.color = f'#{int(self.speed/6*255):02x}{int(self.speed/6*255):02x}{int(self.speed/6*255):02x}'
self.id=None
... |
24d2095c2e430d4fba1969fcfeb7ea312ed54b46 | codeaid-dev/Python_practice | /Practice_function/randomtest.py | 745 | 3.859375 | 4 | import random
import string
def randomword1(length):
return ''.join(random.choice(string.ascii_lowercase) for i in range(length))
def randomword2(length):
x = ""
for i in range(length):
x = x + random.choice(string.ascii_lowercase)
return x
# returns a 10 character long string by calling funct... |
e073bcc273729c105935782ec97b8521d87594c6 | cameron-bam/Python-Files | /myDictionary.py | 701 | 3.65625 | 4 | class myDictionary(object):
def __init__(self):
self.words = list()
def loadWords(self, file_name):
f = open(file_name)
self.words = f.read().splitlines()
def toLowerCase(self):
for i in range(0,len(self.words)):
self.words[i] = self.words[i].lower()
def hasWo... |
669e4f059a924d3e7e8c03e136d7b97bfed4f016 | yaoxiao6/Others-learning | /CS131/ps6.py | 785 | 3.59375 | 4 | def are_parts_nonoverlapping(p):
all = p[0]
q = p[1:]
for i in q:
if(len(all & i) > 0):
return False
all = all | i
return True
def do_parts_contain_element(x, p):
all = p[0]
for i in p:
all = all | i
return x in all
def do_parts_cover_set(s, p):
fo... |
f7de4ba2b9a161df1f920ec4f55b52d64a3b466f | ychnh/SLAM | /core.py | 1,971 | 3.734375 | 4 | import numpy as np
import math
# For sake of clarity of matrix operations, all points and vectors will be represented as matrices
# instead of the traditional list form.
# This means a point [x,y,z] will be expressed as [[x,y,z]] to denote a 1x3 matrix
def solve_homogenous_Ax(A):
''' With constraint that ||x||=1 ... |
a64440a8d026c017fba068f8b0bce93f30c1e49f | Shortrope/Python-60-days-of | /Projects/strFormat.py | 305 | 3.8125 | 4 | animal = 'dog'
color = 'brown'
print("The lazy " + animal + " jumps over the big'ol " + color + " cow!")
print("The lazy {0} jumps over the big'ol {1} cow!".format(animal, color))
print(f"The lazy {animal} jumps over the big'ol {color} cow!")
print(r"The lazy {animal} jumps over the big'ol {color} cow!") |
5b35fa743c0232adf7fb03c6a292f51a30a17816 | Shortrope/Python-60-days-of | /Projects/strings.py | 289 | 3.734375 | 4 | import string
print(string.ascii_letters)
print(string.punctuation)
print(string.whitespace)
print('')
print("hello".ljust(20, '*'))
print("hello".center(20, '*'))
print("hello".rjust(20, '*'))
print("hello".count('l'))
phrase = "The dog jumped over the lazy cow"
print(phrase.count('e'))
|
9fe392e40c2ca309411afc482ab70969f6eaf89c | Shortrope/Python-60-days-of | /Projects/pyfund/reversekv.py | 365 | 3.890625 | 4 | #!/usr/bin/python3
from pprint import pprint as pp
country_to_capital = { 'UK': 'London',
'Brazil': 'Brazilia',
'Moracco': 'Rabat',
'Sweden': 'Stockholm'}
cap_to_country = {capital: country for country, capital in country_to_capital.items()}
pp(coun... |
d32c317da901c4d7c0f5d6fa4b3bb571bcfa58aa | getadeo/code-snippets | /python-snippets/json-dict.py | 169 | 3.546875 | 4 | import simplejson as json
dict = {'profile': ('name': 'genesis tadeo', 'age': 21)}
data = json.dumps(dict)
print data
#for item in data['profile']:
# print (item['name'])
|
7fdcf6cdb2f198e663f5a699eb0c515568969d37 | kaa13051996/test_rep | /code/ex_vk/req/friends.py | 1,933 | 3.5625 | 4 | import requests
from datetime import datetime
from dateutil.relativedelta import relativedelta
def calc_age(uid):
'''
https://www.coursera.org/learn/python-for-web/programming/POfZx/praktika-po-requests
Example url: https://api.vk.com/method/users.get?user_id={uid}&v=5.52&access_token={ACCESS_TOKEN}
:... |
bb6b1d53c7d522f317414de0244e05b7b5113d2f | Jamjomjara/snu-artoon | /Study/StudyTensorFlow/2-MNISTbySoftmax/MNISTBySoftmax.py | 4,856 | 4.09375 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# Constants:
TRAINING_NUMBER = 1_000
# 1. download MNIST data set.
# The downloaded data set has 3 types of data - training, test and validation.
mnist_data = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 2. Design our m... |
aa2b839aa819730bdebd8f03736ef4e1e3c0786e | cklasicki/dataalgorithms | /tasks/recursion/sum_integers.py | 331 | 3.921875 | 4 | def sum_integers(n):
print('entering with n={}'.format(n))
if n == 1:
print('return for n={}, output={}'.format(n, 1))
return 1
output = n + sum_integers(n-1)
print('return for n={}, output={}'.format(n, output))
return output
print(sum_integers(3))
# 1 + 2 + 3
# 1 + 1 +... |
88b1d5ec121975017041e29630caf808aad6b8c5 | mohcinemadkour/ML_Programs | /ML_Basics/Logistic_Regression_GD.py | 2,421 | 3.6875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 10 12:17:26 2018
@author: Das
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class Logistic_Regression:
def fit(self, X, Y, theta, alpha, num_iter):
train = Train()
self.theta, J = train.gradient_des... |
34fc04f19714d1d01ec3e96cf424806066d86657 | StarPony3/403IT-CW2 | /AND gate.py | 729 | 4.09375 | 4 | # program for AND gate
while True:
# applies Boolean operator 'AND' and returns Boolean value
def and_gate (a, b):
if a == '1' and b == '1':
return True
else:
return False
# takes two inputs from user
# loop breaks if either inpu... |
a685dfed0946a9c01454d98f65abab97d25f6ce2 | StarPony3/403IT-CW2 | /Rabbits and recurrence.py | 645 | 4.3125 | 4 | # program to calculate total number of rabbit pairs present after n months,
# if each generation, every pair of reproduction-age rabbits produces k rabbit pairs, instead of only one.
# variation of fibonacci sequence
# n = number of months
# k = number of rabbit pairs
# recursive function for calculating grow... |
85ae4e3113ec69929bb83027b1676db105c6ab6b | CaioLinsCastro/fib | /fib.py | 148 | 3.796875 | 4 | # Calcula a sequência de Fibonacci (sqn)
n = int(input("n: "))
x, y = 1, 1
for _ in range(n):
print(x)
z = x
x = y
y = z + y
|
780fa1fcd64c17a743b0ab858df5c10253ccdff4 | sskenner/spydersPrj | /c4c/executables/b4 oct17/html_to_text.py | 4,322 | 3.546875 | 4 | #!/usr/bin/env python3
""" This module has classes for converting HTML strings and files to plain text versions.
TODO:
- Is there any way to use io.StringIO instead of a temp file?
- this might help avoid the permision error.
"""
# import modules.
import codecs
import os
import subprocess
from bs4 ... |
9e10db07bd159f36235ff5b58654eba48d66a6f3 | manisha-jaiswal/iterator-and-generator-in-python | /OOPS18_iterator_genrator.py | 763 | 4.28125 | 4 | """
Iterable - __iter__() or __getitem__()
Iterator - __next__()
Iteration -
"""
def gen(n):
for i in range(n):
# return i - it returns the value true or false
yield i #yeh i ko yield krega ,
# yeild ek generator h jo on the fly value ko geneerate krega
g = gen(3)
print(g)
... |
12062275a053dfc8aa4f94c04e888c38f619684a | bryanwoods/BryanBurger | /BryanBurgerMain.py | 2,718 | 3.921875 | 4 | from bryan import *
from burger import *
class BryanBurgerMain:
"""The Main BryanBurger Class - This class handles the main
initialization and creating of the Game."""
def __init__(self, width=640, height=480):
"""Initialize"""
"""Initialize PyGame"""
pygame.init()
"""Set the window Size"""
... |
21fbc706321e771b06be18dd923943321d229bf0 | yinjiwenhou/python-notes | /generator/test.py | 1,062 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。
在Python中,这种一边循环一边计算的机制,称为生成器:generator。
第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator
定义generator的另一种方法。如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator:
"""
g = (x*x for x in range(1, 11))
print type(g)
for n in g:
print n
... |
8acda6ab0c3b8d2b347d3282b7b351d58324437e | MBailey019/hackerrank-solutions | /Sorting/Insertion Sort 1/solution.py | 572 | 3.96875 | 4 | #!/bin/python
import os
def insertionSort1(n, arr):
inserted = False
current_index = n-1
to_insert = arr[current_index]
while not inserted:
if current_index == 0 or arr[current_index-1] < to_insert:
arr[current_index] = to_insert
inserted = True
else:
... |
3aa4764c3a154cb9a2d890e887d9bd1ea3e48192 | devenkan/tictactoe | /tictactoe.py | 1,318 | 3.859375 | 4 | import random
import time
list=[0,1,2,3,4,5,6,7,8]
def check(c,p1,p2,p3):
if list[p1]==c and list[p2]==c and list[p3]==c:
return "win"
def check1(c):
if check(c,0,1,2)=="win":
return "win"
elif check(c,3,4,5)=="win":
return "win"
elif check(c,6,7,8)=="win":
return"win"
elif check(c,0,3,6)=="win":
... |
19ec6ec2efe04a2778d45e78b0b0fd69a7ee1c1f | chenjb04/doc | /Python并发编程/process_demo/pipe_process.py | 1,177 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
* @Author: chenjb
* @Date: 2020/10/16 14:29
* @Last Modified by: chenjb
* @Last Modified time: 2020/10/16 14:29
* @Desc: 管道交换数据
"""
import multiprocessing
def create_items(pipe):
output_pipe, _ = pipe
for item in range(10):
output_pipe.send(item)... |
e0e50c54dd300fc0c1a789f09a50e22505face3b | Cieo/PycharmProjects | /AILab5-LogicRegression/DT-temp.py | 6,452 | 3.671875 | 4 | import math
class Datacase:
def __init__(self, x=list(), y=0):
self.x = x
self.y = y
self.y_predict = -1
def __predict__(self, root):
# if we came to the leaf, set the result of this data_case
if root.result != -1:
self.y_predict = root.result
re... |
0e86a0a6f45d918dc6221d2d2e261ee7a67f33c0 | supremepoison/python | /Day06/Code/test_list.py | 586 | 3.6875 | 4 | # 练习:
# 1.写一个程序, 让用户输入很多个正整数,当输入负数时结束输入
# a.将用户输入的数存在于列表 L 中
# b.打印这个列表
# 如:
# 请输入:1
# 请输入:2
# 请输入:3
# 请输入:4
# 请输入:-1
# 打印:
# ... |
022368c60894ce329a406a295b683b04a77249b5 | supremepoison/python | /Day15/Code/test_try.py | 522 | 3.8125 | 4 |
# def get_score():
# a = int(input("Enter a number between 0 and 100:"))
# if not(0 <= a <= 100):
# return 0
# return a
# try:
# score = get_score()
# except ValueError:
# score = 0
# print("The numbr is ", score)
#函数内部加入try语句来进行错误处理
def get_score():
try:
a = int(input("Ente... |
c781d941c5b21e8476a0a3a22c58fca13c835d3f | supremepoison/python | /Day16/Code/test_yield.py | 931 | 4.21875 | 4 | # 写一个生成器函数 myeven(start, stop) 用来生成从 start 开始到stop 结束区间内的一些列偶数(不包含stop)
# 如:
# def myeven(start, stop):
# ...
# evens = list(myeven(10,20))
# print(evens) [10,12,14,16,18]
# for x in myeven(5,10):
# ... |
ed0eca695529347f291b2162a7eb78e6a6c40fca | supremepoison/python | /Day11/Code/test_global.py | 547 | 3.796875 | 4 | # 练习:
# 写一个函数hello,部分代码如下:
# count = 0
# def hello(name):
# print("您好",name)
# ...
# 当调用hello 函数时,全局变量count自动加1操作来记录hello被调用的次数
# 如:
# hello("To")
# hello("jerry")
# print("hello函数共被调用%d次" % count)
count = 0
def hello(name):
global co... |
4938b4db1f5af59844f74ac07e52c557f97caae6 | supremepoison/python | /Day11/Code/nonlocal.py | 584 | 3.5625 | 4 | # 此示例示意nonlocal的用法
# var = 100
# def f1():
# var = 200
# print('f1.var=',var)
# def f2():
# var = 300
# print('f2.var=',var)
# f2()
# print("f1.var=",var)
# f1()
# print("全局的var=",var)
var = 100
def f1():
var = 200
print('f1.var=',var)
def f2():
var = ... |
e74f8d41ff7930114700e43f352f0d15d4e0cd80 | supremepoison/python | /Day09/Code/set.py | 772 | 3.84375 | 4 | # 练习:
# 经理有: 曹操,刘备,孙权
# 技术员有: 曹操,孙权,张飞,关羽
# 用集合求:
# 1.是经理也是技术员的人有谁?
# 2.是经理,但不是技术员的人有谁?
# 3.是技术员,但不是经理的人有谁?
# 4.张飞是经理吗?
# 5.身兼一职的人有谁?
# 6.经理和技术员共有几个人?
# manager = {'曹操','刘备','孙权'}
# tech = {'曹操','孙权','张飞','关羽'}
# a = manag... |
1f9d3ac503a0dc1f0aa5ff074683f01f9df67400 | supremepoison/python | /Day19/Code/homework/student/main.py | 934 | 3.796875 | 4 | import show_menu
import student_info
def main():
L = []
while True:
#打印菜单
#show_menu()
show_menu.menu()
s = input('请选择:')
if s == '1':
L = student_info.input_student()
elif s == '2':
student_info.print_student(L)
... |
b4f55197b30c22fae100a76e8ad27f178bd05d8d | supremepoison/python | /Day12/Code/test_map.py | 410 | 3.796875 | 4 | def power2(x):
return x**2
# a =0
# for i in map(power2,range(1,10)):
# a +=i
# print(a)
# # ********************************************
# m = map(power2, range(1,10))
# print(sum(m))
#****************************
print(sum(map(lambda x:x**3,range(1,10))))
# b= 0
# for i in map(pow, range(1,10), ... |
c68080ca79281df3257d0967c281b10edf93fdfc | supremepoison/python | /Day11/Code/homework.py | 6,656 | 3.9375 | 4 | # # 练习:
# # # 1. 看懂下面的程序在作甚
# # def fx(f, x ,y):
# # print(f(x,y))
# # fx((lambda a,b: a+b), 100, 200)
# # fx((lambda a,b :a**b),3,4)
# # 2.给出一个整数n,写一个函数来计算
# # 1+2+3+4+...+n 的值并返回结果
# # 要求用函数来做
# # 如:
# # def mysum(n):
# # ... ... |
f7b28c1a0bed9581ae5b925335ab59ee88716c69 | supremepoison/python | /Day14/Code/homework/student/student_info.py | 2,589 | 3.734375 | 4 |
list = []
def max_min_score():
L = sorted(list, key = lambda d:d['score'], reverse = True)
print_student(L)
return L
def min_max_score():
L = sorted(list, key = lambda d:d['score'])
print_student(L)
return L
def max_min_age():
L = sorted(list, key = lambda d:d['age'], reverse = True)... |
f2b38059b7fec358b182b3a13e7eb8040cd03c93 | supremepoison/python | /Day16/Code/test_prime.py | 603 | 3.90625 | 4 | # 1.写一个生成器函数,给出开始值begin,和终止值end,此生成器函数生成begin-end 范文内全部素数,不包括end
# 如:
# def prime(begin, end):
# ....
# L = list(prime(10,20))
def prime(begin ,end):
for i in range(begin ,end):
prime = True
if begin < 2:
... |
56fbcb2fab276ccdc45ad2b812b10c9e9f5a6e66 | supremepoison/python | /Day20/Code/enclosure.py | 777 | 3.609375 | 4 |
class A:
def __init__(self):
self.__p1 = 100 #私有属性
print('self.__p1=', self.__p1)
def __m(self):
'''
这是私有方法,此方法只能用此类的方法来调用没不能在地方调用
'''
print('A.__m方法被调用')
def dowork(self):
'''
此方法可调用私有实例变量和私有实例方法
'''
self.__m()
... |
4cf3c5aa4052f8c375fe176cc99feda53152d63c | supremepoison/python | /Day11/Code/return_function.py | 243 | 3.609375 | 4 |
def get_fucntion():
s = input("请输入您要做的操作:")
if s =='求最大':
return max
if s =='求最小':
return min
if s =='求和':
return sum
L= [2,4,6,8,10]
f = get_fucntion()
print(f(L))
|
136bf3af64a40f8d4e404f7214621408690d6cd1 | supremepoison/python | /Day20/Code/mylist.py | 712 | 4 | 4 |
class MyList:
'''
创建一个自定义列表类,此MyList内部用列表来存储信息
'''
def __init__(self, iterable=()):
self.data = [x for x in iterable]
def __repr__(self):
return 'MyList(%s)' % self.data
def __len__(self):
'''
此方法必须返回整数
'''
# return len(self.data)
return... |
89a487a7073cfb2c326b93f4e0c9f544fe5ce54c | supremepoison/python | /Day06/Code/for.py | 744 | 3.75 | 4 |
# s = 'abcde'
# for ch in s :
# print("ch>>>>", ch)
# else:
# print("遍历字符串", s, '结束')
# 练习:
# 任意输入一段字符串
# 1)计算这个字符串的‘a’这个字符串的个数并打印出来
# 2)计算出空格的个数并打印出来
# (要求:用for语句实现,不允许使用S.count方法)
# a = input("请输入字符串:")
# i = 0
# for b in a:
# if b == 'a':
# i +=1
# p... |
16e9c44f152d9aee3e3adaa992e76347844e5542 | supremepoison/python | /Day13/Code/math.py | 385 | 4 | 4 | # 练习
# 1.输入一个圆的半径,打印出这个元的面积
# 2.输入一个元的面积,打印出这个圆的半径
# import math as m
# r = float(input("radius:"))
# area = m.pi * r **2
# print("area:",area)
# area2 = float(input("area:"))
# r2 = m.sqrt(area2/m.pi)
# print("radius", r2)
import math
s= 0
for i in range(1,21):
s += math.factorial(i)
print(s)
|
d9e98e9e793f04ed528d56ee8152f1ba541c1503 | mwangistan/bc-9-tdd | /super_sum_test.py | 794 | 3.71875 | 4 | import unittest
from super_sum import super_sum
class SuperSumTest(unittest.TestCase):
'''
Super sum tests
'''
def test_value_error(self):
#test if non supported types i.e dictionary, string
self.assertEqual(super_sum(10, 5, [6, 's']), "Type not supported")
def test_sum_of_integers(self):
#sum of numbers... |
b4347c97915b34a26f34e51bcd16179dc79bfd4a | MPechman/think_python | /think_python_12.py | 1,984 | 3.703125 | 4 | # Exercise 1
def sumall(*args):
ans = sum(args)
print ans
# sumall(1, 2, 3, 4)
# s = 'abc'
# t = [0, 1, 2]
# t = zip(s, t)
# print t
# for letter, number in t:
# print letter, number
# for index, element in enumerate('abc'):
# print index, element
# Exercise 2
def create_language():
t = []
fin = open('wor... |
187b890c9f32f9557477ee02f1e696f603631d83 | sdasaba/shellScript | /simple sh and python test/test2.py | 131 | 3.546875 | 4 | import pandas as pd
# csv読み込み
df =pd.read_csv("test2.csv",sep=",")
df.columns = ["datetime","id","value"]
print(df.tail()) |
edc4603918a7768c8f013577abb940b77ecde815 | autumnsehy/Python-portfolio | /Name and birthday.py | 146 | 4.03125 | 4 | name=input("enter your full name")
month=input("Birth month?")
day=input("day?")
year=input("year?")
print(name, "was born on", month, day, year)
|
ae6360e9a2800c30e1c6aaaf6465106fb1ce97a3 | clee9604/FINAL | /FINALc/copies/python/dog_class.py | 737 | 4.0625 | 4 | class Dog:
# Attribute - values that should belong to
# each dog type but each dog may have seperate valies
name = None
age = None
def bark(self):
print("Woof! Woof!")
def growl(self):
print("RrRrRrRrRrrrRrRr.....")
def setName(self, name):
self.name = name
def setAge(s... |
f28f7cadd2a425d0eaee08282c6129b5560f05a0 | wasade/Greengenes | /greengenes/chop_taxonomy.py | 1,625 | 3.609375 | 4 | #!/usr/bin/env python
"""chop the genus name from the species names"""
__author__ = "Daniel McDonald"
__copyright__ = "Copyright 2012, Greengenes"
__credits__ = ["Daniel McDonald"]
__license__ = "GPL"
__version__ = "0.1-dev"
__maintainer__ = "Daniel McDonald"
__email__ = "mcdonadt@colorado.edu"
__status__ = "Developm... |
e4914dad4ea69713ae9267ae646ce2a3958fa858 | wenliangz/Rosalind | /count_NT.py | 590 | 3.625 | 4 | #!/usr/bin/env python
DNA=open('/BootStrappers@Umass/Rosalind/rosalind_dna.txt')
seq=DNA.readlines()[0].strip()
print seq
# a=0
# c=0
# g=0
# t=0
# for X in DNA.readline():
# if X =='A':
# a=a+1
# if X =='C':
# c=c+1
# if X =='G':
# g=g+1
# if X =='T':
# t=t+1
# print a,c,g,t
class DNASequence(object):
d... |
65dd3e5a806e4b5448d8abd90612dda87ad9c890 | K8-91/homework-4.2 | /4.2_zad1.py | 567 | 3.875 | 4 | def palindrom_check(word):
word_normal=[]
word_backward=[]
for letter in word:
word_normal.append(letter)
word_backward.insert(-len(word),letter)
palindrom_result= bool(word_normal==word_backward)
return palindrom_result
print(palindrom_check('kot'))
print(palindrom_check('kajak'))... |
763b9f1d3591b71d8ff9ff1f72953bda23d7c8f2 | peterpfand/aufschrieb | /verduche.py | 60 | 3.546875 | 4 | list = [1, 2, 3]
for var in list:
print(var)
|
d9f32b00f9bcaec443b3fc22b1f239333bfb26a3 | peterpfand/aufschrieb | /higher lower.py | 413 | 4.65625 | 5 | string_name.lower() #to lower a string
.higher() #to higher a string
#example:
email = input("What is your email address?")
print(email)
final_email = email.lower()
print(final_email)
string_name.isLower() #to check if a string id written in lowercase letters
.ishigher() #to check... |
14c31d0f7fa24f48c9ad813b9cc7a96edb4f4445 | AlanCramer/manim | /alan2.py | 579 | 3.796875 | 4 |
# tutorial https://github.com/malhotra5/Manim-Tutorial#Running-Manim-Projects
# python3 -m manim alan2.py Shapes -pl
from big_ol_pile_of_manim_imports import *
class Shapes(Scene):
def construct(self):
######Code######
#Making shapes
circle = Circle()
square = Square()
tr... |
d6747215eb67db37d9f3f6233796464b28a8691f | raymondbutcher/django-apn-storage | /apn_storage/contrib/uid.py | 1,821 | 3.71875 | 4 | """
A tool for generating unique ID strings.
Uses a BSON Object ID for the underlying unique value generation.
See http://stackoverflow.com/a/5694803/2835599 for an explanation of "unique".
The class accepts an alphabet to use for the final string. This affects which
characters will be seen in the resulting UID strin... |
44b44b838cc8344547b8a0aea6f1913c7fdd1d89 | bboortz/programming_challenges | /anagram_detector/app.py | 351 | 3.890625 | 4 | #!/usr/bin/env python
import os, sys, math
def detect_anagram(input1, input2):
result = True
def prepare_input(text):
return sorted(''.join([char for char in text if char.isalpha()]).lower())
input1 = prepare_input(input1)
input2 = prepare_input(input2)
if input1 != input2:
re... |
da4035e95c67688efa36b1c03f8c2eca978bfa32 | ladm2110/proactive_forest | /proactive_forest/utils.py | 1,337 | 3.984375 | 4 | import numpy as np
def all_instances_same_class(x):
"""
Returns True only if all belongs to the same class, False otherwise.
>> all_instances_same_class(np.array([0, 0, 0, 0]))
True
>> all_instances_same_class(np.array([1, 0, 2, 0]))
False
:param x: <numpy array> An array with the class... |
0a5519dbc1485168aed53a9896d41e8bb97d553c | lichr3/leetcodeDaily | /20201202_MaximumDepthOfBinaryTree.py | 683 | 3.84375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root != None:
return 1 + max(self.maxDepth(root.lef... |
8c3125e03291d74e737d9381acfdbb3f2bcbc776 | afridig/SeleniumAutomation_Python | /tables.py | 1,142 | 3.65625 | 4 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver=webdriver.Firefox(executable_path="C:\Drivers\geckodriver-v0.27.0-win64\geckodriver.exe")
driver.get("https://techcanvass.com/examples/webtable.html") #opening the website where the webtable resides
tableRows=len(driver.find... |
29ff282d999dd57089bf7b7097d624860d430ddd | afridig/SeleniumAutomation_Python | /XLUtils.py | 1,018 | 3.59375 | 4 | import openpyxl
#this function will capture the number of rows present in the file
def getRowCount(file,sheetName):
workbook = openpyxl.load_workbook(file)
sheet = workbook.get_sheet_by_name(sheetName)
return(sheet.max_row)
#this function will capture the number of columns present in the file
def... |
a2e7fb158af9a15009e7a208e9983007451d2f5c | brouhahaha/programming_1 | /hw2/вариант7.py | 112 | 3.65625 | 4 | print ('Введите число')
n=int(input())
k=1
while k*2<=n:
k=k*2
print (k)
continue
|
b1949348675a5b55584328fc3d6219fbffe28a4d | ToniTSaari/Beginning | /pytty/backday.py | 616 | 3.828125 | 4 | import calendar, os
from time import gmtime, strftime
year = int( strftime ( '%Y', gmtime() ) )
month = int( strftime ( '%m', gmtime() ) )
date = int( strftime ( '%d', gmtime() ) )
day = calendar.weekday(year, month, date)
def backday():
if day == 0:
weekday = 'Maanantai'
elif day == 1:
... |
c8548d00f60aab5741c3c5a467848e3dbe718810 | Lykaos/AI-Task-Planning | /P22-P23/canvas.py | 4,117 | 3.78125 | 4 | # Map rendering
import sys
import pygame
import random
import math
import dijkstra
screen_size = 700
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
white = (255,255,255)
black = (0,0,0)
colors = []
# Transforms a list of points into an adapted list of points for the canvas
def transform_points(points, factor, o... |
ad26db5b5d0e3e5b8c73c190b88db85b16c8fa3c | sawaseemgit/AppsUsingDictionaries | /PollingApp.py | 1,596 | 4.21875 | 4 | print('Welcome to Yes/No polling App')
poll = {
'passwd': 'acc',
}
yes = 0
no = 0
issue = input('What is the Yes/No issue you will be voting on today: ').strip()
no_voters = int(input('What is number of voters you want to allow: '))
repeat = True
while repeat:
for i in range(no_voters):
fname = input(... |
22cdbb990dbb292b7c5460b72b2ca47b95a31fb9 | sujithvm/skynet | /code/approximate_vertex_cover.py | 1,826 | 3.609375 | 4 | __author__ = 'Archana V Menon, Sujith V'
def vertex_cover(G):
"""
Finds a 2-approximation for a minimal vertex cover of the specified
graph. The algorithm promises a cover that is at most double the size
of a minimal cover. The algorithm takes O(|E|) time.
http://en.wikipedia.org/wiki/Vertex_cove... |
a6e245735ec9ab462f2a07dfca05d903d0f6bbc4 | sujithvm/skynet | /code/fibonacci.py | 208 | 3.671875 | 4 | __author__ = 'Archana V Menon, Sujith V'
def fibonacci(N):
if N == 0 : return []
if N == 1 : return [0]
fib = [0, 1]
for i in range(2, N):
fib.append(fib[i - 1] + fib[i - 2])
return fib
|
ea29cde788e8fb55680506dc490b3d7a004a0bb9 | sheauyu/sapy | /src/exercise_solutions/S9_voice.py | 1,173 | 3.703125 | 4 | """ Solution Exercise 'Your voice', Chapter 'Spectral Analysis'
This example should be done with your own voice.
To show how to proceed, I use the sound in 'vowels.wav'.
"""
# author: Thomas Haslwanter
# date: April-2021
# Import the required packages
import numpy as np
from numpy import random
import matplotl... |
375fe7ff8530e6d56ea7ee9f2a98923e62e079b2 | sheauyu/sapy | /src/exercise_solutions/S3_data_gen.py | 5,037 | 3.890625 | 4 | """ Generation of data for Chapter 'Data Input'
It shows how to generate
- formatted text-strings
- CSV files -> 'data.csv'
- otherwise formmated TXT-files -> 'data_tab.txt', 'data_modified.txt'
- Excel files -> 'data.xls'
- Matlab files -> 'data.mat'
... |
c059e1ac36b4c258cf32368b0516702a71a33d14 | sheauyu/sapy | /src/exercise_solutions/S7_simple_stats.py | 3,377 | 3.984375 | 4 | """ Solution Exercises Chapter 'Statistics' """
# author: Thomas Haslwanter
# date: April-2021
# Import the required packages
import numpy as np
from numpy import random
import matplotlib.pyplot as plt
from scipy import stats
from typing import Tuple
def generate_and_analyze() -> Tuple:
"""T... |
107c92b6e7892c187b9d6d01bd7dc1f91defe983 | sheauyu/sapy | /src/figures/F5_filter_characteristics.py | 5,834 | 3.609375 | 4 | """ Shows how filters can be characterized. """
# author: Thomas Haslwanter
# date: April-2021
# Import the required packages
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
from typing import Tuple
def impulse_response(a, b, ax) -> None:
"""Show the impulse respon... |
b17d1720a65b3035b611919f8d8b02b3504d0eb0 | C-TAM-TC1028-003-2113/tarea-1-GBecky20 | /assignments/18CuentaBancaria/src/exercise.py | 437 | 3.828125 | 4 | def main():
# escribe tu código abajo de esta línea
anterior = float(input("Dame el saldo del mes anterior: "))
ingresos = float(input("Dame los ingresos: "))
egresos = float(input("Dame los egresos: "))
cheques = int(input("Dame el numero de cheques: "))
total = (anterior + ingresos - egresos ... |
75e69f37401a483ecb421f940d816f2a793b7cf7 | MukungaV/Python-class | /Classes.py | 4,340 | 4.15625 | 4 | class MyClass: #name of class starts with capital letter s unlike in functions
x = "John" #John is an attribute- variable in a class
y= 12
theList = [22,34,54,78,90]
#Objest creation
c1 = MyClass()
#c1 = object/instance of the MyClass blueprint/clase
c2 = MyClass() #c2 = second object/instanc... |
0874c5cb13efdc095d5ea416095425a759ddf5ae | MukungaV/Python-class | /Lesson7lists.py | 2,941 | 4 | 4 | #scores list
scores=[45,67,87,98,53,42,23,43,2,54,65]
scores.sort()
for mark in scores:
if mark%2!=0:
print(mark,"Yes!")
else:
print(mark, "No!")
if mark>=80:
print(mark,"A")
if mark>=80:
print(mark,"A")
elif mark>=65:
print(mark,"B")
elif mark>=50:
prin... |
935e9637f23383ed84efc1acee4194f8c9dac8be | MukungaV/Python-class | /Assignment 3.py | 507 | 4 | 4 |
# for value in range (1,100):
# if value%2==0 and value%3==0:
# print(value,"Kenya")
#
# elif value%3==0:
# print(value,"Nairobi")
#
# elif value%2==0:
# print(value,"Muchiri")
#
# else:
# print("Samsung")
value=1
while value<=100:
if value%2==0 and value%3==0:
... |
b26e61572e4c0a7dbc3d3f79b5ecd2f30aa53a24 | kudoyoshihiro10xx/12_functions | /sample05.py | 418 | 3.96875 | 4 | # 2分課題: 2つの整数の和を返す関数addを作る
def add(a: int, b: int) -> int:
return a + b
# 2分課題: 2つの整数の差を返す関数を作る
def sub(a: int, b: int) -> int:
return a - b
# if以下のみsample05でtureなので表示される。その他ではfaluseになる
if __name__ == "__main__":
y1 = add(a=3, b=4)
print(y1)
y1 = sub(a=3, b=4)
print(y1)
|
c4917513fe0b670d5d22707540ca7f6f6a07db25 | danielanghell/CIM | /Testing.py | 9,221 | 3.609375 | 4 | import unittest
import Complex
import Methods
import math
import random
import os
class MyTestCase(unittest.TestCase):
#RIGHT principle
def test_sum(self):
self.assertEqual(Methods.sum(6, 11), 17)
def test_diff(self):
self.assertEqual(Methods.difference(10, 6), 4)
def test_remainder(... |
71607c32045bbf9e59ec56eae4ae7d3a934b9fbe | TeodorStefanPintea/Sentiment-mining-of-the-bioinformatics-literature | /words_visualisation.py | 7,266 | 3.5625 | 4 | '''
This program is used to create visual representations of the collected data.
'''
import pandas as pd
from nltk.corpus import words
englsish_words = set(words.words()) #englishwords
sentimental_medical_terms = pd.read_csv("sentimental_medical_terms")
print(sentimental_medical_terms.columns)
sentimental_medica... |
99a2a83c7059b61e14c054e650e4bb1c221047cd | iroro1/PRACTICAL-PYTHON | /PRACTICAL-PYTHON/09 Guessing Game One.py | 699 | 4.25 | 4 | # Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.
import random
numGuess= 0
a = random.randint(1,9)
end= 1
while (end != 0) or (end != 0):
guess = input('Guess a number : ')
guess = int(gues... |
f033cc8e82f2692f55b1531159229168fdb638b9 | iroro1/PRACTICAL-PYTHON | /PRACTICAL-PYTHON/12 List Ends.py | 293 | 4.125 | 4 | # Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list.
def rand():
import random
return random.sample(range(5, 25), 5)
a= rand()
print(a)
newList = [a[0],a[-1]]
print(newList) |
82e7bd95f7a980f9e3646f3facf96270482f8048 | enfageorge/delimiters.citizenFirst.nlp | /backendScripting/userDetail.py | 816 | 3.703125 | 4 | import csv, ast
class User(object):
"""userName is assumed to be a unique identifier for each user. Can be improved later with numeric IDs
userCauses is a list of strings that contains the causes the user identifies with. Limited to just 5 ideally
Further modifications include editing topics, deleting users etc ""... |
f5ae7a1a1381477ef994bf17f524103c4cbaef08 | lynn-study/python | /num.py | 479 | 3.890625 | 4 | #!/usr/bin/python
# Right in Left not in
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9 ,10]
print numbers[3:6]
print numbers[0:1]
print
print numbers[-3:]
print numbers[:3]
print
print numbers[:]
print
print numbers[0:10:2]
print
print numbers[::4]
print
print numbers[7:0:-1]
print
print numbers[10:0:-2]
print
p... |
63f22070edd727c7652ae1c6c930a3443d95710b | lynn-study/python | /seq_op.py | 1,249 | 4.125 | 4 | #!/usr/bin/python
x = [1, 2, 3]
print x
print
x[1] = 4
print x
print
del x[1]
print x
print
name = list('perl')
print name
name[2:] = list('ar')
print name
name_1 = list('perl')
print name_1
name_1[1:] = list('ython')
print name_1
print
numbers = [1, 5]
print numbers
numbers[1:1] = [2, 3, 4]
print number... |
10f62704e249e73a2d76053c6c4d9f1f96b5f761 | HaydenRobert/Projects | /prac_07/guitars.py | 309 | 3.78125 | 4 | """"""
from prac_07.playing_guitar import Guitar
def main():
""""""
print("My guitars!")
name = input("Name: ")
year = int(input("Year: "))
cost = int(input("Cost: $"))
first = Guitar(name, year, cost)
print("{} ({}) : {}".format(first.name, first.year, first.cost))
main()
|
9ea8b267b30c825c1b18846b28ba082a3605cb99 | Kcedrone/advent_of_code_2020 | /problem02.py | 1,601 | 3.609375 | 4 | import parse
import re
with open('problem02_input.txt', 'r') as f:
lines = f.readlines()
# Part one
valid_count = 0
entry_format = "{}-{} {}: {}"
for line in lines:
# Ugh, I wish I was better at regex...
parsed = parse.parse(entry_format, line.strip())
min_count = int(parsed[0])
max_count = int(parsed[1])
lett... |
dade41e98804e0ac58c1101f1d8308b0617d36c6 | Arghyasen08/Machine-learning | /ASSGN6.py | 1,911 | 3.828125 | 4 | #Q.1 - Download the weather dataset
'''
a.) Plot atleast 20 visualization for the same dataset with different data points.
Ensure that the type of visualization is appropriate and follows this chart.
'''
#importing the required libraries
import matplotlib.pyplot as plt
import seaborn as sn
import pandas as pd
... |
69fcac08739e80b6e744295ba65fbf16d5d0f13a | RPodemski/SMU_Classwork_2020 | /03-Python/Instructions/Submissions/pypoll.py | 1,372 | 3.578125 | 4 | import csv
pollingInfo = r"Resources\election_data.csv"
candidateD = {}
votes = 0
with open (pollingInfo,"r") as csvfile:
pollingRead = csv.reader(csvfile, delimiter=',')
pollingHeader = next(pollingRead)
#print(f"pollingHeader: {pollingHeader}")
#total number of votes
for row in pollingRead:
... |
0ee69f03199af3e1ec75cb771f932633bb3c8937 | spyq1992/Face_Recogntion | /test.py | 2,575 | 3.671875 | 4 | import csv
import datetime
import sqlite3
import time
# 1. 创建文件对象
# f = open('D:\\a.csv', 'w', newline='', encoding='utf-8')
#
# # 2. 基于文件对象构建 csv写入对象
# csv_writer = csv.writer(f)
#
# # 3. 构建列表头
# csv_writer.writerow(["工号", "姓名", "打卡时间"])
#
# # 4. 写入csv文件内容
# csv_writer.writerow(["1", 'king', '2021-03-10 09:13:43'])
# ... |
307ba023b4fd27b23772a24191b7ab27e1b8d1ce | carlshan/puzzles | /wolf_sheep/brute_force.py | 4,849 | 4.125 | 4 | """
Puzzle:
Find an arrangement on a 5x5 board where you can put 5 queens and have at least
3 spots that are not under attack by a queen.
This solution is a brute force method of finding the position of the board that
satisfies the above conditions.
"""
import numpy as np
import random
def is_empty(pos, board):
... |
d872533f1f0e28e1b8c772c2e6dd8261135ec43f | carlshan/puzzles | /advent_of_code/2021/day8/day8.py | 5,823 | 4.03125 | 4 | """
Advent of Code
Author: Carl Shan
Day 8
"""
aoc_input = open("day8.in", "r").readlines()
CORRECT_WIRING = {'abcefg': '0',
'cf': '1',
'acdeg': '2',
'acdfg': '3',
'bcdf': '4',
'abdfg': '5',
'abdefg': '6',
'acf': '7',
'abcdefg': '8',
'abcdfg': '9'
}
def count_num_1478(line):
output_values = line.strip(... |
e733eed205ea04d92bf1011989a662ae7d0abd51 | carlshan/puzzles | /advent_of_code/2021/day1/day1.py | 958 | 4.0625 | 4 | """
Advent of Code 2021
Author: Carl Shan
Day 1
Problem: Count the number of times a depth measurement increases from the previous measurement. (There is no measurement before the first measurement.)
"""
day1input = open("day1.in", "r")
data = list(map(int, day1input.readlines()))
test_data = [
199,
200,
... |
0d9ea07b48a503a0577a556a709698f87642df32 | carlshan/puzzles | /advent_of_code/2021/day17/day17.py | 3,537 | 4.0625 | 4 | """
Advent of Code 2021
Author: Carl Shan
Day 17: Trick Shot
"""
data = open('day17.in', 'r').read().strip()
x_start, x_stop = data.split(': ')[1].split(', ')[0].split('x=')[1].split('..')
y_start, y_stop = data.split(': ')[1].split(', ')[1].split('y=')[1].split('..')
x_start = int(x_start)
x_stop = int(x_stop)
y_sta... |
e1d905a34f55a70206d9e6adc8d66f9121de74d0 | carlshan/puzzles | /advent_of_code/2021/day9/day9.py | 3,501 | 4.375 | 4 | """
Advent of Code 2021
Author: Carl Shan
Day 9
Goal: Find the 'low points' in a grid.
A 'low point' is a point in the grid that is surrounded by points that are lower
than it.
Diagonals do not count as adjacent.
"""
with open('day9.in') as f:
data = f.read().splitlines()
def get_neighbors(x, y):
"""
Re... |
b7f9596b12f47a7c6b6805a533342c9b6155b593 | timo-bronseth/timos-neat-little-sudoku-solver | /src/main.py | 28,365 | 3.75 | 4 | # -------------------------------------------------------------------------------------
# The goal I had in mind for this code was to minimise the need for brute force search.
# For that, I use two main algorithms:
# 1) "possibility_eliminator()" for solving almost all determinate puzzles quickly,
# 2) and brute ... |
cbc4448bb252bae1350dc79d189000de9b6ab5d0 | 44858/selection | /selection exercise 1.py | 237 | 3.8125 | 4 | #Lewis Travers
#26/09/2014
#Selection exercise 1
number1 = int(input("Please enter your first number: "))
number2 = int(input("Please enter your second number: "))
if number1 == number2:
print("Those numbers are the same")
|
2d48794787c2cbb34f355e4abd130bf2ec8ffb28 | marcosvpj/The-Nature-of-Code | /chapter-1/walker/Walker.py | 310 | 3.5625 | 4 | from abc import abstractmethod, ABCMeta
class Walker(metaclass=ABCMeta):
def __init__(self, coord):
self.x = coord[0]
self.y = coord[1]
def position(self):
return self.x, self.y
def update(self):
self.step()
@abstractmethod
def step(self):
pass
|
aa9d7a2c261c7a3760735f4e2a2b67bad657a1a6 | Wilson-Wu1/AlphaZeroTicTacToe | /a3.py | 18,916 | 3.5625 | 4 | #a3.py
#Wilson Wu
#301350197
# -----------------------------------------------------------------------------------------------------------------------------------
# Pure MCTS is a greedy algorithm, choosing the optimal solution at a given state.
#
# Due to the random nature of random playouts, a 100% guranatee... |
6ad663e24007cbf743411b9389d75205cc201152 | mattdelblanc/Mypythonscripts | /iflelse.py | 278 | 4.21875 | 4 | number = 15
if number % 2 == 0:
print ('Number is divisible by 2')
elif number % 3 == 0:
print('Number is divisible by 3')
elif number % 4 == 0:
print('Number is divisible by 4')
elif number % 5 == 0:
print('Number is divisible by 5')
|
1972fc4c6f7e307acfa496ab9cde6a56410a10c7 | mattdelblanc/Mypythonscripts | /nestedloops.py | 359 | 4.4375 | 4 | number = 45
if number % 2 == 0:
print('Number is even number')
if number % 3 == 0:
print('number is also divisible by 3')
else:
print('number is not divisible by 3')
else:
print('Number is odd number')
if number % 5 == 0:
print('number is divisible by 5')
else:
print('number ... |
7ef746c4e1ce8c80919f9d912bc23edaa376e2de | mattdelblanc/Mypythonscripts | /while.py | 153 | 3.796875 | 4 | line = '*'
max_length = 10
while len(line) <= max_length:
print(line)
line += '*'
while len(line) > 0:
print(line)
line = line[:-1] |
1a1552ad9a5bd770ad36821b3cd549f27c29dd14 | OwenFeik/roguelike | /map_objects/room.py | 4,932 | 3.640625 | 4 | from random import randint
class Room:
def __init__(self,x,y,width,height):
self.x=x
self.y=y
self.width=width
self.height=height
self.grid=[['ground' for x in range(0,self.width)] for y in range(0,self.height)]
if randint(0,2):
self.grid=make_obstacle_ro... |
06505e2f31d63492dc934b9d2eba7a40ac4c89e3 | OwenFeik/roguelike | /randomutils.py | 584 | 3.53125 | 4 | from random import randint
def from_dungeon_floor(table,floor):
for (value,level) in reversed(table):
if floor >= level:
return value
return 0
def random_choice_index(chances):
random_chance=randint(1,sum(chances))
running_sum=0
choice=0
for w in chances:
run... |
a25fba2603e9632a90dc18a1a01f772bce2cace2 | Yuhta28/TestPJ | /Sets_in_Python.py | 653 | 4.25 | 4 | # Set example
x = set(["Posted", "Radio", "Telegram", "Radio"]) # A set may not contain the same element multiple times.
print(x)
# Set Method
# Clear elements
y = set(["Posted", "Rao", "Teram", "Rdio"])
y.clear()
print(y)
# Add elements
z = set(["Posted", "Rao", "Teram", "Rdio"])
z.add("AAQWER")
print(z)
# Remove el... |
a186fe5f3f8b658705509fbf443dc7fcb7605db5 | Ghoochannej/Python-Projects | /calculadora/calc.py | 550 | 4.125 | 4 | from funcoes import soma, subtracao, divisao, multiplicacao
if __name__ == '__main__':
valor01 = float(input('Digite o primeiro valor '))
valor02 = float(input('Digite o segundo valor '))
operacao = input('Digite a operação ')
if operacao == '+':
resultado = soma(valor01, valor02)
elif operacao == '-':
res... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.