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 |
|---|---|---|---|---|---|---|
e228b782db4838198e427414a3ecbb228af4e6b0 | ga02/kmove_python | /basic/taja_game2 copy.py | 2,156 | 3.5625 | 4 | import random, time
word = ['cat','cute','maple','critics']
n = 5
rank = {}
def sortV(x) : #받은 딕셔너리값(,)중 두번째꺼로 정렬
return x[1]
while True :
print('1.문제불러오기 2.타자게임 3.등수 출력 4.저장 5.등수불러오기 6.문제입력')
menu = input('메뉴를 선택하세요\n')
if menu == '1' :
f = open('basic/test.txt','rb',encoding='utf8')
... |
d0309836ac1fc9f5123f1f2a671e6ddc5e18a5ac | ga02/kmove_python | /basic/def_test.py | 1,135 | 3.71875 | 4 | '''def add(a,b) : #매개변수 ab
return a + b #무조건 0개또는 1개
print(add(5,4)) #5,4 = 인수 !
c = add(1234,523)
print(c)'''
'''def add(choice,*a) :
print(type(a))
print(a)
result = 0
for i in a :
result = result + i
return result
print(add(1,3,5,7,9))
def onestar(*x) :
print(type(x))
... |
3a41d268554afd13808d2eb35158c0850cc482e2 | bevzuk/AdventOfCode2018 | /src/day05/day05.py | 845 | 3.65625 | 4 | import re
from string import ascii_lowercase
def reduce(s):
r = ""
for char in ascii_lowercase:
r += "(" + char + char.upper() + ")|"
for char in ascii_lowercase:
r += "(" + char.upper() + char + ")|"
r = r[:-1]
match = re.search(r, s)
while match is not None:
s = re.s... |
a518906d0c0a063d7b67eef59018f932e33a7be9 | derekduan1028/hm_python | /part3/08_面向对象基础/hm_07_del_方法.py | 515 | 3.515625 | 4 | #!/usr/bin/python
#coding:utf-8
"""
@author:derek
@contract:derek_duan@sina.com
@file: hm_07_del_方法.py
@time: 2020-10-10 09:57
"""
class Cat:
def __init__(self,vName):
self.name = vName
def eat(self):
print("%s爱吃鱼" % self.name)
def __del__(self):
print("%s 离开了" % self.name)
t... |
8a4b7910f8cba0812f647a4be1f8aaec00ef9adc | derekduan1028/hm_python | /part3/08_面向对象基础/hm_16_士兵突击_03_士兵开火.py | 1,526 | 3.953125 | 4 | #!/usr/bin/python
# coding:utf-8
"""
@author:derek
@contract:derek_duan@sina.com
@file: hm_16_士兵突击_03_士兵开火.py
@time: 2020-10-16 15:34
"""
class Gun:
def __init__(self, model):
# 枪的型号
self.model = model
# 子弹的数量
self.count = 0
# load bullet
def add_bullet(self, count):
... |
31ba807e2945181da429a78b5481a34fbac5baf3 | derekduan1028/hm_python | /part3/08_面向对象基础/hm_15_士兵突击_02_士兵类.py | 1,137 | 3.84375 | 4 | #!/usr/bin/python
# coding:utf-8
"""
@author:derek
@contract:derek_duan@sina.com
@file: hm_15_士兵突击_02_士兵类.py
@time: 2020-10-16 15:23
"""
class Gun:
def __init__(self, model):
# 枪的型号
self.model = model
# 子弹的数量
self.count = 0
# load bullet
def add_bullet(self, count):
... |
7f462de146275b154f7c7d802605c53470f3913b | Lemniscite/Challenges-Porfole-Rangers | /28-2/Palindromical.py | 151 | 3.984375 | 4 |
# CHecking palindrome
given = input()
rev = given[::-1]
print(rev)
if given == rev:
print("Palindrome")
else:
print("Not a Palindrome")
|
2852c0144c3cdbcb273772fa12071d60ee5f890d | michel-orozco/AID1 | /ejercicios1/ejercicio3.py | 320 | 4.0625 | 4 | # For númerico
for x in range(10):
print(x+1)
for x in range(5, 11):
print(x)
for x in range(5, 11, 2):
print(x)
# While
i = 1
while i<6:
print(i)
i+=1
# Uso de break
i = 1
while i<6:
if i==3:
break
print(i)
i+=1
for x in range(10):
if x>5:
break
print(x+1)
|
9fa0adcbf767d85a35502a858ef91197d93a0125 | mandypar/Python-Coursework | /PythonCode/Assignment2_3.py | 303 | 3.921875 | 4 | try:
hrs = raw_input("Enter Hours:")
h = float(hrs)
rate = raw_input("Enter Hourly Rate:")
r = float(rate)
except:
print "Error, please enter numeric input"
ovr = r * 1.5
if h > 40 :
oh = h - 40
h = 40
p = (h * r) + (oh * ovr)
print p
else :
p = h * r
print p |
8b52fc4dc8d469ff95986dd77663c1fe0dd5a01d | t1bl3r/-Discrete-Structures-and-their-Applications | /Truth Tables/PA1.py | 3,905 | 3.703125 | 4 | # CS220 - Programming Assignment 1 : Boolean Logic
# author - Asa Ben-Hur and Nirmal Prajapati
# NOTE:
# You must use small single letters for your variable names, for eg. a, b, c
# You may use parenthesis to group your expressions such as 'a and (b or c)'
# Implement the following four functions:
# truth_tab... |
ab4809ebb1eb52ff8d1b43fd68fa3a299ed47c69 | ScITS-Bern/ddip | /solutions/greeter_attributes.py | 393 | 3.671875 | 4 | class Greeter:
def hello(self, target="World"):
print(f"Hello, {target}!")
if hasattr(self, "name"):
print(f"My name is {self.name}.")
else:
print("I don't know my name yet.")
g = Greeter()
g.hello()
# Hello, World!
# I don't know my name yet.
g.nam... |
fbf6fcf8a0efa56f9dacfbe61f3e5a1f3897adde | ScITS-Bern/ddip | /hints/inventory5.py | 2,492 | 3.734375 | 4 | class Item:
def __init__(self, name, price, weight):
self.name = name
self.price = price
self.weight = weight
def __str__(self):
return f"{self.name} ({self.price} gold) [{self.weight} kg]"
class ContainerImmutable:
def __init__(self, name, weight_limit):
... |
c6052207cbffec4471922872d4f227cb131d5eeb | ganming1/CPO_notes | /lab1/mutable.py | 2,001 | 3.875 | 4 | class Node(object):
def __init__(self, value, next=None):
"""node constructor"""
self.value = value
self.next = next
class List(object):
def __init__(self, root=None):
self.root = root
def __str__(self):
"""for str() implementation for printing"""
return " ... |
0af44a4aa1c83f3a2528640c6a90436b402ec93b | Aquarius2020/kitorch | /nn/embedding.py | 2,518 | 3.5625 | 4 | import numpy as np
from typing import List
from ..tensor import Tensor, Edge
from ..utils import rand
from .module import Layer
class Embedding(Layer):
r"""A simple lookup table that stores embeddings of a fixed dictionary and size.
This module is often used to store word embeddings and retrieve them using i... |
66cc65c4ccaf8c6edc09166906bc9c956aa4ca3d | visonpon/Daily-coding | /maxarea.py | 384 | 3.671875 | 4 | '''
leetcode11---container with most water
solution--- use two pointers ,one start at the start place,the other at the end.
'''
class solution(object):
def maxarea(self,height):
ans = 0
l = 0
r = len(height)-1
while l<r:
ans = max[ans,min(height[l],height[r])*(r-1)]
if height[l]<height[r]... |
21e98fdcc1c25578091c94323db0fe31a6bf2a4c | visonpon/Daily-coding | /quick_sort.py | 486 | 3.59375 | 4 | '''
https://www.jianshu.com/p/2b2f1f79984e
'''
class solution(object):
def quick_sort(start,end,arr):
if star < end:
l,r = start ,end
base = arr[l]
while l < r:
while l < r and arr[r] > base:
r -=1
arr[l] = arr[r]
while l < r and arr[l] < =base:
l +=... |
6666f5822831334e7107dff0cd803a981064cbc4 | tanoshiisekai/stockrunnerservice | /tools/timetools.py | 418 | 3.640625 | 4 | # -*-coding:utf-8-*-
#
# 本代码文件用于完成日期时间方面的计算
from datetime import datetime
import pytz
def getdatetime():
"""
得到当前日期
"""
tz = pytz.timezone('Asia/Shanghai')
return datetime.now(tz).strftime("%Y-%m-%d")
def gettime():
"""
得到当前时间
"""
tz = pytz.timezone('Asia/Shanghai')
return d... |
aebd73b4f15e97b86345ee31cd6e0df8e6e57b6d | matthpn2/Library-Database-Application | /backend_database.py | 1,929 | 4.53125 | 5 | import sqlite3
class Database:
'''
SQLite database which can be viewed, searched, inserted, deleted, updated and closed upon.
'''
def __init__(self, db):
self.connection = sqlite3.connect(db)
self.cursor = self.connection.cursor()
self.cursor.execute("CREATE TABLE IF NOT EX... |
fabe8105ef29b3382566b40b2d8ad5e51cc51a74 | AndreiSystem/python_aula | /mundo01/ex025.py | 222 | 4.09375 | 4 | """
Crie um programa que leia o nome de uma pessoa e diga se ela "SILVA" no nome.
"""
nome = str(input('Digite seu nome: ').strip().upper())
verificacao = 'SILVA' in nome
print(f'Possuí Silva no seu nome? {verificacao}')
|
97bc749ebc6f382ace489e57bbe092de06e98025 | AndreiSystem/python_aula | /mundo01/ex031.py | 520 | 4.15625 | 4 | """
Desenvolva um programa que pergunte a distância de uma viagem em Km.
Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km
e R$0.45 para viagens mais longas.
"""
distancia = float(input('Digite a distância da viagem em Km: '))
print(f'Viagem de {distancia:.1f}Km.')
if distancia <= 200:
... |
2b0a51574e4288dbe1431d546a1c628e7d25e45d | AndreiSystem/python_aula | /mundo01/ex030.py | 256 | 4.09375 | 4 | """
Crie um programa que leia um número inteiro qualquer e mostre na tela
se ele é par ou impar
"""
numero = int(input('Digite um número: '))
if numero % 2 == 0:
print(f'O número {numero} é par!')
else:
print(f'O número {numero} é impar!') |
018840bac1a0cbb7a539d9a708eeb7d3a022c8d6 | AndreiSystem/python_aula | /mundo01/Modulo.py | 512 | 4.21875 | 4 | """"
**import math importa toda a biblioteca de matemática
import math
num = int(input('Digite um número: '))
raiz = math.sqrt(num)
print(f'A raíz de {num} é igual a {raiz:.2f} e se arrendoda-la resulta em {math.ceil(raiz)}')
#from math import importa somente um módulo especifico
from math import sqrt
num = int(inp... |
37ab17f40eb3540f1395d2f01dbfe80c4ce7b467 | mbeslic99/zadatak8 | /2048.py | 1,454 | 3.65625 | 4 | class Polje(object):
def __init__(self,broj=0):
self.__broj=broj
@property
def broj(self):
return self.__broj
@broj.setter
def broj(self,value):
self.__broj=value
@property
def jeBroj(self):
if self.__broj !=0:
return True
el... |
fba98b2c2775582ed3fa4dc0e16d18eeb6e7dc09 | changhoonhahn/TaxiTips | /plotting/tip_month.py | 519 | 3.78125 | 4 | '''
Plotting code for Tip as a function of month
Author(s): ChangHoon Hahn
'''
import numpy as np
import matplotlib.pyplot as plt
def plot_tip_month_cash(year):
''' Plot Tip Average Tip Percentage as a function of month for
specified year
Parameters
----------
year : Year (2011, 2012, 201... |
cf22dbf6c38af89c11d6e29c5988f653cc86d222 | sharingplay/Introduccion-a-la-programacion | /Python/Matrices/sumaDiagonal.py | 479 | 3.6875 | 4 | """Sume los valores de la diagonal de una matriz cuadrada de n*n"""
def sumaDiagonalMatriz (matriz):
if isinstance (matriz,list) and len (matriz)== len(matriz[0]):
return sacarDiagonal (matriz,0,len (matriz),0)
else:
return "Error no es una lista"
def sacarDiagonal (matriz,indice,largo,s... |
514acc07466de29f954cb0ff734384a1772592e2 | sharingplay/Introduccion-a-la-programacion | /Recursividad de pila/Listas/listaSumParImpar.py | 850 | 4.15625 | 4 | """Suma valores pares e impares de una lista"""
def suma (lista):
#if type (lista) == list, tambien verifica que lista sea de tipo lista
if isinstance (lista,list):
print "Suma pares: " , validarPar (lista)
print "Suma impares: ",validarImpar(lista)
else:
return "Error, el val... |
fffd7d4971e278419eda4bfe9abfda96dcacb45f | sharingplay/Introduccion-a-la-programacion | /Python/Recursion de Pila/Listas/sumLista.py | 437 | 4.03125 | 4 | """Suma valores de una lista"""
def suma (lista):
#if type (lista) == list, tambien verifica que lista sea de tipo lista
if isinstance (lista,list):
return suma_aux (lista)
else:
return "Error, el valor ingresado no es una lista"
def suma_aux (lista):
if lista == []:
r... |
6bf7618ce1538e6394f9aa52375cdda7e1fcc3a7 | sharingplay/Introduccion-a-la-programacion | /Python/Matrices/tarea matriz.py | 1,627 | 4.3125 | 4 |
"""multiplica los primeros numeros de una columna contra los numeros de
una fila"""
def multiplicacionMatriz(lista1,lista2):
if isinstance (lista1,list) and (lista2,list):
return matrices(lista1,lista2,0,0,0,0,[],[])
else:
return "Error"
def matrices (lista1,lista2,contCol_1,contCol_2... |
e3fa6b4763c2a6862c34cbec37e7fb992158adbb | sharingplay/Introduccion-a-la-programacion | /Proyectos y Tareas/practicaExamen3.py | 2,110 | 3.9375 | 4 | class Multiples:
def __init__(self):
pass
def table(self):
print("Ingrese un numero del 1 al 10 para ver la tabla de multiplicar")
num = int(input("-->"))
for i in range(1,11):
print (str(num)+ " X " + str(i)+" = " + str(num*i))
#.......... |
f5e2ef6ae6c3e324b1bc73e43499fd3996a2d1de | sharingplay/Introduccion-a-la-programacion | /Python/Recursion de Pila/Operaciones Numericas/SumMultip.py | 252 | 3.8125 | 4 | """Multiplicacion de una operacion dada"""
def SumMultip(num):
if isinstance (num, int) and num > 0:
return operacion(num)
else:
return "Error"
def operacion(num):
if num == 0:
return 1
else:
return (3*num-2) * operacion(num-1)
|
b7192589815f75063557c4b81f49aada75d450ca | sharingplay/Introduccion-a-la-programacion | /Python/Recursion de cola/operaciones/listaPar.py | 765 | 3.8125 | 4 | """Usando recursion de cola programe una funcion que recibe una lista y obtenga otra lista
con los numeros pares, utilizando indices."""
def listaPar (lista):
if isinstance (lista,list):
return nuevaLista(lista, len (lista), 0, [ ])
else:
return "Error"
def nuevaLista (lista, largo, indic... |
52dc4d57a30ab00db737bf8d63a3fffc0110c9f2 | ArpanMahatra1999/Inheritance | /hierarchicalInheritance.py | 294 | 3.6875 | 4 | class Parent:
def func1(self):
print("This is func1.")
class Child1(Parent):
def func2(self):
print("This is func2.")
class Child2(Parent):
def func3(self):
print("This is func3.")
ob1 = Child1()
ob2 = Child2()
ob1.func1()
ob2.func1() |
b166c8f75fb4116110c3b26d380efc81e08cad17 | njlopes/03-Quiz | /Passo 1.2.py | 221 | 3.859375 | 4 | print("No Python, como se chama uma 'caixa' usada para armazenar dados?")
resposta = input().lower()
if resposta == "variável":
print(" :)" * 100)
else:
print(" :(" * 100)
print("Obrigado por jogar!")
|
a1aae2c01e88b4bae5dc7a41404ce606f4148257 | ajmarin/coding | /leetcode/00002_add_two_numbers.py | 705 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry = 0
head = ListNode(0)
curr = head
while curr is not None:
... |
46a9afb71cc72943edb81a5934da9a8b32f869ab | ajmarin/coding | /leetcode/00025_reverse_nodes_in_k_group.py | 946 | 3.53125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if k == 1:
return head
pfirst = ListNode(0)
pfirst.next = head
... |
37fdbc8f4b412755e29a55443a936ad60ac837ed | ajmarin/coding | /leetcode/00687_longest_univalue_path.py | 748 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
self.answer = 0
def get_length(n: TreeNode) -> int:
if ... |
7aaba3838f9528e7c69777ea1470ff482ba5b4f1 | ajmarin/coding | /leetcode/00844_backspace_string_compare.py | 326 | 3.5625 | 4 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
def process(s: str):
r = []
for c in s:
if c != '#':
r.append(c)
elif r:
r.pop()
return ''.join(r)
return process(S) == proc... |
516f9b5c3e0c5e64f39a7b99afaf8c876ea3d19b | ajmarin/coding | /leetcode/00867_transpose_matrix.py | 155 | 3.515625 | 4 | class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
return [[A[i][j] for i in range(len(A))] for j in range(len(A[0]))] |
4e5d7c36099415e09ff077fba1e06bc3262950dc | samhita-alla/flytesnacks | /cookbook/core/basic/task.py | 2,089 | 4.15625 | 4 | """
Tasks
------
This example shows how to write a task in flytekit python.
Recap: In Flyte a task is a fundamental building block and an extension point. Flyte has multiple plugins for tasks,
which can be either a backend-plugin or can be a simple extension that is available in flytekit.
A task in flytekit can be 2 ... |
24ce6105e697a716c82323e4e7eea804203366cb | AdrianDel/cos2633 | /chapter2/fixed_point_iteration.py | 434 | 3.640625 | 4 | #!/usr/bin/python3
def fixed_point_iteration(g, p0, tol=0, n0=1000):
i = 1
while i < n0:
p = g(p0)
if abs(p - p0) < tol:
print(p)
return
i += 1
p0 = p
print('The method failed after N0 iteration, N0 = ', n0)
if __name__ == "__main__":
g ... |
251f4cf3e4b649230e0180803aecd6ef3c0e249d | kimchol0/Python | /range.py | 483 | 4.5625 | 5 | #遍历数字序列
for i in range(10):
print(i,end=" ")
print("\n----------")
#遍历指定区间的值
for i in range(0,20):
print(i,end=" ")
print("\n----------")
#以指定数字开始并指定不同的增量(甚至可以为负数,也叫做“步长”)
for i in range(0,10,3):
print(i,end=" ")
print("\n----------")
#负数
for i in range(-10,-100,-30):
print(i,end=" ")
print("\n---------... |
e9054f20506a72e6a7e71023a80e9fffd2cfc849 | kimchol0/Python | /high_low.py | 342 | 4 | 4 | #数字猜谜游戏
number=7
guess=-1
print("数字猜谜游戏!")
while guess!=number:
guess=int(input("请输入你猜的数字:"))
if guess==number:
print("恭喜,你猜对了!")
elif guess<number:
print("猜的数字小了。。。")
elif guess>number:
print("猜的数字大了。。。")
|
c1b9eb611c2891eb25d28d86b9bff04e7c96abf8 | manrajpannu/ccc-solutions | /ccc-solutions/2017/s2_2017b.py | 587 | 3.53125 | 4 | # Problem S2: High Tide, Low Tide
amount = int(input())
data = input().split()
def integerlist(lists):
for i in range(len(lists)):
lists[i] = int(lists[i])
return lists
data = sorted(integerlist(data))
data_lower = sorted(data[:int(amount/2)], reverse=True)
data_upper = data[int(amount/2):]
comple... |
5fe0ad7defc54cb146a4d187e0ec03c001da7b82 | manrajpannu/ccc-solutions | /ccc-solutions/2014/Triangle.py | 1,239 | 4.21875 | 4 | # Triangle
# Manraj Pannu
# 593368
# ICS3U0A
# 23 Oct 2018
firstAngle = int(input()) # input: the first angle of the triangle
secondAngle = int(input()) # input: the second angle of the triangle
thirdAngle = int(input()) # input: the third angle of the triangle
totalAngle = (firstAngle + secondAngle + thi... |
f26ba515002dce326ae0084b2f1a3da70a6fa3f2 | manrajpannu/ccc-solutions | /ccc-solutions/2018/NikkiAndByron.py | 1,552 | 3.78125 | 4 | # Nikky and Byron
# Manraj Pannu
# 593368
# ICS3U0A
# 21 Jan 2018
def Nikki(a,b,s): # Function for nikki with integer parameters: a,b,s
total_steps = 0 # records the distance from starting position
counter = 0 # records the total amount of steps taken
for i in range(s):
for i in range(a):
tot... |
a142ef8889f4d2614e038a3103062425151546e6 | vruyrk/GradeCalculator_Vruyr | /main.py | 2,592 | 3.78125 | 4 | import json
def loadSetupData():
with open('gc_setup.json') as data_file:
course = json.load(data_file)
return course["course_setup"]
def loadStudentGrades():
with open('gc_grades.json') as data_file:
student_grades = json.load(data_file)
grades = student_grades["mygrades"]
retur... |
22ba2fa557e93b942680f71d7b598c6acb356dce | nongfang55/commentFilter | /processor/ToolFunc.py | 809 | 3.53125 | 4 |
"""用于存放一些通用的函数"""
from utils.ExcelHelper import ExcelHelper
def covertListToExcelFromInput():
"""循环从的从终端读取输入,然后不断的追加到临时 Excel"""
ExcelHelper().initExcelFile(fileName='temp.xls', sheetName='sheet1')
while True:
line = input()
line = line.strip()
if line.__len__() == 0:
c... |
790b036fd87b8e76e6a41bc2737dce28fc5ef6f3 | sharifnezhad/python-workout1 | /calculator.py | 1,349 | 4.125 | 4 | import math
i='y'
while i=='y':
number_one=int(input('please enter number1:'))
Operator=input('please enter Operator: (+|-|*|/|^|radical|sin|cos|tan|cot|factorial)')
if Operator == '+' or Operator == '-' or Operator == '*' or Operator == '/' or Operator == '^' :
number_two=int(input('please en... |
8ff6b483daa74eee3ce01f7011eccdec41931dcc | alexeyvas1304/GenAlgorithm | /number_types.py | 1,851 | 4.09375 | 4 | def real(number, ret_er=False):
number_lst = list(map(str, list(range(10)))) + [".", "+", "-", "e"]
for i in number:
if i not in number_lst:
print()
print("Error: {} - не число!".format(number))
print("Повторите ввод")
if ret_er:
return "Er... |
91d4e779f3229fb2f69cab44bf5bacb1945ee80d | nicoleholly/tictactoe | /tictactoe.py | 5,648 | 3.9375 | 4 | class TicTacToe():
def __init__(self):
self.board = [['-'] * 3 for _ in range(3)]
self.player_ones_turn = True
self.quit_commands = ['Q', 'q']
self.game_over = False
# -- player methods --
def get_current_player(self):
if self.player_ones_turn:
return 1
... |
871d961154232ad57478058b1f58f6ca47c9f03f | JustinLaureano/python_projects | /python_practice/is_prime.py | 563 | 4.3125 | 4 | """
Define a function isPrime/is_prime() that takes one integer argument and
returns true/True or false/False depending on if the integer is a prime.
Per Wikipedia, a prime number (or a prime) is a natural number greater than 1
that has no positive divisors other than 1 and itself.
"""
def is_prime(num):
if num ... |
8956e46a6bd33cd33ffbed52e02951a0af8c89e3 | JustinLaureano/python_projects | /python_practice/less_than_ten.py | 300 | 4 | 4 | """
Write a function that takes a list as an input and prints all the items less
than 10.
"""
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
def print_less_than(x):
new_list = []
for item in x:
if item < 5:
new_list.append(item)
print(new_list)
print_less_than(a)
|
e84bee8c7f1151fde0a1d9be3c1bf96400ac5949 | JustinLaureano/python_projects | /python_practice/max_subarray_sum.py | 924 | 4.21875 | 4 | """
The maximum sum subarray problem consists in finding the maximum sum of a
contiguous subsequence in an array or list of integers:
maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
# should be 6: [4, -1, 2, 1]
Easy case is when the list is made up of only positive numbers and the maximum
sum is the sum of the whole arra... |
b3a5f956a4a1cc535f7c22c74b382cb9be7874b0 | andersonvieira/cogbox | /cogbox/memory/sdm.py | 3,267 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module implements a binary associative memory according to
Kanerva's Sparse Distributed Memory (1988). The two main components of
the memory are the address matrix, where each line corresponds to an
address, and the content matrix.
Given an address, the memory wi... |
01407eba6fcdf1ce6ed4de3b2c56e47476a3ebe1 | Cakarena/CS-1 | /license_exercise.py | 414 | 3.734375 | 4 | def nolicense ():
print("No license to be issued")
def license ():
print("You have passed your provisional license")
a=input("Enter your age, use integers: ")
a=float(a)
if a < 16 :
nolicense ()
if a >= 16 :
print("Great")
h=input("Enter the total number of practices hours: ")
... |
cdc81edf3115b4e79f6a6e4b76d723147e06a551 | kmjeganath/ECS_Python | /program3.py | 216 | 3.578125 | 4 | #printing variables with srings
likes = input("what do you like: ")
hates = input("what do you hate: ")
print("Jegan likes : ",likes)
print("Jegan hates : ", hates)
'''
Jegan likes : fish
Jegan hates : chicken
''' |
ea0dc1f1e004c132d7fe29412e5fa40bc4f73f9a | ebold123/cataract | /app/actions.py | 914 | 3.515625 | 4 | from typing import Optional
from typing import Text
PLAYER_ACTIONS = ['draw_two', 'peek', 'swap']
class PlayerAction:
def __init__(self, action:Text, other_player:Optional[int], my_card_id:Optional[int], other_card_id:Optional[int]):
if action not in PLAYER_ACTIONS:
raise ValueError('Invalid action')
self.a... |
54b34dab3d99b90f7a6d199212c982fd8a9305ac | youyouha/Python | /02_python/05.if嵌套.py | 433 | 3.6875 | 4 | '''
坐公交:
如果有钱可以上车,没钱不能上车 ----判断是否有钱
上车后若有空座则可以坐下,没有空座就站着 ----判断是否有空座
'''
money = 0
seat = 1
if money == 1:
print('请上车')
#判断是否能坐下
if seat == 1:
print('这有空座,坐下吧')
else:
print('就站着吧!')
else:
print('朋友跟着跑吧')
|
e84ac4e8bddb1180ff92d4776d078ad406882c19 | itspayaswini/PPA-Assignments | /pattern_matrix.py | 249 | 4.03125 | 4 | import numpy as np
l=int(input("enter the l value "))
m=int(input("enter the number of rows "))
n=int(input("enter the number of col "))
matrix=[[["*"for col in range(n)]
for row in range(m)]
for repeat in range(l)]
print(matrix)
|
dea1a14a5d21acab0295d8cf41cfc85deae87015 | itspayaswini/PPA-Assignments | /exception.py | 221 | 4.15625 | 4 | numerator=int(input("enter the numerator "))
denominator=int(input("enter the denominator "))
try:
result= (numerator/denominator)
print(result)
except ZeroDivisionError as error:
print("Division by zero!")
|
10f00e37f1c707ffffdf18b72623391c00f6109a | JeremyLau01/Neural-Network-Start | /n6 (classes to create layers).py | 2,288 | 3.75 | 4 | import numpy as np
np.random.seed(0)
# X = inputs (X is the standard for input data)
X = [[1, 2, 3, 2.5],
[2.0, 5.0, -1.0, 2.0],
[-1.5, 2.7, 3.3, -0.8]]
class Layer_Dense:
def __init__(self, n_inputs, n_neurons):
'''.randn(sample size of 4, number of neurons)
b/c e/a neuro... |
26290b8991f3f2412585d994730cd14153e63e2f | MichaelHunter-CS/Python_Projects | /Shopping_Cart.py | 16,398 | 4 | 4 | """
Name: Michael Hunter
Student Number: C19365646
Date of submission: 17th of December 2020
Compiler: PyCharm Education Edition
Operating System: Windows 10
Program Description: This program is designed for the purpose of a virtual store, where the user can basically buy any item that is available in the world. Its b... |
5db2515b14384ef59c4dc2459305b3d4f0f91853 | perfectgait/eopi | /python2/7.2-replace_and_remove/telex_encoding.py | 1,401 | 4.25 | 4 | """
Telex encode an array of characters by replacing punctuations with their spelled out value.
"""
__author__ = "Matt Rathbun"
__email__ = "mrathbun80@gmail.com"
__version__ = "1.0"
def telex_encode(array):
"""
Telex encode an array of characters using the map of special characters
"""
special_strin... |
a4329170c9650084e3a24f2f48c7a69783953752 | almir-sne/backup | /Inteligência artificial/EP1/ep1ai_almir/interface.py | 1,460 | 3.890625 | 4 | # -*- coding: latin-1 -*-
from robot import *
from state import *
# Recebe o nome do arquivo de mapa
# Devolve uma matriz de inteiros que representa o ambiente
def read_map (map_file="map1"):
map = open(map_file)
mat = []
x = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in range(0, 18)... |
433ba8db6b528c45c0f5fdae9c1d7e5b614f9abd | andrewzach/TravelingSalesperson | /inputoutput.py | 7,167 | 3.890625 | 4 | # Author: Andrew Zacharias
# Student #: D14127051
# Date: May 2015
import csv
import os
from traveldb import Airport, Country, Currency
class InputHandler:
def __init__(self, travel_db):
self.travel_db = travel_db
def airportCodeInput(self, prompt):
""" Return an airport code inpu... |
2d9b2e241a24df7fa44ce2fd51be999d07a1d40e | Vangasse/NumPyTutorial | /NumPySortSearch.py | 725 | 4.28125 | 4 | # %%
import numpy as np
import matplotlib.pyplot as plt
# %% How to get the indices of the sorted array using NumPy in Python?
a = np.array([2, 4, 8, 6, 1, 9, 5, 3, 7])
print(np.argsort(a))
# %% Finding the k smallest values of a NumPy array
a = np.array([2, 4, 8, 6, 1, 9, 5, 3, 7])
k = 3
print(np.sort(a)[:k])
# %% H... |
5f889da07acef96828787f7597a1a614d37d1eeb | kevinwilde/hackerrank | /hackerrank/data-structures/heaps/running_median.py | 1,919 | 3.921875 | 4 | ## Given an input stream of integers, you must perform the following task for each integer:
##
## 1. Add the integer to a running list of integers.
## 2. Find the median of the updated list (i.e., for the first element through the element).
## 3. Print the list's updated median on a new line.
import heapq
class ... |
2c185fd3cf00818ac18a1926690c547b013a06a6 | kevinwilde/hackerrank | /interviewbit/strings/multiplyString.py | 624 | 3.6875 | 4 | # Given two positive integers as strings, return their product as a string
def multiply(A, B):
outputs = []
for (idx,j) in enumerate(B[::-1]):
output = '0'*idx
carry = 0
for i in A[::-1]:
output = str((int(j) * int(i) + carry) % 10) + output
carry = (int(j) * int... |
7039b42db88b155544f82a1a3df525b06338fe7e | kevinwilde/hackerrank | /hackerrank/algorithms/dynamic-programming/maximum_subarray.py | 643 | 3.875 | 4 | def max_contiguous_subarray(A):
max_ending_here = max_so_far = A[0]
for x in A[1:]:
max_ending_here = max(x, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
def main():
T = int(input())
for _ in range(T):
N = int(input())
a = [int... |
119ad4562a428e59220c859b43ac0e9230176c39 | hayamiz/minipy | /testdata-parser/basics/big_list.py | 1,211 | 3.625 | 4 | def mk_list_fast(n):
L = []
i = 0
while i < n:
L.append(i) # takes O(1) time
i = i + 1
return L
def mk_list_slow(n):
L = []
i = 0
while i < n:
L = L + [ i ] # takes O(#L) time
i = i + 1
return L
def list_sum_fast... |
956a8132621441940e0aaa51b2de1838b5e1c01b | hayamiz/minipy | /pybench/full/nbody.py | 4,969 | 3.921875 | 4 | # see ../graphics/README
#
# You can run this program with native python if you uncomment the following five lines.
# ---------------- FOR NATIVE PYTHON ----------------
import sys,random
def print_string(s):
sys.stdout.write(s)
def ntv_random():
return random.randint(0, (1 << 30))
#
# ---------------- FOR mini... |
9edf45129b1218af9a70099d059375e469602626 | KelvinSajere/ud120-projects | /svm/svm_author_id.py | 1,476 | 3.578125 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("./tools/")
from email_preprocess import preproces... |
8a842f826dea5bad467e680ff4704d7853b13509 | occultism/leetcode-python | /problems/search-insert-position.py | 2,246 | 4.09375 | 4 | """
We use the concept of binary search to find the index.
`l` and `r` indicates the range we are going to search.
First, check if the target is out of range. [0]
Second, check if the target is the same at `l` or `r`. [1]
Third, we use a pivot to navigate our `l` and `r`. [2]
* If the value on the pivot is larger ... |
458ef850343fd93df8035f0f490c130299ba3127 | rockniu/Python101 | /tuple_usage.py | 151 | 3.546875 | 4 |
t1=(1,2,3,4)
print (dir(t1))
print (type(t1))
t2=(3,4,5)
t3=t2+t1
print (t3)
print (len(t3))
print (t3.count(3))
print (t3.index(5))
print (t3[1:]) |
c4d8a7398a895035637e2c36ca6c26f9a2fdf666 | gmendiol-cisco/aer-python-game | /brehall_number-guessing-game.py | 1,073 | 4.1875 | 4 | #random number generator
import random
number=random.randint(1,100)
#define variables.
TOP_NUM=100
MAXGUESS=10
guesscount=0
#game rules
print("Welcome to the Number Guessing Game...")
print("I'm thinking of a number between 1 and", TOP_NUM,". You have", MAXGUESS,"chances to figure it out." )
#collect information
... |
830e8f5959e6d5559772e7384c58dd46acbc266e | App-Dev-League/gamedev-course-jun-2021 | /Day2/Hangman.py | 3,846 | 4.03125 | 4 | import random
from Words import list_words
def get_word():
word = random.choice(list_words)
return word.upper()
def play(word):
word_completion = "_ " * len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
print("Let's play Hangman!")
print(display_hangma... |
bce3876c11b2044a7c5647a9da381874e086b5d2 | eminent0225/password_test | /password.py | 206 | 3.8125 | 4 | password = "a123456"
i = 3
while i > 0:
code = input("請輸入密碼")
if code == password:
print("登入成功")
break
else :
i = i - 1
print("密碼錯誤還有", i,"次機會")
|
a8c3f3bfecf7932dd5d1e221e910ebc603db003f | em-fong/addition-and-subtraction-drill-game | /game_functions.py | 7,563 | 4.21875 | 4 | # function: horizontal_line
# input: a width value (integer)
# processing: prints a single horizontal line of the desired size
# output: does not return anything
def horizontal_line(integer):
print("*" * integer)
# function: vertical_line
# input: a shift value and a height value (both integers)... |
dc002ed84d38f8b5d09c1f49690bf3381da5bf9f | TACC/abaco | /actors/encrypt_utils.py | 794 | 3.75 | 4 | from cryptography.fernet import Fernet
from config import Config
key = Config.get('web', 'encryption_key')
f = Fernet(key.encode())
# Encrypt the string 'value' passed in.
def encrypt(value):
# needs to be a byte string to encrypt, which is why we use .encode()
encrypted = f.encrypt(value.encode())
# aba... |
5e7d481cc7bd2dd2184f83a1bc5d585f53709de7 | Valido-101/SGE_Python | /clase_26_10_2020/Yardas_Metros.py | 170 | 3.671875 | 4 | '''
Created on 26-oct-2020
@author: maxus
'''
yardas=input("Introduzca las yardas: ")
print("\n",yardas," yardas son equivalentes a ", (int)(yardas)*0.9144," metros.") |
fa209d01a77ef44fb8d5b9064a22b8a7350e809d | Bshreyasharma/jnbk-for-Brain-Tumor-Classification | /JupyterNotebook/cnnModel.py | 2,572 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
@author: karnika
"""
#importing keras libraries and packages
#initialize (layers/graph)
from keras.layers import Sequential
#image type+basic step
from keras.layers import Convolution2D
#adding pooling layers, feature maps
from keras.layers import MaxPooling2D
#input for fully connected lay... |
a6b27f425f7600c1567effcb98d0afbb4908eed6 | mushabo101/urairajut | /uraiRajut.py | 914 | 3.765625 | 4 | def urai(huruf):
hasil = ''
for i in range(len(huruf)): #menghitung panjang karakter
for j in range(i+1):
hasil += huruf[j] #ditambahkan setiap index ke j
return hasil
def rajut(huruf):
hasil = ''
counter = 2
j = 1
while j <= len(huruf):
hasil+= huruf[j-1]
j += counter
... |
f108ad1fc937a8db395b82bdf3e98b6dcdb5c372 | mosesmaxwell/udacity-logs-analysis | /news.py | 1,420 | 3.515625 | 4 | #!/usr/bin/env python
"""Log analysis of the news articles"""
from newsdb import *
def most_popular_three_articles():
"""
What are the most popular three articles of all time
"""
logs = get_most_popular_article()
print('*******************')
print('Top three articles!')
print('********... |
63228bfd042567b34bec1469c422e4a9f9e6182f | joeinus134131/GUI_Tkinter_Python_Webinar | /example2.py | 275 | 3.796875 | 4 | import tkinter as tk
window = tk.Tk()
text = tk.Text(window)
text.pack(side="left")
scroll_y = tk.Scrollbar(window, orient="vertical", command=text.yview)
scroll_y.pack(side="left", expand=True, fill="y")
text.configure(yscrollcommand=scroll_y.set)
window.mainloop() |
c3579733c39f33466b99d31c84679efb00651b77 | Tony363/Dataquest-modules | /client_homework/assignment3.py | 5,519 | 4.6875 | 5 | # Intro to Programming Using Python - Assignment #3
# Completed by:
# Be sure to read the instructions carefully!
# 1. Create three dictionaries, each one will contain information about a particular student: Steve, Alice and Tyler
# a. Assign each dictionary to a variable – eg. steve, alice and tyler
# b. Create ... |
041ffe050a97fba474cfce090fd30bf5f7ff3a5f | Tony363/Dataquest-modules | /client_homework/chuck_norris_api.py | 1,384 | 3.65625 | 4 | import sys
import requests
import json
import pandas as pd
# url = 'https://api.chucknorris.io/jokes/random'
# def prompt_input():
# url = str(input('Please enter request:'))
# return url
# def more_jokes():
# confirmations = str(input('[Y]/n: '))
# return confirmations
# def get_joke(url):
# r... |
47520e1c7e2217d97f0f53d2b00ae2d6c6c948c5 | Laronk/Python | /Src/matrix_multiplication.py | 948 | 3.890625 | 4 | def multiply_matrixes(matrix_1, matrix_2):
row_length = 0
col_length = 0
if len(matrix_1) > len(matrix_2):
row_length = len(matrix_1)
else:
row_length = len(matrix_2)
if len(matrix_1[0]) > len(matrix_2[0]):
col_length = len(matrix_1[0])
else:
col_length = le... |
3c753584e9f473894738c44581790d4f37024d35 | Djalma447/ProgramationBasic | /Python/Exercícios/Propostos/04 - Vetores/media_pares.py | 401 | 3.734375 | 4 | N = int(input("Quantos elementos vai ter o vetor? "))
vet: [int] = [0 for x in range(N)]
for i in range(0, N):
vet[i] = int(input("Digite um numero: "))
pares = 0
soma = 0
for i in range(0, N):
if vet[i] % 2 == 0:
soma = soma + vet[i]
pares = pares + 1
if pares == 0:
print("NENHUM NUMERO ... |
a29be448e73647ffec81f3dfea6c55d4d2590e3b | Djalma447/ProgramationBasic | /Python/Exercícios/Propostos/02 - Estrutura Condicional/lanchonete.py | 365 | 3.6875 | 4 | codigo = int(input("Codigo do produto comprado: "))
quantidade = int(input("Quantidade comprada: "))
if codigo == 1:
valor = quantidade * 5.0
elif codigo == 2:
valor = quantidade * 3.5
elif codigo == 3:
valor = quantidade * 4.8
elif codigo == 4:
valor = quantidade * 8.9
else:
valor = quantidade * 7... |
53d41e839ee64ed43b50186fc2df9c59ad1742ff | Djalma447/ProgramationBasic | /Python/Exercícios/Propostos/02 - Estrutura Condicional/troco_verificado.py | 377 | 3.84375 | 4 | precoUnitario = float(input("Preço unitário do produto: "))
quantidade = int(input("Quantidade comprada: "))
dinheiro = float(input("Dinheiro recebido: "))
total = precoUnitario * quantidade
if dinheiro >= total:
troco = dinheiro - total
print(f"TROCO = {troco:.2f}")
else:
resto = total - dinheiro
pri... |
f047cd3de075fc8dcb6383a9d7b11c6b61ba3e3c | slip-slap/code | /python_code/genetic_algorithm/src/plot.py | 284 | 3.515625 | 4 | import matplotlib.pyplot as plt
def my_plot(data_x, data_y):
fig = plt.figure(111)
axes1 = fig.add_subplot(111)
axes1.plot(data_x,data_y,color='black')
axes1.scatter(data_x, data_y, color='black')
plt.show()
if __name__=="__main__":
my_plot([1,2,3],[2,1,3])
|
6d7975dbc3619247fa22c42c49800d96ed4e5dfa | slip-slap/code | /tensorflow/mnist_lower.py | 1,181 | 3.640625 | 4 | from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
testlabel = mnist.test.labels
#print(testlabel)
print(" 训练数据%d" % (mnist.train.num_examples))
import tensorflow as tf
x = tf.placeholder("float", [None, 784])
W = tf.Variable(tf.zeros([784, 10])... |
00cdc9d8758ff5522bada9a704ed230fb302d233 | VinBots/world_models | /src/rnn/train.py | 811 | 3.578125 | 4 | """
The MDN-RNNs were trained for 20 epochs on the data collected from a random policy agent. In the Car Racing task, the LSTM used 256 hidden units
"""
import numpy as np
import collections
import itertools
import torch
import torch.optim as optim
def train_lstm(model, buffer, preprocess, config, device):
... |
a7a0c0dab6e711c2dc9bad765d2217f58e2591b5 | sanskrit-lexicon/CORRECTIONS | /dhaval/alphamismatch/alphamismatch.py | 4,738 | 3.53125 | 4 | # -*- coding: utf-8 -*-
import sys, re
import codecs
import string
import datetime
"""
Usage - python alphamismatch.py
Input - sanhw2.txt
This would find out words which are not in proper alphabetic order.
"""
# Function to return timestamp
def timestamp():
return datetime.datetime.now()
def sanhw2(inputfile):
fin ... |
db2d4ef4cfe8cdc1f1b836af9fc6941ec98d5303 | jason-jc-lee/django_python | /snek.py | 2,185 | 3.625 | 4 | import random
import turtle
import time
delay = 0.2
score = 0
high_score = 0
screen = turtle.Screen()
#randomized background color
screen.bgcolor("#" + "%06x" % random.randint(0, 0xFFFFFF)
)
segment = turtle.Turtle()
segment.shape("turtle")
segment.color("#" + "%06x" % random.randint(2, 0xFFFFFF))
se... |
515f7a4759159f791b74339a2665663f569cf67e | AdegokeFawaz/RPG | /userinput.py | 467 | 4.09375 | 4 | rental_car = input("should I get you a Toyota?: ")
print(rental_car)
prompt = "If you tell us how many people in your group, we can personalize the messages you see."
prompt += "\nHow many people are in your group? "
name = input(prompt)
print(f"\nHello, {name}!")
number = input("Enter a number, and I'll tell you if it... |
87fd3e53533f12a4f71b09e391bdf8507919fb93 | xiaotwins/excel_py | /day6.py | 626 | 3.5 | 4 | # 函数填充,计算列
import pandas as pd
table = pd.read_excel('/Users/apple/Work/excel_py/day6.xlsx', index_col='id')
# table['总价'] = table['单价'] * table['库存']
# for i in table.index:
# table['总价'].at[i] = table['单价'].at[i] * table['库存'].at[i]
# for i in range(3, 8):
# table['总价'].at[i] = table['单价'].at[i] * table['... |
ded3e0219922eb6440c7901bc97a3ce4003c8a05 | leeseu95/MetodosNumericos | /Parcial1/SeungLee_P1.py | 2,320 | 4.15625 | 4 | # Seung Hoon Lee Kim - A01021720
# Examen - Parcial 1
# Pregunta 1 Manejo de inventario
# Solución escrita en Python 3
# Librerías utilizadas: random
# Librerías utilizadas: math
# Librerías utilizadas: statistics
import random
import numpy
import math
import statistics
inventory = 0
limite = 5
order = 0
costOrder ... |
b7387aa241877be12735b45f492f48bd3f89699a | leeseu95/MetodosNumericos | /Parcial2/18.py | 3,584 | 3.71875 | 4 | # Alonso Iturbe Sotomayor
# A01021621
# Problema de Tarea II #18 - Barcazas 2.0
# Solución escrita en Python 3
# Librerías utilizadas: random
# Librerías utilizadas: math
# Librerías utilizadas: statistics
# python3 barcazas.py
# Resultado ejemplo
import random
import math
import statistics
# Vectores de datos ha... |
7dd7bf560a7a8e02089b9a0f950fcfb453e9a213 | MacHu-GWU/compress-project | /compress/string_encoding.py | 6,245 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
string encoding is a technique to convert arbitrary binary data to string
based encoding binary, which is easily to represent string.
"""
import inspect
import base64
import binascii
_example_data = ("Hello World" * 1000).encode("utf-8")
class EncodingAlgorithm:
"""
Base encodin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.