blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
10b0648c0be2fab0dcc8337bfdcdd08ff3541777 | ad-freiburg/question-generation | /tools/count_questions_in_squad_file.py | 1,108 | 3.953125 | 4 | """
Copyright 2020, University of Freiburg
Author: Natalie Prange <prange@cs.uni-freiburg.de>
Count number of questions, paragraphs and articles in the input SQuAD format
json file.
"""
import json
import argparse
def count_questions(input_file):
with open(input_file, "r", encoding="latin1") as f:
sour... |
2add0edc14d3f3fdcab3f3413746cd29750b5f36 | momentum-morehouse/uno-with-python-Ikemefula | /uno2.py | 2,199 | 3.96875 | 4 | from random import randint
NUMBERS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
COLORS = ["🔴","🟢","🟡","🔵"]
class Card:
def __init__(self, number, color):
self.number = number
self.color = color
def __str__(self):
return f"{self.number} {self.color}"
class Player:
def __init__(self, ... |
ee9e355bb3fd3b338a84cc71e9cf6c8ebbeb0f70 | DerZc/FICS | /utils/computation.py | 194 | 3.515625 | 4 | import numbers
def is_number(num):
try:
if isinstance(float(num), numbers.Number):
return True
else:
return False
except:
return False
|
b0ef7476a8efbb7fa24911d5147121c84d2e78ba | WellerQu/LearnPython | /lesson2/practice.py | 838 | 3.71875 | 4 | #!/usr/bin/env python
# -- coding: utf-8 --
# 基础数据类型
a = 1
b = 0xFF
c = 1.12
d = 2e-4
e = True
f = None
g = "Hello"
print a, b, c, d, e, f, g
PI = 3.141592627
print PI
print u'这里是中文'
print '%d, %x, %5.3f, %f, %s, %s, %s' % (a, b, c, d, e, f, g)
print '%06.2f' % PI
ls = [1, 2, 'abc']
print ls, ls[2]
ls.append(3)... |
ae27b6bec80d98d336648d36b1022382dcdf8b8c | damiantacik/air_reservation_system | /flight/flight.py | 2,708 | 3.609375 | 4 | class Flight:
def __init__(self, flight_number, plane):
self.plane = plane
self.flight_number = flight_number
rows, letters = self.plane.get_seating_plan()
self.seats = [None] + [{letters: None for letters in letters} for _ in rows] # _ zamiast zmiennej x gdy wiemy ze używamy jej t... |
d1c27b047e7c3afe2ddd47d577a303bc937abc90 | Cherrmann8/10_Days_of_Statistics | /Day_5/normal_distribution_2.py | 1,427 | 4.0625 | 4 | """
Author: Charles Herrmann
Date: 4/18/21
Objective: In this challenge, we go further with normal distributions.
Task: The final grades for a Physics exam taken by a large group of students have a mean of μ = 70 and a standard deviation of σ = 10. If we can approximate the distribution of these grades by a normal d... |
6969eaf8551e9ebbde322d2def943be39992b2a1 | Valen0320/TutorialesPython | /ejercicio26.py | 382 | 3.703125 | 4 | sueldo=int(input("Ingrese el sueldo del empleado:"))
antiguedad=int(input("Ingrese la antiguedad en años:"))
if sueldo<500 and antiguedad>=10:
aumento=sueldo*0.20
totalsueldo=sueldo+aumento
print(totalsueldo)
else:
if sueldo<500:
aumento=sueldo*0.05
totalsueldo=sueldo+aumento
... |
53f5f6e75f983298ca4dda00fb08c315c414dca1 | Benersy1337/Av1-Pi2-Phyton | /jogodaadvinhacao.py | 1,846 | 3.828125 | 4 | from random import randint
from time import sleep
login = True
while login:
print('='*20)
print('Eu sou o computador...')
sleep(1)
print('Escolha um número entre 1 a 10')
sleep(1)
print('O que você acha?')
sleep(1)
print('='*20)
cont = 0
computer = randint(0, 10)
... |
6eb3c97438a03bc8019bb23ab9cffd833d8c8f07 | BuenasBuenasSergio/Ejercicio-Python | /Ejercicios Datos Simples/Ejercicio 03.py | 132 | 3.84375 | 4 | """"Mostrando mensaje con variable en la que pones el nombre"""
name = input("Introduce tu nombre: ")
print("¡Hola " + name + "!") |
8fe8fa3f0acd9d57fdcb1277c2a01266f787e8ac | KamilJantos/Python_XII | /memento/Memento.py | 3,068 | 3.625 | 4 | import pickle
class Quote:
def __init__(self, text, author):
self.text = text
self.author = author
def save_state(self):
current_state = pickle.dumps(self.__dict__)
return current_state
def restore_state(self, memento):
previous_state = pickle.loads(memento)
... |
d76d20f48e156d50f85fe15384f604ce304b6898 | Vanclief/bitfinex-python | /bitfinexpy/helpers.py | 491 | 4.3125 | 4 | def dict_to_float(d):
"""
Converts all strings to floats from a dict
"""
if type(d) is dict:
for key, value in d.items():
if type(value) is str:
try:
d[key] = float(value)
except ValueError:
d[key] = str(value)
... |
62e76f06e371f1acb3d509ce3cefe0ea7a0502ba | shaunakganorkar/PythonMeetup-2014 | /15.functions.py | 205 | 4 | 4 | num1= int(raw_input("Enter the First Number: "))
num2= int(raw_input("Enter the Second Number: "))
def sum(a,b):
return a + b
print 'The addition of the given two numbers is %d '%sum(num1,num2)
|
ea1a9bc6f6225937f697ad54b7548fe1eb519638 | ebubekirtrkr/pythonWorkShop | /Sololearn/Vigenere Chipper.py | 940 | 3.796875 | 4 | import sys
print "Please don't use special character"
word = raw_input("please enter Original Message\n").lower()
key = raw_input("please enter Masking Key\n").lower()
lenw=len(word)
lenk=len(key)
h= ""
if lenw>lenk:
wk=lenw-lenk
for x in range(0,(wk)):
key = key + key[x]
for y in range(0,lenw):
to1_... |
45ffd8bbbee8fa878019a15aafa6e445229e5cc5 | wmm98/homework1 | /视频+刷题/6章2/-求两组整数的或集.py | 1,397 | 3.65625 | 4 | '''【问题描述】从标准输入中输入两组整数(每行不超过20个整数,每组整数中元素不重复),合并两组整数,每个整数只出现一次(重复整数只保留一个),
并从小到大排序输出(即两组整数的或集)。
【输入形式】第一行输入第一组整数的个数,第二行输入第一组整数,整数间以空格分隔;然后第三行输入第二组整数的个数,第四行输入第二组整数,
整数间以空格分隔。
【输出形式】按从小到大顺序排序输出合并后的整数,并不含重复整数。
【样例输入】
8
5 1 4 3 8 7 9 6
4
5 2 8 10
【样例输出】1 2 3 4 5 6 7 8 9 10
【样例说明】第一组整数个数为8,分别为5 1 4 3 8 7 9 6,第二组整数个数为4,分别为5 ... |
d94aa2cc26aebd60e74852a6c44ae841ff80d2fe | SmischenkoB/campus_2018_python | /Oleksandr_Kotov/3/crypto_square.py | 1,302 | 4.15625 | 4 | from math import sqrt, ceil
def encode(string):
"""encode string using crypto square
Arguments:
string str -- string to encode
Returns:
str -- encoded string
"""
string = string.lower()
characters = [char for char in string if char.isalpha()]
step = ceil(sqrt(len(charact... |
72ab32f8a2cee022b37b400dee9e3f0d23f82619 | maxianren/algorithm_python | /BST_BST_fill_in_the_blanks.py | 4,399 | 4.0625 | 4 | '''
Given a binary tree structure and a list of integers,
please fill the integers into the corresponding nodes of the binary tree to make it a binary search tree;
please output the value2tree of the binary search tree hierarchically.
Input format:
The first line of each test sample contains an integer, which is the t... |
430d17f0c31a670ccdb324ce90a840f224764c47 | mom4ilakis/Internship-Nemetschek | /Python Tasks/In Deep/Tasks/zip_with.py | 340 | 3.78125 | 4 | def zip_with_map(func, *iterables):
yield list(map(func, *iterables))
def concat3(x, y, z):
return x + y + z
def concat_many(*args):
return "".join(list(args))
first_names = ['John', 'Miles']
last_names = ['Coltrane', 'Davis']
spaces = [' '] * 2
print(list(zip_with_map(concat_many, first_names, space... |
0740e751cd46fb95652f8f3bae6e6fa659c5a9b6 | dliang2/csci127-assignments | /hw_08/hw_08.py | 2,014 | 3.953125 | 4 | def read(file):
f = open(file)
text = f.read()
f.close()
return text
def clean(text):
text = read(text)
for p in "?!.:,;—\"'“”":
text = text.replace(p, " ")
word_list = text.split()
word_list = [word.capitalize() for word in word_list]
for word in word_list:
if not w... |
f37740a917c2241d11be27801630976249b93d59 | shealutton/ProjectEuler | /ProjectEuler-028.py | 1,466 | 3.75 | 4 | '''Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
43 44 45 46 47 48 49
42 21 22 23 24 25 26
41 20 7 8 9 10 27
40 19 6 1 2 11 28
39 18 5 4 3 12 29
38 17 ... |
1c6a69361c67989e22f8928441335793935a32ee | viliam-gago/engeto_python_course_projects | /car_database/car_database.py | 11,305 | 3.71875 | 4 | import os
def greet():
separator()
print('Welcome to our car rental database.')
separator()
print('''What would you like to do ? Please choose from options below:
a) Show all available cars
b) Search cars
c) Rent a car
d) Return a car
e) Exit the program''')
separator()
... |
6f11001bfe2fd74b1a11d9abadcc89cf7e9f66b2 | brenoassp/algoritmos | /pilhas-e-filas/exercicio5-a.py | 1,448 | 3.8125 | 4 | class No:
valor = None
proximo = None
anterior = None
class ListaDuplamenteEncadeada:
primeiro = None
ultimo = None
def contido(self, valor):
'''
Complexidade: O(n)
'''
no_atual = self.primeiro
while no_atual:
if no_atual.valor == valor:
... |
5d9c58ae8292dc9ecd631375d80fe7ecf2e469cd | parapente/AoC2018 | /6b.py | 759 | 3.59375 | 4 | #!/usr/bin/python3
def is_digit(n):
try:
int(n)
return True
except ValueError:
return False
def manhattan(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
with open('6.dat') as f:
data = f.read()
points = data.split('\n')
points.pop()
for i in range(len(points)):
... |
1576c63b77655957ff7ad7707f2b2c5e53af11a4 | JhonatasWilly/probabilidade-e-estatistica | /testeOrdenacao.py | 2,969 | 3.75 | 4 | # PROBABILIDADE E ESTATÍSTICA --- CALCULO DA CURVA POLIDA
import math
#lista = [15,18,18,16,15,23,18,19,23,19,18,15,19,16,19,17,15,19,19,22,18,16,19,21,18,18,20,16,34,21,23,17,20,20]
lista = [150, 155, 160, 162, 166, 151, 156, 160, 162, 167, 152, 156, 160, 163, 168, 153, 156, 160, 163, 168, 154, 157, 161, 164, 169, 15... |
fdb1b86590287c2063d838b20d84fbef8db9b932 | b000579040/Machine-Learning | /LeeCode/ToLowerCase.py | 167 | 3.71875 | 4 | # 709 转换成小写字母
s = ""
str = "Hello"
for i in str:
if (ord(i) <= 90) & (ord(i) >= 65):
s += chr(ord(i) + 32)
else:
s += i
print(s)
|
895bda73d01a658e59568582d58d76bf4845267e | AwesomeCoder30/Python_Pratice | /Challenge_Questions.py | 167 | 4.0625 | 4 | #Question 1
import datetime
now = datetime.datetime.now()
print(now)
age = input("How old are you?: ")
age = int(age)
YearofBirth = now.year - age
print(YearofBirth)
|
4c53392b33bf9c1a865fc786e78e4c62d2f812dc | ioanzicu/python_for_informatics | /ch_12_networked_programs/ch_12_networked_programs_exercise_12_4.py | 654 | 4.15625 | 4 | # Ex 12.4 pg. 154
# Change the urllinks.py program to extract and count paragraph
# (p) tags from the retrieved HTML document and display the count of the paragraphs
# as the output of your program. Do not display the paragraph text, only
# count them. Test your program on several small web pages as well as some large... |
4a7cb8d1aae8da79a75a82df6bb22e32de566fee | NPT156/Python-Calculator | /Calulator.py | 787 | 3.859375 | 4 |
import time
operator = 1
x = 1
y = 1
def calculator():
print("Enter first number")
x = input()
print("Enter operator. 1 for multiply, 2 for divide , 3 for add")
print("4 for subtract, 5 for exponet")
operator = input()
print("Enter second number")
y = input()
if str(operator) == "3":
prin... |
f1704c75fdfbfdc8d421470a02a7eca2bdea84a1 | gerbyzation/Python | /week1/chat.py | 1,263 | 4.09375 | 4 | # read stopwords file
file = open("stopwords.txt")
stopwordsRaw = file.readlines()
stopwords = []
# read countries file
countries = []
countriesRaw = open("countries.txt").readlines()
for country in countriesRaw:
countries.append(country.split('|')[1].strip())
person = {}
for word in stopwordsRaw:
stopwords.... |
ec61b931e48f9c12437ea3fbb64f98df040cb044 | ameya468/house-points-counter | /House points counter.py | 4,006 | 3.75 | 4 | import os
import datetime
houses= ["Asgard","Valhalla","Wakanda","Xandar"]
file = open("house points data.txt", "a")
file.write("")
file.close()
size=os.stat('house points data.txt').st_size
if size == 0:
print("this is your first time running the program")
for i in range (len(houses)):
... |
4b903c9e183ba76b0d020de4554d91176758d118 | steve-77/Learning_Python | /Assignment1/exercise6.py | 574 | 3.796875 | 4 | def metropoly(c,p,i):
if (c == 'yes' and p > 100000) or (c == 'no' and p > 200000 and i > 720000000):
status = "metropoly"
print name, "is a metropoly"
elif c == 'no' and p < 200000:
status = "not_metropoly"
print name, "is not a metropoly because its not a capital with populatio... |
934d374b603b4c2cf93c24bf4e91d603de235992 | IlyaLab/kramtools | /lib/c/strset.py | 2,747 | 3.59375 | 4 |
"""
This script pounds on an executable generated from strset.c
that, in turn, exercises the hash set implementation.
1. A random set of ASCII strings of random lengths is generated, and
a random sampling with replacement of this set is written to a
tmpfile (so the tmpfile *will* have duplicates).
2. The test execut... |
aaa232ee23b78b4223ccfe735ad637a105814e47 | 2597688js/Python_OOPs | /oops16_part2_Property_setters.py | 466 | 3.671875 | 4 | class Don:
def __init__(self):
self._age = 0
# using property decorator
# a getter function
@property
def age(self):
print("getter method called")
return self._age
# a setter function
@age.setter
def age(self,a):
if (a<8):
raise ValueError("S... |
d8ff96ecd2b2c4e9c23bbb33c7f40235e724aa8b | cchawn/python-qa-project | /backOffice.py | 3,782 | 3.5625 | 4 | # CHRISTINA CHAN
# LAURA BROOKS
def mergeTransactions():
#Merges the transaction summary file to the end of the mergedTransactions file
transactionFile = open("transactionSummary.txt",'r')
merged = open("mergedTransactions.txt", 'a') #append to mergedTransactions.txt
merged.write(transactionFile.read())
m... |
eb3963a8250c0b4b72ea77aa68bdb4475caae944 | Jhonathan-Pizarra/Deberes_2018 | /OperadoresCondicionales.py | 484 | 4.3125 | 4 | print("*** CONDICIONAL-IF ***")
print("OPERADORES DE COMPARACIÓN...")
print("COMPARACIÓN <, >, >= , <=, <> ")
numeroX = 10
numeroY = 10
if numeroX > numeroY:
print("Numero 'X' es mayor")
elif numeroX < numeroY: #else if
print("El numero 'Y' es mayor")
else:
print("Los numeros 'X' y 'Y' son i... |
f72b26ccf6f18541ef66f669c4b6c24b45f9a78e | darioadanez/CursoDevnet | /calculadora.py | 12,793 | 4.125 | 4 | #!/usr/bin/env python3
import sys
import math
#from getch import getch
ans = 0 #Variable global utilizada para guardar el resultado de la última operación
#####################################################################
#Función que calcula pide un número y calcula su logaritmo neperiano#
########################... |
2f483b799525932d7392ab627aa0ba00c3f194c6 | techdragon/pyTree | /src/pyTree/Tree.py | 10,223 | 3.734375 | 4 | '''
pyTree: A list-derived TREE data structure in Python
Created on Aug 21, 2012
@author: yoyzhou
'''
import collections
(S,T) = range(2)
class Tree(object):
'''
A Python implementation of Tree data structure
'''
def __init__(self, data = None, children = None):
'''
... |
b1e75dea6180d9127a68f34c89ce22d5493d4ebd | Koorimikiran369/Innomatics_Internship | /day_5/8_Val_Phno.py | 213 | 3.78125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import re
for i in range(int(input())):
if re.match('^[7-9][0-9]{9}$', input()):
print("YES")
else:
print('NO')
|
3e9c85361ef8c6430443a2ec01fc678cd5f9f481 | bmallred/FibonacciFun | /src/StopWatch.py | 1,502 | 3.875 | 4 | '''
Created on Jun 10, 2011
@author: BMAllred
'''
import datetime
class StopWatch(object):
'''
Stop watch object.
'''
def __init__(self):
'''
Initializes a new instance of the StopWatch class.
'''
self.StartTime = None
self.StopTime =... |
ecce86f6268ca74190462a8f6b2c6f2b4c88b626 | TheMilubi/DWES | /Python/Cadenas/01d.py | 568 | 4 | 4 | """
Ejercicio 01d
Escribir funciones que dada una cadena de caracteres:
cad = "En un lugar de la Mancha de cuyo nombre no quiero acordarme"
d) Dicha cadena en sentido inverso.
Ej.: ¡Hola mundo! debe imprimir !odnum aloH¡
"""
def inversa(cad):
""" DocString
"""
salida = ""
for i in range(len(cad)-1... |
e36d994b4c88ebf06c2cf51faf378aa48800438d | kishorrepo/DataStructures | /arrays/SortByFrequency.py | 897 | 4.0625 | 4 | def findFrequency(arr):
frequency = dict({})
for i in arr:
if i in frequency.keys():
frequency[i] = frequency[i]+1
else:
frequency[i] = 1
return frequency
def sortArrayBasedOnFrequency(arr):
sortedArr = []
frequency = findFrequency(arr)
frequencyOrder = so... |
a08b7cd1ddd67b04afa13428ad6294783523fefd | janhaj/da_data | /lekce6/ukol_10_hadanky.py | 601 | 3.75 | 4 | print('cast 1:')
cisla = [3, 5, 8, 0, 4, 2, 0, 7, 6, 2, 0, 5]
sum = 0
for cislo in cisla:
sum = sum + cislo
if cislo == 0:
print(sum)
sum = 0
# program bude pocitat soucet hodnot v seznamu
# pokud bude zpracovavany prvek roven 0, vypise dosavadni soucet a bude
# pocitat znovu od nuly. Posledni soucet nebud... |
db7e0f9b14ae78d7073e754c3553f7c2220776fa | ditesh/project-euler | /10.py | 437 | 3.515625 | 4 | import sys
import math
import time
i = 5
total = 5
primes = [2, 3]
sixTime = 0
primeTime = 0
while True:
aPrime = True
if i % 3 != 0:
sq = math.sqrt(i)
for k in range(1, i):
if ((6*k -1) <= sq) or ((6*k + 1) <= sq):
if (i % (6*k+1) == 0) or (i % (6*k-1) == 0):
aPrime = False
break
else:... |
4146e0517f6ea7ee55f9a6488a1cf1c66570117f | aliensmart/week1 | /assessemen_week_1/controller.py | 1,969 | 3.5 | 4 | import view
import model
import random
def run():
model.load()
view.welcome_menu()
main_menu()
def main_menu():
while True:
selection = view.choice()
if selection == "1":
create_account()
elif selection == "2":
login()
elif s... |
3eb433bcdde7f8e8818d2d5255388f95ed00e871 | liyong1995/pythons | /day02/demo03.py | 824 | 3.828125 | 4 | if __name__ == '__main__':
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 使用for in
for i in arr:
for j in arr[0:i]:
a = i*j
print(i, end="*"), print(j, end="="), print(str(a).rjust(2), end=" ")
if j == i:
print()
j=0
for i in range(120) :
j +=... |
ee3e3cb22d20ceabab29a99b4f05eb9dd0608ec4 | srikanthpragada/PYTHON_19_APR_2021 | /demo/assignments/join_names.py | 150 | 3.828125 | 4 | names = []
while True:
s = input("Enter the string [end to stop] :")
if s == 'end':
break
names.append(s)
print(':'.join(names))
|
759e6a8150e36d65c3ab7acfc86348b3e77f1a3e | abernatskiy/sparsModGECCO2015 | /eswclientMedium/parseStr.py | 323 | 3.546875 | 4 | import numpy as np
def parse1d(string):
return np.array(map(int, string.split(' ')))
def parse2d(string):
arr = parse1d(string)
size = np.sqrt(len(arr))
if not size.is_integer():
raise ValueError('String parsing failed: the string does not encode a square matrix')
size = int(size)
return arr.reshape(size, siz... |
4a841929d8277ce9ebdc78055bf26752aea6e4b2 | yarosmar/beetroot-test-repo | /calculator.py | 667 | 4.1875 | 4 | def calculate():
operation = input()
number_1 = int(input())
number_2 = int(input())
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(numb... |
84fb94c887f0be51efd4178b2c4ec7cebb281ead | jiangshen95/UbuntuLeetCode | /IncreasingTripletSubsequence.py | 550 | 3.59375 | 4 | import sys
class Solution:
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
print(sys.maxsize)
a, b = sys.maxsize, sys.maxsize
for num in nums:
if num <= a:
a = num
elif num <= b:
... |
1c7eba47830d14468c65f397d8a7cff23c4bca57 | KRHero03/College_Labwork | /4th_Year/CNS/Assignment_5/1.py | 4,266 | 4.0625 | 4 | # sample text : once upon a time there was a little girl named goldilocks she went for a walk in the forest pretty soon she came upon a house she knocked and when no one answered she walked right in at the table in the kitchen there were three bowls of porridge goldilocks was hungry she tasted the porridge from the fir... |
77ab15a0c5172b39f5063990cf1de7004eb690d8 | renjieliu/leetcode | /0001_0599/109.py | 858 | 3.875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = r... |
eed520abca91eac5329ce0a66e486a51ea6d511a | TharlesClaysson/Python-Basico | /primeiroModulo/return_par.py | 213 | 3.875 | 4 | def par(n=0):
if n%2==0:
return True
else:
return False
num = int(input('Digite um número: '))
print(par(num))
if par(num):
print(f'{num} é par')
else:
print(f'{num} é impar')
|
f9fe3cda58da69fa068de83790c429df7f878183 | banginji/algorithms_sot | /chapter3/animal_shelter.py | 914 | 3.828125 | 4 | from chapter3 import my_queue
import random
def random_name():
return ''.join(random.choice('0123456789ABCDE') for _ in range(5))
def first_animal_in_line(queue1, queue2):
_, queue1_number = queue1.stack_one.stack_data[queue1._len_queue()-1]
_, queue2_number = queue2.stack_one.stack_data[queue2._len_que... |
0d5825f6572521f24f47ea11409bb24962bcc8d5 | Davvott/CP1404 | /prac_01/loops.py | 720 | 3.8125 | 4 |
# Count odds to 20
for i in range(1, 21, 2):
print(i, end=' ')
print()
# Count in 10's
for i in range(0, 101, 10):
print(i, end=' ')
print()
# Cound down from 20 to 1
for i in range(20, 0, -1):
print(i, end=' ')
print()
# print n stars
user_input = int(input("How many stars?: "))
for i in range(1, use... |
f6c94549e702b48467f7dc127c9698ae12101825 | tokc/guardian | /guardian.py | 1,396 | 3.515625 | 4 | from time import time
class Guardian:
"""Antiflooding mechanism. Track how fast users are sending messages."""
def __init__(self, flood_limit):
# Abstract number that represents how quickly you can flood
self.flood_limit = flood_limit
# "username": (int) number of messages
self... |
07b547b86ac44143b08f0262bcdfc239f12ff658 | computingForSocialScience/cfss-homework-jmausolf | /Assignment5/fetchAlbums.py | 1,573 | 3.8125 | 4 | import requests
from datetime import datetime
def fetchAlbumIds(artist_id):
"""Using the Spotify API, take an artist ID and
returns a list of album IDs in a list
"""
album_url = "https://api.spotify.com/v1/artists/"+artist_id+"/albums?market=US&album_type=album"
#Error Checking for False ID's... |
d319286b57134414881eb23d8771d66484f7b18c | justinjoco/coding_interview_practice | /trapping_rain.py | 1,928 | 4.09375 | 4 | """
Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped... |
15a7ba1f4a7690630a3f66f7757a8d858288f930 | armsky/OnlineJudge | /LeetCode/validSudoku.py | 2,043 | 4 | 4 | """
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cell
s are filled with the character '.'.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable.
Only the filled cells ... |
a06500878ea1c9428cb9157a10002f039cf741af | manvika123/MyFirstPythonProject | /GeneralPrograms/CollectionModule.py | 422 | 3.5625 | 4 | from collections import Counter, defaultdict, OrderedDict
li = [1, 2, 3, 4, 5, 5, 6]
print(Counter(li))
sentence = 'blah blah blah thinking about python'
print(Counter(sentence))
# defualt function lambda
dictionary = defaultdict(lambda: 'does not exist', {'a': 1, 'b': 2})
print(dictionary['c'])
#maintains the orde... |
c6f6eb3a9cab84ae0f465e350d86fd4ff62eb77d | Jheller11/python | /code_samples/class.py | 573 | 3.75 | 4 | class Person(object):
def __init__(self, name, age, location):
self.name = name
self.age = age
self.location = location
def greeting(self):
print(f"{self.name} says hi.")
def how_old(self):
print(f"I am {self.age} years old.")
def where(self):
print(f"I... |
5d8b5358b6ea59d08357871c99a962b2d52ca026 | Alan-luo1991/PythonTest | /04.py | 350 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# def jiecheng(n):
# if n == 1:
# return 1
# else:
# return n*jiecheng(n-1)
# print(jiecheng(3))
def fib(x):
if x == 1 or x == 2:
return x
# 当x > 2时,开始递归调用fib()函数:
return fib(x - 1) + fib(x - 2)
print(fib(50)) # 打印结果为:8
|
ac2c51600c3ab5d1b6e9d996c63ac2b594f99a35 | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/50_7.py | 2,281 | 4.09375 | 4 | Python – Remove digits from Dictionary String Values List
Given list of dictionaries with string list values, remove all the numerics
from all strings.
> **Input** : test_dict = {‘Gfg’ : [“G4G is Best 4”, “4 ALL geeks”], ‘best’ :
> [“Gfg Heaven”, “for 7 CS”]}
> **Output** : {‘Gfg’: [‘GG is Best ‘, ‘ AL... |
505a6a12f3f1d428165b5cbcd1d3e206306953c2 | fredbellinder/lpthw | /ex43.py | 8,439 | 3.84375 | 4 | from sys import exit
from random import randint
from textwrap import dedent
class Scene(object):
# this method would run if a inheriting class had yet not implemented a enter method
def enter(self):
print("Not yet implemented")
exit(1)
class Engine(object):
def __init__(self, scene_map... |
313012b8153a84fb675f405b1e8212c12d3c6326 | yusufkontoglu/Python-Ders-2021 | /Listeler/listeler.py | 1,409 | 4.0625 | 4 | # Liste String iliskisi
text = 'ali topu at'
# print(text.split())
# print(text[2:6])
# Liste tanımlama String list Numeric list Dynamic list + Constructor
ints = [ 1, 2, 3 ] # integer list
floats = [ 1.0 , 3.4 , 46.5 ] # float list
texts = [ 'a' , 'asfasd', 'name' ] # String list
dynamicList = ['a' , 23, 1.0 , True... |
29606dcefe1539a54f7caa99b928e86bce9772c0 | kirigaikabuto/distancelesson2 | /lesson2/11.py | 891 | 4.125 | 4 | a = int(input())
b = int(input())
c = int(input())
maxi = 0
mini = 0
#find max
if a>b and a>c:
maxi=a
elif b>a and b>c:
maxi=b
elif c>a and c>b:
maxi=c
else:
print("Error")
#find min
if a<b and a<c:
mini=a
elif b<a and b<c:
mini=b
elif c<a and c<b:
mini=c
else:
print("Error")
#find middl... |
4a2fc99b68c7eb5462514c4b2ab6ce2120a7ff66 | Qespion/linear_regression | /train.py | 2,266 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import argparse
import matplotlib.pyplot as plt
def check_file_ext(filename):
"""
Check file extension
:param filename:
:return filename:
"""
if not filename.endswith('.csv'):
raise argparse.ArgumentTypeError('wrong fil... |
8d53afd01d7ed8e528909ca547212283243d2695 | kjkjv/test01 | /파이썬 프로그래밍/02_2 문자열.py | 5,827 | 4.0625 | 4 | # ====================0702==========================
# 02-2 문자열.py
'''
파이썬 문자열 자료
'''
a = "python is great"
print(a)
b = 'life is short, you need python'
print(b)
c = "he said 'i love you'"
print(c)
d = 'he said "i love you"'
print(d)
# d = "he said "i love you"" ==> SyntaxError가 난다.
# print(d)
f ='''
HERE!!
hell... |
8fb00c80e8fa2cb9d107cfd89b4af3364e53c451 | masoumehaemmi/tamrin-4 | /multiplication table.py | 283 | 4 | 4 | def multi_table(n , m):
for i in range(1 , n+1):
for j in range(1,m+1):
print('{:>4}'.format(i*j),end='')
if j == m :
print()
n = int(input("enter your number1:"))
m= int(input("enter yore number2:"))
multi_table(n , m) |
7e6ea6f01ee6b42a55704ac841833d8e2960a00d | SupakornNetsuwan/Prepro64 | /test66.py | 427 | 3.765625 | 4 | """Func"""
def func():
"""Dota2 kebab"""
price = int(input())
amount = int(input())
feedb = input()
if feedb == "This kebab is very good":
print("%.2f" %((0.7*price) * amount))
elif feedb == "This is not good not bad":
print("%.2f" %((0.95*price) * amount))
elif feedb == "Th... |
31b62744df90de5bb021b149d8dcba6f5c3baec8 | jaykumarvaghela/myPythonLearning | /Data_Struture/Exercise Array DataStructure/ThirdExercise.py | 127 | 3.96875 | 4 | list_of_odd_number = []
n = int(input())
for i in range(1, n, 2):
list_of_odd_number.append(i)
print(list_of_odd_number)
|
91c8288c480154bf142fee11487d93d161e76d9f | ethanbhuang/Mini-Pygame-Sprite-Test | /controller.py | 6,454 | 3.953125 | 4 | import pygame
import character
import obstacle
import button
import sys
class Controller():
"""
A Controller class
"""
def __init__(self, width=800, height=600):
"""
Initializes a Controller object
Args:
self (Controller): a Controller object
width (int... |
c91aecfd16ef7c8dc2d94d9f1eda68a29258d6a5 | ecanning/inf1340_2015_asst2 | /test_exercise2.py | 1,396 | 3.96875 | 4 | #!/usr/bin/env python
from exercise2 import find, multi_find
""" Assignment 2, Exercise 2, INF1340, Fall, 2015. DNA Sequencing
Test module for exercise2.py
"""
__author__ = 'Erin_Mib'
def test_find_basic():
"""
Test find function.
"""
assert find("This is an ex-parrot", "parrot", 0, 20) == 14
... |
edc538855848b314164924b7e21c6b311a20cedd | yujin0719/Problem-Solving | /백준 using python/5052.py | 1,033 | 3.84375 | 4 | # 5052: 전화번호 목록
import sys
input = sys.stdin.readline
class Node:
def __init__(self,key,data=None):
self.key = key # 한 글자
self.data = data # 마지막 글자의 경우에만 값이 들어감
self.children = {} # dict
class Trie:
def __init__(self):
self.head = Node(' ') # key = None
def insert(self, string):
cur_node = self.head
... |
ddc8914fec04b6f17c7c911c1b527be93d06d70e | marcelosoliveira/trybe-exercises | /Modulo_4_Ciencia da Computacao/Bloco 34: Introdução à Python e Raspagem de Dados da Web/dia_1: Aprendendo Python/exercicios/exercicios.py | 5,107 | 4.53125 | 5 | """ Exercícios
Exercício 1: Crie uma função que receba dois números e retorne o maior deles.
Copiar """
def bigger(number, other):
if other > number:
return other
return number
""" Exercício 2: Calcule a média aritmética dos valores contidos em uma lista.
Copiar """
def mean(numbers):
sum = 0
fo... |
d4839931f400486981a16ff65b571820f59339b8 | Anfercode/Codigos-Python | /Clase 1/Capitulo1/Ejercicio5/OperadoresLog.py | 681 | 3.859375 | 4 | '''
And = Multiplicacion logica
or = Suma Logica
Not = Negacion
^ = Xor(O Exclucivo)
Orden
1-not
2-and
3-or
'''
a = 10
b = 12
c = 13
d = 10
Resultado = ((a > b) or (a < c))and((a == c) or (a >= b))
print(Resultado)
'''
#####################################################################
Prioridad ejecucion ope... |
7a2ee91c5223be5bc606031ecc55594e02fee805 | smvazirizade/INFO521 | /HW3/test/HW1.py | 511 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 1 12:30:35 2017
@author: smvaz
"""
#improting requeired lib
import math
def POISSON(Lambda, y):
#define a function to calculate poisson dist
pmf= math.exp(-Lambda) * Lambda**y / math.factorial(y)
return pmf
# a for loop for calculation of 4=<y=<9
Lambda=3
... |
e51f4a5459287c1bf3d58b9737dc99a23c7f4d14 | linfengzhou/LeetCode | /archive/python/Python/binary_search/74.search-a-2d-matrix.py | 907 | 3.5625 | 4 | class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
n_row = len(matrix)
n_col = len(matrix[0])
start, end... |
31d1e4a76320a6a40106de6587e22ac1d324554e | CaimeiWang/python100 | /013.py | 617 | 3.546875 | 4 | #encoding:utf-8
#打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方
'''
##method1:
a=[1,2,3,4,5,6,7,8,9]
b=[0,1,2,3,4,5,6,7,8,9]
c=[0,1,2,3,4,5,6,7,8,9]
for i in a:
for j in b:
for k in c:
x=i**3+j**3+k**3
y=100*i+10*j+k
if x==y:
... |
069a33b5d0e8a30bf6bd255e0fd08756ef492b7c | ccom33/python_practice | /python_practice/9.12 첨자..py | 923 | 3.625 | 4 | def line():
print("#", "-" * 40)
#-------------------------------
s = "I love python"
print(s[3])
print(s[7])
print(s[-6])
#-------------------------------
s = "python"
for c in s:
print(c ,end = ',')
line()
#--------------------------------
s = "I love python"
for i in range(len(s)):
print(s[i], end = '... |
7bc0571244db142a14cc7ea6de1b6179ebb9bdb2 | jeremyprice/PythonForDevs | /DemoProgs/lcl_glbl.py | 468 | 3.5625 | 4 | """
This program shows what variables are known locally in the main program
as well as the function. It also demonstrates why you need to be
careful when modifying a global, immutable variable from a function.
"""
def lcl_tst(a, b):
z = a + b
print dir(), '\n'
x = 'changed'
print 'x =', x, '... |
5bf3842b174d871c12dfba85daabf8e8030f633c | thongdhv1010/GapoTest | /GapoTest/test/test_check_paragrap.py | 1,369 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: nguyenthong
Date Created: 9/30/20
"""
from src.controller.check_paragraph_controller import Paragraph
def check_function(fun, expect):
check = False
if fun:
check = True
if check == expect:
return 'passed'
else:
... |
90b4390ef3f87153d5cd6c54df1a3f8a891e3c13 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2479/60636/249839.py | 759 | 3.71875 | 4 | MAX_CHAR = 26
def findAndPrintUncommonChars(str1, str2):
present = [0] * len(str1)
for i in range(0, len(str2)):
present[i] = 0
l1 = len(str1)
l2 = len(str2)
for i in range(0, l1):
present[ord(str1[i]) - ord('a')] = 1
for i in range(0, l2):
if(present[ord(str2[i]... |
ad248914eae3ae1bd5c15c02c99b0a0843b4889b | qkrrudtjr954/programmers | /solutions/행렬회전/solution.py | 3,212 | 3.5 | 4 | # import math
#
#
# def solution(rows, columns, queries):
# # 행렬을 초기화 한다.
# matrix = [[0] * columns for _ in range(rows)]
#
# for i in range(rows):
# for j in range(columns):
# matrix[i][j] = i * columns + (j + 1)
#
# answer = []
#
# for x1, y1, x2, y2 in queries:
# # 배열 ... |
926b566804e5c948b0180fa7e269503840494bc5 | lss0312/PY4E | /programming for everybody/course 02/course02_week05.py | 1,310 | 4.28125 | 4 | # dictionaries
# give every element a key and the value
dict1 ={'money':2,'phone':3,'cards':4}
print(dict1['money'])
#>>> 2
dict2 ={}
dict2['money']=1
dict2['apple']=2
dict2['banana']=3
print(dict2)
#>>>{'apple':2,'banana':3,'money':1} dictionaries will not contain the elements in the order you put them in.
... |
b92ddcd7f7a7fe01b8546a8e18ce394c7b6d4d3e | aggiebck/Py | /Python/Lab3 Programs/q5.py | 1,042 | 4.0625 | 4 | #Variables
n1 = float(input("Number #1: "))
n2 = float(input("Number #2: "))
n3 = float(input("Number #3: "))
#Check for different permutations
if n2>n3 and n1>n3:
if n1>n2:
print("Sorted Order: ", n3, n2, n1)
if n2>n1:
print ("Sorted Order: ", n3, n1, n2)
if n1>n2 and n3>n2:
... |
dc262e0b4c73be7dd5fd133830121faa9327f6b8 | lmoshood/python201bookcode | /chapter11_builtins/map_example.py | 110 | 3.703125 | 4 | def doubler(x):
return x * 2
my_list = [1, 2, 3, 4, 5]
for item in map(doubler, my_list):
print(item) |
9ea67e54ce348ceba599f73dd9d51794297d4e08 | maorgottlieb/shapes | /tests/test_circle.py | 595 | 3.875 | 4 | import math
from shapes import Circle
class TestCircle(object):
radius = 10
circle = Circle(radius)
def test_area(self):
expected = math.pi * self.__class__.radius ** 2
assert self.circle.get_area() == expected
def test_perimeter(self):
expected = 2 * math.pi * self.__class_... |
eae2ce5f98d2c85c44fbe32373b997987eaad355 | miteto82/Python-Coursework-2019 | /hacker_rank_challenges/Write a function.py | 304 | 3.671875 | 4 | def is_leap(year):
leap = False
quard = int(year / 4)
one_hund = int(year / 100)
four_hund = float(year / 400)
if year % quard == 0:
leap = True
if year % one_hund == 0:
leap = False
if year / 400 and four_hund % 1 == 0:
leap = True
return leap
|
9e39ccff8c752c768db9c4669a74e6760fb06c5e | Inchara-Ramesh/Python-activities | /activity8.py | 190 | 3.8125 | 4 | userinput=input("enter the list of numbers")
firstelement = userinput[0]
lastelement= userinput[-1]
if (firstelement == lastelement):
print(True)
else:
print(False) |
3d96810aff14ab94b53ae943e5c8505ff832f20a | OlexandrGamchuk1/Homework-5 | /Exercise 2.py | 114 | 3.5625 | 4 | a = int(input('Enter the number '))
b = 1
if 4 < a < 16:
for i in range(1, a + 1):
b *= i
print(b) |
3a0dcb64c0f4bfe52a7e8fab6823c0c2c7abe950 | Yohager/Leetcode | /python版本/Some_Common_DS_Function/Shortest-Path-Algorithms.py | 2,992 | 3.6875 | 4 | '''
一些最短路径算法的汇总
'''
from heapq import heapify, heappop
def dijkstra_basic(edges,n,start):
'''
这是最朴素的dijkstra算法
数据量较小的稠密图 n^2复杂度
不允许边权重为负数
'''
adjs = [[float('inf') for _ in range(n)] for _ in range(n)]
#将顶点的序号归一化到从0开始
for x,y,c in edges:
x -= 1
y -= 1
adjs[x][y]... |
78c092954f9d26ff3f07a7bb8a7e61db1abecdaf | daydaychallenge/leetcode-python | /01358/number_of_substrings_containing_all_three_characters.py | 1,724 | 4.15625 | 4 |
class Solution:
def numberOfSubstrings(self, s: str) -> int:
"""
### [1358. Number of Substrings Containing All Three Characters](https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/)
Given a string `s` consisting only of characters *a*, *b* and *c*.
... |
2073d310c6ce38ce3e7ab353817be5a913308af9 | washing1127/LeetCode | /Solutions/0168/0168.py | 386 | 3.5625 | 4 | # -*- coding:utf-8 -*-
# Author: washing
# DateTime: 2021/1/25 17:38
# File: 0168.py
# Desc:
class Solution:
def convertToTitle(self, n: int) -> str:
s = ""
while n:
r = n % 26
n = n // 26
if r == 0:
r = 26
n -= 1
... |
066d1a28b4799a3444dac6bb9f879392fb800965 | ndrk/pandas-practical-python-primer | /training/level-2-command-line-interfaces/dragon-warrior/tmarsha1/primes/Tests/PrimeGeneratorTests.py | 411 | 3.734375 | 4 | """
Test the Prime Generator class
"""
import unittest
from primes.Primes import PrimeGenerator
class PrimeGeneratorTests(unittest.TestCase):
def test_find_prime(self):
prime = PrimeGenerator.PrimeGenerator()
self.assertEqual(prime.find_prime(6), 13)
def test_find_answer(self):
prime ... |
420dd8e189414a1fd290527b471a5ad252397c0a | Chegeek/IRIS | /RaspberryPi/audioOutput.py | 6,380 | 3.671875 | 4 | '''
This file contains algorithms related to audio output. During navigation, the user receives audio feedback (turn-by-turn
navigation information) over the earphone.
@author: chen-zhuo
'''
import os
from threading import Thread
from time import sleep
audioDict = {} # to map 'audioName' (key) to the corresponding f... |
289e5f89c428b86255b50256f2433947374f26d9 | dohyekim/hello | /lesson_function/4_function_method.py | 1,337 | 3.875 | 4 | # Class에 존재하는 function을 method라고 함
# 반복되는 logic을 재사용할 수 있게 묶어두는 것이 Function(함수)
# def는 keyword. "얘는 함수야"라고 선언해주는 것
# ()는 argument. ".format()처럼" ()안에는 argument로 또다른 함수를 받을 수도 있다.
def fn():
print("fn called")
# fn() 부르기
fn()
# fn() 안 부르면 아무것도 안 나옴.
# ()에 argument를 받는 경우
# 얘는 input(즉 x)도 있고 output도 있다.
def exp(x):... |
bd12dc2e9a41cc3ab0b515f8d665f81532db82a8 | dchandrie/Python | /agebydecade.py | 440 | 4 | 4 | age = float(input("What is your age? "))
if age >= 50 and age <= 60:
print("You are a Quinquagenarian", age)
elif age >=40 and age <= 50:
print("You are a Quadragenarian")
elif age >= 30 and age <= 40:
print ("You are a Tricenarian")
elif age >= 20 and age <= 30:
print ("You are a Vicenarian")
elif ag... |
6ac85a19bd39f62dea55cdd0d7edf519efe42e15 | ankitjindal7240/Algorithms | /unique_path.py | 534 | 3.625 | 4 | rows =6
columns=9
matrix=[]
for i in range(rows):
matrix.append([1]*columns)
# using recursion
def paths(row,column):
if row ==1 or column ==1:
return 1
else:
return paths(row-1,column) +paths(row,column-1)
p=paths(rows,columns)
print(p)
# using dp
def unique_paths(rows,columns):
for... |
898dcb55b5c62a19eb0d9c32d90fa014dd31d291 | Boumaiza-kais/AirBnB_clone | /tests/test_models/test_user.py | 1,240 | 3.65625 | 4 | #!/usr/bin/python3
"""
User Class Unittest
"""
import unittest
import models
from models.user import User
class TestUserClass(unittest.TestCase):
"""
testing user class
"""
def test_user(self):
"""
user test
"""
self.one = User()
self.assertTrue(hasattr(self.on... |
7519f7df6ff36b12c65f50f7f3e5ba9716dcbc40 | Wjun0/python- | /day03/06-列表的遍历.py | 960 | 4 | 4 | # 遍历容器类型中的每一个数据,可以使用for循环来完成,因为比较方便和简单
my_str = 'abc'
for value in my_str:
# 依次打印每次获取的数据
print(value)
# for 结合range 获取字符串中的每一个数据
# 获取字符串的长度: len(字符串)
for index in range(len(my_str)):
print(index, my_str[index])
# while循环
index = 0
while index < len(my_str):
print(index, my_str[index])
... |
5ba3a2d27ec8f58f97c54cc837c81f210362508a | Roooommmmelllll/Python-Codes | /largerNumber.py | 241 | 4.125 | 4 |
def largeNumbers():
value = 0
for i in range(7):
user = int(input("Please input seven numbers: "))
if user > value:
value = user
print("The largest number you entered was: " + str(value) + ".")
largeNumbers()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.