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 |
|---|---|---|---|---|---|---|
fd04ccf9ff99d03411e91becbc5511334dd5b164 | nitianabhigyan/My-experiments-with-turtle | /Letters/h_letter.py | 864 | 3.84375 | 4 | import turtle
pen = turtle.Turtle()
pen.clear()
pen.color("#d2d2d2")
turtle.setup(.95,.8)
print("CLick to kill")
"""
Goal: Exploit the symmetry.
1. Vertical symettry in "H"
"""
def draw_half(base=200,side = 90):
pen.forward(base)
pen.right(side)
pen.forward(int(base/10))
pen.right(side)
pen.f... |
7f9a4d22f1ea31143cd3c042ccb5df97887f0b24 | thetimed/Maximising-value-given-constraint-for-list | /p1q3.py | 1,348 | 3.609375 | 4 | # Name: <TODO: replace with your name>
# Section: <TODO: replace with your section>
# p1q3
# All statements should only be in functions. Do not include statements outside functions in this file.
# You may insert additional helper functions into this file if desired.
# We need to max V, How do we max V???
# ... |
628955d3bf057e53acb031832b4d26066cc9034e | rjbohn/PythonSnippets | /Files-and-IO/print_encoding_problems.py | 275 | 3.53125 | 4 | for codec in ['latin_1', 'utf_8', 'utf_16','ascii']:
print(codec, 'Łószczykięwicz'.encode(codec,errors='ignore'), sep='\t')
print('Łószcz')
import codecs
f = codecs.open('myutf8file.txt','r', encoding='utf-8',errors='ignore')
file=f.read() |
4016cb4b2816199a772a02e9a7522ff7fadff619 | Readypompan20/isat252s20_03 | /fizzbuzz.py | 350 | 3.984375 | 4 | for fizzbuzz in range (0,101):
if (fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0):
print ("fizzbuzz")
continue
elif(fizzbuzz % 3== 0 and fizzbuzz % 5 != 0):
print("fizz")
continue
elif(fizzbuzz % 5 == 0 and fizzbuzz % 3 != 0):
print("buzz")
continue
... |
0124b0f309c33c571552a59bebd8ff52d7c1eeb4 | ShruthiAnand30/Class98 | /file1.py | 268 | 4.09375 | 4 | def wordCount():
fileName = input("Enter the file name ")
file = open(fileName)
noWords = 0
for line in file:
words = line.split()
noWords = noWords + len(words)
print("number of words ")
print(noWords)
wordCount() |
12277858c990302740f476a9812d1914b2400c2e | thej123/CodingDojo-Python | /OOP/car.py | 961 | 3.890625 | 4 | class Car(object):
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if (self.price > 10000):
self.tax = 0.15
else:
self.tax = 0.12
self.display_all()
d... |
232ab821e41d0a96d5b85faef64d41fb1b40c1df | thej123/CodingDojo-Python | /Basic Python/findCharacters.py | 520 | 3.953125 | 4 | word_list = ['hollo','world','my','name','is','Anna']
char = 'o'
def findCaracters(li,character):
new_list = [] #intitalize an empty list
for count in li: #goes thorugh every word
if character in count: #checks if any letter matches the 'charact... |
c61f5c5bd1a72e7053d46c6fe438facc717bce2d | thej123/CodingDojo-Python | /OOP/product.py | 1,477 | 3.78125 | 4 | class Product(object):
def __init__(self, price, item_name, weight, brand, cost):
self.price = price
self.item_name = item_name
self.weight = weight
self.brand = brand
self.cost = cost
self.tax = 0.12
self.status = "for sale"
def sell(self):
self... |
7335a8367c1143d935288dadce535c23e6f0c1e5 | thej123/CodingDojo-Python | /Basic Python/tuples.py | 358 | 3.859375 | 4 | my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
def tuples(x):
newlist = []
newlist_two = []
for key in x.keys():
newlist.append(key)
for count in x.values():
newlist_two.append(count)
newlist_three = zip(newlist, newlist_two)
... |
bb691a996cfe72d61ca004dd5acac7d763cdfa6c | thej123/CodingDojo-Python | /Basic Python/typeList.py | 1,337 | 4.03125 | 4 | l1 = ['magical unicorns',19,'hello',98.98,'world']
l2 = [2,3,1,7,4,12]
l3 = ['magical','unicorns']
def typeList(val): #Function typeList
strOutput = "" # intializing 2 variable to keep count and adding strings.
intOutput = 0
for count in val: # go th... |
979f16dbf00d504ef4c417b445bf0d0d1fbf957e | eminde/sudoku | /simple_sudoku_solver.py | 1,569 | 3.5625 | 4 | """
http://freepythontips.wordpress.com/2013/09/01/sudoku-solver-in-python/
"""
class MyException(Exception):
pass
import sys
def same_row(i,j): return (i/9 == j/9)
def same_col(i,j): return (i-j) % 9 == 0
def same_block(i,j): return (i/27 == j/27 and i%9/3 == j%9/3)
def r(a):
i = a.find('0')
if i == -1:
... |
e38197efcd64d6ad928d207bf789273cb0a6fb08 | cr8ivecodesmith/basic-programming-with-python | /lpthw/ex11.py | 756 | 4.25 | 4 | # Exercise 11: Asking questions
print('How old are you?', end=' ')
age = input()
print('How tall are you?', end=' ')
height = input()
print('How much do you weigh?', end=' ')
weight = input()
print("So you're %r old, %r tall and %r heavy." % (age, height, weight))
# Note
# Notice that we put an end=' ' after the str... |
36ee8b976d639081d56657e81c3dc1880fe5c5c1 | cr8ivecodesmith/basic-programming-with-python | /lpthw/ex13.py | 728 | 4 | 4 | # Exercise 13: Parameters, Unpacking, Variables
from sys import argv
script, first, second, third = argv
print('The script is called:', script)
print('Your first variable is:', first)
print('Your second variable is:', second)
print('Your third variable is:', third)
# Study Drills
# 1. Try giving fewer that three a... |
ab5116fcca80310d98e4dd640fed9bef25100f3b | hchung1/pycrypto | /cipher.py | 1,926 | 3.6875 | 4 | # Nick attempted to aid in fixing the main problem
# Medina help solved the creation of blank pages by seperating the two open statements
# Main code is from tutorial
from Crypto.Cipher import ARC4 #from tutorial
msg = raw_input("Input a series of numbers for a key. Otherwise, default key. >> ")
try: #If the input... |
9f55828f9488fc21410cbf60f6948f171c3f695b | stummalapally/Week2 | /factor.py | 235 | 3.984375 | 4 | #%-modulo
#print the remainder for dividing each integer frm 0 to 10 by 3
# 0%3=0
#1%3=1
#2%3=2
#3%3=0
#4%3=1
#for
#range
#%
divisor = 4
for number in range(0,11):
print(str(number)+ "%"+str(divisor)+ "=" +str(number%divisor))
|
00c3ff8a607f398f527108ae7451dd955b97fbad | ZsNagy89/Python | /PE_01_LAB_Day_of_the_year.py | 1,379 | 3.6875 | 4 | def day_of_year(year,month,day):
months=range(month)
for i in range(month):
days_vector=[]
if year%4==0: #maybe Leap year
if year%100==0 and year%400!=0: #not a leap year
if months[i] in x:
if months... |
e87fedf114da997b04e19d043dd569fbc4831f00 | ZsNagy89/Python | /PE_02_LAB_Digit_of_Life.py | 236 | 3.640625 | 4 | date=input('Please, write your birthday:')
lst=list(date)
suma=0
for i in range(len(lst)):
suma+=int(lst[i])
if len(str(suma))>=2:
suma2=list(str(suma))
suma_f=int(suma2[0])+int(suma2[-1])
print(suma_f)
|
fbfe72c2a1f0007aa66454e39ca7f2134c09ce8a | maximkavm/algorithms-and-data-structures | /part-2/01-Class-Recirsia/class_1.py | 518 | 3.546875 | 4 | import random
class Animal():
count = 0
def __init__(self, h = 10):
self.height = h
self.__class__.count += 1
def __repr__(self):
return "Мой рост = {}".format(self.height)
@staticmethod
def get_cout():
return "Общее кол-во живых = %3d" % Animal.count
lst... |
c370411e8e44200ec67fd07de7c6353c4cae00e3 | maximkavm/algorithms-and-data-structures | /part-2/04-Pareto/2-Pareto-tkinter/pareto-0.py | 227 | 3.53125 | 4 | import tkinter as tk
from init import *
window = tk.Tk()
canvas = tk.Canvas(window, width=w, height=h, bg='#fda')
canvas.pack()
canvas.create_line(x0, y0, xm, y0, fill="#000", arrow=tk.LAST, dash=(6, 2))
window.mainloop()
|
4a38625e22a946c51ec06587feb668169df6cd97 | maximkavm/algorithms-and-data-structures | /part-2/04-Pareto/3-CSV-reader/example-3.py | 284 | 3.546875 | 4 | import csv
# второй способ - через словарь
name_file = 'smartphones.csv'
with open(name_file) as file:
reader = csv.DictReader(file, delimiter=';')
for dct in reader:
# print(dct)
print(dct['name'], dct['power'], dct['price'])
|
641d1661abae825b056537e84253182330bf1730 | ajaxj/pyweb | /sqlalchemydemo/th1.py | 3,406 | 3.765625 | 4 | # -*- coding:utf-8 -*-
# 最简单的线程调用
'''
import threading
import datetime
class ThreadClass(threading.Thread):
def run(self):
now = datetime.datetime.now()
print "%s says Hello at time: %s" %(self.getName(),now)
for i in range(2):
t = ThreadClass()
t.start()
'''
#不用线程
'''
import urllib2
... |
1093c84c2d8ba03ab50792b0d1ef01c45a94001b | rudbog011/Python_07 | /work_7_8.py | 486 | 4.03125 | 4 | print('Введите количество натуральных чисел n ≥ 2:')
n = int(input())
if n < 2:
print('Неверное число')
else:
print('Введите', n, 'чисел:')
n_max = int(input())
n_min = n_max
for i in range(n - 1):
n = int(input())
if n > n_max:
n_max = n
elif n < n_min:
... |
05a7167fa47f59bf9598cfad7f9f46f73b72c897 | QiaoRuoZhuo/PythonCode | /数据结构/模拟算法/蛇形矩阵2.py | 1,512 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 4 22:16:52 2019
@author: Administrator
描述:输出p行q列的蛇形矩阵。
函数名:serpentine_matrix(p, q)
参数表:p--总行数;
q--总列数
返回值:无返回值,按要求输出蛇形矩阵。
示例1:p, q = 6, 5时,输出:
1 12 13 24 25
2 11 14 23 26
3 10 15 22 27
4 9 16 21 28
... |
f1efee98d0d375d726a7143be51cedc20c5931d0 | QiaoRuoZhuo/PythonCode | /数据结构/数组基本操作/数组基本操作之插入排序.py | 2,755 | 3.953125 | 4 | #!/usr/bin/python3
# 文件名: 数组基本操作之插入排序
# 作者:巧若拙
# 时间:2018-12-17
'''
例题1.使用插入排序算法对列表a排序。
函数名:bubble_sort(a, reverse=False)
参数表:a -- 待排序列表。
reverse -- 排序规则,reverse=True,降序;reverse=False,升序(默认)。
返回值:该方法没有返回值,但是会对列表的对象进行排序。
'''
def insert_sort(a, reverse=False):
if reverse:
exp = 'j >= 0 a... |
14961f8de7168d2d595453971330e615d1c6fb7b | MatthewDuggan/cp1404practicals | /prac_02/write_name.py | 138 | 3.625 | 4 | OUTPUT_FILE = "name_output"
out_file = open(OUTPUT_FILE,'w')
name = input("Enter your name:")
print(name, file=out_file)
out_file.close()
|
75c85cb2ab827ef76e15e61855963f33610f7794 | gitsuke/autopy_s10 | /day1/dict_test.py | 340 | 3.59375 | 4 | # -*- coding:utf-8 -*-
data = {'name':'alex',
'age':18,
'job':'CEO',
'salary':5555}
print '1.', data
data['info'] = 'beijing'
print '2.', data
del data['job']
print '3.',data
for key in data:
print key,data[key]
print '4.',data.get('job')
for key,val in data.items():
print key,val
print... |
3a3cbe79c2d5fc5af87d1a8d85bf736182cc0e17 | gitsuke/autopy_s10 | /day2/ex1.py | 139 | 3.8125 | 4 | # -*- coding:utf-8 -*-
name = '老男孩Python'
print name
print len(name)
name2 = u'老男孩Python'
print 'unicode -->', len(name2) |
a221c12ef96033cbf073b1d0b046e50b28093528 | mzminhaz5683/URI-Online-Judge_Python-3 | /1035 - Selection Test 1.py | 223 | 3.6875 | 4 | list = input().split(" ")
A, B, C, D = int(list[0]), int(list[1]), int(list[2]), int(list[3])
if B>C and D>A and (C+D)>(A+B) and C>=0 and D>=0 and A%2==0:
print("Valores aceitos")
else:
print("Valores nao aceitos") |
0a06ce78ba0d1740816113c0226f39a9c208a506 | mzminhaz5683/URI-Online-Judge_Python-3 | /1010 - Simple Calculate.py | 400 | 3.6875 | 4 | # -*- coding: utf-8 -*-
'''
Escreva a sua solução aqui
Code your solution here
Escriba su solución aquí
'''
take1 = raw_input().split(' ')
take2 = raw_input().split(' ')
code1, unit1, price1 = int(take1[0]), int(take1[1]), float(take1[2])
code2, unit2, price2 = int(take2[0]), int(take2[1]), float(take2[2])
t1 = unit1... |
d6665bc508f6029faca72ae84625475401700379 | mzminhaz5683/URI-Online-Judge_Python-3 | /1158 - Sum of Consecutive Odd Numbers III.py | 212 | 3.53125 | 4 | x = int(input())
for i in range(0, x):
x, y = list(int(i) for i in input().split(" "))
sum = i = 0
while i<y:
if x%2 != 0:
sum += x
i += 1
x += 1
print(sum) |
04853e3853e11525a4cf6810c3aac88082e347b9 | mzminhaz5683/URI-Online-Judge_Python-3 | /1064 - Positives and Average.py | 233 | 3.65625 | 4 | list = []
for i in range(0, 6):
list.append(float(input()))
counter = sum = 0
for i in list:
if (0 <= i):
sum += i
counter += 1
print("{0} valores positivos\n{1:.1f}".format(counter, round(sum/counter, 1))) |
8b86260f77309b11ae1d28c0aee1211f84f36fb0 | mzminhaz5683/URI-Online-Judge_Python-3 | /1008 - Salary.py | 111 | 3.515625 | 4 | a = int(input())
b = int(input())
c = float(input())
print("NUMBER = {0}\nSALARY = U$ {1:.2f}".format(a, b*c)) |
55314f2b32cb6056ad8dc577e0a51f976776e6c4 | mzminhaz5683/URI-Online-Judge_Python-3 | /1070 - Six Odd Numbers.py | 115 | 3.625 | 4 | x = int(input())
counter = 0
while counter < 6:
if (x%2 != 0):
print(x)
counter += 1
x += 1 |
66ea63a830f41978f0785c5c8a25f531fb6fd7e9 | mzminhaz5683/URI-Online-Judge_Python-3 | /1072 - Interval 2.py | 186 | 3.5625 | 4 | N = int(input())
cIn = cOut =0
for i in range(0, N):
X = int(input())
if (10 <= X <= 20):
cIn += 1
else:
cOut += 1
print("{} in\n{} out".format(cIn, cOut)) |
3dd2d44260364f758f6c767c8f6c8424f33077b0 | onkcharkupalli1051/pyprograms | /ds_nptel/filehandling_write.py | 234 | 3.65625 | 4 | fh = open("new.txt","w")
fh.write("This is new line\n")
fh.write("this is second line\n")
l = "hi how are you"
fh.writelines(l)
fh.close()
fh = open("new.txt","r")
for i in fh.readlines():
i = i.rstrip()
print(i)
fh.flush() |
637c98c17ed65d72a4538fb19958ed10198a017b | onkcharkupalli1051/pyprograms | /ds_nptel/test 2/5.py | 676 | 4.28125 | 4 | """
A positive integer n is a sum of three squares if n = i2 + j2 + k2 for integers i,j,k such that i ≥ 1, j ≥ 1 and k ≥ 1. For instance, 29 is a sum of three squares because 10 = 22 + 32 + 42, and so is 6 (12 + 12 + 22). On the other hand, 16 and 20 are not sums of three squares.
Write a Python function sumof3squares... |
62d34f53a47d2e6eebf2207456076b5a825f6522 | onkcharkupalli1051/pyprograms | /ds_nptel/test 2/8.py | 1,212 | 4 | 4 |
"""
Question 8
Write a Python function maxaggregate(l) that takes a list of pairs of the form (name,score) as argument, where name is a string and score is an integer. Each pair is to be interpreted as the score of the named player. For instance, an input of the form [('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara',1... |
d41a0b5459373da54f119b331b3f9091c19125ff | onkcharkupalli1051/pyprograms | /ds_nptel/sample test/6.py | 557 | 4.0625 | 4 | """
Question 6
Write a Python function sublist(l1,l2) that takes
two sorted lists as arguments and returns True if
the the first list is a sublist of the second list,
and returns False otherwise.
A sublist of a list is a segment consisting of
contiguous values, without a gap. Thus, [2,3,4] is a
sublist of [2,2,3,4,5]... |
812dde47bf82dde83275c5a6e5c445ef6a0171ab | onkcharkupalli1051/pyprograms | /ds_nptel/NPTEL_DATA_STRUCTURES_TEST_1/ques4.py | 580 | 4.34375 | 4 | """
Question 4
A list is a non-decreasing if each element is at least as big as the preceding one. For instance [], [7], [8,8,11] and [3,19,44,44,63,89] are non-decreasing, while [3,18,4] and [23,14,3,14,3,23] are not. Here is a recursive function to check if a list is non-decreasing. You have to fill in the missing ar... |
cbfeb441eb0a13350319426bfaae29016bff9d70 | onkcharkupalli1051/pyprograms | /ds_nptel/week7_class1program.py | 554 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 2 16:11:19 2020
@author: Onkar
"""
from math import sqrt
class point:
def __init__(self,a,b):
self.x = a
self.y = b
def print(self):
print("a :",self.x,"b :",self.y)
def translate(self,deltax,deltay):
self.x += d... |
d5dc375d9945ddf738a501ed389824c7b0c99b7f | onkcharkupalli1051/pyprograms | /ds_nptel/week7_class_user_defined_lists.py | 369 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 14:25:10 2020
@author: Onkar
"""
class node:
def __init__(self,initval = None):
self.value = initval
self.next = None
def isempty(self):
return(self.value == None)
l1 = node()
l2 = node(5)
x = l1.isempty() #returns True
... |
be140a2520d37baee32008b12d2682a6dc30cf39 | onkcharkupalli1051/pyprograms | /ds_nptel/binary_search.py | 828 | 3.734375 | 4 | """
def bs(l,x,start,end):
while(end != start):
mid = start+end//2
if (x == l[mid]):
print("Element found")
elif (x < l[mid]):
return bs(l,x,start,mid-1)
elif x > l[mid]:
return bs(l,x,mid+1,end)
"""
def bs(l,x,start,end):
if start == end:
... |
f5e00fba2fa8762aa9d5bf283852a73a953858c2 | onkcharkupalli1051/pyprograms | /ds_nptel/fibonacci nos.py | 159 | 4.09375 | 4 | def fibonacci(n):
if n<2:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
n = int(input("Enter limit : "))
print(fibonacci(n))
|
62edb5acaf0f4806e84966e822083a39cdf66805 | YhHoo/Python-Tutorials | /enumerate.py | 477 | 4.125 | 4 | '''
THIS IS enumerate examples****
it allows us to loop over something and have an automatic counter
'''
c = ['banana', 'apple', 'pear', 'orange']
for index, item in enumerate(c, 2): # '2' tell the enumerate to start counting from 2
print(index, item)
'''
[CONSOLE]
2 banana
3 apple
4 pear
5 orange
'''
c = ['... |
60e3da512fd271b5cdf2027360b986799eddb9b5 | dfrail/PyBites_Solutions | /PyBites15.py | 556 | 3.5625 | 4 | names = 'Julian Bob PyBites Dante Martin Rodolfo'.split()
countries = 'Australia Spain Global Argentina USA Mexico'.split()
def enumerate_names_countries():
"""Outputs:
1. Julian Australia
2. Bob Spain
3. PyBites Global
4. Dante Argentina
5. Martin ... |
c8951a2c91e2fbbc9354681a0add022ba42096e8 | masintech/epi_python | /ch1_primitive_type/parity.py | 2,354 | 3.84375 | 4 | import functools
class Parity:
"""Bitwise operation
Find the parity
from EPI Ch 1
"""
def __init__(self, x):
self._x = x
def set_x(self, x):
self._x = x
def print_result(fun):
@functools.wraps(fun)
def wrap(self):
result = fun(self)
... |
d25b40e16db26e3e15275fccda70055ff78f2c28 | Montana/tensorflow | /tensorflow/examples/skflow/iris.py | 981 | 3.515625 | 4 | """Example of DNNClassifier for Iris plant dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from sklearn import cross_validation
from sklearn import metrics
import tensorflow as tf
from tensorflow.contrib import learn
def main(unused_argv):
# ... |
44cf64192726ea1ac467601ec692c34e83a173fb | xzy103/learn_python_course | /chap03/3.6.2.py | 2,184 | 3.515625 | 4 | # -*- coding:UTF-8 -*-
# Author:徐熙林-金融162班
# Date:2019.4.28
import csv
class Score:
def __init__(self, id_, name, class_, math, literature):
self.id = id_
self.name = name
self.class_ = class_
self.math = math
self.literature = literature
filename = 'ex2-2.scores.csv'
w... |
e5c0490721c8a9965cc21378f234cb57497ef13d | xzy103/learn_python_course | /chap01/1.1.py | 203 | 3.640625 | 4 | # -*- coding:UTF-8 -*-
# Author:徐熙林-金融162班
# Date:2019.3.21
name = input("请输入您的姓名:")
age = input("请输入您的年龄:")
print(f"{name},你好!你今年{age}岁。")
|
b91d59fd31ed799afdbd0f1b0ca92d45f14aaf3d | xzy103/learn_python_course | /chap03/3.8.1.py | 1,708 | 3.59375 | 4 | # -*- coding:UTF-8 -*-
# Author:徐熙林-金融162班
# Date:2019.4.28
import csv
class UserInfo:
def __init__(self, id_, username, name, gender, Tel, password, mail, rank):
self.id = id_
self.username = username # 用户名
self.name = name # 用户姓名
self.gender = gender
self.Tel = Tel
... |
d365712c99b071f3bedf2a668c2eb7f7243b1ffb | xzy103/learn_python_course | /chap01/1.8.py | 936 | 3.90625 | 4 | # -*- coding:UTF-8 -*-
# Author:徐熙林-金融162班
# Date:2019.3.21
def get_tax(income):
"""
通过收入获取应缴税额
:param income:收入数额
:return:应缴个人所得税额
"""
if income > 85000:
tax = (income-5000)*0.45-15160
elif income > 60000:
tax = (income-5000)*0.35-7160
elif income > 40000:
tax ... |
04afb4822b154d326c47749166d19dd558b4c94a | xzy103/learn_python_course | /chap04/4.3.py | 1,284 | 3.84375 | 4 | # -*- coding:UTF-8 -*-
# Author:徐熙林-金融162班
# Date:2019.4.28
import csv
class Score:
def __init__(self, id_, name, class_, math, literature):
self.id = id_
self.name = name
self.class_ = class_
self.math = math
self.literature = literature
def read_csv(filename: str):
... |
a00f2cf439713a048a018db4985da8c70f2951f7 | barraganma/400B_Barragan | /Homeworks/Homework2/ReadFile.py | 1,042 | 3.703125 | 4 | import numpy as np
import astropy.units as u
# A function that outputs useful values from a simulation data file
def Read(filename):
# Inputs:
# filename is the name of the text file that is to be read
# Return:
# time is the instance of the simulation that the file represents
# particles is the t... |
2d9a77a32642e6a71bd42e598e684798b4a91834 | JasonAmpec/Bosch_Tester | /GUI/buttons.py | 447 | 3.578125 | 4 | from tkinter import*
from tkinter.ttk import *
root = Tk()
def myClick():
myLabel = Label(root,text = "Starting Test Sequence")
myLabel.pack()
photo = PhotoImage(file = "test.png")
photoimage = photo.subsample(3, 3)
myButton = Button(root,text = "Learn Cable", image = photoimage, compound = BOTTOM, command... |
a2e137d94c521a29edf20bc9c8316bcfc3bd0bc1 | funfun313/catobject | /cat.py | 245 | 3.796875 | 4 | class Cat:
name = ""
color = ""
favoritetoy = ""
def __init__(self,name):
self.name = name
def purr(self):
print("Meow! My name is " + self.name)
fluffy = Cat("Fluffy")
snowball = Cat("Snowball")
|
ee51176fb0009b79510a680b9766bb77c7798bfe | paiv/aoc2018 | /code/08-1-memory-maneuver/solve.py | 1,358 | 3.59375 | 4 | #!/usr/bin/env python -OO
class Node:
def __init__(self, parent=None):
self.parent = parent
if parent:
parent.children.append(self)
self.children = list()
self.meta = list()
def __repr__(self):
return '{}-{}'.format(tuple(self.meta), self.children)
def... |
1dd0e6d8e73c6dbd174227baf893ad6695f56dab | thisguyisbarry/Uni-Programming | /Year 2/Python/labtest2.py | 2,048 | 4.5 | 4 | import math
class Vector3D(object):
"""Vector with 3 coordinates"""
def __init__(self, x, y, z):
"""Takes in coordinates for a 3d vector"""
self.x = x
self.y = y
self.z = z
self.magnitude = 0
def __add__(self, v2):
"""Adds two 3D vectors
(x+a, ... |
30e68edadbaba888f4e0c6b4f04e074a43051738 | The-Blue-Wizard/Miscellany | /easter.py | 627 | 4.40625 | 4 | #!/bin/python
# Python program to calculate Easter date for a given year.
# This program was translated from an *ancient* BASIC program
# taken from a certain black papercover book course on BASIC
# programming whose title totally escapes me, as that was
# during my high school time. Obviously placed in public
# domai... |
c8e9e9fe2a02ba95ed603fc7b674c8dc8bd2d6dc | rilpires/q_learning_jogo_da_velha | /learning_agent_vs_human.py | 2,216 | 3.53125 | 4 | from jogo_da_velha_rules import *
from learning_agent import *
import sys
import os
simbolo_humano = 'X'
simbolo_computador = 'O'
exploration_p = 0
computador = LearningAgent( actions=[str(x) for x in range(1,10)] , alpha=0.9 , discount_factor=0.9 )
sair_do_jogo = False
while not sair_do_jogo:
S = [ ' ' , ' ' ,... |
95e18c417b5d32404a6957888029ad315f40e54e | ialab-puc/VisualRecSys-Tutorial-IUI2021 | /utils/hashing.py | 2,918 | 3.75 | 4 | """Utilities to hash elements.
This module contains a class (HashesContainer) that calculate hashes
and notify collisions.
"""
def pre_hash(triple, contains_iter=True):
"""Prepare tuple to be hashed.
This means that each element of the tuple will be converted to
string. The first item (profile) should b... |
7feb18f93d677759bd37323fbd9b256098aa2fe5 | DavidDeLille/poker | /poker.py | 6,345 | 3.734375 | 4 | """This script is used to colculate probabilities and best strategies while playing poker."""
import itertools
import time
import collections
def calc_probability(amount_players, hand, flop=None, turn=None, river=None):
"""Calculate the probability of winning the hand."""
# check inputs
if amount_players < 2:
pr... |
35b4c59c73e963327d278b3b75e14b9b699d7999 | chickert/multi-agent-systems | /MRTA/nerd-herd.py | 20,411 | 3.875 | 4 | import random
import numpy as np
class Robot:
def __init__(self, x, y):
# index for row position in grid env
self.x = x
# index for column position in grid env
self.y = y
class Env:
def __init__(self, bots, size=10):
# number of rows and columns in square grid
... |
6dc96cff7559c46fe7ab139a2e3533389d65145c | genkinanodesu/competitive | /libraries_python/shortest_path_BellmanFord.py | 906 | 3.59375 | 4 | '''
V, E : Vは頂点数、Eは辺数
nodes : e = [from, to, cost] を要素とする辺のリスト(有向辺)
'''
def shortest_path(s):
'''
ベルマンフォード法:ループをV回回す→負の辺がなければアルゴリズムは停止 (update = Falseのまま)、あればV回回したあとも更新が続く
O(|V| * |E|)で計算できる
:param s: スタート
:return: 負の辺があればNoneを、なければd = sを始点とする最小距離のリスト を返す
'''
d = [float('inf')... |
29d1e4022ecb5430b048477ee633ae6f14c93c00 | genkinanodesu/competitive | /AtCoder/AGC/agc028/agc028a.py | 558 | 3.65625 | 4 | import math
def gcd(a, b):
#aとbの最大公約数を求める
#math.gcdもしくはnp.gcdを使えばいいのだが、AtCoder上のpythonでは使えない
if a < b:
return gcd(b, a)
if b == 0:
return a
else:
c = a % b
return gcd(b, c)
def lcm(a, b):
return (a * b // gcd(a, b))
n, m = map(int, input().split()... |
38801b58886ff25604402f111dbd3d57656ff1c3 | genkinanodesu/competitive | /AtCoder/ABC/abc070/abc070c.py | 789 | 3.6875 | 4 | import math
def gcd(a, b):
#aとbの最大公約数を求める
#math.gcdもしくはnp.gcdを使えばいいのだが、AtCoder上のpythonでは使えない
if a < b:
return gcd(b, a)
if b == 0:
return a
else:
c = a % b
return gcd(b, c)
def lcm(a, b):
return a * b // gcd(a, b)
def gcd_list(l):
#リストlに対して、l... |
38059c9a929e01a914962d19feb1bfd0e55765f2 | genkinanodesu/competitive | /libraries_python/BIT.py | 578 | 3.75 | 4 | class BIT:
'''
1-based self.bit[0] は無視している
'''
def __init__(self, n):
self.bit = [0] * (n+1)
def sum(self, i):
'''
:param i:
:return: bit[i]までの和
'''
s = 0
while i > 0:
s += self.bit[i]
i -= i & -i
... |
9ba3054974f45a391f5953769b568698ee94d83b | genkinanodesu/competitive | /libraries_python/primelist.py | 423 | 3.75 | 4 | def sieve(n):
'''
:param n:
:return: n以下の素数のリストを返す
'''
prime = []
is_prime = [True] * (n + 1) #is_prime[i] = Trueならiは素数
is_prime[0] = False
is_prime[1] = False
for i in range(2, n+1):
if is_prime[i]:
prime.append(i)
for j in range(2 * i, ... |
af409f10aa823867fdac8e377ec8f9fab9d90168 | ColinWilder/pythonBasics | /while_ex.py | 91 | 3.640625 | 4 | i=10
while i>0:
print("Lift off in %s!" %i)
i=i-1
print("Boooooooooom! Lift off!")
|
0b43dfa68488c170ec85a5fbc9ac45cd4401aacd | ColinWilder/pythonBasics | /string-to-list.py | 266 | 4.0625 | 4 | # string-to-list.py
# First, define some strings
s1 = 'hello world'
s2 = 'howdy world'
# list of characters
charlist = []
for char in s1:
charlist.append(char)
print(charlist)
# illustration of how the split method works
wordlist = s2.split()
print(wordlist)
|
970fd25900733d3fbc31bae31db94e4e1c460ce6 | Hamza746/assigment-2 | /sy2.py | 119 | 3.9375 | 4 | # Write a Python program to get the largest number from a numeric list.
num =[12,22,55,44,77,55,66,99]
print(max(num))
|
4ec7fe82df806bae7c58e3c6e2d82ed833236bb0 | Quinnan-Gill/PCV | /PCV/chapter_1/gaussian_filter_intro.py | 681 | 3.859375 | 4 | from PIL import Image
from numpy import *
from scipy.ndimage import filters
"""
Gaussian blurring or a Gassian filter is used to define an image
to work in (for interpolation) for computing interest points
"""
# im = array(Image.open('data/empire.jpg').convert('L'))
# im2 = filters.gaussian_filter(im,10)
im ... |
5dd7ec69f38fb216b279525070b6b7dbec6fe0a7 | L-ByDo/OneDayOneAlgo | /Algorithms/General_Algorithms/Maximum Pairwise/MaxPairProduct.py | 738 | 4.0625 | 4 | #given code implements maximum pairwise sum to find maximum possible sum..for this, first sort an array and print sum of last two numbers.
def quicksort(seq): #function to sort array
length=len(seq)
if length<=1:
return seq
else:
pivot=seq.pop() #take out the pivot element
great=[]
l... |
132c7a205f2f0d2926e539c172223fb505a0f2c1 | L-ByDo/OneDayOneAlgo | /Algorithms/Searching_Algorithms/Binary Search/SquareOfNumber.py | 1,338 | 4.25 | 4 | #Find the square of a given number in a sorted array. If present, Return Yes with the index of element's index
#Else return No
#Program using Recursive Binary Search
#Returns True for Yes and False for No
def BinarySearch(arr, left, right, NumSquare):
#check for preventing infinite recursive loop
if right >=... |
cc7f7f946e11fb66266b3761e3a051bfff65a50a | geekhub-python/cycles-mdtehwgp | /task3.py | 206 | 3.890625 | 4 | #!/usr/bin/env python3
# Найти произведение 5 * 6 * 7 * ... * 13.
begin_seq = 5
end_seq = 13
gen = begin_seq
for i in range(begin_seq, end_seq):
gen += gen * i
print(gen)
#print(gen)
|
94e17585ee5d0fc214dea1cbc886bd8fa33af30e | EmreCenk/Breaking_Polygons | /Mathematical_Functions/coordinates.py | 2,277 | 4.5 | 4 |
from math import cos,sin,radians,degrees,sqrt,atan2
def cartesian(r,theta,tuple_new_origin=(0,0)):
"""Converts height given polar coordinate r,theta into height coordinate on the cartesian plane (x,y). We use polar
coordinates to make the rotation mechanics easier. This function also converts theta into ra... |
5378f94a85f0833c075e0b70fcdecd136a1feec5 | dannygosain1/CanMap | /processing/create_tables.py | 1,309 | 3.65625 | 4 | #Takes in a CSV file and creates + populates a mysql database with the values
import argparse
import csv
import MySQLdb
import os
import processing_utils
def parse_args():
"""
Parses the arguments passed to the script if none are passed through the function call
Returns an object containing the argument v... |
893fff12d545faa410309b4b2b087305e6ad99cc | AxiomDaniel/boneyard | /algorithms-and-data-structures/sorting_algorithms/insertion_sort.py | 1,596 | 4.59375 | 5 | #!/usr/bin/env python3
def insertion_sort(a_list):
""" Sorts a list of integers/floats using insertion sort
Complexity: O(N^2)
Args:
a_list (list[int/float]): List to be sorted
Returns:
None
"""
for k in range(1, len(a_list)):
for i in range(k - 1, -1, -1):
... |
fa638b33f6e422f07208bcebab4267cf311bef36 | AxiomDaniel/boneyard | /algorithms-and-data-structures/data_structures/Heap.py | 2,459 | 3.890625 | 4 | #!/usr/bin/env python3
class Heap:
""" Self-implemented Min-Heap data structure
Notes:
Index of root node in the array is 1
Left Child of a node,k is 2 * k
Right Child of a node, k is 2 * k + 1
Parent of the node,k is k // 2
"""
def __init__(self):
self.count =... |
807572a90558a6e3bd39d8178c64e7769d7f357b | AxiomDaniel/boneyard | /algorithms-and-data-structures/dynamic_programming/rod_cutting.py | 4,323 | 3.9375 | 4 | #!/usr/bin/env python3
def rod_cutting_top_down_DP(rod_length, length_list, price_list):
""" Utilizing top down dynamic programming to solve the rod cutting problem.
Args:
rod_length (int):
length_list (list[int])
price_list (list[int])
TODO: The memoization for the cut list is p... |
2b2e0f26ad06d49d58268bc469ab671d81f6099f | bogdanpreda/Algo-University | /classcoada.py | 1,266 | 3.625 | 4 | class Coada:
def __init__(self, nmax):
self.nmax = nmax
self.s = -1
self.f = 0
self.data = [None]*(nmax+1)
def isGoala(self):
return self.f == self.avIndex(self.s)
def isPlina(self):
return self.f == self.avIndex(self.avIndex(self.s))
def a... |
deb7f660c0f607492dbbcd59c71936876c893b35 | Erik-D-Mueller/Python-Neural-Network-Playground | /Version1point0/initial.py | 1,363 | 4.3125 | 4 | # 02-12-2020
# following along to a video showing how to implement simple neural network
# this is a perceptron, meaning it has only one layer
import numpy as np
# sigmoid function is used to normalize, negatives values return a value below 1/2 and approaching zero, positive values return above 1/2 and approaching 1... |
39a759572772b1ac52dcb6aef6c10fb8fb8906d6 | hossain-bd/small_python_works | /helloworld.py | 278 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 25 20:36:10 2018
@author: nazmul
"""
#greeting = "Hello"
#name = input("Please enter your name ")
#print(greeting + ' ' + name)
splitstring = """ This srting
has been
split over several lines"""
print (splitstring) |
f178a80e3b6bfa83c1711b61637f4c7dcb3ec5d8 | abhigya-ps/python-problems | /reverse-integer.py | 159 | 3.796875 | 4 | def reverse(x):
sign = [1, -1][x < 0]
rev = sign * int(str(abs(x))[::-1])
return rev if -(2**31) - 1 < rev < (2**31) else 0
print(reverse(-120))
|
0d5096c903c4eff116e983e147dc35083490373d | abhigya-ps/python-problems | /twosum.py | 302 | 3.5625 | 4 | def twoSum(nums, target):
if len(nums) <= 1:
return False
pairs = {}
for i in range(len(nums)):
if nums[i] in pairs:
return [pairs[nums[i]], i]
else:
pairs[target - nums[i]] = i
nums = [2, 7, 11, 15]
target = 9
print(twoSum(nums, target)) |
fb827ddc6bd519953f20788d869b07cd86f0490e | nekojess1/lab_programa-o | /fila.py | 3,666 | 3.5 | 4 | class No:
def __init__(self, dado):
self.__dado = dado
self.__prox = None
self.__ant = None
def getDado(self):
return self.__dado
def getProx(self):
return self.__prox
def getAnt(self):
return self.__ant
def setDado(self, dado):
self.__dado... |
16b40739e329206ab64ad2446273ff2932456fcf | laraguerreiro/Python-Ubi | /trabalho1/Trabalho_ex2.py | 746 | 3.921875 | 4 | # escrever um programa que conte a ocorrência de cada vogal do alfabeto latino num texto teterminado.
# a letra em minúsculo e a equivalente em maiúsculo são consideradas uma diferente da outra
#texto = "Várias são as formas de manipularmos um navegador Web através do Python. Talvez a maneira mais desconhecida seja a... |
4d93394bde93d2fae68d33c1bcc138ba37fed32b | amirmojarad/maze | /models/astar.py | 5,017 | 3.984375 | 4 | from FibonacciHeap import FibHeap
from priority_queue import FibPQ, HeapPQ, QueuePQ
def solve(maze):
# Width is used for indexing, total is used for array sizes
width = maze.width
total = maze.width * maze.height
# Start node, end node
start = maze.start
startpos = start.Position
end = ma... |
de7a654f7d65f5ef062c09bbdd21ca633d8c96da | arshdeepdgreat/Audio-Text-transcribing | /aud_tx.py | 598 | 3.828125 | 4 | import speech_recognition as sr
from os import path
from pydub import AudioSegment
# transcribe audio file
AUDIO_FILE = input("enter audio file name: ")
OUTPUT_FILE = input("enter output file name: ")
# use the audio file as the audio source ... |
3cd553db790a7f794626adf42ce26dd512d09e38 | lisamarieharrison/Py-Algorithms1 | /queues.py | 5,328 | 4.25 | 4 | #Coursera Algorithms 1 - week 2
import unittest
class DequeNode(object):
def __init__(self, item, next, previous):
self.item = item
self.next = next
self.previous = previous
class Deque(object):
def __init__(self):
self.head = None
self.tail = None
self.sz = 0... |
1afb0c7ab4ad1c76075eddad4161de4607fb4ec7 | victord96/middle_level_python | /debugging/assert_statements.py | 342 | 4 | 4 | def divisors(num):
divisors = [x for x in range(1,num+1) if num % x == 0]
return divisors
def run():
num = input('Write a number: ')
assert num.isnumeric(), 'Please, write a number'
#assert int(num) > 0, 'Please enter a positive number'
num = divisors(int(num))
print (num)
if __name__ ==... |
4c0075155062aa001e0d140312f49dde72567350 | zestrells/Networking-Scripts | /VRRP_ STP.py | 6,795 | 3.609375 | 4 | #import netmiko import ConnectHandler
from datetime import datetime
import ipaddress
class UserInput():
def __init__(self):
self.routers = {}
self.num_of_Routers = 0
def quantity(self):
#establishes how many routers the user is configuring
while True:
try:
... |
33c4e0504425c5d22cefb9b4c798c3fd56a63771 | rodneyp290/DrapTVTutorials | /begPy3/9tut.py | 238 | 4.0625 | 4 | #!/usr/bin/python
import math
def Main():
try:
radius = float(input("Please enter the radius: "))
area = math.pi * radius**2
print("Area =", area)
except:
print("You did not enter a number")
if __name__ == "__main__":
Main()
|
ce77f0130af101bcf95e07cf67fa9190fd6d6485 | digideskio/python-lessons | /12-tabelline-con-funzioni.py | 1,124 | 3.859375 | 4 | from random import randint, shuffle
print('Programma tabelline')
insulti = ['semo', 'piva', 'pirla', 'esen']
complimenti = ['bravo', 'wow', 'ottimo!', 'WTF!!!!', '<3 <3 <3']
def get_rnd_from_list(lista):
r = randint(0, len(lista)-1)
return lista[r]
def insulta():
insulto = get_rnd_from_list(insulti)
return ins... |
f203d61ad0bdae2d29d4169b6c13a8ee4e5ed0e0 | digideskio/python-lessons | /10-liste.py | 207 | 3.515625 | 4 | listaSpesa = ['salame', 'pane']
lista = [6, 81.6, 39, 25]
listaSpesa.append('marmellata')
#listaSpesa.remove('pane')
lista.sort()
print(listaSpesa[0:len(lista)])
lista.reverse()
lastIndex = len(lista)-1
|
f588504c0e8fcc2cc07279af2e53cfbd5d04fb0a | DexterCooke/coding_problems_python | /perm.py | 283 | 3.78125 | 4 | def permutations(str):
if str == '':
return ['']
permutes = []
for char in str:
subpermutes = permutations(str.replace(char, '', 1))
for each in subpermutes:
permutes.append(char + each)
return permutes
print(permutations('abc')) |
c264d799761e0ae4e3643f29251a7871b67755d9 | sjoelee/caltech_machine_learning | /HW1/HW1.py | 2,434 | 3.59375 | 4 | import random
import numpy as np
import matplotlib.pyplot as plt
import copy
def generate_dataset(num_of_points=10):
X = np.ones((num_of_points, 3)) # these are 1 because of x0 = 1 for the constant term
X[:, 1:] = np.random.uniform(-1, 1, (num_of_points, 2))
return X
def classify(X, w, y=None):
return np.sign... |
ab09919be28f74c02a546124aab2d92293122c90 | IMCHO/CODING_DOJANG | /STEP_3/STEP_3/STEP_3.py | 1,613 | 3.75 | 4 | def printnum(list,size,string):
for i in range(2*size+3):
for j in range((size+3)*len(str(string))-1):
print(list[i][j],end='')
print('')
def one(list,r,size):
for i in range(2*size+3):
if i==0 or i==(2*size+3)//2 or i==2*size+2: continue
else:
list[... |
f92b62b507043190fc44e531743433bd493b13d4 | ImtiazMalek/PythonTasks | /practice_string.py | 187 | 3.5625 | 4 | phrase = "welcome to imtiaz Academy"
print("Hello \n" + phrase+ ", which is bad ass")
print("the 5th character is "+ phrase[5])
print(phrase.replace("imtiaz", "junaid"))
print(phrase) |
1326800eed0a49d19b8e959f7d58e2e65195963a | ImtiazMalek/PythonTasks | /input.py | 215 | 4.375 | 4 | name=input("Enter your name: ")#user will inter name and comment
age=input("Enter your age: ")#and we are saving it under various variables
print("Hello "+name+", you are "+age+" years old")#it'll print the result |
464574dd981dc1b91f191c6f4aa87e47d32e3d15 | ImtiazMalek/PythonTasks | /GuessGame.py | 349 | 3.9375 | 4 | counter=0
limit = int(input('How many time you wanna guess? :'))
correct_word = 'panda'
check =False
#taking the guesses
while counter<limit:
guess=input('Guess a word: ')
if guess == correct_word:
check=True
break
counter+=1
#checking the boolean
if check:
print('You win')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.