blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
0b4d452a26c2b44684c2eae50ba622c56dd97f4f | kriti-ixix/python2batch | /python/Functions.py | 614 | 4.125 | 4 | '''
Functions are of two types based on input:
- Default
- Parameterised
Based on return type:
- No return
- Some value is returned
'''
'''
#Function definition
def addTwo(first, second):
#first = int(input("Enter first number: "))
#second = int(input("Enter second number: "))
third = ... |
82deb8bb0d6155e821c4c134d0b9e53a59ed7531 | kriti-ixix/python2batch | /python/Email.py | 682 | 3.546875 | 4 | import re
class Error(Exception):
pass
class EmailError(Error):
pass
class DomainError(Error):
pass
class PasswordTooShortError(Error):
pass
try:
email = input("Enter your email: ") #abc@gmail.com
listOfDomains = ['com', 'org', 'co.in', 'net']
password = input("Enter your password: ")
if '@' not in email:... |
a1d617b28ef55b1b705be2f5ada60daf3323e443 | mecosteas/Coding-Challenges | /rotated_array.py | 1,872 | 3.921875 | 4 | # O(n) time | O(1) space
def find_pivot_index(input_list):
# We have a start, end, pivot, and min_index. Start and min_index begin at first element
s = min_index = 0
e = len(input_list) - 1
# while the start and end don't meet or pass each other, we iterate
while s < e:
# pivot is calculated... |
2bbe8852b53fe5d099afbbd8a310704c04c0423b | mecosteas/Coding-Challenges | /count_words.py | 1,260 | 4.375 | 4 | """
Given a long text string, count the number of occurrences of each word. Ignore case. Assume the boundary of a word is whitespace - a " ", or a line break denoted by "\n". Ignore all punctuation, such as . , ~ ? !. Assume hyphens are part of a word - "two-year-old" and "two year old" are one word, and three differen... |
17abe34e9e04a0a5c633de9d07192d6296d30021 | mecosteas/Coding-Challenges | /max_events.py | 2,347 | 3.796875 | 4 | import heapq
"""
def maxEvents(events):
events.sort() # sort in ascending order by start time
cnt = 0 # the number of events we'll attend
event_id = 0 # think of this as the index for the event
day = 1 # start at day 1
last_day = max(d for d in events[1])
min_heap = []
while day <= last... |
b365d7ed1500d61ee8c8aa336271fb2eae8d3fd9 | emilabraham/advent-of-code-2019 | /day5/intCode.py | 1,985 | 3.65625 | 4 | import copy
#Instructions
instructions =[
1,12,2,3,
1,1,2,3,
1,3,4,3,
1,5,0,3,
2,1,9,19,
1,10,19,23,
2,9,23,27,
1,6,27,31,
2,31,9,35,
1,5,35,39,
1,10,39,43,
1,10,43,47,
2,13,47,51,
1,10,51,55,
2,55,1... |
0b1eb8b80a943a669eaf7657500a32549df76a0f | Rawleassano/Website-Picture-Text | /My Python Codes/Crypto.py | 304 | 4 | 4 | alphabet= "abcdefghijklmnopqrstuvwxyz"
def encrypt(plaintext):
ciphertext= ""
for i in range(0, len(plaintext)):
for j in range(0, len(alphabet)):
if plaintext[i]==alphabet[j]:
ciphertext+=alphabet[(j+3)%26]
print("Encrypted Message:", ciphertext) |
507e4a5ea9054c11509e8d6f678d74aa6c3f545e | sleepingsaint/DS-ALG | /DS/linkedList.py | 2,724 | 4.21875 | 4 | # defining stack element object
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
# defining stack object
class Stack(object):
def __init__(self, head=None):
self.head = head
# helper class functions
# function to add elements
def append... |
0b3708888ad00b904dac5c5c86780afeeeb20c9a | obtitus/osm_no_tunnels_bicycle | /util.py | 835 | 3.90625 | 4 | def remove_empty_values(dct):
"""Remove all dictionary items where the value is '' or None."""
for key in list(dct.keys()):
if dct[key] in ('', None):
del dct[key]
def is_name_tag(key):
"""Returns true if 'key' looks like a name tag
>>> is_name_tag('name')
True
>>> is_name_t... |
4f68439ae72982cd4b8d9fe82c21630b034fb58e | lexust1/algorithms-stanford | /Course4/04c01w.py | 3,069 | 4.1875 | 4 | # 1.Question 1
# In this assignment you will implement one or more algorithms for
# the all-pairs shortest-path problem. Here are data files describing
# three graphs:
# g1.txt
# g2.txt
# g3.txt
# The first line indicates the number of vertices and edges, respectively.
# Each subsequent line describes an edge (the ... |
24d57e7435b7a0951137a43f7d222363f289b291 | lexust1/algorithms-stanford | /Course3/03c01w.py | 5,210 | 3.890625 | 4 | # 1. In this programming problem and the next you'll code up the greedy
# Download the text file below.
# algorithms from lecture for minimizing the weighted sum of completion
# times..
# jobs.txt
# This file describes a set of jobs with positive and integral weights
# and lengths. It has the format
# [nu... |
65ba1736caf91d2e67271692f9402b9b937f8c0a | Bennables/bensiri | /listwork.py | 1,169 | 3.75 | 4 | #activity1
y=0
a=0
b=0
for sume in range(1,21):
y = y+sume
print(y)
for summ in range(1,51):
a = a+summ
print (a)
for smmm in range (1,101):
b = b+smmm
print(b)
tur = True
while tur == True:
one = int(input("Gimme Number"))
two = int(input("Gimme Number"))
tre = int(input("Gimme Number"))
f... |
813618a912922a57fba345d6d89bfc94269bb050 | Bennables/bensiri | /rockps.py | 668 | 3.90625 | 4 | continu = True
while continu == True:
p1 = int(input("1. Rock, 2. Paper, or 3. Scissors"))
p2 = int(input("1. Rock, 2. Paper, or 3. Scissors"))
if p1 == p2:
print("draw")
elif p1 == 1 and p2 == 2:
print("p2 wins")
elif p1 == 2 and p2 == 3:
print("p2 wins")
elif p1 == 3 a... |
2287950abb5b12620d20fefa13b2a8a6a12162ef | Bennables/bensiri | /gradebook.py | 227 | 3.96875 | 4 | grade = int(input("Grade (1-100):"))
if grade >= 90:
print("U get A")
elif grade >= 80:
print("U get B")
elif grade >= 70:
print("U get C")
elif grade >= 60:
print("U get D")
elif grade < 60:
print("U dum") |
8b2c75d39589bccf67594511666edd66b59051f7 | dooli1971039/Codeit | /BasicPython/ch3_1_1.py | 892 | 3.953125 | 4 | #리스트 (list)
numbers=[2,3,5,7,11,13]
names=["윤수","혜린","태호","영훈"]
print(numbers)
print(names)
#인덱싱 (indexing)
print(names[1]) #인덱스는 0번부터 시작
print(numbers[1]+numbers[3])
print(numbers[-1])
print(numbers[-2])
#리스트 슬라이싱
print(numbers[0:4]) #인덱스 3까지
print(numbers[2:])
print(numbers[:3]) #인덱스 2까지
#리스트 함수
arr=[]
print(len(... |
2c608746289af185bb2b884e2af08586cc137678 | dooli1971039/Codeit | /BasicPython/ch3_2_ex5.py | 271 | 3.765625 | 4 | numbers = [2, 3, 5, 7, 11, 13, 17, 19]
# 리스트 뒤집기
# 코드를 입력하세요.
for i in range(int(len(numbers)/2)):
tmp=numbers[i]
numbers[i]=numbers[len(numbers)-1-i]
numbers[len(numbers)-1-i]=tmp
print("뒤집어진 리스트: " + str(numbers)) |
877e94cc8ab083d7dbee0119eb5ce05f942f0888 | dooli1971039/Codeit | /BasicPython/ch3_1_ex4.py | 657 | 4.09375 | 4 | # 빈 리스트 만들기
numbers = []
print(numbers)
# numbers에 값들 추가
numbers.append(1)
numbers.append(7)
numbers.append(3)
numbers.append(6)
numbers.append(5)
numbers.append(2)
numbers.append(13)
numbers.append(14)
# 코드를 입력하세요
print(numbers)
# numbers에서 홀수 제거
num=len(numbers)-1
while num>=0:
if numbers[num]%2!=0:
de... |
9338036792282ca6497c15861e45135a6d72403b | dooli1971039/Codeit | /BasicPython/ch3_3_2.py | 383 | 3.5625 | 4 | fam={
"엄마":"김자옥",
"아빠":"이석진",
"아들":"이동민",
"딸":"이지영"
}
print(fam.values()) #value들의 목록을 보여준다.
print("이지영" in fam.values())
for i in fam.values():
print(i)
print(fam.keys())
for i in fam.keys():
vv=fam[i]
print(i,vv)
#위와 아래가 같은 내용
for i,j in fam.items():
print(i,j)
|
1efcc0eb52d7fad0956a37dfe9102b69b26cfc69 | dooli1971039/Codeit | /BasicPython/ch3_2_ex1.py | 164 | 3.890625 | 4 | numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
# 인덱스와 원소 출력
# 코드를 입력하세요.
for i in range(len(numbers)):
print(i,numbers[i]) |
6030a734dd07ed14b77934cc55104ce2585da66a | myumiguani/AI | /agents.py | 5,843 | 3.859375 | 4 | import random
import math
BOT_NAME = "INSERT NAME FOR YOUR BOT HERE OR IT WILL THROW AN EXCEPTION" #+ 19
class RandomAgent:
"""Agent that picks a random available move. You should be able to beat it."""
def __init__(self, sd=None):
if sd is None:
self.st = None
else:
... |
948c58fc91dc33d268c3680c6f560ee9de8b31a8 | MohfezRahman/Readable-Password | /ReadablePasswordGernerator.py | 526 | 3.515625 | 4 | import random
wordList = []
specialChar = ['@', '!', '#', '%', '^', '&', '*', '_', '-']
with open("paragraphForPassword.txt", 'r') as file:
data = file.readlines()
for line in data:
words = line.split()
for item in words:
if len(item) > 5:
wordList.append(item.capi... |
08455b28089a4dd2898734791e9dc072bab729c6 | germandouce/Computacion | /Tps/básico_mascaras%_y _condicionales.py | 2,316 | 4.0625 | 4 | '''
Las mascaras sirven xa "llamar" el contenido de una variable dentro de
un print o un input cuando la operacion esta hecha dentro de la misma funcion. la sintax es
%s' %variablecuyocontenidollamo (en vez de 's' va a 'f' si es un float e 'i' si es un entero)
5f%' %variablecuyocontenidolllamo (el 4 mete 4 espacios C... |
4b27504c3c898435e99261b771c4c3d30783176c | germandouce/Computacion | /Tps/tp_04_estructuras_de_datos_simples.py | 26,162 | 4.125 | 4 | #TP IV: ESTRUCTURAS DE DATOS SIMPLES
#PRIMERA PARTE: "EDICIÓN" DE TEXTO
# tipos de variables
#bool-string-char-int-float
#coercion de tipos
#int float string
'''
a=4
print('a =',a,'es un entero')
c=a/2
print('c = a/2 =',c,'es float pero a y 2 siguen siendo enteros')
d=('d')
print(... |
d5891584688ff83c60bf74fc7611c625f57b14db | Sukanyacse/Assignment_2 | /assignment 2.py | 254 | 4.1875 | 4 | numbers=(1,2,3,4,5,6,7,8,9)
count_even=1
count_odd=-1
for value in range(1,10):
if(value%2==0):
count_even=count_even+1
else:
count_odd=count_odd+1
print("Number of even numbers:",count_even)
print("Number of odd numbers:",count_odd)
|
92ff8e67eb22909831b10bfcdd1faedef658825e | Lauraparedesc/Algoritmos | /Actividades/ejercicios/exlambda.py | 1,291 | 4.25 | 4 | #Exponente n de un # dado
exponente = lambda base = 0, exponente = 0 : base**exponente
resultado = exponente (5,2)
print (resultado)
#string
string = lambda cantidad = 0 : print ('♡'*cantidad)
string (60)
#maximo #
listaEdades1 = [18,12,14,13,12,20]
listaEdades2 = [19,47,75,14,12,22]
lambdamaximos = lambda x = [], y... |
301b32d25e52c85b97af1d04b99e95e04d81c892 | Lauraparedesc/Algoritmos | /Actividades/ejercicios/exreduce.py | 925 | 3.8125 | 4 | #resta elementos lista
from functools import reduce
lista = [85,22,18,19,14,12,8]
restar = lambda acumulador = 0, elemento = 0: acumulador - elemento
resultado = reduce (restar,lista)
print (resultado)
#devolver frase
palabras = ['Hola','buenos','días']
unir = lambda palabras, frase: palabras+' '+frase
resultado1 = re... |
40f9dd03d16b4af8f58e7addc627029819bd532f | mishindmitry/intern | /3stage/xrange.py | 440 | 3.640625 | 4 | """Реализация xrange"""
def my_xrange(start=0, stop=None, step=1):
"""Реализация xrange"""
if stop is None:
start, stop = 0, start
while start > stop if step < 0 else start < stop:
yield start
start += step
for k in my_xrange(10):
print(k, end=' ')
print('\n')
for k in my_xr... |
a42d880d9f805d287b387982a6626cfa097605d6 | PPPy290351/FromZeroToPy | /typeForce.py | 772 | 4.0625 | 4 |
num1 = 12 + 2.7
print( num1 ) #//Key:(integer->floating) + floating = floating
num2 = 22 + True
print( num2 ) #//Key:True->1 + 22 =
#//@In some case, the type couldn't be transformed automatically, so need manually to override
#// @int()
#// @float()
#// @str()
try:
num3 = 32 + "132"
except:
print( 'see! I... |
e5e9b39c53c7953ab8ff3557f0970e31b8708916 | prendradjaja/ebfpp | /old-python-compiler/code_generator.py | 4,031 | 3.75 | 4 | ### The code generator module. (This file doesn't do anything, just defines
### the compile() function for main.py to call.)
import node_types
pointer = 0
# Keeps track of where the pointer goes during the program. This is used
# for variables.
variables = []
# A stack (implemented as a list) of the variable names u... |
66e6e6e1375b9800d860b85b92772b77c83cf338 | taomujian/leetcode | /0002_Add_Two_Numbers.py | 1,235 | 3.828125 | 4 | #!/usr/bin/env python3
class ListNode:
def __init__(self, val):
'''
初始化一个单链表结点
:param str val: 结点的值
:return:
'''
self.val = val
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
'''
完成2个链表的相加,并倒序输出
... |
e644585b9b3a99f72e3ed4fc948ecb26ca0465f0 | moheed/python | /languageFeatures/python_using_list_as_2d_array.py | 1,976 | 4.5625 | 5 | #NOTE: creating list with comprehension creates many
#pecularities.. as python treats list with shallow copy...
#for example
arr=[0]*5 #=== with this method, python only creates one integer object with value 5 and
#all indices point to same object. since all are zero initially it doesn't matter.
arr[0]=5 #when we ... |
79a1c0c8ff608484e39f59bc5c4912498de7c002 | moheed/python | /ds/alltripletsLessthanGivenSum.py | 535 | 4.03125 | 4 | #input [1,2,3,4,5,0]
#target=4
def tripletLessthan(arr:[int], target:int) -> int:
#print all triplets
arr.sort()
for x in arr:
print("first nest", x)
for y in arr:
print("\tsecond nest", x,y)
if y>x:
for z in arr:
print("\t\tthird nest", x,y,z)
if z>y and x+y+z < target:
print (x, y,z)... |
4441a049a51692e194cb587caedb9f0cadc285c5 | spiralizing/DeepCourse | /MultilayerPerceptron/BinaryClassifications/prueba_iris.py | 786 | 3.890625 | 4 | from sklearn import datasets
import matplotlib.pyplot as plt
import DL_Classes as DL #se importa la clase "perceptron"
# Import the Iris dataset
iris = datasets.load_iris()
X = iris.data[:100, :] # Features: Take just the first 2 dimensions from the first 100 elements.
y = iris.target[:100]
plt.scatter(X[:50, 0], X[:... |
2e266fb6155742f3ec7e31da417b043ecbb790c3 | jonathanf/Curso_odoo | /clases.py | 1,177 | 3.890625 | 4 | # -*- coding: utf-8 -*-
# copyrigth (c) 2015 Javier Campana <jcampana@cyg.ec>
__author__ = 'Javier'
class television():
def __init__(self, encendido=False, volumen=5, canal=0):
self.encendido = encendido
self.volumen = volumen
self.canal = canal
def prender(self):
if self.enc... |
789c8bf87b2747e734a1dbe1b2ef1b71f5db3e23 | kesleyroberto/aula-redes-neurais | /Trabalho 2/Trabalho2.py | 2,903 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 6 15:42:59 2021
@author: Kesley
"""
from keras.datasets import mnist
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, Flatten, Dropout
import numpy as np
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#veri... |
e1627b112c6509a44fa323e2549b23e402beb229 | worthurlove/ACM-PRACTICE-Python | /envision-1.py | 524 | 3.71875 | 4 |
'''
远景笔试题-1
Description:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
Author:worthurlove
Date:2019.4.2
'''
array = [1,2,3,4,5,6,7]
tmp = 0
end = len(array)
i = 0
while i < end:
if array[i] % 2:
array.insert(tmp,array.pop(i))
tmp += 1
i += 1
else:
... |
65090c1e800de086e81864f76f7d76fea953a487 | worthurlove/ACM-PRACTICE-Python | /leetcode-932.py | 1,101 | 3.625 | 4 | '''
leetcode系列:题号-932
Description:For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, ..., N, such that:
For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].
Given N, return any beautiful array A. (It is guaranteed that one exists.)
... |
928316b918b968a3cd45deb3153bb1fd60f48bce | worthurlove/ACM-PRACTICE-Python | /leetcode-141.py | 1,297 | 3.578125 | 4 | '''
leetcode系列:题号-134
Description:Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list,
we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked ... |
7d78f1fe55ded13f313a51a4b1012c95c3a4c818 | worthurlove/ACM-PRACTICE-Python | /huawei-2.py | 2,270 | 3.59375 | 4 | '''
leetcode系列:题号-394
Description:Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input strin... |
9bca8ae11465c53d2024b44644e26cfa8db4a4f5 | lorenzolfm/URI | /uri1029.py | 491 | 3.65625 | 4 | #memoizacao
f_cache = {}
fib_cache = {}
def f(n):
if n in f_cache:
return f_cache[n]
counter = 0
if n < 2:
counter = 1
return counter
counter = 1+f(n-1)+f(n-2)
f_cache[n] = counter
return counter
def fib(x):
if x in fib_cache:
return fib_cache[x]
if x <= 2:
return 1
val = fib(x-1)+fib(x-2)
fib_cac... |
3bf90866be3a90149bc29825f9554dc527635a30 | lorenzolfm/URI | /uri2654.py | 412 | 3.5 | 4 | n = int(input())
gods = []
names = []
powers = []
kills = []
deaths = []
for i in range(n):
name, power, kill, death = input().split()
power = int(power)
kill = int(kill)
death = int(death)
gods.append([name,power,kill,death])
for i in range(len(gods)):
names.append(gods[i][0])
powers.append(gods[i][1])
kills.... |
7504f9184da92808e116b6c49c54ec259edcdbf5 | lorenzolfm/URI | /196.py.py | 148 | 3.53125 | 4 | i =
j = 7
while i <= 9:
for n in range(3):
print('I=%d J=%d' % (i,j))
j-=1
print('I=%d J=%d' % (i,j))
j-=1
print('I=%d J=%d' % (i,j))
|
a9016b1ffef0c88b08974ded653fb6d730c235bf | lorenzolfm/URI | /2456.py | 154 | 3.53125 | 4 | cards = list(map(int, input().split()))
if cards == sorted(cards):
print('C')
elif cards == sorted(cards, reverse = True):
print('D')
else:
print('N') |
c895289f699039484ff8ec9605daeaf239b6f263 | lorenzolfm/URI | /uri2310.py | 1,318 | 3.53125 | 4 | numeroJogadores = int(input())
totalSaques = 0
totalBloqueios = 0
totalAtaques = 0
totalSaques1 = 0
totalBloqueios1 = 0
totalAtaques1 = 0
estatSaques = 0
estatAtaques = 0
estatBloqueios = 0
for _ in range(0, numeroJogadores):
nome = str(input())
s,b,a = input().split()
s1,b1,a1 = input().split()
#Formatacao dos... |
4a2e878943f0cba40e5751ff57258665a3350db8 | lorenzolfm/URI | /1171.py | 275 | 3.578125 | 4 | testCases = int(input())
lista = []
listaUnica = []
for _ in range(testCases):
num = int(input())
lista.append(num)
lista.sort()
for i in lista:
if i not in listaUnica:
listaUnica.append(i)
for i in listaUnica:
ap = lista.count(i)
print('%d aparece %d vez(es)' % )
|
b624e48996f9bb3e005f575340495282bad6b7fb | lorenzolfm/URI | /1281.py | 383 | 3.53125 | 4 | testCases = int(input())
lista = {}
for _ in range(testCases):
dispProducts = int(input())
for _ in range(dispProducts):
fruit, price = input().split()
price = float(price)
lista[fruit] = price
total = 0
wannaBuy = int(input())
for _ in range(wannaBuy):
key,qnt = input().split()
qnt = int(qnt)
price = ... |
635c307ff7434485534fb973e2aa7ab5cd2f6e91 | lorenzolfm/URI | /uri1052.py | 205 | 3.5 | 4 | ano = {1:"Janeiro",
2:"Fevereiro",
3:"Março",
4:"Abril",
5:"Maio",
6:"Junho",
7:"Julho",
8:"Agosto",
9:"Setembro",
10:"Outubro",
11:"Novembro",
12:"Dezembro"}
num = int(input())
print(ano[num]) |
2fe549a4378723f377e09f2333252049b7f82bcc | ZaynAliShan/3120-Python | /repStructures/amicableNum(4.3).py | 580 | 3.96875 | 4 | # Amicable number
def main7():
amicable1 = int(input('Enter first number: '))
amicable2 = int(input('Enter second number: '))
isAmicable1 = amicable_check(amicable1)
isAmicable2 = amicable_check(amicable2)
if amicable1 == isAmicable2 and amicable2 == isAmicable1:
print (amicable1,'an... |
7cc37dc2b2888106efb3c2ee41d61bb86b511f5b | moluszysdominika/PSInt | /lab02/zad3.py | 644 | 4.15625 | 4 | # Zadanie 3
# Basic formatting
text1 = "Dominika"
text2 = "Moluszys"
print("{1} {0}" .format(text1, text2))
# Value conversion
class Data(object):
def __str__(self):
return "Dominika"
def __repr__(self):
return "Moluszys"
print("{0!s} {0!r}" .format(Data()))
# Padding and aligning strings
... |
5df4dd52de52d19f26ec24f873f44407a670f045 | Fortune-Adekogbe/python_algorithms | /union_find.py | 1,049 | 3.828125 | 4 | class UF(object):
"""Weighted union find with path compression. Find operations are
effectively constant time because the height of the tree grows as
order log * N, i.e. < 5 for any reasonable N."""
def __init__(self, N):
self.id = [i for i in range(N)]
self.sz = [1 for i in range(N)]
... |
6b23ec836b519b7ea3fd41298155b7d25c7084aa | Fortune-Adekogbe/python_algorithms | /binary_heap_dict.py | 4,147 | 3.90625 | 4 | class BinaryHeapDict(object):
"""docstring for BinaryHeapDict"""
def __init__(self, mx=True):
self.mx = mx
self.L = [None]
self.D = {}
self.N = 0
self.compare = self.less if mx else self.more
def less(self, a, b):
return self.D[self.L[a]][0] < self.D[self.L[... |
92a753e7e633025170d55b3ebdb9f2487b3c4fa0 | HayleyMills/Automate-the-Boring-Stuff-with-Python | /Ch6P1_TablePrinter.py | 1,352 | 4.4375 | 4 | ##Write a function named printTable() that takes a list of lists of strings
##and displays it in a well-organized table with each column right-justified.
##Assume that all the inner lists will contain the same number of strings.
##For example, the value could look like this:
##tableData = [['apples', 'oranges', '... |
6ab89cc0faccd09c4c8b5a7a9242dcb9dcf5dde0 | bepetersn/chimai | /chimai/mapmaking/edit_map.py | 5,317 | 3.546875 | 4 | import os.isfile
import pickle
## INCOMPLETE
def get_filename():
maps = glob.glob('../maps/*.pkl')
print "Which map do want to edit?"
print "Possibilities: "
for map in maps:
print map[8:]
while True:
map = '../maps/' + raw_input()
if not isfile(map):
print "that's not a... |
5c37ca2494cdbbbad1462c8189b610e32c99c360 | blaresadn/DataAnalysis_TS2020 | /ts_da_contest1/task_c.py | 328 | 3.75 | 4 | change = float(input())
coins = [10, 5, 2, 1, 0.5, 0.1, 0.05, 0.01]
ch_dict = {}
for coin in coins:
ch_dict[coin] = change // coin
change -= coin * ch_dict[coin]
if change > 0.001:
ch_dict[0.01] = ch_dict.get(0.01, 0) + 1
for elem in ch_dict:
if ch_dict[elem]:
print('%5.2f\t%d' % (elem, ch_dict[... |
e317905dca19712d90a62f463a4f782bd22668e5 | Ahmad-Magdy-Osman/IntroComputerScience | /Classes/bankaccount.py | 1,195 | 4.15625 | 4 | ########################################################################
#
# CS 150 - Worksheet #11 --- Problem #1
# Purpose: Practicing User-Defined Classes.
#
# Author: Ahmad M. Osman
# Date: December 9, 2016
#
# Filename: bankaccount.py
#
########################################################################
cla... |
53213e82e49a85909cc96c8283a03667c0dbbab3 | Ahmad-Magdy-Osman/IntroComputerScience | /LAB Exam 2/mOsmanLabExam2.py | 1,292 | 3.984375 | 4 | #################################
# Author: Ahmad M. Osman
#################################
def readFile(file):
infile = open(file, "r")
list = infile.readlines()
list = [int(number) for number in list]
infile.close()
return list
def mergeAndSort(list1, list2):
list = list1 + list2
list.sort()
return list
d... |
b19db0ac2fef12e825b63552fbd0b298fcb632ec | Ahmad-Magdy-Osman/IntroComputerScience | /Turtle/ex10.py | 859 | 4.65625 | 5 | ######################################
#
# CS150 - Interactive Python; Python Turtle Graphics Section, Exercise Chapter - Exercise 10
# Purpose: Drawing a clock with turtles
#
# Author: Ahmad M. Osman
# Date: September 22, 2016
#
# Filename: ex10.py
#
#####################################
#Importing turtle module
imp... |
b1e0261d3384a2dd2cb61d1c83ec002d17ec17f4 | Ahmad-Magdy-Osman/IntroComputerScience | /Dictionaries #2/practice-dictionaries-2.py | 1,019 | 3.921875 | 4 | # read from a file to a list
def readFile(file):
infile = open(file, 'r')
list = infile.readlines()
list = [item.strip().split() for item in list]
infile.close()
return list
#convert list to dictionary
def convertListToDict1(numList):
numDictionary = {}
for item in numList:
#print(item)
numDictionary[item[0... |
dcaf391bbd68ce0c7581383e4902cc08049193df | Ahmad-Magdy-Osman/IntroComputerScience | /LAB Exam 1/mOsmanAhmadp1.py | 489 | 4.03125 | 4 | ####################################
# Author Name: Ahmad M. Osman
####################################
import turtle
def triangle(t):
for i in range(3):
t.forward(100)
t.left(120)
def funShape(t):
t.color("orange")
for i in range(18):
triangle(t)
t.left(20)
def stampCenter(t):
t.shape("turtle")
t.colo... |
b7e8bafb487de06f8513e4ea64a4264d3178f3f8 | coderlubo/python_base | /02_面向对象基础/01_面向对象案例(封装)/小明爱跑步.py | 722 | 3.796875 | 4 |
# 小明体重 75.0 公斤
# 每跑步一次体重减少 0.5 公斤
# 每吃一次东西体重增加 1 公斤
class Person:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def __str__(self):
return "%s 的体重是 %.2f" % (self.name, self.weight)
def run(self):
print("%s 爱跑步" % self.name)
self.weigh... |
00d05008007019cdc7133a92d628feb1add427be | coderlubo/python_base | /01_Python基础/02_分支/02_逻辑运算.py | 932 | 3.71875 | 4 | var = "-" * 50
# case1: 定义一个整数变量 age, 编写代码判断年龄是否正确 0 <= age <= 20
print(var + "case1" + var)
age = int(input("请输入你的年龄:"))
if 0 <= age <= 120:
print("你的年龄是正确的")
else:
print("你的年龄是错误的")
print("case1结束")
# case2:定义两个整数变量 python_score,c_score, 判断是否有成绩合格 (>=60)
print(var + "case2" + var)
python_score = int(input(... |
08f2f1b66475c69543407c714409f380d7ef0bb1 | GGearing314/Mechanical_Modelling | /BouncingBalls/bouncingBall.py | 1,951 | 3.640625 | 4 | #Bouncing Ball Model | GGearing | 15/09/2018
from tkinter import *
from time import sleep,time
class Particle():
def __init__(self,mass,velocity,acceleration,x,y,direction):
self.mass=mass
self.velocity=velocity
self.acceleration=acceleration
self.x=x
self.y=y
self.... |
e881bc154016e8be0f655627fca3380dbf179dc3 | chloe-wong/pythonchallenges | /GC07.py | 298 | 3.921875 | 4 | balance = 1000
n = int(input("How much would you like to withdraw?"))
if n%5== 0:
if n<=1000:
balance = balance-(0.5+n)
print("Your balance is", balance)
else:
print("You have insufficient funds.")
else:
print("Your withdrawal amount must be a multiple of 5.")
|
848a8fecc04b20dc1ba1c11ab1b2b7f11e38d21c | chloe-wong/pythonchallenges | /A203.py | 423 | 3.890625 | 4 | import random
def GenerateList():
array = []
for x in range(9):
array.append(random.randint(1,1000))
return(array)
def InsertionSort(array):
for x in range(1, len(array)):
current = array[x]
position = x - 1
while position >= 0 and current < array[position]:
... |
a2bcfb8d274e84e4cd9da87fd7fc8cc2bc3a346b | chloe-wong/pythonchallenges | /AS71.py | 1,404 | 3.578125 | 4 | import random
uppers = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lowers = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
special = ['!','@','#','$','%','^','&','*']
randoma... |
3798c53a543f4d4a473795e6dedf9fbb1e0ac10f | chloe-wong/pythonchallenges | /AS01.py | 318 | 3.796875 | 4 |
numbers = input("Input your numbers with spaces inbetween")
nums = numbers.split()
digits = len(nums)
print(nums)
for x in range(len(nums)):
if x in range(len(nums)-1):
if int(nums[x])> int(nums[x+1]):
temp = nums[x]
nums[x] = nums[x+1]
nums[x+1] = temp
print(nums) |
e3f3fa92bec58898dcfaad21378090999313659c | chloe-wong/pythonchallenges | /AS05.py | 645 | 3.9375 | 4 | import pandas as pd
import random2 as rand
df = pd.read_excel(r'C:\Users\chloe\Downloads\words.xls')
mylist = df['Word'].tolist()
def split(word):
return[char for char in word]
word = split(rand.choice(mylist))
chances = 10
spaces = []
for x in range(len(word)):
spaces.append("_")
while True:
if chances == 0:
prin... |
1f1cc040d6d9e9d2815c6529caba23bff82c8c96 | chloe-wong/pythonchallenges | /AS53.py | 1,691 | 3.84375 | 4 | votes = [["Alice","Bob","Charlie"],
["Alice","Bob","Charlie"],
["Bob","Alice","Charlie"],
["Bob","Alice","Charlie"],
["Bob","Alice","Charlie"],
["Charlie","Alice","Bob"],
["Charlie","Alice","Bob"],
["Charlie","Bob","Alice"],
["Charlie","Bob","Alice... |
21837806e9ec01cc30e470516f0588acdef945da | chloe-wong/pythonchallenges | /AS72.py | 723 | 3.765625 | 4 | import random
alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
substitution = [x for x in alphabet]
random.shuffle(substitution)
message = input("Input your message in all caps")
print("Your initial message is:",message)
message = message.split()
encod... |
48bc538aa87e4e8684327f0dd9a415a9c46c0042 | chloe-wong/pythonchallenges | /AS52.py | 2,116 | 3.78125 | 4 | #e1b
import calendar
cal = calendar.TextCalendar() # Create an instance
cal.pryear(2012)
#e1c
import calendar
cal = calendar.TextCalendar()
cal.setfirstweekday(calendar.THURSDAY)
month = int(input("Input Number of Birthday Month"))
year = int(input("Input Birthday Year"))
cal.prmonth(year,month)
#e1d
1) When the... |
3cb3949fa1cbba0c129190d909a0b62eaedcb6f4 | gmroughton/advent-of-code | /2020/dec_8.py | 2,725 | 3.9375 | 4 | import copy
from pprint import pprint
def program_to_list(filename):
"""
Convert a file into a list representing commands in an assembly-like language
:param filename: File containing instruction set
:return: The program loaded into memory as a list of instructions
"""
output = []
with op... |
6ca7c10bca83d9f0414bccfc7330cc80c1aae62b | gmroughton/advent-of-code | /2020/dec_9.py | 2,285 | 3.84375 | 4 | from utils.file_utils import file_to_list
TEST_CYPHER = file_to_list("files/test_xmas_cypher.txt")
CYPHER = file_to_list("files/xmas_cypher.txt")
def two_number_sum(array, target_sum):
"""
Find if there are two values in an array that sum to the target value
:param array: List of Integers
:param tar... |
cbf4b3e5c800151dc774a24ca38ef2451dc1959a | galdrasdottir/practice | /lpthw/ex15.py | 185 | 3.625 | 4 | from sys import argv
script, username = argv
print("Hello %r! What file would you like to read?" % username)
txt = input("> ")
print("Here's your file %r:" % txt)
print(txt.read())
|
a402cdc551e63f13f42ee3cc203295bee2372319 | fereche95/mainApp | /functions.py | 967 | 3.96875 | 4 | #Var
index = 0
index2 = 2
options = [
["A", "B"],
["C", "D"],
["E", "F"],
["G", "H"]
]
category = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
products = [True, False]
unitPrice = ""
totalPrice = ""
quantity = ""
#Functions
def showOptions(index):
print("Opciones: ")
while(index < len(opti... |
69f19f78121df43eb960a36eb815100a40169d1c | Daniela000/ARC_project | /single_scale.py | 5,727 | 3.78125 | 4 | import networkx as nx
from Node import Node
import random
import pandas as pd
import matplotlib.pyplot as plt
def summation(node_y, node_x):
summation = 0
for node_i in graph.neighbors(node_x):
if node_i != node_y:
summation += (cost/(k+1)) * node_i.strategy - (cost/(k+1)) * node_y.strategy... |
dcb2f35e6552043fef086b076e34a6d912233d6b | Skayfall/classes | /OddEvenSeparator.py | 323 | 3.578125 | 4 | class OddEvenSeparator:
def __init__(self):
chet = []
nechet = []
def add_number(self, n):
if n % 2 == 0:
self.chet.append(n)
elif n % 2 != 0:
self.nechet.append(n)
def even(self):
return self.chet
def odd(self):
return self.nech... |
dabe1a62cbfe3d085509ecd3abcce0f10b647699 | lihua0617/Language-C | /produit.py | 104 | 3.515625 | 4 | from cs50 import get_int
x = int(input("x: \n "))
y = int(input("y: \n "))
print("leur produit: ", x*y) |
44692bbff8efecdcb5539a2d5a8894015a8a2aca | Chiens/learnPy | /important_moudles/contextlib_contextmanager_test0.py | 803 | 3.734375 | 4 | #coding:utf-8
'''上下文管理的实现,
即__enter__ __exit__ 方法的实现
以及with语句使用的关键'''
#一个正确实现上下文管理的类
class Query(object):
def __init__(self, name):
self.name = name
def __enter__(self):
'''这是正确实现上下文管理的关键方法之一'''
print("Begin")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
... |
93367d34d0d7401c86bbbb32d5419538b2486ab6 | Chiens/learnPy | /Process&Thread/Thread_Lock1.py | 979 | 3.6875 | 4 | #coding:utf-8
'''
各进程的变量是独立的,而线程的是共享的,如果不处理这个问题会导致出错.
由于线程的调度是由操作系统决定的,当t1、t2交替执行时,只要循环次数足够多,balance的结果就不一定是0了
给change_it 加上一个锁
'''
from threading import Thread, Lock
import time
#实例化一个锁对象
lock = Lock()
balance = 0
def change_it(n):
#先存后取,结果应该为0
global balance
balance += n
balance -= n
def run_thread... |
85ebb32222e04f3f02283f7c8bd82a2253386b42 | guajiropa/Beyond-the-Basics | /escape_unicode.py | 550 | 3.890625 | 4 | """
This is an exercise in using function decorators. Please note that
the function executes and then returns to the decorator before
returning to the code that called it. Also note tha functions are
not the only objects that can be decorators.
"""
# Setup the function to use as a decorator
de... |
849286cac8d53e793e11fd490d4be3ccf90eee83 | olimpiadi-informatica/oii | /2020/territoriali/download/managers/generator.py | 1,308 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf8 -*-
from limits import *
from sys import argv, exit
from random import randint, random, seed, shuffle
cases = 0
if __name__ == "__main__":
if len(argv) < 3:
print("Generatore di 'download'")
print("{} SEED 0".format(argv[0]))
exit(1)
S, _ = ... |
b678eeae851bb3dc2c35d37dea782f3a7ffeebc5 | osanseviero/ProyectoIntegrador | /app/app/ai/models/classifier_models.py | 2,072 | 3.859375 | 4 | """TensorFlow classifier models estimators.
Implements TensorFlow estimators that are able to classify a discrete variable
(regresion). The supported models are Baseline, Deep Neural Network and a
Linear Regressor.
"""
import tensorflow as tf
def get_baseline_classifier(model_dir, label_names, classes):
"""Creat... |
74f82a375dc900e923a3e344db809125d5a1cc98 | okest12/leetCode | /add_two_number.py | 1,018 | 3.71875 | 4 | class listNode(object):
def __init__(self, x):
self.value = x
self.next = None
def add_two_number(s1, s2):
l1 = create_list_node(s1)
l2 = create_list_node(s2)
result = dummy = listNode(-1)
carry = 0
while l1 or l2 or carry:
sum = carry
if l1:
... |
6813e4912ec59dfec6cbc5a1af401d8bc4dc03ca | jgolatkar/algorithms-and-data-structures | /max_subarray_div&conq.py | 911 | 3.609375 | 4 | # Find maximum sum of contiguous sub-array
# Divide and Conquer Solution - O(nlogn)
import sys as sys
def max_subarray(A, low, high):
if high == low:
return A[low]
else:
mid = (high + low)//2
max_left = max_subarray(A, low, mid)
max_right = max_subarray(A, mid + 1, high)
max_cross = max_cross_... |
d1465bd8e627fc83f4621903b35e77e91ba5b9ec | nsaggu/python | /dictionary.py | 458 | 3.515625 | 4 | import operator
def sortDict(list):
#return sorted(list.items(), key=operator.itemgetter(0))
return sorted(list.items(), key=operator.itemgetter(0), reverse=True)
print(sortDict({1:10, 2:20, 7:70, 3:30}))
def ConctDict(dict, dict1):
list = dict.items()+dict1.items()
return list
print(ConctDict({1:1... |
c10a05225468c61c553923d9e92b0341394f0433 | jangidsampat/N_Queen | /AIProject.py | 2,987 | 3.5625 | 4 | from random import randint, choice
class AIProject:
MaxStillHn = 30
def __init__(self, nQueens):
self.nQueens = nQueens
self.initBoard()
def initBoard(self):
self.board = [randint(0,self.nQueens-1) for i in range(self.nQueens)]
self.noOffStillHn = 0
self.lastHn = s... |
b6792c776aa1dd746a1c9d327a873eac544d12bd | anshraj0805/Project | /Ext of file.py | 125 | 3.984375 | 4 | filename= input('enter the filename')
extnsn= filename.split(".")
print("the extension of the filename is "+(extnsn[-1]))
|
40048ca4fa89eabcd45b3a0f50d1102a1d8a6234 | iangraham20/cs108 | /labs/11/gui.py | 2,968 | 3.875 | 4 | '''
Created on Nov 17, 2016
Lab 11 Exercise 2
@author: Ian Christensen (igc2)
'''
from tkinter import *
from calculator import *
class Gui:
def do_calculation(self):
''' Calculates the answer using the input values and the Calculator class. '''
try:
result = self._calc.calculate(s... |
96b507b9c4f9f4d93689cff112ab17e3e06f6aec | iangraham20/cs108 | /labs/10/sun.py | 1,507 | 3.9375 | 4 | ''' Model of a sun.
Created Fall 2014
Lab 10 Exercise 3
@author: smn4
@author: Ian Christensen (igc2) '''
import turtle
class Sun:
def __init__(self, name, rad, m, temp):
self._name = name
if rad <= 0 or m <= 0:
raise ValueError('Sun numeric demension properties must be positive')... |
bbcefac3f0243ed8df81ed8a4875626b78ab3ca4 | iangraham20/cs108 | /labs/10/driver.py | 976 | 4.5 | 4 | ''' A driver program that creates a solar system turtle graphic.
Created on Nov 10, 2016
Lab 10 Exercise 5
@author: Ian Christensen (igc2) '''
import turtle
from solar_system import *
window = turtle.Screen()
window.setworldcoordinates(-1, -1, 1, 1)
ian = turtle.Turtle()
ss = Solar_System()
ss.add_sun(Sun("SUN", 8.... |
0e75d78ea6d8540a5417a8014db80c0b84d32cc9 | iangraham20/cs108 | /projects/07/find_prefix.py | 1,677 | 4.125 | 4 | ''' A program that finds the longest common prefix of two strings.
October 25, 2016
Homework 7 Exercise 7.3
@author Ian Christensen (igc2) '''
# Create a function that receives two strings and returns the common prefix.
def common_prefix(string_one, string_two):
''' A function that compares two strings, determines... |
579bf55f2cfbb42b51cb0dbd11593e5e954c640a | iangraham20/cs108 | /labs/10/exercise1.py | 951 | 3.734375 | 4 | ''' This program tests varying try blocks.
Created on Nov 10, 2016
Lab 10 Exercise 1
@author: Ian Christensen (igc2) '''
try:
import happiness
except ImportError as ie:
print('ImportError occurred:', ie)
try:
'hi' + 4
except TypeError as te:
print('TypeError occurred:', te)
try:
10 / 0
except Zer... |
b3e1ca7c075544d30a3a7cbd65193871f62f7a64 | iangraham20/cs108 | /projects/12/polygon.py | 881 | 4.25 | 4 | '''
Model a single polygon
Created Fall 2016
homework12
@author Ian Christensen (igc2)
'''
from help import *
class Polygon:
''' This class represents a polygon object. '''
def __init__(self, x1 = 0, y1 = 0, x2 = 0, y2 = 50, x3 = 40, y3 = 30, x4 = 10, y4 = 30, color = '#0000FF'):
''' This is the ... |
39dec7fddaa3e23c4d9c178878f46be2dd094a1f | MyselfSuhyun/startcamp | /swea/6217.py | 600 | 3.625 | 4 | class Student:
def __init__(self,name):
self.__name = name
@property
def name(self):
return self.__name
def __repr__(self):
return '이름: {0}' .format(self.name)
class GraduateStudent(Student):
def __init__(self,name,major):
super().__init__(name)
self.__... |
7090e968b286f84ea9daafd71c8f7ea5fd5d5707 | MyselfSuhyun/startcamp | /hello.py | 586 | 3.75 | 4 | #greeting 이라는 변수에 인사말 저장하고,
#인사말(greeting) 다섯 번 출력하기
greeting = '안녕하세요! 잘 부탁 드립니다!!'
# print(greeting)
# print(greeting)
# print(greeting)
# print(greeting)
# print(greeting)
# while문으로 작성해보세요! 30분까지
# 다섯 번 반복하기
# n=0
# while n<5:
# print(greeting)
# n=n+1
i=0
while i<5:
print(greeting)
i= i+1 # i 에 ... |
6477b75901d132cdcd55f98421bb24a9374c49db | MyselfSuhyun/startcamp | /swea/2025.py | 688 | 3.53125 | 4 | #내가 제출한 거
# N=int(input())
# sum = 0
# for i in range(1,N+1):
# sum+=i
# print(sum)
#교수님이 알려주신 것
#input() >> 한 줄 입력 받기 :
#input()의 결과는 문자열 '26' >> 26
#정수형 문자열을 정수로 바꾸는 함수 int('문자열')
N =int(input())
i=1
#계속 누적합을 알고 있어야 합니다.
# 누적합을 저장할 변수를 하나 선언합니다.
result = 0 # 아무것도 더하지 않으면 0이니까 0으로 초기화
while i <=N:
result ... |
338aeaa27a70a175df100bee90037b6e1c59e336 | SeanHorner/python | /number_guess_game/main.py | 15,980 | 3.78125 | 4 | # * Creator: Sean Horner
# * Date: 09/02/2021
# * Updated: 09/02/2021
# * Purpose: A simple text game that asks users to guess combinations of numbers
# * given a few hints. This code practices a few alternative methods to
# * perform a switch code block (i.e. dictionary and if-elif chain
# * method... |
bfbc6c249e8ad70fba0a86cf04a92456f2493789 | SeanHorner/python | /pandas/realpython/data_manipultaion.py | 39,858 | 3.953125 | 4 | # The common aliases used for Pandas, NumPy, and MatPlotLib are pd, np, and plt, respectively.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Spacer function to put some space between different queries.
def spacer():
print("\n\n")
# Read the CSV file into pandas to create a ... |
04404fd9ba0eaa52ee45df9647e2f5717912c2d4 | Meher143/CSPP-1--Assignments | /M6/p3/digit_product.py | 611 | 4 | 4 | '''
Given a number int_input, find the product of all the digits
'''
def main():
'''
Read any number from the input, store it in variable int_input.
'''
int_input = int(input())
ans = int_input
cou = 1
if ans > 0:
while ans > 0:
bat = ans%10
cou = cou*bat
... |
051e5a1b189aeea6742016d796c35a74c401c4e1 | lovychen/NG_class_2014_Machine-Learning | /w_6_svm/showdata.py | 956 | 3.71875 | 4 | import matplotlib.pyplot as plt
from numpy import *
def showdata(train_x, train_y):
# notice: train_x and train_y is mat datatype
numSamples, numFeatures = shape(train_x)
if numFeatures != 2:
print "Sorry! I can not draw because the dimension of your data is not 2!"
return 1
# draw all ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.