blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9e3760d9db3a03b823915252c567442ec1ffbf7d | HenriqueCCdA/BC_DS_Projeto2 | /Notebooks/Modulos/Funcoes_de_apoio.py | 1,286 | 3.5 | 4 | import pandas as pd
def lendo_o_df(path, head = True, tail = True):
'''
Le o dataframe
@param path - Caminho do DataFrame
@param head - Plot o head DataFrame
@param tail - Plot o tail DataFrame
@return retorna do DataFrame lido
'''
df = pd.read_csv(path,
... |
63b17ebf37d5df48485dfe53adcaf6d2e76209aa | AntonYermilov/fall-2019-paradigms | /practice1/small_tasks/functions/functions.py | 4,008 | 4.0625 | 4 | from typing import List
"""
Задание 1.
Дан массив целых чисел.
Необходимо изменить его, оставив числа из отрезка [l, r] и возведя их в квадрат.
"""
def transform_simple(arr: List[int], l: int, r: int) -> List[int]:
result = []
for x in arr:
if l <= x <= r:
result.append(x * x)
retur... |
94ac5d0fd13f94fbe58b75b971bfb4c5356d0001 | AntonYermilov/fall-2019-paradigms | /practice3/practice/entity.py | 392 | 3.875 | 4 | from abc import ABC, abstractmethod
class Entity(ABC):
def __init__(self, x: int, y: int, name: str):
self.x = x
self.y = y
self.name = name
@abstractmethod
def draw(self):
pass
class Wall(Entity):
def __init__(self, x: int, y: int):
super().__init__(x, y, 'wal... |
b6367af8a53bb82e21f79b5f15d9c1052d38630f | allanstone/cursoSemestralPython | /TareasGrupo/Juan-Manuel_martinez/fibonacci.py | 535 | 4.03125 | 4 | ##Serie de Fibonacci. Esta serie se forma de la siguiente manera:
#a1=1
#a2=1
#a3=2
#an=a(n-1)+a(n-2) para n>=3
#Una primera forma de hacerla sería
n=int(input("Dame el numero: "))
def fibonacci(n):
if n==0:
return 0
elif n==1:
return 1
else:
return(fibonacci(n-1)+fibonacci(n-2))
print(fibonacci(n))
#Una ... |
a73f1a32f84a2f6689e0b57d6d56de9c59626e3e | allanstone/cursoSemestralPython | /SegundaClase/estrWhileTrue.py | 231 | 3.96875 | 4 | ######
# Loop infinito
######
#while True:
# print("Infinito!!!")
var=1
while var==1:
num=int(input("Dame un cero para salir: "))
print("El numero es ",num)
if num==0:
break
break
print("Terminó!!")
estructuras6214@gmail.com |
a1df8a9cdc19ad71478d6233509e5f63248c00d0 | allanstone/cursoSemestralPython | /CuartaClase/conjuntos.py | 1,265 | 4.21875 | 4 | ###########
##Conjuntos
###########
#Parecidos a las tuplas pero sin elementos repetidos
numeros={1,2,2,3,4}
print(type(numeros))
#Podemos crearlos apartir de una tupla
numeros2=set((1,4,10,3))
#Operaciones con conjuntos
print(numeros-numeros2)
print(numeros|numeros2)
print(numeros&numeros2)
#longitud del conjunto... |
ddc2e553d4a2821e9448f02d1bdbf66bf9bb30b9 | allanstone/cursoSemestralPython | /TareasGrupo/Calculadora_conjuntos.py | 1,328 | 3.984375 | 4 | ##############################################
# Calculadora de conjuntos
##############################################
import os
os.system('cls')
print("Esta es una calculadora de conjuntos")
while True:
print("Los conjuntos se deben de ingresar separando cada elemento con un espacio. Ej. 1 2 3")
res1=i... |
cc7c2bbb428dea062cdb860751aa653d0dce0534 | allanstone/cursoSemestralPython | /SextaClase/objetos.py | 1,595 | 4.125 | 4 | #######
# Objetos
#######
class Persona:
#atributos de la clase
edad=0
genero=""
nombre=""
altura=0
#metodos de la clase
def caminar(self):
print("Estoy caminando!!")
def saludar(self):
print("Hola!! soy %s"%self.nombre)
def comer(self,comida):
print("Me gusta ",comida)
def cumpleaños(self):
self... |
25b2a17a7497216dfab287d5618c24e037bb76a4 | vesche/adventofcode-2017 | /day03.py | 1,008 | 3.8125 | 4 | #!/usr/bin/env python
with open('day03.input') as f:
data = int(f.read().rstrip())
coords = [(1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1)]
def part1(goal):
x = y = dx = 0
dy = -1
step = 0
while True:
step += 1
if goal == step:
return abs(x) + a... |
f0b34585144c8804e2eeab55fb75375d330c95ca | FreakyGecko/FirstStart | /Lesson02_LoopFor.py | 464 | 3.890625 | 4 | secret = 13
for Versuche in range(3):
guess = int(input("Noch " + str(3 - Versuche) + " Versuche! Rate eine Zahl: "))
if guess == secret:
print("You got it!")
break # Beenden der Schleife, wenn diese Zeile erreicht wird
# exit = Beendet das gesamte Programm, wenn die Zeile erreicht wird... |
21795ad95b4ac06113274eead8eb8ca9af593140 | xhf79/test | /贪心算法安排活动.py | 1,073 | 3.65625 | 4 | #-*- coding:utf-8 -*-
#usr!/bin/env python
def bubble_sort(s,f):
for i in range(len(f)):
for j in range(0,len(f)-i-1):
if f[j] > f[j+1]:
f[j], f[j+1] = f[j+1], f[j]
s[j], s[j+1] = s[j+1], s[j]
return s, f
def greedy_activity(s,f,n):
a = [True... |
343b8c052bf550b93ad86fd9d6424e05a7b3613b | jagan/ze-learnpythehardway | /euler/p13.py | 1,484 | 3.671875 | 4 | """
Large sum
Problem 13
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
"""
def read_numbers(filename, length, count):
try:
file = open(filename)
except IOError:
return None
numbers = []
for line in file:
line = line.strip()
if not... |
fe918dbd665c35aee81eee7cc7107bc6f4524370 | jagan/ze-learnpythehardway | /collections/collections_namedtuple.py | 650 | 4.15625 | 4 | "Named Tuple"
import collections
Student = collections.namedtuple('Student', 'name sex clazz section greet')
def say_hello(self):
print 'Hello! I am ', self.name
print 'Type of Student', type(Student)
adam = Student('Adam', 'boy', '8', 'B', say_hello)
print adam
eve = Student(clazz='6', sex='girl', section='D'... |
c091cb99d08f2f474b96f76168800add80cf2c99 | tareqobaida/LeetCode | /medium/531 Lonely Pixel I.py | 1,418 | 3.71875 | 4 | """
Given a picture consisting of black and white pixels, find the number of black lonely pixels.
The picture is represented by a 2D char array consisting of 'B' and 'W', which means black and white pixels respectively.
A black lonely pixel is character 'B' that located at a specific position where the same row and s... |
c22d638225601f6e4db7a5d3c3a5711eb83b9ca5 | tareqobaida/LeetCode | /easy/520_DetectCapital.py | 1,183 | 4.28125 | 4 | """
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in ... |
6d5642b1a8568964f9295cad18323fba23b57384 | 1drs/my-py3 | /6_operasi_komparasi.py | 1,339 | 4.0625 | 4 | # setiap hasil dari operasi komparasi hasilnya adalah boolean
# >, <, >=, <=, ==, !=, is, is not
print("--- lebih dari (>)")
a = 9
b = 7
hasil = a > b
print(a, ">", b, "=", hasil)
hasil = a > 9
print(a, ">", "9", "=", hasil)
print("--- kurang dari (<)")
a = 9
b = 7
hasil = a < b
print(a, "<", b, "=", hasil)
hasil =... |
143b9302a4a3ca47c491be4bb5b6589d8afde773 | oakejp12/Algos | /DynamicProgramming/unique_paths.py | 872 | 4.0625 | 4 | '''
A robot is located at the top-left corner of a m * n grid
The robot can only move either down or right at any point in time
The robot is trying to reach the bottom-right corner of the grid
How many possible unique paths are there?
'''
def unique_paths(m: int, n: int) -> int:
if (m == 0 and n == 0):
r... |
c83acc91eca2db811d6f8e9bde0a8ef781aebf44 | oakejp12/Algos | /DynamicProgramming/test/minimum_path_sum_test.py | 478 | 3.671875 | 4 | import DynamicProgramming.minimum_path_sum as min_path
import unittest
class Test_TestMinPathSum(unittest.TestCase):
def test_should_get_min_path(self):
A = [[1, 3, 1],
[1, 5, 1],
[4, 2, 1]]
D = min_path.calc_min_path_sum(A, 3, 3)
min_path_sum = 7 # 1 -> 3 -> 1... |
f4ec09220fea777acbca594afa431564680b88c1 | majapklm/google_python | /list_1/3.py | 129 | 3.53125 | 4 | a = [(1, 7), (1, 3), (3, 4, 5), (2, 2)]
def myfn(a):
return a[-1]
def srt (a):
return sorted(a,key = myfn)
print srt(a)
|
2823fe4bdf676f529a63ea1978e2ee6c5dc4d756 | EldarAlekhin/Test_n2 | /Script0003.py | 1,374 | 3.84375 | 4 | # Перечисление операций деления
# / обычная операция деления
#a = 10
#b = 3
#c = a/b
#print(c)
# // дление с выводом результата как целого числа без остатка
#d = 20
#e = 3
#f = d//e
#print(f)
# % деление с выводом результата как остатка
#g = 14
#h = 3
#i = g%h
#print(i)
# socks
pricesocks = 3
moneysocks = 50
... |
51c2a1d44e59283901472b9c23d97c550c0af1e1 | csy1993/PythonInterview | /python021_可变和不可变数据类型.py | 1,031 | 3.9375 | 4 | '''
@Author: CSY
@Date: 2020-01-25 12:39:31
@LastEditors : CSY
@LastEditTime : 2020-01-25 12:47:54
'''
"""
21、列出python中可变数据类型和不可变数据类型,并简述原理
"""
# 不可变数据类型
int01=1
str01="a"
tuple01=(1,2)
# 不允许变量的值发生变化,如果改变了变量的值,相当于是新建了一个对象,而对于相同的值的对象,在内存中则只有一个对象(一个地址)
print(id(int01))
int01=2
print(id(int01))
# 可变数据类型
list01=[1,2,3]
d... |
95448110bd10264dbbb840102660dc6205b6210e | mdark1001/pygen | /queens/board.py | 1,009 | 4.0625 | 4 | """
@author miguelCabrera1001 |
@date 12/12/19
@project
@name board
"""
class Board(object):
"""
Se crea una clase para representar el tablero de ajedrez,
Genes como indices de filas y columnas para representar la
úbicación de las reinas en el tablero
"""
def __init__(self, gen_... |
61be9b558d7b1ba921521324aa7ade487436019a | YunSeok-Yeo/projectEuler | /first.py | 123 | 3.78125 | 4 | list = [x for x in range(1, 1000) if x % 3 == 0 or x % 5 == 0]
total = 0;
for i in list:
total = total + i;
print total;
|
d55eb5dc867a065f2e4572dd5b92da2c7fe0d225 | nicholexsun/gwc | /gwc_2019/survey.py | 937 | 4.34375 | 4 | # Create a list of survey questions and a list of related keys that will be used when storing survey results.
survey = [
"What is your name?",
"How old are you?",
"What is your hometown?",
"What is your date of birth? (DD/MM/YYYY)"]
keys = ["name", "age", "hometown", "DOB"]
all_responses = []
done = "n... |
1657ff8a1160a510a9aa816f1adf4acdb1289708 | jasminsaromo/python_fundamentals2 | /exercise6.py | 187 | 3.984375 | 4 | print("What fahrenheit temperature would you like to convert?")
fahr = int(input())
def cels (fahr):
return (fahr - 32) * (5/9)
print("{}°F is {:.0f}°C.".format(fahr, cels(fahr))) |
b41c5884d0ddc4891fd027e2bc6d629df3138eb5 | fredcamps/playground | /python/structures/hashtable.py | 2,458 | 3.65625 | 4 | class HashTable:
def __init__(self, size=10):
self.size = size
self.keys = [None] * self.size
self.values = [None] * self.size
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.insert(key, value)
def __repr__(self)... |
ff52c3c1087e39a003bcef2cf4f5d231ad9ba590 | Mua12/Python_ | /flatten_function.py | 854 | 4.3125 | 4 | """"
Bir listeyi düzleştiren (flatten) fonksiyon yazın.
Elemanları birden çok katmanlı listtlerden ([[3],2] gibi) oluşabileceği gibi,
non-scalar verilerden de oluşabilir.
Örnek olarak:
input : [[1, 'a', ['cat'], 2], [[[3]], 'dog'], 4, 5]
output: [ 1, 'a', 'cat', 2, 3, 'dog', 4, 5 ]
"""""
sample_list = [ [1, 'a', ['c... |
a4d75726b8f63a052a23e0949fd28063ef68e326 | IDevSandy/AssignmentStarterKit_v2 | /Day2/P22.py | 345 | 3.609375 | 4 | # Template for P22
def main():
# Write your code below
# Take input, the text and the key.
# Find the number of occurrences of the key in the text.
# Print the count.
print()
# This is required to ensure that we can import your solve function without activating other parts of code
if __name__ ... |
8f7ba0280c2a6ce16b131fe523140a27b63b4574 | IDevSandy/AssignmentStarterKit_v2 | /Day1/P11.py | 604 | 4.03125 | 4 | # Template for P11
def main():
# Write your code below. Take care of indentation
# Take input for temperature in Fahrenheit. Remember to convert the type for the input from string to the required type.
# Calculate the temperature in Celsius (C) using the formula C=(F−32)×5/9. Also, round the value obtai... |
e679101ae790935c45e4a52a985fb1afa74d7ca9 | nlizanar/introduccion_python | /ejemplo_funciones.py | 911 | 3.84375 | 4 | #!/urs/bin/python
#guardar en ñla carpeta de proyecto
# las funciones en python parten con def...
def funcion_tonta(nombre):
separador =" "
print(separador.join(("hola",nombre, "eres un tonto")))
#calcular el digito veriifcador
def digito_verificador (rut_sin_digito):
digito = ""
multiplo = 0
a... |
1040135099330057ff82cf81afb951b5fd8029f7 | jamesdvance/meal_maker | /web_app/desktop-meal-maker/macro_pref.py | 395 | 3.53125 | 4 |
def macro_preferences():
# Can build this out to a 'grams of protein for 1 g of bodyweight' later
macro_perc = input("what percentage of protein, fat, and carbs do you prefer? (seperate by commas)")
split_mac = macro_perc.split(",")
if(len(split_mac) == 3):
return int(split_mac[0].strip()), int(split_mac[1].st... |
4b9b3ddf62d57b9ee00b2812b913a68a6238acbd | G-codered/Glearn | /lazy.py | 1,115 | 4.15625 | 4 | print("hello everyone!!!")
chorus=input()
print("how are you guys today?")
chorus=input()
if chorus == ("fine"):
print("that is great")
else:
print("what is the problem?")
chorus1=input()
print("hey, whats your name?")
myName=input()
print("it is great to have you here " +myName)
print("the lenght of y... |
1be79045dc262bce3d62ab1271fce6d40a381955 | GC211DS/project | /project_model.py | 13,912 | 3.6875 | 4 | """
Title: Data Science Team Project
Class: 2021-1 Data Science
Member: 201533645 배성재
201533631 김도균
201633841 LEE KANG UK
"""
# =========================== Library ===========================
### Step 1. Import the libraries
import numpy as np
import pandas as pd
from sklearn.linear_model import Linear... |
b2ea00f61fefd759153f48f509d54046f6429420 | yuanxu1990/studyday | /day28/dya28c.py | 2,193 | 3.65625 | 4 | '''
用户注册
用户 输入用户名
用户 输入密码
明文的密码进行摘要 拿到一个密码的密码
写入文件
# >>> import hashlib
# >>> md5=hashlib.md5()
# >>> md5.update('123'.encode('utf-8'))
# >>> print(md5.hexdigest())
# 202cb962ac59075b964b07152d234b70
# >>> md5.update('123'.encode('utf-8'))
# >>> print(md5.hexdigest())
# 4297f44b13955235245b2497399d7a93
经过测试发现 md5.... |
84beab1a29237e37c4d172ae9526a0f5be4d4398 | yuanxu1990/studyday | /day10/day10a.py | 1,326 | 4.3125 | 4 | """
函数
可读性强 复用性强
def 函数名()
函数体
return 返回值
所有的函数 只定义不调用就一定不执行
#先定义后调用
函数名()
返回值=函数名()
返回值
没有返回值
不写return
只写return
return None
返回一个值 结束函数 且返回返回一个值 返回的是内存地址
返回多个值 结束函数 且返回多个值 可使用多个对应变量接受 也可以使用一个变量接受 元组
参数
形参 定义函数的时候
实参 调用函数的时候
... |
17450af85b12aab7cc277fcf19d60602fb69e438 | yuanxu1990/studyday | /day03/day03.py | 1,136 | 3.640625 | 4 | '''
过犹不及 平庸懒惰的人多了 这就是现实 老祖宗的中庸之道 不是没有道理
公司不是自己的,负责好自己的那一份责任就行了,同事之间没有真正的朋友
遇到困难不是想着烦躁和逃避,这些都没有用,还不如想想需要什么样的资源去解决问题
想领导说明
'''
'''
等待用户输入内容,检测用户输入内容中是否包含敏感字符,如果存在提示有敏感字符重新输入
并且允许用户重新输入打印
'''
# lista=["n","m"]
# a=0
# while a<3:
# msg=input(">>>>")
# if msg in lista:
# print("有敏感字符,请重新输入3次机会")
# ... |
e55d1cc048663f48d850f9fb3e6be5c036829e36 | yuanxu1990/studyday | /day14/day14b.py | 1,590 | 3.5625 | 4 | '''
生成器表达式和列表推倒式
#括号不一样
#返回值不一样
列表推倒式
[每一个元素或则和元素相关的操作 for元素 in 可迭代数据类型] 遍历后挨个处理
[满足条件的元素相关的操作 for 元素 in 可迭代对象 if 元素相关的条件] 筛选条件
'''
#列表推倒式 最前边放想要放到列表的值 后边跟for循环
# egg_list=['鸡蛋%s'%i for i in range(10)]
# print(egg_list)
# #生成器表达式
# g_03=(i for i in range(10))
# print(g_03)
# for i in g_03:
# print(i)
#1... |
3b79ae81b6452896962285bb7902f7c9b178556d | yuanxu1990/studyday | /day26/day26c.py | 1,232 | 3.546875 | 4 | '''
反射
hasattr getattr deattr
'''
class teacher:
dic={'查看学生信息':'show_student','查看讲师信息':'show_teacher'}
@classmethod
def show_student(cls):
print('show_student')
@classmethod
def show_teacher(self):
print('show_teacher')
@classmethod
def func(cls):
print('sdf')
# ... |
92eaf2beacc6a2e898b0796e009ead1e1fc13c54 | gjkim44/Test | /Module05/Module05Demo/Lab5-2.py | 1,077 | 4.21875 | 4 | # 2) Add code that lets users appends a new row of data.
# 3) Add a loop that lets the user keep adding rows.
# 4) Ask the user if they want to save the data to a file when they exit the loop.
# 5) Save the data to a file if they say 'yes'
dictRow1 = {'Id': 1 ,'Name':'Bob Smith','Email':'BSmith@Hotmail.com'}
dictRow... |
28c1cf2c8e23c24d0be31bf2f45d216686b2d755 | gjkim44/Test | /Module10/Module10Demo/tes2.py | 1,394 | 3.6875 | 4 | import tkinter as tk
from tkinter import ttk
class MathProcessor():
@staticmethod
def add_values(n1, n2): return n1 + n2
class IOProcessor():
@staticmethod
def write_results(n1, n2):
text = str.format('The Sum of {n1} and {n2} is {result}\n',
n1=n1, n2=n2, result=Math... |
0f48d8a558b4b629dc2e8cccd4e94e812f9568b4 | gjkim44/Test | /Module08/Assignment08-Answers/test.py | 1,812 | 3.71875 | 4 |
class Product:
def __init__(self, ProductID, ProductName, ProductPrice):
self.ProductID = ProductID
self.ProductName = ProductName
self.ProductPrice = ProductPrice
def __str__(self):
return self.ProductID + ',' + self.ProductName + ',' + self.ProductPrice
class dataprocessi... |
510bc0c937c3fad64f62c1df99f23ce217a5cbdb | joemccall86/cap5600-project2 | /county.py | 2,183 | 3.6875 | 4 | """
/**
* Represents a county in this simulation. Each county is responsible for running their own tests,
* keeping track of the number of test kits they have, and reporting back the results.
*
* @author Joe McCall; Chris Zahuranec
* @date 4/24/2020
* @info Course CAP5600
*/
"""
from scoring_strategy import Sco... |
3cf0c9fc15d51152e04ee55fd76a45439fd915d9 | TakeshiKatada/pygame_stady | /pocker.py | 821 | 3.671875 | 4 | """
CPU3名とプレイヤー1名でポーカーをプレイするプログラム
"""
# pocker game
import pygame
import random
WIDTH = 640
HEIGHT = 480
BLACK = (0,0,0)
WHITE = (255,255,255)
YELLOW = (255,255, 0)
GREEN = ( 0,255, 0)
CARDW = 30
CARDH = 48
OUTSIDE = 999
class Cardclass(pygame.sprite.Sprite):
def __init__(self,num):
pygame.sprite.Sprit... |
70b48fed668785641a4dad9d008cb9e9419a0ce1 | camoy/gym-kidney | /gym_kidney/embeddings/embedding.py | 528 | 3.515625 | 4 | from gym import spaces
#
# Embedding is an abstract class defining the interface every
# embedding method must conform to.
#
class Embedding:
# params : Dict
# The parameters defining the embedding
params = {}
# stats : Dict
# The values to record after embedding
stats = {}
# observation_space : Space
# The ... |
4ed4d14f4dbb82f4c58a82fe646fe8bd6dde20f1 | StrongerQ/learnpy | /网络/多线程(并发)/信号量.py | 533 | 3.578125 | 4 | # BoundedSemaphore(num) 信号量也是一把锁,可以同时进多个线程(看似)
import threading,time,random
class myThread(threading.Thread):
def run(self):
if semaphore.acquire():
print(self.name)
times = random.randint(0,3)
time.sleep(times)
semaphore.release()
if __name__ == "__main__":
... |
69660c5126c714ca95abd8b4f0ab72ab2d5eba15 | AdamKatborgpy/Virtuel-assistent | /Va-Project/assistent.py | 2,971 | 3.671875 | 4 | import os
import time
import datetime as datetime
from datetime import date
print("My Name is Eli, and i am your virtuel assistent")
input("Press Enter to continue...")
global client_name
client_name = str(input("What is your name?: "))
print("Hello",client_name,"now i will be introducing you to the commands")
input("... |
d9aba0d92985b33d2f084c59bb85090876390913 | noamgand/PolyrizeTask | /MagicList.py | 755 | 3.640625 | 4 | from dataclasses import dataclass
@dataclass
class Person:
age: int = 1
class MagicList(list):
def __init__(self, **kwargs):
if len(kwargs) == 1:
age = kwargs.get('cls_type').age
super().append(Person(age))
else:
super().__init__(range(1))
def __setitem... |
6b869503123449e0c33f8a46dc1bacd4b5768e41 | Amit-iris-2020/python-code | /ex5 by me.py | 3,212 | 3.84375 | 4 | def getdate():
import datetime
return datetime.datetime.now()
fun2=input("1 for written and 2 for view:")
if fun2=="1":
fun1 = (input("Please enter \n Harry: \n Rohan: \n Hamid:\n "))
if (fun1 == "Harry"):
d1 = (input("Please enter \n 1 for Harry food: \n 2 for Harry ex:\n "))
... |
b416ea318a8fdb77186604fedd796310329b65c8 | AryamanSrii/my_first_tic_tac_toe | /game.py | 3,301 | 4.0625 | 4 | # tic tac toe
# 1 2 3
# 4 5 6
# 7 8 9
# create board
# display --> board
# global variables
# --- funnction-----
# play_game()
# display_board()
# handle_turn()
# check_won()
# change_turn()
#--------global variables------
board = [ '-','-','-',
'-','-','-',
'-','-','-',
]
# is there ... |
21edff2d802a283a0a019f3c1a6a5987696317c8 | Cloudxtreme/optimal_cdn | /placement_algorithms_unittest.py | 5,280 | 3.890625 | 4 | import unittest
from client import ClientManager
from server import ServerManager
from placement_algorithms import placement, optimal_placement
class TestPlacementAlgorithms(unittest.TestCase):
def assertNear(self, x, y, precision):
"""
assert | x - y | < precision
"""
self.assert... |
1a3b592d2f5bf0c47d30f7b07aa6ee05183db38b | lanaGV/Geekbrains | /task_1.5.py | 1,543 | 4.15625 | 4 |
def check_input(num):
if num < 0:
raise RecursionError("You put a negative number.")
else:
return num
while True:
try:
revenue = int(input("Please, enter the revenue: "))
result = check_input(revenue)
except RecursionError:
print("You put a negative number.")
... |
26255c94eba9fe74c370a9d18a8ec1405597cc70 | JohnCMitchell493/SeigeGame17 | /castle.py | 1,110 | 3.578125 | 4 | import pygame
import math
class Castle(pygame.sprite.Sprite):
def __init__(self, xcoor, ycoor, filename):
'''
Description: Initializes the Castle class
Parameters: self, xcoor, ycoor, filename - self is the default class parameter, xcoor and ycoor are the passed in coordinates, filename is the file's name
Retu... |
e14204809041426b58ff1880389c5c3b95781663 | flsing/ITI1120 | /lab3/lab 3 .py | 588 | 3.515625 | 4 | #question 1
def pay(w,h):
wh=w*h
if h>40 and h<=60:
return w*40+((h-40)*(w*1.5))
elif h>60:
return w*40+((h-41)*(w*1.5))+(h-60)*(w*2.0)
else:
return wh
#question 2
def rps(p1, p2):
rock='R'
paper="P"
scissors="S"
if (p1 is rock and p2 is scissors) or (p1 i... |
24a730a6d6ac0f019876605abe291265282c06c6 | flsing/ITI1120 | /Assignments/Assignment 4/a4_solved.py | 3,435 | 4.03125 | 4 | def read_initial_info():
''' None->(float, 2D-list)
Reads the file a4-input.txt and returns a tuple. The first element of that tuple is the limit,
the second is a 2D list called banks of a format as follows (for this particular file a4-input.txt_:
[[25.0, 1, 100.5, 4, 320.5], [125.0, 2, 40.0, 3, 85.0], ... |
cc4449207117c959d6740a6ae96fb3c59742f3a0 | flsing/ITI1120 | /Assignments/Assignment 1/a1_7970742/a1_7970742.py | 7,103 | 3.71875 | 4 | #Family Name: Felix Singerman
#Student number: 7970742
#Course: ITI 1120
#Assignment Number 1
import math
import turtle
###################################################################
# Question 1
###################################################################
def f2k(t):
return (((t-32)*5/9)+273.15)
... |
056be3410065e8f39b9b09b6834739b8192dadb8 | flsing/ITI1120 | /Assignments/Assignment 2/a2_7970742/a2_part1_7970742.py | 775 | 3.78125 | 4 | import random
def perform_test():
if (n==0):
print ("Good bye")
else:
print("This software tests you with", n, "questions .....")
print("0) Addition")
print("1) Multiplication")
am=int(input("Please make a selection (0 or 1): "))
if am == 0:
... |
35bd81b0f066443d08b42b89e84fa648075d6d68 | flsing/ITI1120 | /lab9/lab9-solutions/applications-solved.py | 5,373 | 4.09375 | 4 | '''We study algorithms
O(1) - basic operations addition/multiplication function call, accessing a set
O(log n) - bigger than O(1), but less than O(n)
O(n) - iterating over a list (of length n)
O(n^2)
'''
def element_uniqueness(L):
'''(list)->bool
Returns True if all the elements in the list are distinct... |
77ddfe6eb189d6d39de3e7da8204932e5fbe7a62 | yukisa2010/python_0502 | /lesson1.py | 204 | 3.65625 | 4 | import numpy as np
x = np.array([1,2,3])
y = np.array([2, 3.9, 6.1])
xc = x - x.mean()
yc = y - y.mean()
xx = xc * xc
print(xx, 'xx')
xy = xc * yc
print(xy)
print('a')
a = xy.sum() / xx.sum()
print(a) |
39f5c2f067976f87eb8a659f700693a965b43c6c | yukisa2010/python_0502 | /lesson4.py | 732 | 3.921875 | 4 | import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('original.csv')
df_c = df - df.mean()
print(df_c.head(3))
print(df_c.describe())
x = df_c['x']
y = df_c['y']
plt.scatter(x,y,label='y')
xx = x * x
xy = x * y
a = xy.sum() / xx.sum()
print(a)
plt.plot(x, a*x,label='y_hat',color='red')
plt.legen... |
68ebdcac283177a5f6f12ae25f1f97516047a5b5 | Upasna4/Training | /tablewithwhileloop.py | 113 | 3.625 | 4 | tb=int(input("enter table value"))
c = 0
while (c <= 9):
c=c+1
print(tb, " x ", c, " = ",tb*c)
print()
|
ac3716fee8fedba26bc347a8f971fff91146373a | Upasna4/Training | /pattern11.py | 160 | 3.875 | 4 | for i in range(1,6):
for j in range(1,6):
if(i==j or i==6-j ):
print("*",end=" ")
else:
print(end=" ")
print() |
1aee20be8f9094d97d6a4ef55ca205b0c12ed371 | Upasna4/Training | /tableinfinitytimes.py | 367 | 3.859375 | 4 | while(True):
n=int(input("enter number"))
for i in range(1,11):
print(n*i)
while(True):
n=int(input("enter number"))
for i in range(1,11):
print(n*i)
while(True):
n=int(input("enter number"))
for i in range(1,11):
print(n*i)
ch=input("continue yes or no")
if ch... |
52d8d4f59df5b80d30b8c0f193d088e548cd25de | Upasna4/Training | /libprojetct.py | 4,257 | 3.78125 | 4 | memberData = dict()
bookData = dict()
m_id = 101
b_id = 201
def repeat():
choice = input("Continue Y/N: ")
if choice == 'y':
return True
elif choice == 'n':
main_menu()
def main_menu():
print("Library Management System\n"
"1. Add Member\n"
"2. Add Book\n"
... |
46cada705d2cd1ab9f754b2bf3a9ce6d365fd71c | Upasna4/Training | /csvregister.py | 1,356 | 3.71875 | 4 | import csv
while True:
print("1.Registration\n2.Login")
choice = int(input("select option:"))
if choice == 1:
while True:
print("User Registration Page")
name = input("Enter name:")
email = input("Enter email")
password = input("Enter password")
... |
19237e8b01eab168aa67a9a6169a3902ab409317 | Upasna4/Training | /ifelse.py | 105 | 3.984375 | 4 | x=int(input("enter any number"))
y=int(input("enter any number"))
if x>y:
print(x)
else:
print(y) |
34cd14c8312b1bf303e9a3760773147be197237e | Upasna4/Training | /funcoverloading.py | 409 | 3.59375 | 4 | def add(*a): #single * se tuple bnta h
print(a)
add(1) #funcoverloading
add(1,2)
add(1,2,3)
add(1,2,3,4)
def add(*a):
c=0
for i in a:
c=c+i
print(c) #toaddelements
add(1,2,3,4)
#double astrisk
def dataDict(**a):
return a
record=dataDict(name='user',age=23... |
9f0681bc82355e229f8fc708e288e354eff55221 | Upasna4/Training | /dictpracques.py | 238 | 3.90625 | 4 | d={}
n=int(input("enter size of elements"))
for i in range(n):
key=input("enter key")
m = d.get(key)
if m == None:
val = input("enter value")
d.update({key: val})
else:
print("key already exist")
|
bf2590082c460971c585e54f7ace4cfe46ada3ff | Upasna4/Training | /charinput.py | 438 | 4.125 | 4 | ch=input("enter any character")
if (ch<='9' and ch>='0'):
print("number")
elif(ch<='z' and ch>='a'):
if(ch=='a' or ch=='e' or ch=='i' or ch=='u' or ch == 'o'):
print("Vowel")
else:
print("consonant")
elif(ch<='Z' and ch>='A'):
print("Capital Alpha")
if (ch == 'A' or ch == 'E' or ch =... |
15e029865db7f37f69b0ef9762e5ca6aae529199 | Upasna4/Training | /stringkaproject.py | 76 | 4.03125 | 4 | stringInput=input("enter a string")
print("string is: ",stringInput)
while>
|
fea6bde07261c01916af3d0227929576fbbd0817 | Upasna4/Training | /libmngtmwithfunc.py | 894 | 3.765625 | 4 | memberData = {}
bookData = {}
m_id = 101
b_id = 201
def menu():
print("Library Management System\n"
"1.Add Member\n"
"2.Add Book\n"
"3.Book Borrowing\n"
"4.Book Returning\n"
"5.Member Status\n"
"6.Book Status\n"
"7.Exit")
def memberadd():
... |
984f78056c14fa8625a168e44301ace8f5cbe5a7 | Upasna4/Training | /numberreverse.py | 67 | 3.8125 | 4 | c=int(input("enter a number"))
d=" "
for i in c:
d=i+d
print(d) |
f6902f120114efd5e328f0e478138f207dc72f3f | Upasna4/Training | /primeornot.py | 161 | 4 | 4 | n=int(input("enter a number"))
f=0
for i in range(2,n):
if (n%i==0):
print("composite number")
f=1
break
if(f==0):
print("prime") |
62aa6e0c7095dffaf91f8b61b60a949acb6993b0 | naveentnair96/machine-learning | /list.py | 210 | 4.03125 | 4 | var1=[]
var2=[1,2,3,4,5]
var3=[1,2,3,'a','b','c']
print(var1,var2,var3)
print(max(var2))
print(min(var2))
print(len(var3))
print(var2.append(6))
print(var2)
print(var2.reverse())
print(var2.pop())
print(var2)
|
56ab0ff2a675ba66e1a16fbdf394b220770b98e7 | sonibla/pytorch_keras_converter | /pytorch_keras_converter/cadene_to_tf/utils.py | 5,575 | 4.28125 | 4 |
def removeBorderSpaces(inputStr):
"""
Function that removes trailing and leading whitespaces
Argument:
-inputStr (str)
Returns:
A str of inputStr without leading and trailing whitespaces
"""
if len(inputStr) == 0:
return str()
if inputStr[0] == ' ':
return... |
bca2415aae6edaeb57a044733e31f30ab96d35a4 | srirachanaachyuthuni/Search-Algorithms | /BinarySearch/test_binary_search.py | 484 | 3.625 | 4 | # Testing the implementation of Binary Search Algorithm
import unittest
from binary_search import binary_search
class TestBinarySearch(unittest.TestCase):
def test_found(self):
array = [1,4,2,3]
x = 1
self.assertTrue(binary_search(array,x))
def test_not_found(self):
array = [4,2,5,2]
x = 6
self.assert... |
4e685ee805cff2782db0be11fb25e853e28e3aad | pedroyoung95/python20201005 | /제어문/For.py | 512 | 4.0625 | 4 | for waiting_no in range(1, 6):
print("대기번호 : {}".format(waiting_no))
starbucks = ["아이언맨", "토르", "캡틴"]
for customer in starbucks:
print("{}님, 커피가 준비되었습니다.".format(customer) )
#한 줄 for
students = [1,2,3,4,5]
students = [i+100 for i in students]
print(students)
students = ["Iron man", "Thor", "Captine"]
students... |
a20d1ac8fcabeb5db16ac9824eed7a2d9e51d146 | bob53124/Charlies-Adventure | /game2.py | 18,279 | 3.921875 | 4 | # This is a simple command-line adventure game
# Written in Python 2.7
# Don't Use this -- here for reference only
# Copyright 2012 Robert Greener
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License... |
8b8bf24fdfd2d3946b63d9b5f24dbe16e1d3452b | priyalorha/python | /life.py | 494 | 4.21875 | 4 | '''sTEST - Life, the Universe, and Everything
#basic #tutorial #ad-hoc-1
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely...
rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers ... |
969f80c0d5e69e4d905f6ec8b4968d75d1e9aabd | priyalorha/python | /bubble.py | 269 | 3.78125 | 4 | def bubble(arr):
leng=len(arr)
i=0
for i in range(0,leng):
min=arr[i]
for j in range(i,leng):
if(arr[i]>arr[j]):
arr[i],arr[j]=arr[j],arr[i]
return arr
arr=[231,23,12,65,768,32,54,12,86,89,9]
print(bubble(arr)) |
8f8142b4c50103ca18d0d2831d898dee9f06b59b | priyalorha/python | /tree.py | 1,214 | 3.90625 | 4 | class Node:
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None
class Tree(Node):
def __init__(self):
return
def root(self,value):
root=Node(value)
return root
def left(self,root,value):
if root==None:
root=Node(v... |
08cb10995c4d76adae694fb158cbdef98126f799 | terehovandrej/Zadachi_Python | /lists/middle_element.py | 702 | 4.25 | 4 | # Create a function called middle_element that has one parameter named lst.
# If there are an odd number of elements in lst, the function should return the middle element.
# If there are an even number of elements,
# the function should return the average of the middle two elements.
def middle_element (lst):
lst_... |
d19570f7ddadb6c4019b0fbaa439e9f947d1958b | slizh222/PythonProject06_02_2021 | /Hometask/home_tasks_after_2_chapter/task06.py | 1,356 | 3.96875 | 4 | # Напишите программу, которая попросит пользователя ввести величину
# покупки. Затем программа должна вычислить федеральный и региональный налог с продаж.
# Допустим, что федеральный налог с продаж составляет 5%, а региональный - 2.5%.
# Программа должна показать сумму покупки, федеральный налог с продаж, региональный
... |
a8ec984150e8746bfe2c64254f78509cb045f9e2 | slizh222/PythonProject06_02_2021 | /Hometask/home_tasks_after_2_chapter/task12.py | 1,347 | 3.703125 | 4 | #Напишите программу, которая для владельца виноградника выполняет расчеты. Данная
#программа должна попросить пользователя ввести:
#• длину гряды в метрах;
#• объем пространства, занимаемого концевой опорой в метрах;
#• объем пространства между виноградными лозами в метрах.
#V - количество виноградных лоз, которые пом... |
89597ea34bf0ac5615f1a3416e7740c9971e54b3 | rec/pyitunes | /old/pyitunes/Util.py | 130 | 3.71875 | 4 | def plural(value, name, plural=None):
if value != 1:
name = plural or (name + 's')
return '%d %s' % (value, name)
|
70cb3a16a1a3b5243e6e6d94cfc2a7042d424e56 | biwenKey/Python_study_backup | /day02/find.py | 304 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
s = "alex hello"
print(s.find('ex'))
print(s.index('ex'))
print(s[2])
print(s[0:2])
print(len(s))
print(s[0:10])
for i in s:
print(i)
start = 0
while start < len(s):
temp = s[start]
if temp == 'l':
continue
print(s[start])
start += 1
|
150f923d1add711b05a8189599001aabd4581c55 | biwenKey/Python_study_backup | /day02/dict/in.py | 308 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
user_info = {
"name":"jinbiwen",
"age":27,
"shengao":170,
"dizhi":"青浦区,罗家四队"
}
ret = 'wocao' in user_info.keys()
#print("age"in user_info.keys())
if ret == True:
print("this is a True")
else:
print("wocao,this is False")
|
4dcfdf5d976a423ec094a1542ceb8670ddee568a | biwenKey/Python_study_backup | /day02/dict/enumerate.py | 275 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
while True:
li = ["电脑","鼠标垫","U盘","游艇"]
for key,item in enumerate(li):
print(key,item)
inp = input("请输入商品:")
inp_num = int(inp)
print("您的选择为:",li[inp_num])
|
72561b40eca2590f3516aa6041081da15a0400ef | biwenKey/Python_study_backup | /day02/dict/enumerate02.py | 339 | 4 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#让enumerate默认从1开始:
li = ["电脑","鼠标垫","U盘","游艇"]
for key,item in enumerate(li,1):
print(key,item)
#inp = input("请输入商品:")
#inp_num = int(inp)
#print(li[inp_num - 1])
#根据元素找索引
inp = input("请输入内容:")
ret = li.index(inp)
print(ret)
|
8c9888082e45f71fdbb20bdad5a625d074f6bca0 | biwenKey/Python_study_backup | /day03/s3.py | 106 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
name = "李露"
print(len(name))
for i in name:
print(i)
|
586b24c22510812fb27a641c486c6a205860bb55 | biwenKey/Python_study_backup | /day02/tuple/for_tuple.py | 172 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
name_tuple = ("eric","alex","jinbiwen")
for i in name_tuple:
if i == "alex":
#continue
break
print(i)
|
e87af7fd84958212474dba9b884dcf506efd1eb1 | S-Hawks/game-of-chance | /game of chance.py | 4,058 | 3.828125 | 4 | import random
money = 100
#Write your game of chance functions here
#coin_flip
def coin_flip(guess, bet):
#cheaking balance and validity
if bet == 0:
print("Bet mustn't be Zero")
return 0
if bet > money:
print("Insifficient Balance")
return 0
if (guess != "Head") and (guess... |
a4ce1f0dea39944f097ad5851fd7605d385570d9 | zirfuz/python_alg_str | /lesson_5/task_2.py | 2,939 | 3.703125 | 4 | # 2. Написать программу сложения и умножения двух шестнадцатеричных чисел.
# При этом каждое число представляется как массив, элементы которого это цифры числа.
# Например, пользователь ввёл A2 и C4F.
# Сохранить их как [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’] соответственно.
# Сумма чисел из примера: [‘C’, ‘F’, ‘1’], ... |
c248a126227788118d6496b610f4072ebc4790bb | llenita/data_analysis | /hw4python_KorepinaY_Fib.py | 216 | 3.75 | 4 | f1 = 1;
f2 = 1;
n = int(input())
if n < 1:
quit()
elif n = 1 or n = 2:
print("1")
quit()
else:
for i in range(2, n):
fn = f1+f2
f1=f2
f2=fn
print(fn)
|
b96d3e052fbb7bb50b312c57d3da905abf8ffd21 | entuapi/entu | /tests/unittests/add_properties_in_list_test.py | 3,999 | 3.546875 | 4 | import unittest
import urllib
import sys
import json
from sqlalchemy import *
"""
Test for controlling validity of creating many new properties at a time by giving them in list in JSON format.
--HELP
How to use:
1) Firstly, create text file. This text file will be used to read
values that you want ... |
cb586efea71d6a464e84d6608ebb7386e61970fe | karlamagueta/pablito | /exercicio1.py | 178 | 3.5 | 4 | #pgm que calcula a media de uma listaaaaaaaaa :D
numeros = list(range(0,100))
def media(numeros):
media = sum(numeros)/len(numeros)
return media
print (media(numeros)) |
7316704420a6029ed5a3fc056b6bf2364a38b11e | Huangwenchao97/networking | /Chapter2/SMTP/SMTP.py | 1,963 | 3.65625 | 4 | # 创建一个向任何接收方发送电子邮件的简单右键客户
# 1.与邮件服务器创建一个TCP连接
# 2.使用STMP协议与邮件服务器进行交谈
# 3.经该邮件服务器对接收方发送一个电子邮件报文
# 4.关闭TCP连接
from socket import *
def receiveFromServer():
msg = clientSocket.recv(1024).decode()
print(msg)
return msg
# qq邮箱SMTP服务器,端口25
serverName = 'smtp.163.com'
serverPort = 25
# 需要在内容开始部分加msg, 在结束部分加e... |
e7ed9e3649730f18b9c77b57aa25ce3bd8d44c72 | xmc186/MyDemos | /Python/ConstellationInfo/Weather/weather.py | 2,836 | 3.546875 | 4 | import heweather
import weatherquery
from urllib import quote
apiKey = '7a9c88f9af7b5b6f835968c1c60de8a8'
cityName = '????'
cityCode = '101280601'
cityPintYin = 'shenzhen'
weatherInfo = heweather.getWeather(apiKey,cityPintYin)
if(weatherInfo):
weatherNow = heweather.getWeatherNow(weatherInfo)
if(weatherNow an... |
0f2da5b532c12d7350993b1f6bd40df68f8a8bf2 | cancanomar/python-wordsearch-maker | /wordsearchmaker.py | 2,551 | 3.765625 | 4 | import random
import string
from pprint import pprint #creates a visual interface for application
handle = open("wordlist.txt") #Linux dictionary of words. included in text file
words = handle.readLines():
handle.close()
words = [
random.choice(words).replace("'",'').strip() \
for _ in range(5)
] #takes 5 ... |
510bb98873274b07d4cee9f9428cec4a59366c97 | arracinim/Chess | /piece.py | 5,670 | 3.8125 | 4 | import random
class piece(object):
def __init__(self, tipoFicha):
"""
Inicializamos la ficha en una pocisión generica 0,0
"""
self.tipo = tipoFicha
self.position = (0,0)
def setPosition(self):
"""
Esta función selecciona una pocisión al azar para una... |
d2aa29295f945fabd59195ff4a3690350d6ef423 | guilherme-pombo/PhilosophyLSTM | /create_word2vec.py | 1,442 | 3.625 | 4 | # -*- coding: UTF-8 -*-
from __future__ import print_function
import gensim
from utils import load_text
class VectorCreator:
def __init__(self, source, bigrams=False):
"""
Construct a vector creators class to generate the word2vec vectors for a given source text
:param source: The text t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.