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 |
|---|---|---|---|---|---|---|
6584fa89d166255a67ca21a19332ffece0a79857 | viva0330/APS | /IM_study/0319/baekjoon_10871.py | 153 | 3.546875 | 4 | N, X = map(int, input().split())
number_arr = list(map(int, input().split()))
for number in number_arr:
if number < X:
print(number, end=" ") |
b2d43d77e438a382c29f2936fc8155a90892313d | viva0330/APS | /IM_study/0320/baekjoon_1157.py | 379 | 3.796875 | 4 | words = input().upper()
max_count = 0 #
chk = {}
answer = ''
for word in words:
# count = chk.get(key값, default값) + 1
count = chk.get(word, 0) + 1
# 세어진 word값을 가진 dict의 value값 == count
chk[word] = count
if max_count < count:
max_count = count
answer = word
elif max_count == count... |
3605b6c998149755c422dd7c8e07a4955b857086 | tnjman/python-scripts | /removedup.py | 798 | 3.59375 | 4 | # Orig: https://gist.github.com/redrambles/c099b771a76e7ade81b5fb463b72126b
# Improved below:
def remove_duplicates(lista):
# -- Start of function
# lista2 = [] <-- Orig had an empty "lista2"
lista2 = [2,4,6] # <- Pre-populate lista2 for different behavior
for item in lista:
if item not in li... |
0ab09c21227e240bc038eedb3accf2b32c755187 | xk314/python- | /Myprogram/面向对象.py | 996 | 3.96875 | 4 |
#python中以双下滑线开始和结束的方法为魔法方法,这是python自带的,
#可以通过重新定义来重写
class person(object):
__country = '中国' #类属性
__part = '共产党' #类的私有属性
@classmethod #通过修饰器定义类的方法
def get(cls):
return cls.__part
def ch(self):
self.__part = '国民党'
def __init__(self, name, age):
self.name = name
... |
1c07dff69922e5ff2d7a4c8a7ebbb2bad2589459 | xk314/python- | /Myprogram/字典.py | 465 | 3.875 | 4 | my_dict = {'name': 'xk', 'age': '24', 'sex': '男'}
'''
字典的相关操作:
get my_dict.get('key', '默认值')
获取字典中相关键对应的值,如果该键不在字典中,则返回默认值
setdefault my_dict.setdefault('key', '默认值')
获取字典中指定的键所对应的值,如果该键不存在则返回默认值,并将该键和默认值添加到字典中
'''
print(my_dict.get('name'))
print(my_dict.setdefault('name1', 'xue')) |
4ba5e815699e5ef11699248e87ddb38c2e88a697 | vijayalaxmibhoonekar/python | /regular exp/sub.py | 93 | 3.65625 | 4 | import re
st = "C is programming language"
result = re.sub(r"C","Python",st)
print(result) |
7b24cb7dbc9e7b597fb97f56400c9249c5e0928c | AlexSuv-Tob/1_class | /4.py | 355 | 3.828125 | 4 | a = int(input('Введите целое положительное многозначное число: '))
b = a % 10# принимаем за максимум последнее число цифры
a = a // 10#убираем последнюю цифру числа
while a > 0:
if a % 10 > b:
b = a % 10
a = a // 10
print(b) |
893f227b7d7e2fb5c18666e89d31d6896c6be2ad | alexaustin456/Pi-Approximations | /Basel Approx.py | 119 | 3.75 | 4 | import math
pi = float(0)
for x in range (1, 10000000):
pi += 1.0/float(x)**2.0
pi = math.sqrt(pi*6)
print(pi)
|
fadcd4db1ea97d8d55397f6ba32ec107e69cbfb8 | ValeWasTaken/Random_Programs | /Python_Programs/Misc/survey_results.py | 963 | 3.921875 | 4 | '''
This program was made to count the video game recommendations I was given.
'''
import re # For getting rid of unrequired characters.
from collections import Counter # For counting how many of each game title.
def count_games():
# Open text file and read through it.
with open('games_survey.txt','r') as sur... |
1794a40f6967b0ffb8cd89fa9ab3b6bc4b20e024 | ajfrierson/Algorithms | /rock_paper_scissors/rps.py | 854 | 3.78125 | 4 | #!/usr/bin/python
import sys
def rock_paper_scissors(n):
output = []
plays = ['rock', 'paper', 'scissors']
# using a helper recursion method since need to return a list
def helper_method(m, lst):
# base case
if m == 0:
output.append(lst)
return
# loop... |
90b6cf9cbeda44094c6a974f80b6600650b68ed7 | gladysmorales/module5 | /M5P5.py | 179 | 3.796875 | 4 | # Gladys Morales
# February 11th, 2020
# This program draws a star.
import turtle
star = turtle.Turtle()
for i in range(100):
star.forward(100)
star.right(200)
turtle.done()
|
5ce794b234f2a30066460085a5ceddd49b745cc2 | iamashruu/ProjectEulerSolution | /smallest-num-5.py | 1,354 | 4.09375 | 4 | import time
#Time at the start of program
start_time = time.time()
#More Efficient
#gcd function for calculating lcm
def gcd(n1,n2):
if n1==0:
return n2
return gcd(n2%n1,n1)
"""
remainder = 1
while remainder != 0:
remainder = n1%n2
n1 = n2
n2 = remainder
return n1
"""
#lcm of ... |
0cfb3321890779daad3d1ce8c3a001b2b8a17d22 | DesiPilla/MachineLearning | /Homework 1/hw1_part1_group3.py | 19,503 | 3.6875 | 4 | # Homework 1 Group Project
# ********************* Implement tree using variance impurity heuristic ******************************
import pandas as pd
import sys
import math
import random
#data1 = pd.read_csv('./data_sets1/training_set.csv')
#data2 = pd.read_csv('./data_sets2/training_set.csv')
#test_data1 = pd.read_... |
fb862528041961c371722c7f537c76f5806ee8c4 | Asgavar/things | /codefights/arcade/intro/edge_of_the_ocean/05_shapeArea.py | 187 | 3.53125 | 4 | def shapeArea(n):
current_n = n - 1
total_area = (n * 2) - 1
while current_n > 0:
total_area += 2 * ((current_n * 2) - 1)
current_n -= 1
return total_area
|
44f2e032f122099a6189ab8ecd20ab674f76c38b | KRHS-GameProgramming-2016/Madlibs_Harrison_Joe | /input.py | 5,860 | 3.65625 | 4 | def isSwear(word):
swearList = ["poop",
"pee",
"ass",
"asshole",
"bastard",
"bitch",
"blowjob",
"boner",
"bitchy",
"bullshit",
"chink",
... |
3adf36c101447d8f8151556722951e1e9031412b | tlavitz/java | /Function1.py | 1,123 | 3.921875 | 4 | # 1 Recieve and Return
#prameters and return values
def display(message):
print(message)
def giveMeFive():
five=5
return five
def yesNo(question):
response=""
response=None
while response not in ("y","n"):
response=input(question).lower()
return response
#main
display("heres my m... |
8218d7cf7b2a9e7f18cc6b0ac0ff40a9dcff9f3d | tlavitz/java | /hangman.py | 1,785 | 3.90625 | 4 | import random
HANGMAN=("""
------
| |
|
|
|
|
|
|
|
----------
""",
"""
------
| |
| 0
|
|
|
|
|
|
----------
""",
"""
------
| |
| 0
| -+-
|
|
|
|
|
----------
""",
"""
------
| |
| 0
| /-+-
|
|
|
|
|
----------
""",
"""
------
| |
| 0
| /-+-/
|
|
|
|
|
----------
""",
"""
------
| |
... |
107af0b3a1dd202027b513a89ee6a9366b596497 | Edward-Lengend/python | /PycharmProjects/06函数拆包与引用参数/py_03_引用.py | 325 | 3.828125 | 4 | # python中, 值是靠引用传递的
a = 1
b = a
if id(a) == id(b): # id()可以查看变量的十进制地址
print(f'id(a) = {id(a)}')
print(f'id(b) = {id(b)}')
print('a与b为同一段地址')
print('int为不可变类型')
a = 2
print(f'b = {b}')
print(f'id(a) = {id(a)}')
print(f'id(b) = {id(b)}')
|
da7819b144bddbeaca8c88494df6954a5ae26e6a | Edward-Lengend/python | /PycharmProjects/11面向对象/py_16_修改和获取私有属性.py | 1,071 | 3.828125 | 4 | class Master:
def __init__(self):
self.kongfu = '古法煎饼果子技术'
def make_cake(self):
print(f'运用{self.kongfu}制作煎饼果子')
class School:
def __init__(self):
self.kongfu = '黑马煎饼果子技术'
def make_cake(self):
print(f'运用{self.kongfu}制作煎饼果子')
class Prentice(Master, School):
def __... |
03c27d7eb3ef9e6bf127b499ab14ffbf995ad6b4 | Edward-Lengend/python | /PycharmProjects/15StudnetManagerSystem/dict拓展.py | 225 | 4.09375 | 4 | # 1.定义类
class A(object):
a = 0
def __init__(self):
self.b = 1
# 2.创建对象
aa = A()
# 3.调用__dict__
print(A.__dict__) #
print(aa.__dict__) # 当前对象的实例属性 返回一个字典
|
657c69154eae6ef1027b7a81147f0664dd51cb91 | Edward-Lengend/python | /PycharmProjects/01_Python基础/py_14_while..else.py | 196 | 3.828125 | 4 | # while...else...
i = 0
while i < 5:
print("老婆我错了")
i = i + 1
break
else:
print("老婆原谅我了") # while正常循环结束才会执行 break退出的不能执行
|
2ec1bbb6b24e3267cf8ee6e95f8302ddc7e1bb47 | Edward-Lengend/python | /PycharmProjects/01_Python基础/py_03_注释.py | 192 | 3.5 | 4 | # 这是第一个注释
print("hello")
# print("彩蛋")
print("2hello") # 也可以这样使用注释
"""
这是一个多行注释
。
。
注释结束了!!
"""
print(1+2)
print(22/7)
|
f660f5697880e3e443c53de9c8239c4d8a1043bb | Edward-Lengend/python | /PycharmProjects/18人工智能基础/02numpy/py_09_数组运算.py | 1,778 | 3.71875 | 4 | import numpy as np
# 数组和数字的运算
arr_1 = np.array([1, 2, 3, 4])
print(arr_1+1) # 所有值加一, 加减乘除都能运算
# 数组和数组的运算(满足两条中的任意一条即可运算)
# 一、两个数组要同维度
# 二、 当两个数组的形状并不相同的时候,我们可以通过扩展数组的方法来实现相加、相减、相乘等操作,这种机制叫做广播
# 1.若两个数组的后缘维度(从末尾开始算起的维度)的轴长度相符,或其中的一方的长度为1,则认为它们是广播兼容的。
# 广播会在缺失和(或)长度为1的维度上进行。
# 例如
# arr1 = np.array([[0, 0, 0... |
40626631a907c84562a9cb5d4fc47b0aab78da5f | Edward-Lengend/python | /PycharmProjects/11面向对象/py_18_类属性.py | 1,178 | 4.4375 | 4 | """
类属性就是类对象所拥有的属性,它被该类的所有实例对象所共有。
类属性可以使用类对象或实例对象访问。
类属性的优点
·记录的某项数据始终保持一致时,则定义类属性。
·实例属性要求每个对象为其单独开辟一份内存空间来记录数据,
而类属性为全类所共有,仅占用一份内存,更加节省内存空间。
"""
# 1.定义类, 定义类属性
class Dog(object):
tooth = 10
# 2.创建对象
wangcai = Dog()
xiaoqi = Dog()
# 3.访问类属性和类对象
print(Dog.tooth) # 类属性可以通过类访问
print(wangcai.tooth)
print(xi... |
e2c3be09165fbf5d343647f7611e3cb915a42a33 | Edward-Lengend/python | /PycharmProjects/03_高级数据类型/py_11_集合的创建.py | 419 | 3.8125 | 4 | # 创建集合使用 set() 或 {}
# 创建空集合只能用set()
# 1. 创建有数据的集合
s1 = {10, 20, 30}
print(s1)
# 集合数据展示顺序可能与代码顺序不同, 因此不支持下标
s2 = {10, 20, 30, 40, 50}
print(s2)
# 集合会去掉重复的数据、
s3 = {10, 10, 20, 30, 30, 50}
print(s3)
s4 = set('hello')
print(s4)
# 创建空集合
s5 = set()
print(s5)
print(f's5为{type(s5)}类型')
|
b44767e3b7c6cd53d8ade5ec9b888ec0c6ea2baf | Edward-Lengend/python | /PycharmProjects/18人工智能基础/02numpy/py_05_数组索引和切片.py | 661 | 3.578125 | 4 | import matplotlib.pyplot as plt
import numpy as np
#
stock_change = np.random.uniform(0, 1, (8, 10))
# 前两行 前三列
# print(stock_change[0:2, 0:3])
# 形状修改
# ndarray.reshape(shape, order)
# 返回一个具有相同数据域,但shape不一样的视图
# 行、列不进行互换
# 在转换形状的时候,一定要注意数组的元素匹配
stock_change.reshape([10, 8]) # 改为5行4列, 生成新的ndarray
stoc... |
aa7ab0dce6fc0c0f9eac7bb14ade24d593c8c510 | Edward-Lengend/python | /PycharmProjects/09高阶函数/py_03_reduce.py | 298 | 3.90625 | 4 | """
reduce(func,lst),其中func必须有两个参数
每次func计算的结果继续和序列的下一个元素做累积计算
"""
import functools # 使用reduce需要模块
list1 = [1, 2, 3, 4, 5]
def func(a, b):
return a + b
result = functools.reduce(func, list1)
print(result) |
c9eecbccd3d43c44873563886562a231ef21c9d7 | aisusuriya/Letsupgrade-Python | /list.py | 370 | 3.859375 | 4 | #list
l=[1,2,3,4,5]
print(l)
#default function
print(len(l))
print(max(l))
print(min(l))
value=l.count(5)
print(value)
l2=[2,5,6,9]
l2.reverse()
print(l2)
l2.sort()
print(l2)
l2.append(10)
print(l2)
l2.insert(1,4)
print(l2)
l.extend(l2)
print(l)
l3=l2.copy()
print(l3)
l3.remove(5)
print(l3)
l3.p... |
c7fc1c2bcaa24697becb8ee152b9d24614af04e3 | luc-tielen/DSPy | /filter_builder.py | 1,686 | 3.609375 | 4 | from dsp_filter import Filter
from band_filter import BandFilter
class FilterBuilder:
"""
Class to easily construct a lowpass, highpass, bandpass or bandstop filter.
"""
@staticmethod
def build():
"""
Builds a lowpass, highpass, bandpass or bandstop filter after
the user ... |
9e3858944480f31ede133fa8626c20ad4e74f360 | Banustard/Screen-timer-application | /Screen Timer/Old - Working with/libs/test.py | 308 | 3.703125 | 4 | import tkinter as tk
root = tk.Tk()
for row, text in enumerate((
"Hello", "short", "All the buttons are not the same size",
"Options", "Test2", "ABC", "This button is so much larger")):
button = tk.Button(root, text=text)
button.grid(row=row, column=0, sticky="ew")
root.mainloop()
|
cbbfe90a63cbc735dca2f3a9a3a2b209673f24a2 | cugis2019-sfo/Elijah-Casilang-Coding | /ElijahCasilangPythonCodeDay2.py | 526 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
5/8 #divison
print("You are in San Francisco the number","1",)
5*2 #multiplication
5-2 #subtraction
5**2 #exponent
(8/9)*3 #multiplication
#writing code to sum any two numbers
def area (b,h):
area = (b*h)/2
... |
e5e5a221a700f988246d84926bf1f453f17405a0 | HaliteChallenge/Halite-III | /starter_kits/Python3/hlt/positionals.py | 3,566 | 3.984375 | 4 | from . import commands
from . import constants
class Direction:
"""
Holds positional tuples in relation to cardinal directions
"""
North = (0, -1)
South = (0, 1)
East = (1, 0)
West = (-1, 0)
Still = (0, 0)
@staticmethod
def get_all_cardinals():
"""
Returns all... |
0f5fd940efaf04528b1b08fb84700c56ccdf49ff | Hodaaa/Test | /ISwon.py | 1,335 | 3.875 | 4 | #--------------------- Function who is winner ? ------------------------------- #
#this is function return winner if exist else return none let's see
def iswon(board):
sblack ,Empty, swhite = 0 , 0 , 0
for i in xrange(len(board)):
for j in xrange(len(board[i])):
if (board[i][j] != 'E'):... |
1afc51185b6641a0a31e885ae1d138e79ab737b9 | Jyldyzbek/P2Task6 | /task-6.py | 153 | 3.53125 | 4 | a = input("Ведите число:")
b = a * 10
c = list(b)
print(c[9:10])
# a = input()
# b = list(a)
# c = b[0] + b[1]
# print(int(c))
# # print(b) |
37d6fcc9daf7a28802ba11626c9a4b3cf8726bba | amyyto/MapQuest | /user_main.py | 1,884 | 3.984375 | 4 | ### Amy Vo 29305960 Project 3 Lab 2 ###
#Taken from Project 3 Directions#
#This program will describe a trip taken between a sequence of locations,
#the goal being to travel from the first location to the second, then from
#the second location to the third, and so on, until reaching the last location.
#Based on the us... |
d283621c19e18f8edeb3892d4e15884fc1714d4a | jsanjose-sfsu/Project2HandWriting_SVD | /main.py | 7,758 | 3.890625 | 4 | from typing import List
import numpy as np
import matplotlib as mat
def informationListConversion(set, labels):
"""
This is for formatting our information into lists so we can
manipulate the data into matrices.
:param set: this is the string-ified version of the set
:param labels: this is the str... |
f373ad2ac5715752c59d43d874a630fb07c79e53 | Aiyane/Bytecode | /test.py | 240 | 4.0625 | 4 | #!/usr/bin/env/python3
# -*- coding: utf-8 -*-
# test.py
c = True
a = 2
b = 5.5
d = a + b * a // 2 - 1
print(a - b)
print(a + b)
print(a * b)
print(a // b)
print(a / b)
print(a % b)
print(b ** a)
if c:
a = 3 + b
else:
b = d + 2
|
e95af055e1d7cadec9a943c8053b9cf50d74a048 | RebeccaMariahDEV/luiza_labs_python | /classe.py | 2,820 | 3.71875 | 4 | """
func_1 = Funcionario()
func_1.nome = "Leia"
func_1.sobrenome = "Organa"
func_1.email = "leia@rebeliao.com"
func_1.salario = 1_000_000
print(func_1.email)
print(func_1.nome)
#Forma manual de criar
print(func1.email)
print(func2.email)
#print(f"{func1.nome} {func1.sobrenome}")
print(func1.nomeCo... |
911635fe0aef9c5c34e23975fbdd00f18b16d8ab | RebeccaMariahDEV/luiza_labs_python | /amigos2.py | 368 | 3.515625 | 4 | from random import shuffle
amigos = ["Dani", "Mussi", "Becca", "Cacau", "Nescau", "Chewie", "Luke"]
shuffle(amigos)
for index in range(len(amigos)):
comprar = index
receber = index+ 1
try:
print(f"{amigos[comprar]:>8} --Tirou--> {amigos[receber]}")
except IndexError:
print... |
ff104a42ccf66a05063ba01872680dc7760804cb | Palmerlxp/lxf_learn | /s3.py | 973 | 3.796875 | 4 | #构造一个1,3,5....,99的列表,可以通过循环实现
L=[]
n=1
while n<=99:
L.append(n)
n=n+2
print('list(L)=',L)
def calc_sum(*args):
ax = 0
for n in args:
ax = ax + n
return ax
print(calc_sum(1,3,5,7,9))
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
re... |
6a5970ff01a3a08cdd25c8f6358aeb948c556151 | Palmerlxp/lxf_learn | /special_str.py | 1,434 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self,name):
self.name=name
def __str__(self):
return 'Student object (name:%s)'%self.name
__repr__=__str__
print(Student('Michael'))
class Fib(object):
def __init__(self):
self.a,self.b=0,1
... |
7ae4b8e3485df6a76e0fbd3a931c119e698e04f0 | Palmerlxp/lxf_learn | /s2.py | 562 | 4.125 | 4 | height=input('身高:')
weight=input('体重:')
h=float(height)
w=float(weight)
bmi=w/(h*h) #bmi=w/h**2 另一种平方的写法
if bmi<18.5:
print('过轻')
elif bmi>18.5 and bmi<25:
print('正常')
elif bmi>25 and bmi<28:
print('过重')
elif bmi>28 and bmi<32:
print('肥胖')
else:
print('严重肥胖')
#other way
height=1.75
weight=80.5
BMI... |
60c1eff37bb984a529b3e7e120f4abe14d73421d | sienning/algojour1-ENG | /tri/merge_sort.py | 1,591 | 3.765625 | 4 | # ENG Léna
# Merge sort
import sys
import time
start_time = time.time()
listeDep = []
nbComp = 0
nbIteration = 0
def is_int(value):
try:
int(value)
return True
except:
return False
def convert(str):
liste = str.split(';')
for i in liste:
if is_int(i):
listeDep.append(int(i... |
e7c605e605ab8e094acd62a9656edfce3e9c9512 | ruihaoliu2001/Python_Learning_GiraffeAcademy | /learning_5_numbers.py | 476 | 3.828125 | 4 | from math import * #floor 等函数
print(2.945)
print(-3.5)
print(3+4)
print(3/4, 3*4) # note that ',' means a whitespace between two same types
print(4/3+15,"\n")
print(10 % 3)
my_num = -5
print(my_num)
print(str(my_num) + " is my favorite") # convert number into string, 数字+字符串不被允许
print(abs(my_num)) # absolute func.
p... |
f7341ae145d5692290bdf7c2fa211f533c22747b | ruihaoliu2001/Python_Learning_GiraffeAcademy | /learning_27_Writing To Files.py | 961 | 3.859375 | 4 |
"""
employee_file = open("Reading Files_w.txt", "w")
employee_file.write("Xavi -- Football Player")
employee_file.close()
# 仅仅w会覆盖原先的文件内容,指针指向文件头部。应该用a来在文件的末尾进行添加
"""
employee_file = open("Reading Files_w.txt", "a")
employee_file.write("23Xavi -- Football Player")
employee_file.close()
#注意,如果多次运行该段程序,会出现添加同一内容在同一行多次的... |
4c243fe6117ff6cdc3f3a57a8988276fc86df194 | mohit-singh4180/python | /Taking multiple input from console.py | 1,468 | 3.921875 | 4 | #Taking input from console using split() function input().split(separator, maxsplit)
name= input()
print(name)
# type casting to string
name= str(input())
# type casting to int
abc=10
integerValue=int(abc)
print('type of abc is ',type(abc))
floatValue=float(abc)
print('type of abc is ',type(abc))
# Taking multiple... |
7b9277b29346c58baf1e8c15068bb2894ab4043d | mohit-singh4180/python | /datatypes/Dictionary.py | 1,085 | 4.59375 | 5 | #Dictionary holds key:value pair.
# Creating an empty Dictionary
Dict = {}
Dict1={"Name": "Mohit", "EMPID":122333, "test_values":[1,2,3,4,5,6,7,8,9,10]}
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict3 = dict([(1, 'Name'), (2, 'Age')])
print(Dict)
# Creating a Nested Dictionary
# as shown in the b... |
c8ded57ab8b9ccf4f5d3eff3f6c07558910adfd6 | mohit-singh4180/python | /methodcallusingmain.py | 705 | 3.65625 | 4 | import math
def Main():
num=-85
num=math.fabs(num)
print(num)
if __name__=="__main__":
Main()
#Boolean operation
print (False == 0)
print (True == 1)
#True=1 and False=0
print (True + True + True)
print (True + False + False)
num4=80 or 50 or 30 or 10 or 70 or 40
print(num4)
num5=10 and 20 an... |
ce6840467ee5ec0a8cb7748bd7441527b6fad2da | mohit-singh4180/python | /string operations/StringLogical operation.py | 645 | 4.3125 | 4 | stra=''
strb='Singh'
print(repr(stra and strb))
print(repr(stra or strb))
stra='Mohit'
print(repr(stra and strb))
print(repr(strb and stra))
print(repr(stra or strb))
print(repr(not stra))
stra=''
print(repr(not stra))
# A Python program to demonstrate the
# working of the string template
from string import Tem... |
9caa26df66ad442987a0001f543641d0ce11cce1 | Sale1996/Pattern-detection-of-eye-tracking-scanpaths | /EyePatterns/prepare_data/format_sequences.py | 2,150 | 3.5625 | 4 | # collecting all csv files from forwarded directory
import os
def collect_csv_data_collection_from_directory(path):
import pandas as pd
import os
data_collection = []
for csv_name in os.listdir(path):
csv_path = os.path.join(path, csv_name)
data_collection.append(pd.read_csv(csv_path)... |
0efd9eddc56f16c3ff37e4247e59bffaae1e95c2 | nikel4610/sparta_coding | /알고리즘공부/week4/fibo_recursion.py | 744 | 3.765625 | 4 | #input = 20 숫자가 크면 느림
#def fibo_recursion(n):
# 구현해보세요!
#if n == 1 or n == 2: #fibo_recursion(3) = fibo_recursion(2) + fibo_recursion(1)
# return 1
#return fibo_recursion(n - 1) + fibo_recursion(n - 2)
#print(fibo_recursion(input)) # 6765
input = 50 #숫자가 커도 빠름
# memo 라는 변수에 Fibo(1)과 Fibo(2) 값을 ... |
8d18d62cde219b45c9160bd43d019b7afa8a32a3 | nikel4610/sparta_coding | /알고리즘공부/week3/selection.py | 388 | 3.546875 | 4 | input = [4, 6, 2, 9, 1]
def selection_sort(array):
# 이 부분을 채워보세요!
n = len(array)
for i in range (1,n):
for j in range(i):
if array[i-j-1] > array[i-j]:
array[i-j-1], array[i-j] = array[i-j], array[i-j-1]
else:
break #시간복잡도 줄이기
return
s... |
e588700967cbb73814c1c31c07d0aef9955ffce9 | mikilauda95/software_development | /python1/solution.py | 838 | 3.71875 | 4 | # Import libraries
import sys
import string
# Initialize list
my_list=[[-1,"ciao"]]
# Read the lines
for line in sys.stdin:
for word in line.split():
# Check if it is a digit
if word.isdigit() == True:
numbers=[x[0] for x in my_list]
if word in numbers:
tmp... |
d94265f320c2adc06781f91fc5fd242f6d2bc7bb | arun04ceg/Python3.1-Compiler | /pycps/tests/tests_old/69.py | 620 | 4.09375 | 4 |
def nested_loop(var):
for i in [1,2,3,4,5]:
print(i)
try:
for j in (7,6,5,4):
print("begin inner"); print(i); print(j)
if i > 4 and j == 4:
print("raise"); raise "reached 6"
elif i < 2 and j > 5:
print("inner break"); break
elif 2 < i < 4 and j == 4:
prin... |
4c32745120cafc3c4ad324b417697d6d6f2240dd | arun04ceg/Python3.1-Compiler | /pyparse/tests/loops1.py | 131 | 3.90625 | 4 | while True: pass
while True:
return 3
while 1 == 2:
return 4
else:
x=3 if 5 else 2
for i in range(10):
return (3)
else:
pass
|
ff639e6558e6e750146d9bc4cb87efbc15030f85 | ZYZhang2016/think--Python | /chapter06/Exercise6.3.py | 199 | 3.984375 | 4 | #coding:utf-8
import math
def is_between(x,y,z):
'''计算是否x<y<z
x:数1
y:数2
z:数3
return:返回布尔值
'''
if x<y<z:
return True
else:
return False
print is_between(3,6,5) |
dfcbe481b4493b91ef2d7577be0ec645f5ba9a72 | ZYZhang2016/think--Python | /chapter17/Exercise17.2.py | 577 | 3.8125 | 4 | # coding:utf-8
class Point():
'''a 2-d point
'''
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return '{},{}'.format(self.x, self.y)
def __add__(self, other):
if isinstance(other, tuple):
return self.x + other[0], self.y + oth... |
792fb5a5e0485f2f278d15290bbb7058d236ba7f | ZYZhang2016/think--Python | /chapter06/Exercise6.5.py | 239 | 3.53125 | 4 | #coding:utf-8
import math
def ack(m,n):
'''计算Ackerman公式
m:数1
n:数2
return:返回计算值
'''
if m==0:
return n+1
elif m>0 and n==0:
return ack(m-1,1)
elif m>0 and n>0:
return ack(m-1,ack(m,n-1))
print ack(3,4)
|
7764effac0b95ad8f62b91dd470c1d0e40704a7d | YogaVicky/NewsApp | /imageurl.py | 1,521 | 3.8125 | 4 | ''' tk_image_view_url_io.py
display an image from a URL using Tkinter, PIL and data_stream
tested with Python27 and Python33 by vegaseat 01mar2013
'''
import io
# allows for image formats other than gif
from PIL import Image, ImageTk
try:
# Python2
import Tkinter as tk
from urllib2 import urlopen
except... |
ea291fcdc704b8133b4b0ef66f3883c251776399 | gonegitdone/MITx-6.00.2x | /Week 5 - Knapsack and optimization/L9_Problem_2.py | 1,897 | 4.15625 | 4 | # ==============L9 Problem 2 =================
'''
L9 PROBLEM 2 (10 points possible)
Consider our representation of permutations of students in a line from Problem 1. In this case, we will consider a
line of three students, Alice, Bob, and Carol (denoted A, B, and C). Using the Graph class created in the lecture,
we c... |
38829c600a52bf5e486d20efb568254283f46f36 | patezno/ejercicios-propuestos | /ejercicio06.py | 865 | 4.25 | 4 | # Escribe un programa que pida por teclado dos valores de tipo numérico
# que se han de guardar en sendas variables. ¿Qué instrucciones
# habría que utilizar para intercambiar su contenido? (es necesario utilizar
# una variable auxiliar). Para comprobar que el algoritmo ideado es correcto,
# muestra en pantalla el ... |
f51a0370e1f47d29023c422f3e68374c73c658fa | patezno/ejercicios-propuestos | /ejercicio03.py | 380 | 3.921875 | 4 | # Repite el ejercicio 2 utilizando una constante que represente el valor de PI.
import math
radius = eval(input("Escribe el radio de una circunferencia: "))
num_pi = math.pi
long_circum = 2 * num_pi * radius
circle_area = num_pi * (radius ** 2)
print("La longitud de la circunferencia es " + str(long_circu... |
42b80812e0ab3b02bd7f71891647c4dfd671c84f | dpetz/codility | /bit_util.py | 567 | 4.0625 | 4 | def is_power_of_2(n):
"""" https://stackoverflow.com/questions/57025836/check-if-a-given-number-is-power-of-two-in-python """
return (n & (n-1) == 0) and n != 0
def next_power_of_2(x):
""" https://stackoverflow.com/questions/14267555/find-the-smallest-power-of-2-greater-than-n-in-python """
return 1 i... |
a05b26542169a4cb883d87c62baee613856ece9d | CallieCoder/TechDegree_Project-1 | /01_GuessGame.py | 938 | 4.125 | 4 | CORRECT_GUESS = 34
attempts = [1]
print("Hello, welcome to the Guessing Game! \nThe current high score is 250 points.")
while True:
try:
guess = int(input("Guess a number from 1 - 100: "))
except ValueError:
print("Invalid entry. Please enter numbers as integers only.")
else:
if guess < 1 or guess > 100:
... |
8ce052ff392939b106f2689351359e7c1d621019 | va1337/Ozon-newskills-Python | /Ozon/lesson_11/professor.py | 1,408 | 3.71875 | 4 | # Задание №3
import random
class Person:
def __init__(self, surname, name):
self.surname = surname
self.name = name
def __str__(self):
return(f'{self.name} {self.surname}')
class Student(Person):
def __init__(self, surname, name, course_name, marks):
self.surname = surname
... |
3f99b3aa407ffe6f7374b133e8c5d5d44ce54f36 | va1337/Ozon-newskills-Python | /Ozon/lesson_11/class_naslednik.py | 796 | 3.546875 | 4 | # Задание №2
class Person:
def __init__(self, surname, name):
self.surname = surname
self.name = name
def __str__(self):
return(f'{self.name} {self.surname}')
class Student(Person):
def __init__(self, surname, name, group_number, marks):
self.surname = surname
self.... |
28b749e2ea944bcd4e56112453fd2b9836da0cca | amrfekryy/daysBetweenDates | /daysBetweenDates.py | 1,800 | 4.375 | 4 | # Given your birthday and the current date, calculate your age
# in days. Compensate for leap days. Assume that the birthday
# and current date are correct dates (and no time travel).
# Simply put, if you were born 1 Jan 2012 and todays date is
# 2 Jan 2012 you are 1 day old.
def isLeapYear(year):
"""returns T... |
b1545d03a2ae61fa8c7858f14183f60ff9ff4493 | joshp123/Project-Euler | /4.py | 460 | 4.21875 | 4 | def isPalindrome(string):
if string == string[::-1]:
return 1 # string reversed = string
else:
return 0 # not a palindrome
palindromes = []
for num1 in xrange(999, 100, -1):
for num2 in xrange(999, 100, -1):
product = num1 * num2
if isPalindrome(str(product)) == 1:
... |
5da058b165afd4f385ade8342eaaa56e00c19e77 | sfvitor/monitoria | /processo_selecao/prova/q1.py | 2,375 | 4.1875 | 4 | # Prova de Monitoria para Fundamentos da Computacao
# Questao #1
# Aluno: Vitor Fernandes
# caso o numero seja triangular, retorna os 3 inteiros positivos
# consecutivos que, multiplicados, sao iguais ao numero informado
# caso contrario, retorna None
def numero_triangular(numero):
# loop percorrendo todos os inte... |
56047603fc21b9ffdd67201dca22b193ab4ed6a6 | JagVerches/Repository---Verches- | /Assignment - Handling Files/205338_VERCHES_RICARDOHERNAN_HANDLINGFILES.py | 4,417 | 3.890625 | 4 | # NON-INTERACTIVE CODE CELL. YOU MAY RUN THIS CELL, BUT DO NOT EDIT IT.
# FOR DEMONSTRATION PURPOSES ONLY. DO NOT EDIT.
products = {
"americano":{"name":"Americano","price":150.00},
"brewedcoffee":{"name":"Brewed Coffee","price":110.00},
"cappuccino":{"name":"Cappuccino","price":170.00},
"dalgon... |
af83251e88f06cb350ab5e3e6f24bdfc94be0bef | hallmluke/AdventOfCode2020 | /06/day6part1.py | 477 | 3.59375 | 4 | import string
f = open("testinput.txt", "r")
lines = f.readlines()
f.close()
count = 0
questions = set()
print(string.lowercase.index("c"))
print((1 << 26) - 1)
for line in lines:
if line == "\n":
print(len(questions))
count += len(questions)
questions = set()
continue
for c... |
e805d017fb69438e5cf968288dfd77488a00246f | zjuKeLiu/PythonLearning | /GUI.py | 1,306 | 4.21875 | 4 | import tkinter
import tkinter.messagebox
def main():
flag = True
#change the words on label
def change_label_text():
nonlocal flag
flag = not flag
color, msg = ('red', 'Hello, world!')\
if flag else ('blue', 'Goodbye, world')
label.conflg(text = msg, fg = color)... |
1a2e2500ac760f7fb4641809450d4a2ed8a969f1 | Leonkruijer/test1 | /les2/les3/pe3_2.py | 175 | 3.796875 | 4 | leeftijd= eval(input ('Geef je leeftijd: '))
paspoort= input ('Nederlands paspoort: ')
if leeftijd >= 18 and paspoort == 'ja':
print ('Gefeliciteerd, je mag stemmen!') |
a0e7d34066b3d33da5d3aeb204568185049cecc2 | marisaroude/Ejercicios-Lista | /ejercicio5.py | 1,472 | 3.734375 | 4 | #Dada una lista de números enteros eliminar de estas los números primos
from lista import Lista
from random import randint
lista_num = Lista()
for i in range(10): #la cargamos
num = (randint(1,10))
lista_num.insertar(num)
def es_primo(numero): #funcion para saber si un numero es primo
cantid... |
c79fe6eb140e8634338d54285cd4f1da2a88fed4 | ayushgarg12/Python-programs | /python/checkel.py | 166 | 4.03125 | 4 | test_list = [ 1, 6, 3, 5, 3, 4 ]
for i in test_list:
if(i == 8) :
print ("Element Exists")
else:
print("element doesnot exist")
|
3bf1635c04e8ab56e756e9117ee4f32b91d68738 | ColeEdwards97/sock_chat | /sock_chat/chat_gui.py | 1,991 | 3.5 | 4 | import threading
import tkinter as tk
from tkinter import *
class chat_gui(object):
# INIT
def __init__(self, client, width=None, height=None):
self.client = client
self.tThread = threading.Thread(target=self.main_loop, args=(width, height))
self.tThread.start()
# CREATE GUI
... |
bb699830dbbd101b5e2d7c9fee4dbaeb48fbe7d6 | Nian-Jingqing/nbackexpsampling | /src/datastructure/stimulus.py | 2,810 | 3.8125 | 4 | # -*- coding: utf-8 -*-
'''
stimulus feature generator
'''
from random import shuffle, randint
from itertools import product
class stimulus_ExpSample(object):
'''
experience sampling stimulus generator
save features and generate stimuli
features: list, dictionaries of questions
'''
def __i... |
aee1047d6ea2cc00ce356bc61446feb82d96c822 | ohmyjons/Tugas-KB | /MInMax_TicTacToe/main.py | 1,430 | 3.90625 | 4 | """
Minimax implementation for Tic Tac Toe
Author: Akira Wang
"""
# Import Dependencies
from minmax import *
def main():
"""
Main function.
"""
system('cls')
human_piece = False
while not human_piece: # Originally defined as '' so it should be None
print("ORDER: X goes first, and O goe... |
5cf3479a04b352bfddb0d6467cd2925f4715ccb5 | ldumay/esiee_2020_python_apprentissage | /sceance4_1_Listes.py | 747 | 3.9375 | 4 | def rechercheDansListeNonTrie():
print("Liste Non Trié :")
a = 3
print("-> Recherché : [" + str(a) + "]")
trouve = -1
#--
demo = [4, 3, 1, 9, 12, 11, 6, 37, 28, 7]
for b in range(0, len(demo)):
if a == b:
trouve = b
# --
if trouve > -1: print("-> Trouvé : [" + str... |
8e2d6a61f496019516105ac71b5623e8958c1e79 | devkaspee/practice_BST | /AVL.py | 9,661 | 3.546875 | 4 | class Node:
def __init__(self, key, bf=0, rightChild=None, leftChild=None):
self.key = key
self.rightChild = rightChild
self.leftChild = leftChild
self.bf = bf
class BST:
def __init__(self):
self.root = None
def getNode(self, key, bf=0):
return Node(key, bf... |
79900931be8c9d61143dae63fde65b009ff6d2ca | GabrielMella/Print-Livros | /print.py | 1,210 | 3.625 | 4 | # COMO SABER AS COORDENADAS DO MEU MOUSE :
#
#import pyautogui
#print(pyautogui.position())
import pyautogui
import pyautogui as p
import time
print("[ + ] Iniciando script ...")
time.sleep(10)
# Movendo Dado para Área de click
# Primeira vez que a aplicação irá mover o mouse para a coordenada do botão de passar ... |
c324cf8203b1fd785180e61eecdf4efc8ebc279d | DimejiAre/shop_api_mongo | /common/sql_database.py | 3,128 | 3.59375 | 4 | import sqlite3
def create_item_table():
connection = sqlite3.connect("../common/shop.db")
cursor = connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS item (id INTEGER PRIMARY KEY, item_id TEXT, name TEXT,"
" description TEXT, type TEXT, quantity INTEGER, price REAL)")
co... |
46fb6e8b9e213547366014053b2419f8146102c4 | pizzaisdavid/challenges | /py/711Pricing/calc.py | 547 | 3.5 | 4 |
from itertools import combinations_with_replacement
def main():
goal = 7.98
count = 3
pool = [7.98, 1.05, 7.06, 1.25, 4.75, 3.04, 1.52, 2.0, 1.6]
combos = list(combinations_with_replacement(pool, count))
for c in combos:
add = 0
multi = 1
for n in c:
add = add +... |
330b0518f93a2b231731a8d2b0ac91dc4784c1e4 | mateusfavarin/CTR-AutoIGT | /src/imageProcessing.py | 10,481 | 3.640625 | 4 | import cv2
import numpy as np
# CTR digit constants
DIGIT_WIDTH = 13
DIGIT_HEIGHT = 22
DIGIT_MULTIPLIER = 3
DIGIT_SIZE = (DIGIT_WIDTH, DIGIT_HEIGHT)
DIGIT_SIZE_HIGH = (DIGIT_WIDTH * DIGIT_MULTIPLIER, DIGIT_HEIGHT * DIGIT_MULTIPLIER)
KERNEL = np.ones((4, 4), np.uint8)
# Color constants
BLACK = 0
WHITE = 255
GRAY = 127... |
3c68c2d01c4ca8bec96ffc090be29dbcb69ff608 | Olfi01/IndefiniteLoop | /src/text_helper.py | 1,597 | 3.71875 | 4 | """A helper class for rendering text.
Caches fonts and rendered text images to reduce load on the system when rendering stuff like menus."""
import pygame
def make_font(fonts, size):
"""Gets a font from the pygame font object. Takes a list of preferences, using the first available alternative."""
available = ... |
225bdf326fda64aa0ac88723da91488f1bf9daad | Olfi01/IndefiniteLoop | /src/image_button.py | 1,166 | 3.71875 | 4 | """Contains the image button class. Used to avoid redundant code."""
import pygame
from button import Button
class ImageButton(Button):
"""Represents a button based on an image. Used by the GUI class."""
def __init__(self, position, image, image_hovered, on_click, enabled=True):
"""Initializes a new ... |
6eac42b3de26297cfa2e50a245a03717a426b1df | sgalicia/lesson8 | /Lesson 8/problem1.py | 440 | 3.96875 | 4 | print('-' * 65)
print ('Morbid Predictions Program : ')
print()
print("Description: This program asks you for you current age and tells you the year that you will die (on average).")
age = input('What is your age today? ')
age = int(age)
print('...thinking...')
print('...thinking...')
print('...thinking...')
year = ... |
5851b0b4b7653c2e7c0357d12608491f20cf36af | reyanshgupta/Grade_12_Cbse | /q4.py | 193 | 4.09375 | 4 | a=int(input("Enter the first number: "))
b=int(input("enter the second number: "))
if a%b == 0:
print("the first number is divisible by second number")
else:
print('not divisible') |
bd6ae9d815ff47895fec0e8865a73938593491fe | codeschool-uz/type_conversion_test | /test_type01.py | 1,963 | 3.8125 | 4 | import importlib
import type01 as main
#Create a test to check if the variable 'var' is defined
def test_defined():
assert hasattr(main, 'var'), "The variable var is not defined"
#Create a test to check if the variable 'var_float' is defined
def test_float_defined():
assert hasattr(main, 'var_float'), "The ... |
1603adb378d36caaba42ea862482e4810f3591b2 | igusia/python-algorithms | /binary_search.py | 452 | 4.125 | 4 | import random
#searching for an item inside a search structure
def binary_search(search, item):
low = 0
high = len(search)-1
while low <= high:
mid = (low + high)//2 #if odd -> returns a lower number
guess = search[mid]
if guess < item:
low = mid+1 #it's not mid, so we d... |
fa6662bd01caa53e841cce3a0db429e7ca897040 | raulb98/RC-Proiect | /Concat_dict.py | 111 | 3.59375 | 4 | def concat_dict(dict):
rez = b''
for key,val in dict.items():
rez += dict[key]
return rez
|
cd70df45ab8f7635e3e4d4ae38fed02e8bab4e51 | oluyalireuben/python_workout | /session_one.py | 1,398 | 4.25 | 4 | # getting started
print("Hello, World!")
# syntax
if 5 > 2:
print("Five is greater than two")
# Variables
x = 23
y = 45
print(x + y)
a = "python "
b = "is "
c = "awesome"
print(a + b + c)
u = "I like "
j = "Codding "
k = "with python language"
print(u + j + k)
# python numbers and strings
h = "Welcome to eMobi... |
04abf6cec9e7b64edf4cc61c72969cb6749e1f98 | pass-culture/data-science | /scripts/reshape_initial_responses.py | 3,445 | 3.515625 | 4 | """
Reshape initial cultural habits responses in a pandas dataframe and save it in data/dataframe_api_responses.csv.
"""
import json
import os
import re
import pandas as pd
from typeform import Typeform
API_KEY = os.getenv("TYPEFORM_API_KEY")
FORM_ID = os.getenv("PROD_FORM_ID")
# We use the python API to retrieve d... |
f5f31049750b3ecdc4cdf5dc33ac70dcf104d331 | rajgaurav7800/python_basic_projects- | /str shufeler.py | 3,427 | 3.546875 | 4 | import random
temp = ""
x = ["Why does a light ray incident on a rectangular glass slab immersed in any medium emerges parallel to itself? Explain using a diagram.",
"A pencil when dipped in water in a glass tumbler appears to be bent at the interface of air and water. Will the pencil appears to be bent to the sam... |
83d050f2f8148e909bdc29bca0575f43f1de2b0f | neervenks/Concordia-W2020-CEBD1100 | /Weeks/Week 3/userinput_multiple10.py | 236 | 4.09375 | 4 | inp = ""
while True:
inp = input("Please enter a number >")
if inp.upper() == "Q":
break
if int(inp) % 10 == 0:
print("Number is divisible by 10")
else:
print("Number is not divisible by 10")
|
f1defe8ea2ddcff86cab846b24d8876b24f2bbff | neervenks/Concordia-W2020-CEBD1100 | /Weeks/Week 5/test.py | 76 | 3.625 | 4 | d1 = {999: "a", 888: "b"}
print(d1[888])
for x in d1.keys:
print(x)
|
27761ee89c56489e90bed5cc206230c635053103 | daniellozuz/Project-Euler | /Problem59/problem59.py | 2,201 | 3.71875 | 4 | '''
ProjectEuler
Problem 59 : XOR decryption
'''
def load_cipher():
'''Returns cipher from .txt file as a string'''
string = ''
f = open("cipher.txt", "r")
for n in f.read()[:-1].split(','):
string += chr(int(n))
return string
def encr(message, password):
'''Returns a message encrypted... |
e53961a7b9e31f375060a10f8eeb20db3b7ad3b7 | daniellozuz/Project-Euler | /Problem127/problem127.py | 4,709 | 3.625 | 4 | '''
ProjectEuler
Problem 127 : abc-hits
'''
from math import sqrt
def gcd(a, b):
'''Returns greatest common divisor of the two numbers a and b'''
if b == 0:
return a
return gcd(b, a % b)
def dpf(number):
'''Returns a set of distinct prime factors of the given number'''
factors = set()
... |
13d6c7c2aa990a99847a14c3b8533ad7a7690c43 | daniellozuz/Project-Euler | /Problem65/convergents.py | 1,563 | 3.578125 | 4 | import math
from abc import ABC
from fractions import Fraction
class Base(ABC):
def convergent(self, limit):
return Fraction(self.constant()) + self.series(self.approximation(limit))
def series(self, generator):
try:
return Fraction(1) / (next(generator) + self.series(generator))
... |
5c76b9c6331a08caf15152bd0d9d6833ec5541ff | daniellozuz/Project-Euler | /Problem203/problem203.py | 2,199 | 4.0625 | 4 | '''
ProjectEuler
Problem 203 : Squarefree Binomial Coefficients
'''
def create_pascal_triangle(size):
'''Returns representation of Pascal's triangle of the given size.'''
triangle = [[1]]
for r in range(size-1):
next_row = []
next_row.append(1)
for i in range(len(triangle[r]) - 1):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.