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 |
|---|---|---|---|---|---|---|
ed897e650426c5ec970be08668957c5a5cbc428c | teresahu/digitalcrafts | /CS-Elective/selection.py | 797 | 3.703125 | 4 | """
@package examples
@author Christopher Gallo
This is the base for all examples. Put what your example does here.
"""
from pprint import pprint as pp
class selection_sort():
def __init__(self):
"""Setup
"""
pass
def main(self, arr):
length = len(arr)
for i in range (0, ... |
786f32496a51e2b28c13b5d9d399d9aef392a5fc | teresahu/digitalcrafts | /python-exercises-1/madlib.py | 315 | 3.703125 | 4 | from time import sleep
verb = input("Give me an infinitive verb: ")
noun = input("Now give me a noun: ")
adj = input("Finally, give me an adjective: ")
print("Get ready for the mad lib sentence!")
sleep(1)
print("Ready?")
sleep(1)
print("You like {0} a(n) {1} {2}!".format(verb.lower(), adj.lower(), noun.lower()))
|
c832a751575f447083ab7ac082083f708ae68085 | teresahu/digitalcrafts | /CS-Elective/bubble.py | 831 | 3.859375 | 4 | """
@package examples
@author Christopher Gallo
This is the base for all examples. Put what your example does here.
"""
from pprint import pprint as pp
class bubble_sort():
def __init__(self):
"""Setup
"""
pass
def main(self, arr):
is_sorted = False
while is_sorted is Fal... |
0cd5b92fbce3315dca5f35c815a7b6d73f91bbef | teresahu/digitalcrafts | /python-exercises-2/caesar_cipher.py | 726 | 4.15625 | 4 | caesar = {
'a' : 'n',
'b' : 'o',
'c' : 'p',
'd' : 'q',
'e' : 'r',
'f' : 's',
'g' : 't',
'h' : 'u',
'i' : 'v',
'j' : 'w',
'k' : 'x',
'l' : 'y',
'm' : 'z',
'n' : 'a',
'o' : 'b',
'p' : 'c',
'q' : 'd',
'r' : 'e',
's' : 'f',
't' : 'g',
'u' :... |
4cba3859b876d081b9306cbe828a030cf169e9bf | KrutiiDmytro/homework8 | /hm8.py | 1,918 | 3.8125 | 4 | # Задание 1
# Заполнить список ста нулями, кроме первого и последнего элементов, которые должны быть равны единице;
lst = [0] * 50
lst[0] = lst[-1] = 1
print(lst)
# Задание 2
# Сформировать возрастающий список из чётных чисел (количество элементов 45)
sps = list(range(0, 45, 2, ))
print(sps)
# Задание 3
# Пользовател... |
c194ad908c58e8e8c82408b5f49b262972591d07 | jonatan098/cursopython | /mundo 3/aula 17/exer80.py | 519 | 3.96875 | 4 | valores = []
for p, c in enumerate(range(0,5)):
num = int(input('digite um numero: '))
if c == 0 or num > valores[-1]:
valores.append(num)
print(f'{num} foi adicionado na ultima posição...')
else:
pos = 0
while pos <= len(valores):
if num <= valores[pos]:
... |
3ac8aafbbbf2786db5d0c02222f7775eb85790bc | jonatan098/cursopython | /mundo 1/aula 7/exer7.py | 128 | 3.75 | 4 | n1 = float(input('digite a primeira nota '))
n2 = float(input('digit a segunda nota '))
print(f'a media do aluno e {(n1+n2)/2}') |
fd9bfaf1414748b977c7cf8e6bea850e93bf468b | jonatan098/cursopython | /mundo 2/aula 15/exer69.py | 633 | 3.625 | 4 | #ANALISE DE DADOS
cont18 = conth = contm20 = 0
while True:
age = int(input('idade: '))
sex = ' '
while sex not in 'MF':
sex = str(input('sexo [M/F]: ')).upper().strip()[0]
if sex == 'M':
conth += 1
if age < 20 and sex == 'F':
contm20 += 1
if age > 18:
cont18 += 1... |
f7d92ff7d26e20753ff667fe3ab0ff2aba183550 | jonatan098/cursopython | /mundo 2/aula 13/exer50.py | 253 | 3.90625 | 4 | #CALCULANDO A SOMA DOS NUMEROS PARES
soma = 0
cont = 0
for c in range(1,7):
numb = int(input(f'digite {c}° numero: '))
if numb % 2 == 0:
cont += 1
soma += numb
print(f'voce digitou {cont} numeros pares e a soma deles é {soma}') |
460dce7d8fba709357fe2a963e9b10b1ec19ede6 | jonatan098/cursopython | /mundo 1/aula 10/exer28.py | 520 | 3.84375 | 4 | #JOGO DE ADIVINHAÇÃO
from random import randint
from time import sleep
comput = randint(0,5) #faz o computador "PENSAR"
print('\033[0;34;0m-=-\033[m' *20)
print('vou pensar e um numero entre 0 e 5. tente adivinhar...')
print('\033[0;34;0m-=-\033[m' *20)
jog = int(input('em qual numero eu pensei? ')) #jogador tenta adiv... |
a156cabe8201b6436ff663a1a6c4f1484e8acd2a | jonatan098/cursopython | /mundo 1/aula 7/exer11.py | 137 | 3.65625 | 4 | larg = float(input('qual e o largura ? '))
alt = float(input('qual e a altura ? '))
print(f'A quantidade de tinta necessaria e {c*l/2}l') |
0da9926f184beec27769fb1f3b45854e6b0ed54e | jonatan098/cursopython | /mundo 3/aula 20/exer98.py | 785 | 3.734375 | 4 | # uma PA personalizada
from time import sleep
def contador(p1,pn,r):
if r < 0:
r *= -1
if r == 0:
r = 1
print('-='*20)
print(f'contagem de {p1} até {pn} de {r} em {r}')
sleep(2.5)
if p1 < pn:
cont = p1
while cont <= pn:
print(cont, end=' ', flush=True)... |
c330b1cecb419db4c6d2f74734ed113fcf342149 | jonatan098/cursopython | /mundo 1/aula 9/exer24.py | 89 | 3.859375 | 4 | city = str(input('digite o nome da cidade: ')).strip().lower()
print(city[:5] == 'santo') |
080b0602b23d648372b60e3a99fd393b093b3cf7 | jonatan098/cursopython | /mundo 1/aula 9/exer23.py | 187 | 3.796875 | 4 | numb = int(input('digite um numero: '))
n = str(numb)
print('unidade: {}'.format(n[3]))
print('dezena: {}'.format(n[2]))
print('centena: {}'.format(n[1]))
print('milhar: {}'.format(n[0])) |
a0208582f00a6f392e80905246e296dd45e843ca | b-ark/lesson_4 | /Task3.py | 820 | 4.375 | 4 | # Create a program that reads an input string and then creates and prints 5 random strings
# from characters of the input string.
# For example, the program obtained the word ‘hello’, so it should print 5 random strings(words)
# that combine characters ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ -> ‘hlelo’, ‘olelh’, ‘loleh’ …
# Tips: Use ... |
7e43ce6347926ccb51eeedfa6592f7e0a64e2851 | harr1424/tutoring | /battleship.py | 8,669 | 3.640625 | 4 | import random
class Board():
def __init__(self):
self.matrix = self.get_matrix(10, 10)
def get_matrix(self, n, m):
matrix = [[None for j in range(m)] for i in range(n)]
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix[i][j] = "_"
r... |
52173ccafabc815efd1c6c5099eb6c7d75edc4a7 | ataipale/phonebook | /phonebook.py | 3,270 | 4 | 4 | #!/usr/bin/env python
'''
Requirements:
pip install pymongo
brew install mongodb
run the command 'sudo mongod' before running this program to initiate connection to mongodb
example:
$ python phonebook.py lookup sarah friend
'''
import sys
import pymongo
def create(phonebook_name):
'''cr... |
14a4b02855d5b08a9a4c3b2eb8ee8e69474fed12 | Atularyan/Letsupgrade-Assignment | /Day_3_Assignment/Day_3(Question2).py | 338 | 4.25 | 4 | """
Question 2
Define a function swap that should swap two values and print the swapped variables outside the
swap function.
"""
def swap(n):
rev=0
while(n>0):
rem=n%10
rev=(rev*10)+rem
n=n//10
return (rev+n)
n=int(input("Enter the number = "))
res=swap(n)
print("swap... |
814e3e873cfdcb52aff5e22aea9bc666c136aab0 | Atularyan/Letsupgrade-Assignment | /Day_2_Assignment/Day_2(Question1).py | 325 | 4.0625 | 4 | """Question 1
Write a Python program to print even numbers in a list.
Sample:
Input: list1 = [12, 3, 55, 6, 144]
Output: [12, 6, 144]
Input: list2 = [2, 10, 9, 37]
Output: [2, 10]"""
n=[int(i) for i in input("Input: List1 = ").split(",")]
k=[]
for i in n:
if i%2==0:
k.append(i)
print("Output :... |
e770c8743de1d4c6bfa63a269daaebfbc301d318 | stefano-lupo/CS4404-Project-2 | /linearRegression.py | 2,484 | 3.6875 | 4 | ####
####Loading in Data and organising it
####
import matplotlib.pyplot as plt
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error,mean_absolute_error, r2_score
#import util functions
from util import *
# Prepends a column of ones to design matrix to represent bias term
def pre... |
7e25647bc9770cb2c11e2b0d781e410dc8d67441 | vijay-Jonathan/Python_Training | /bin/4_str_class_example.py | 8,815 | 4.09375 | 4 | """
In this section, we are discussing about
Core Data Types, That too
2. str class
"""
a = 'WEL COME' # Internally it calls str('WEL COME')
b = "WEL COME" #Internally it calls str("WEL COME")
c = '''WEL COME''' # Internally it calls str('''WEL COME''')
d = """WEL COME""" # Internally it calls str("""WEL COME""")
e = ... |
bffabf29fc5de18d768b496a88876b60a54d8e6b | vijay-Jonathan/Python_Training | /bin/31_program_log_process_functions.py | 1,547 | 3.734375 | 4 | """
If we make 22nd log processing example to function,
we can use same function to process different log files
Finally,
write a function to take filename/path as an argument, extract all info like
IP
DATE
IMAGE
URL
and return list of tuples. where each tuple will be having one line details
Ex: [ (''123.123.123.123',d... |
e47a5b27a63194e1a59814f5ce3d9d5fe1f0c5cc | vijay-Jonathan/Python_Training | /bin/44_classes_static_methods.py | 2,156 | 4.15625 | 4 | """
Client Requiremnt is :for 43rd example, add method to compute percentage,
if student pass marks, method should return percentage.
Now,
for this compute_percentage method, not required to pass instance object OR
class object, only passing 2 marks is enough method will return perecnetage.
Other methods inside the ... |
f14ac23d41d53f6cb09d94da5facd833aa3bb7f6 | vijay-Jonathan/Python_Training | /bin/2_core_datatypes.py | 1,842 | 4.25 | 4 | """
CORE DATA TYPES :
Similar to other languages, in python also we ALREADY have SOME options to store SOME kind of data.
In that,
1. int,float,hex,bin classes : ALREADY have option to store numbers like int, float, hex, bin, oct etc
2. str class : ALREADY have option to store Strings like "My Name", "My Addess" etc
3... |
7193d0566d17bede6c3fe0c3e52769a0a4e1a17c | vijay-Jonathan/Python_Training | /bin/7_list_class_example.py | 3,280 | 3.796875 | 4 | """
List class : help us to store morethan one element
List class : MUTABLE (ADD/REMOVE/UPDATE)
"""
L1 = [10,12.5,"Python",["a","b"]] # Shortcut is []
L2 = list([10,12.5,"Python",["a","b"]])
print("Lists are : ",L1,L2,sep="\n")
# List also having indexes similar to strings.
# Please 4_str_example.py for
# 1) accessin... |
c065a41651f03ca8f13fa7ae3f1102006e602962 | N1ck079/lessons | /hw06_easy.py | 2,972 | 4.28125 | 4 | # Задача-1:
# Следующая программа написана верно, однако содержит места потенциальных ошибок.
# используя конструкцию try добавьте в код обработку соответствующих исключений.
# Пример.
# Исходная программа:
def avg(a, b):
"""Вернуть среднее геометрическое чисел 'a' и 'b'.
Параметры:
- a, b (int или fl... |
f5b2a6bf38789deeaec673496bac8bbee43fd73d | InspiredCoders/inception | /inception/core.py | 1,129 | 3.65625 | 4 | import os
from pathlib import Path
def get_file_names(folder_path):
'''
Function to get the file names inside the folder provided.
File names from the nested directories are not included.
'''
if not os.path.isdir(folder_path):
return None
files = tuple(item for item in os.listdir(folde... |
ba07cec6d0f3f8f0131b8ac1680314dedb04dd89 | dmonzonis/advent-of-code-2019 | /day3/day3.py | 2,192 | 4.28125 | 4 | def compute_path(path):
"""Return a set with all the visited positions in (x, y) form"""
current = [0, 0]
visited = {}
total_steps = 0
for move in path:
if move[0] == 'U':
pos = 1
multiplier = 1
elif move[0] == 'D':
pos = 1
m... |
bf6b49cc5fdd3fdd77d8e383268c96861f339cff | KhuziamaR/Algorithms_Dynamic_Programming | /Memoization/canConstruct.py | 1,742 | 3.5625 | 4 | def canConstruct(string, array, memo = dict()):
if string in memo:
return memo[string]
if string == "":
return 1
count = None
for st in array:
if string.startswith(st):
size = len(st)
if canConstruct(string[size::],array) == 1:
if count == ... |
2fe35426a0e03f5898a1d703beed6e2fb5d65132 | bruno319/personal-studies | /python/src/exceptions/division.py | 690 | 3.71875 | 4 | def divide(n):
try:
return n / 0
except ZeroDivisionError:
print('divisão por zero')
def open_file():
try:
arquivo = open('palavras.txt', 'r')
except IOError:
print('não foi possível abrir o arquivo')
else:
print('o arquivo tem {} palavras'.format(len(arquiv... |
e2cc8edfc6e6d035998e670e5478936867a5bc5e | ThomasMLawrence/shell | /myshell.py | 684 | 3.90625 | 4 | #Michael Lawrence
#CS 350
#Professor Lund
def shell_gap(array, gap):
for i in range(gap, len(array)):
#make a hole at the first gap item
temp = array[i]
j = i
while(j >= gap and array[j - gap] >= array[j]):
#insertion short by the gap size
array[j] = array[... |
98384603d3d6630d5a1d71500e41a9bbe45a619c | Ads99/python_learning | /MITx-6.00.1x/ProblemSet2/ps2.py | 3,116 | 4.59375 | 5 | # Problem 1
# Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment
# required by the credit card company each month. The following variables contain values as described below:
# balance - the outstanding balance on the credit card
# annualInterestRate... |
e32be6c2e8f82107962b74223c131d2d6bbfed63 | Ads99/python_learning | /Kaggle/Titanic Problem/Python Only Solution.py | 10,809 | 3.90625 | 4 | __author__ = 'ABaker'
'''
The first thing to do is to import the relevant packages
that I will need for my script,
these include the Numpy (for maths and arrays)
and csv for reading and writing csv files
If I want to use something from this I need to call
csv.[function] or np.[function] first
'''
import csv as csv
im... |
1f0098777ff3a2e76c59da3a5adaabb0cda212e8 | Ads99/python_learning | /python_crash_course/_7_user_input_while_loops.py | 5,553 | 4.3125 | 4 | message = input("Tell me something: ")
print(str(message))
prompt = "If you tell us who you are, we can pesonalise messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello," + str(name) + "!")
# Letting the user choose when to quit
prompt = "\nTell me something, I will repeat:"
... |
17baad513d548bf71b1ec6eea648fa0ca2917d7d | Ads99/python_learning | /python_crash_course/names.py | 924 | 4.15625 | 4 | name = "ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
message = "Hello, " + full_name.title() + "!"
print(message)
# whitespace demo
print("\tPython")
print("Languages:\nPython\nC\nJavaScri... |
1eb80efb19d1ef10b0b5ef2cfe6db47a3d3dc2ff | Ads99/python_learning | /python_crash_course/_11_3_example_employee_class.py | 1,023 | 4.46875 | 4 | # Example 11.3 - Employee
# Write a class called Employee. The __init__() method should take in a first
# name, last name and an annual salary and store each of these as attributes.
# Write a method called give_raise() that adds $5000 to the annual salary by
# default but also accepts a different raise amount
class Em... |
a56cc0fb1280a564f452e9f36dc07e5d2b6fd17e | chxtan/Faulty-Calculator | /Faulty_Calculator.py | 545 | 4.09375 | 4 | num1= int(input("Enter first number:"))
num2= int(input("Enter Second number:"))
print("Select any of the one '+,-,*,/,%'")
num3= input()
if num1== 45 and num2 == 3 and num3 == '*':
print("555")
elif num1== 56 and num2 == 9 and num3== '+':
print("77")
elif num1== 56 and num2 == 6 and num3== '/':
print("4")
... |
96531e78d6b8ac9e453209bd9ed7222460527dcb | RPietersma/learning-python | /basic_string_ops.py | 587 | 3.5625 | 4 | catname = "Andromeda"
print len(catname)
dloc = catname.index("m")
print dloc
print catname.count("d")
print catname[0:5]
# Andromeda is a cutie!
message = "Andromeda is not a cutie!"
print message[0:13] + message[17:25]
print("%s %s") % (message[0:12], message[17:25])
print message[::-1]
# I'm so happy we have h... |
b87eaf767df26066a7abb2c833eccb12a918db37 | shenjiangqiu/tptpu-sim | /generate_dram_config.py | 2,058 | 3.5625 | 4 | # the code should be run in the following format:
# python generate_dram_config.py dram_name num_channels num_ranks
# for example, python generate_dram_config.py DDR3_1600K 1 1
# This file looks specifically for the file named "dram-config.cfg" in the directory.
# It will replace the first line that has " standard = "... |
6e8e0d0010bef792b0974a2b7b4bf19b9a0fcc4f | Kamisi24/dottv | /python dottv/movies.py | 1,221 | 3.6875 | 4 | #class Movies:
#def __init__(self, name, genre1, genre2):
#self.name = name
#self.genre1 = genre1
#self.genre2 = genre2
#Avengers = Movies('Avengers', 'Superhero', 'Action')
#Darknight = Movies('The Dark knight', 'Superhero', 'Action')
#Soundofmus = Movies('Sound of Music', 'Musical', 'Roma... |
940ec26dc0122c0827f8c1d862c4e59ecbf84d42 | HetoreDev/Python | /exercicios/ex010.py | 295 | 3.703125 | 4 | import os
os.system('cls')
real = float(input('Insira a quantidade de reais que você tem? R$'))
cotacao = float(input('Qual a cotação do dolár de hoje: '))
dolar = real / cotacao
print('Com R${:.2f} pela cotação de US${:.2f}, você pode comprar US${:.2f}'.format(real, cotacao, dolar)) |
4e17829fe663ca1eeafe3c74593475ed05f99192 | HetoreDev/Python | /aula04/desafio02.py | 178 | 3.796875 | 4 | dia = input('Em que dia você nasceu?')
mes = input('Em que mês?')
ano = input('De qaul ano?')
print('Você nasceu no dia ',dia,' do mês de',mes,' do ano de ',ano,'.Correto?')
|
9d24845dd609cd4e9d3f4bcc5948ca15482506d7 | aaronhnash/CSE-212-Project | /03-tree.py | 8,507 | 4.59375 | 5 | # Introducing recursion!
def recursive_message_1(message):
print(message)
recursive_message_1(message)
#recursive_message_1("hello") # uncomment if you dare!
def recursive_message_2(message, count):
count -=1
if count >= 0:
print(f"{message} {count}")
recursive_message_2(message, cou... |
a3708c4ef199292e934de62f9da4bfe1f57aaa79 | ytf513/python_code | /regular expression/search_test.py | 561 | 3.546875 | 4 | #coding=utf8
#search:查找内容,将字符串的所有字符与正则表达式匹配,只找到第一个匹配的内容;findall是返回元组序列
import re
searchStr="You are deleted yintianfeng@gis.com"
rx=r"deleted (.*)@gis\.(.*)$"
searchResult=re.search(rx,searchStr)
#group=group(0),group(1)=第一个返回的元素
print type(searchResult)
print searchResult.group(1),type(searchResult.group(1))
print s... |
3bdd8fc21474c7e976a1480dcf8178cbbd740a85 | ytf513/python_code | /list/map_test.py | 353 | 3.8125 | 4 | #coding=utf8
#map函数
#假设有一个数列,如何把每个元素都翻倍;如何求和两个数列
list_1=[1,2,3,4,5,6]
list_2=[1,3,5,7,9,11]
list_12=[i*2 for i in list_1]
print list_12
list_122=map(lambda i:i*2,list_1)
print list_122
list_22=map(None,list_1,list_2)
print list_22
list_221=map(lambda x,y:x+y,list_1,list_2)
print list_221
|
c680eefbc77c54ae771f11545ebdbe4790b5b0ee | spatala/gbpy | /gbpy/byxtal/tools.py | 27,851 | 3.828125 | 4 | import numpy as np
from . import integer_manipulations as int_man
from . import quaternion as quat
from math import pi
class Col(object):
"""
This class is defined to ouput a word or sentence in a different color
to the standard shell.
The colors available are:
``pink``, ``blue``, ``green``, ``dgr... |
54df13132f5fb1a4736a56b6ae723fe55d3865e3 | mattogrady87/Python_Crash_Course_Pygame | /exercises/13-5.Catch/score.py | 722 | 3.859375 | 4 |
class Score():
"""A Class to keep track of score and modify settings"""
def __init__(self, settings):
self.score = 0
self.high_score = 0
self.settings = settings
def increase_score(self):
self.score += 1
if self.score > self.high_score:
self.high_score =... |
3ca41415e21429ff50cc17df60a9d67aa566cca8 | kat-kime/Word-Count-Program | /word_count.py | 3,001 | 4.5 | 4 | # word_count.py
# ===================================================
# Implement a word counter that counts the number of
# occurrences of all the words in a file. The word
# counter will return the top X words, as indicated
# by the user.
# ===================================================
import re
from ... |
3cfab52ab94424f9c3418a5fb4d7d37b32376b8b | sbsreedh/Heaps-1 | /mergeKLists.py | 1,175 | 4.03125 | 4 | #Time complexity:O(nklogk)
#Space complexity:O(k)
#Ran successfully on leetcode:Yes
#Algorithm:
#1. Create a heap with such that all the heads of each linked list is added to it and heapify it.
#2. Now declare Head and Tail as None.
#3. Now take out the top element from heap and store in a temp node. If head is None ... |
757ce8588b98ef26d76e0a09739532bc25d17f3a | aryanjbm/algorithms | /lcs.py | 1,624 | 3.515625 | 4 |
def find_lcs(x,y):
i=len(x)
j=len(y)
cost=[]
s=[]
for k in range(i+1):
temp=[]
for l in range(j+1):
temp.append(None)
cost.append(temp)
for k in range(i+1):
temp=[]
for l in range(j+1):
temp.append(None)
... |
8b918360be7f45468c503e81f9c32b52e174ca17 | AdarshSubhash/C-97- | /hwpro.py | 351 | 4.15625 | 4 | number=6
guess=int(input("Guess a number between 1 to 10"))
if(guess==number):
print("You Guessed The Right Number")
elif(guess>number):
print("Try a bit lower number")
guess=int(input("Guess a number between 1 to 10"))
else :
print("Try a bit higher number")
guess=int(input("Guess a number... |
bc9d1eab9d6814507a2f7c0458034592ee8d0472 | umidori/nqueens | /procedural/queens.py | 568 | 3.65625 | 4 | #!/usr/bin/env python
import sys;
def nqueens(size):
row = [True] * size
up = [True] * (2*size-1)
down = [True] * (2*size-1)
board = [None] * size
def queen(n):
if n >= size:
print ' '.join(map(str, board))
else:
for i in range(0, size):
if r... |
e2895d452fd5f38fcec1469a2ce60e14feb96d13 | cambers/ReallyRealFlask | /2_SQL/6_script.py | 645 | 3.8125 | 4 | import sqlite3
with sqlite3.connect('newbie.db') as conn:
c = conn.cursor()
cities = [
('Atlanta','GA',200),
('Macon','GA',200),
('Dawson','GA',400)
]
c.executemany("INSERT INTO population VALUES(?,?,?)", cities)
c.execute("DELETE FROM popula... |
e9381d80852be29aa4eb5b2cbf5e80b0781e6b41 | WensiPeng/Ormuco-TechnicalTest | /checkOverlap.py | 420 | 3.6875 | 4 | # function checkOverlap
# returns true if two lines overlap
# returns false if not
def checkOverlap(x1, x2, x3, x4):
#rearrange inputs such that x1 < x2 and x3 < x4;
if x1 > x2:
x1, x2 = x2, x1
if x3 > x4:
x3, x4 = x4, x3
#check if two lines are overlapped
if(min(x2, x4) - m... |
3bbd1dd83bbe07ad0548784fd5957472c493c920 | ricpelo/pro2021 | /fib/aleatorio.py | 434 | 3.546875 | 4 | from random import randint
x = randint(1, 100)
fin = False
while not fin:
try:
a = int(input('Adivina el numero: '))
if a == x:
print('Has acertado.')
fin = True
elif a == 0:
print('Adios.')
fin = True
else:
print('Vuelve a... |
22864f379c0cba0db8f5ae291d5827ce356d9d29 | ricpelo/pro2021 | /racional.py | 1,675 | 3.703125 | 4 | from math import gcd
class Racional:
def __init__(self, num, den):
"""
Constructor que crea un racional a partir de un numerador y
un denominador.
"""
Racional.__simp = False
self.__set_numer(num)
self.__set_denom(den)
Racional.__simp = True
s... |
5c63432eb9b2cf3500404924e9810f7f048318f5 | MelWavestone/pygorithm | /pygorithm/data_structures/queue.py | 3,156 | 4.375 | 4 | # Author: OMKAR PATHAK
# Created On: 3rd August 2017
# queue implementation
class Queue(object):
'''
size : return the current size of the queue
enqueue : insert an item into the queue
dequeue : remove an item from the queue which was first inserted
isEmpty : check if the queue is empty
''... |
3a4ea73c530944c6a2f84c030142475408105000 | jerrylovepizza/amazing-python | /Study/interesting_program/leap_year.py | 259 | 3.71875 | 4 | """
Copyright: Copyright (c) 2019
License : WTFPL License
owner : pynickle
title : amazing-python study projects
description : projects for studying python
"""
x = int(input())
if x % 4 == 0 and x % 100 != 0 or x % 400 == 0:
print(True)
else:
print(False)
|
a65868681fd44ee53b5afb6253f6d486cc6f17bf | jerrylovepizza/amazing-python | /Study/interesting_program/calculator.py | 868 | 4.0625 | 4 | """
Copyright: Copyright (c) 2019
License : WTFPL License
owner : pynickle
title : amazing-python study projects
description : projects for studying python
"""
symbol1 = ("+", "-", "*", "/", "//", "**", "(", ")")
symbol2 = ("1", "2", "3", "4", "5", "6", "7", "8", "9", "0")
question=input(">>>")
legal=True
split_eval="... |
c875cd518292114580184e6ace335dea9ac697ee | jonathanchu/python-remove-quotes | /remove_quotes/cli.py | 614 | 3.5 | 4 | import os
import click
@click.command()
@click.option('--filename', '-f', help='Filename to process.')
@click.argument('filename', required=True)
def main(filename):
"""Removes all quotes in a file."""
read_filename = filename
orig_filename, ext = os.path.splitext(read_filename)
write_filename = orig_... |
88698f3beb713272e519ae8b3310ff0ae4e4d254 | allenlgy/Django-project | /01—python基础/hm_09_格式化输出.py | 552 | 3.875 | 4 | # 定义字符串变量 name
name = "小"
print("我的名字叫 %s,请多多关照" % name)
# 定义整数变量 student_no,%06d是如果数字没有六位,则前面自动补零
student_no = 200000
print("学生学号为 %06d" %student_no)
# 定义小数%f,float类型,%.2f显示两位小数,可以任意改
price = 8.5
weight = 7.5
money = price * weight
print("苹果单价 %.2f,购买了 %.3f 斤, 一共用了 %.4f 元" %(price,weight,money))
# 定义个小数,输出百分号
sale ... |
ea668076811923f7b85680ec30555f5d7c4510c4 | allenlgy/Django-project | /03_循环/hm_09_print函数的结尾.py | 175 | 4.03125 | 4 | # 在默认情况下, print 函数会在末尾自动加上换行
for i in range(3):
print(i)
# 要想不要换行,可以加上
for i in range(3):
print(i,end='') |
a05f993abb9e050600a4a084b2ff23cc0e4717a7 | allenlgy/Django-project | /面向对象特性/hm_08_父类的共有方法.py | 935 | 4 | 4 | # 子类可以间接访问父类的私有属性和方法
class A:
def __init__(self):
self.num1 = 100
self.__num2 = 200
def __text(self):
print("私有方法 %d %d" % (self.num1, self.__num2))
def test(self):
print("父类的共有方法 %d "% self.__num2)
self.__text()
class B(A):
def demo(self):
# 1. 在子... |
576b6297c815e257711d05a8deb4d23f7dfcb3d2 | allenlgy/Django-project | /高级数据类型/hm_20_for语法演练.py | 149 | 3.9375 | 4 | for num in [1,2,3]:
print(num)
if num == 3:
break
# 如果循环不正常结束, else 不会被触发
else:
print('over') |
3447f51022cd359f6296c8bdcc96db18bb51dfff | buratina/Learning-Python-v- | /Section 7/function002.py | 132 | 3.609375 | 4 | def func():
global k
k=k+7
print "variable k is now global",k
k=10
func()
print "Accessing the value of k outside the function",k |
6ca9a14f342d6f6a7d52a97e816abc56fc5a68f1 | buratina/Learning-Python-v- | /Section 9/finally1.py | 166 | 3.765625 | 4 | try:
num = int(raw_input("Enter the number "))
re = 100/num
except:
print "Something is wrong"
else:
print "result is ",re
finally :
print "finally program ends" |
20e9da32a0c3f2859bcaf33e713c1d6fd1164eec | edhaarmanniv/blackjack | /blackjack.py | 5,798 | 3.671875 | 4 | from random import shuffle as rshuffle
from terminaltables import SingleTable
class Card:
def __init__(self, face, value, suit):
self.face = face
self.value = value
self.suit = suit
self.card = face + suit
self.front = f"[{self.card}]"
self.back = "[**]"
sel... |
9412ad01afec9e8a7d918decc3291397621ccfef | Fantasia-Infinity/Simulations | /Slime12.py | 19,748 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 03 14:03:42 2017
@author: Fantasia
"""
import random
import pygame
import math
class Unit:
def __init__(self, c, state, c2, c3, c4, life):
self.c = c # 信息素浓度
self.c2 = c2
self.c3 = c3 # b反捕食者信息素
self.c4 = c4 # 尸体腐烂的味道... |
2e381618f6ddccb586e33ac6c8e7dd5c3c60d21b | jimmyandres10/preinformerepetici-n | /mainpreinforme2.py | 485 | 3.96875 | 4 | def main():
numero_de_notas = int(input("escriba el numero de notas que va a colocar "))
cont_d = 0
cant_n = 0
for i in range(1,numero_de_notas+1):
if cont_d < numero_de_notas :
nota = float(input("escriba su nota "))
cant_n = nota + cant_n
cont_d = cont_d +... |
535078210140bdc0e65ad177ecd878311c199a85 | mandyabernathy/BiofilmGui | /model.py | 4,620 | 3.65625 | 4 | # Mandy Abernathy
# model.py
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from scipy.integrate import solve_ivp
import numpy as np
class Model:
"""
A class for modeling bacterial biofilm growth according to a logistic
equation that also describes inhibitory treatments.
... |
46a80d2f2be7f50395d1d80fda9d5b56375abb9a | StYaphet/learn_python | /exception.py | 1,723 | 4.15625 | 4 | # print(5 / 0)
# ZeroDivisionError是一个异常对象。当python无法按照你的要求做的时候,就会创建这样的对象
# 在这种情况下,python将会停止运行程序,并指出发生了哪些异常,饿哦们就可以根据这些信息对程序进行修改
# 当认为可能发生了错误时,可编写一个try-except代码块来处理可能引发的异常。
try:
print(5 / 0)
except ZeroDivisionError:
print("You can't divide by zero!")
# 如果try-except 代码块后面还有其他代码,程序将接着运行,因为已经告诉了Python如何处理这种错误
#... |
4d5aea2f9d176c16b665064761a8053cef554793 | StYaphet/learn_python | /store_data.py | 980 | 4.28125 | 4 | # 模块json 让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。
# 你还可以使用json 在Python程序之间分享数据。
# 更重要的是,JSON数据格式并非Python专用的,这让你能够将以JSON格式存储的数据与使用其他编程语言的人分享。
# 这是一种轻便格式,很有用,也易于学习。
# 首先导入模块json,在创建一个数字列表。
import json
numbers = [2, 3, 5, 7, 11, 13]
# 指定了要将该数字存储到其中的文件的名称,通常使用文件扩展.json来指出文件存储的数据为JSON格式。
filename = "numbers.json"
# 接下... |
9d95145297511d6e74baabb29372d62a922ad8e0 | marciohssilveira/airports_climatology | /src/d01_data/get_data.py | 11,701 | 3.578125 | 4 | import urllib.request
from urllib.error import HTTPError
import pandas as pd
from pandas.io import parsers
import os
import math
import re
import numpy as np
from pathlib import Path
import warnings
import datetime
class GetIsdData:
"""
Contain functions to gather data from ISD,
organise the files in dire... |
05b771a27856ba085e7185fe44f9b92657abea9e | daltonfury42/truecase | /tests/test_truecase.py | 1,604 | 3.859375 | 4 | import unittest
import truecase
class TestTrueCase(unittest.TestCase):
def setUp(self):
self.tc = truecase.TrueCaser()
def test_get_true_case(self):
sentence = "I live in barcelona."
expected = "I live in Barcelona."
result = self.tc.get_true_case(sentence)
assert res... |
3e277a9df280c58d7cfd03ea7b385fdeb0044900 | challengers01/spending-data-importer | /src/dbutil.py | 2,386 | 3.65625 | 4 | import sqlite3
expenses_table_name = "expense_data"
categories_table_name = "categories_data"
db_location = "../expenses360.db"
create_expenses_table_sql = "CREATE TABLE IF NOT EXISTS " + expenses_table_name + "(tx_id INTEGER PRIMARY KEY AUTOINCREMENT, tx_date DATE, tx_description TEXT NOT NULL, tx_amount TEXT, tx_ca... |
1b97982833b28ea5929a9cca461eb6b93cb5b63f | jordonwu/weio | /things/servomotor.py | 1,778 | 3.578125 | 4 | ###
# Authors :
# Uros PETREVSKI <uros@nodesign.net>
###
###
# Controling servo motor with PWM signal
# Pulse length is constant of 20ms, variate impulse from 1ms to 2ms
#
# +---+ +---+
# | | | |
# | | | |
# | | | |
#---+ +-------------... |
c5925fd4f8ac5311b357686f69e0d7d0633a28aa | StatisticsOfExtremes/Programming-for-Computations | /exercices_1.py | 2,672 | 3.890625 | 4 | from numpy import linspace, zeros, mean
import matplotlib.pyplot as plt
import numpy as np
from numpy import pi
from random import randint, randrange, uniform
h = np.array([1.60,1.85, 1.75, 1.80])
H = np.array([0.50, 0.70, 1.90, 1.75])
family_member_no = np.array(range(0,4))
plt.plot(family_member_... |
df84bbcb8cdc4452c70c206ada26ab72e56c708a | Zorro-Lin-7/WebScraping-in-Action | /斗鱼AJAX.py | 1,136 | 3.515625 | 4 | from selenium import webdriver
from bs4 import BeautifulSoup
url = 'http://www.douyu.com/directory/all'
browser = webdriver.PhantomJS() # 用PhantomJS 作浏览器
browser.get(url) # request动作
soup = BeautifulSoup(browser.page_source,'lxml')
count=0 #用于计数
while True: # 一般已知总页数65,采用For循环更保险,这里为了熟悉seleni... |
80b0ce279718045bda81edbaabe6f23f7cbafbb8 | nemborkar/coding-challenges-to-gitgud | /Python/min-max.py | 542 | 3.625 | 4 | # https://www.hackerrank.com/challenges/np-min-and-max/problem
# after understanding numpy and figuring out the input process,
# this one was too easy
import numpy
# this chunk is working and enable it later
n, m = input().split()
n = int(n) # 0 axis
m = int(m) # 1 axis
first_array = numpy.zeros((n,m))
for i in ran... |
12262d57204befd5e00a76f89a08fe67c3156c5b | nemborkar/coding-challenges-to-gitgud | /Python/arithmetic-operators.py | 299 | 3.71875 | 4 | #https://www.hackerrank.com/challenges/python-arithmetic-operators/problem
import sys
if __name__ == '__main__':
a = int(input())
b = int(input())
if a < 1 or a > 10**10:
sys.exit()
elif b < 1 or b > 10**10:
sys.exit()
print(a+b)
print(a-b)
print(a*b) |
a299d477015b60d595abc9e01fb9869d5e74bdbc | natkhosh/Algorithms__Data_structures | /Tasks/c1_fact.py | 637 | 4.375 | 4 | def factorial_recursive(n: int) -> int:
"""
Calculate factorial of number n (> 0) in recursive way
:param n: int > 0
:return: factorial of n
"""
if n < 0:
raise ValueError
elif n == 0:
return 1
else:
p = 1
for i in range(1, n+1):
p *= i
return factorial_recursive(n-1) * n
def factorial_iterativ... |
542639fac60d62ef7169eeddedd6b170de648ee0 | natkhosh/Algorithms__Data_structures | /Tasks/e0_breadth_first_search.py | 1,130 | 3.625 | 4 | from typing import Hashable, List
import networkx as nx
from collections import deque
def bfs(g: nx.Graph, start_node: Hashable) -> List[Hashable]:
"""
Do an breadth-first search and returns list of nodes in the visited order
:param g: input graph
:param start_node: starting node for search
:return: list of nod... |
75a90c29ab8bfdb98dfc5ba1efe5cb3cea258a98 | williancae/pythonUri | /iniciante/exercicio13.py | 795 | 3.90625 | 4 | valor = int(input())
print(valor)
notas = [100,50,20,10,5,2,1]
for nota in notas:
quantidadeNotas = int(valor/nota)
print("{} nota(s) de R$ {},00".format(quantidadeNotas,nota))
valor -= quantidadeNotas * nota
"""dinheiro = int(input())
# dinheiro = 20 #Valor inicial
a = dinheiro/100 #20/100 = 0.20 [0] mos... |
90ee877129c5b04cd0b7a6ac1ea4b5201f76b5d2 | strongpear/Algebra-2-Video | /Algebra2Video.py | 11,695 | 3.953125 | 4 | # Author: Jason Lee
# Goal: Create Animations to make an introductory video about Algebra 2
from manim import *
class Introduction(ThreeDScene):
def construct(self):
# Define all of the Mobjects
text = Text(r"Welcome to Algebra 2!")
circle = Circle(radius = 1, color = BLUE)
... |
d73920a0fdf4e817bd0cc0e82017ad7ab638db16 | Monarch132/Python_ex_lab1 | /14.py | 478 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Ввести с клавиатуры текст предложения, завершить точкой. \
Вывести на консоль все символы, \
которые входят в этот текст ровно по одному разу.
"""
s = raw_input("Введите предложение: ")
ns = {}
for el in s:
if el in ns:
ns[el] += 1
else:
ns[el] = 1
print [el for ... |
a7f9383611ca9846f68f29817f038e1db872313e | Monarch132/Python_ex_lab1 | /Small/01.py | 504 | 3.921875 | 4 |
N = int(raw_input("Введите целое число N в интервале [1;100]: "))
if N < 0:
print "Ошибка! Вводите только положительные числа"
else:
A = str(N)
if N >= 10 and N <= 20:
print A + " лет"
elif A.endswith('1') is True:
print A + " год"
elif A.endswith('2') is True \
or A.endswith('... |
f451e55062269509c97e72a12aa227fe4e208e8c | AdamPellot/AutomateTheBoringStuffProjects | /Ch4/characterPictureGrid.py | 645 | 3.6875 | 4 | #! python3
# characterPictureGrid.py - Prints a grid passed as a 2D list.
# Adam Pellot
# Prints grid.
def characterPictureGrid(grid):
for y in range(len(grid[0])):
for x in range(len(grid)):
print(grid[x][y], end='')
print('')
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O'... |
f182a8ca4c91fe0e7a2141667bbce2ba1ddbf1c2 | AdamPellot/AutomateTheBoringStuffProjects | /Ch17/resizeAndAddLogo.py | 1,705 | 3.78125 | 4 | #! python3
# resizeAndAddLogo.py - Resizes all images in current working directory to fit
# in a 300x300 square, and adds catlogo.png to the
# lower-right corner.
# Adam Pellot
import os
from PIL import Image
SQUARE_FIT_SIZE = 300
LOGO_FILENAME = 'catlogo.png'
logoIm = Ima... |
2d399ea3fb78d5432b8022b88d00de8ea7065324 | AdamPellot/AutomateTheBoringStuffProjects | /Ch9/fillTheGaps.py | 3,208 | 4.125 | 4 | #! python3
# fillTheGaps.py - Finds all files with a given prefix, such as
# spam001.txt, spam002.txt, and so on, in a single
# folder and locates any gaps in the numbering. Have
# the program rename all the later files to close this
# gap.
# Adam Pell... |
dfab7297e65adcbf4e618d6132472fd5f29a8c42 | ThomasCREPINGE/hackinsciencesprojects | /CommandLine - 4. calculator/app.py | 633 | 3.546875 | 4 | import sys
if len(sys.argv) < 4:
print("usage: ./solution.py a_number (an_operator +-*/%^) a_number")
else:
try:
num1 = int(sys.argv[1])
num2 = int(sys.argv[3])
op = sys.argv[2]
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(nu... |
147f2b992037e348e16b448dd2bee18f7acc0262 | grg909/LCtrip | /Binary_Tree/LintCode.448.Inorder_Successor_in_BST.py | 1,865 | 4.09375 | 4 | # -*- coding: UTF-8 -*-
# @Date : 2020/1/6
# @Author : WANG JINGE
# @Email : wang.j.au@m.titech.ac.jp
# @Language: python 3.7
"""
"""
"""
Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
# stack迭代,... |
8076d65eb633decb068c6a97f4a33173c20b6ac4 | grg909/LCtrip | /Yama2020/LintCode.28.Search_a_2D_Matrix.py | 912 | 4.09375 | 4 | # -*- coding: UTF-8 -*-
# @Date : 2019/12/25
# @Author : WANG JINGE
# @Email : wang.j.au@m.titech.ac.jp
# @Language: python 3.7
"""
解题报告:二分搜索要熟练
"""
class Solution:
"""
@param matrix: matrix, a list of lists of integers
@param target: An integer
@return: a boolean, indicate whether matrix c... |
a6176bb67bec9c4cc533936d8c2e718520582032 | grg909/LCtrip | /LinkedList/LintCode.96.Partition_List.py | 1,045 | 4 | 4 | # -*- coding: UTF-8 -*-
# @Date : 2020/1/7
# @Author : WANG JINGE
# @Email : wang.j.au@m.titech.ac.jp
# @Language: python 3.7
"""
解题报告:双dummy加双指针
"""
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution... |
4ecedfa6667d6a763f4f266364a23f091a581ea3 | grg909/LCtrip | /Yama2020/120.Triangle.py | 1,807 | 3.6875 | 4 | # -*- coding: UTF-8 -*-
# @Date : 2020/3/14
# @Author : WANG JINGE
# @Email : wang.j.au@m.titech.ac.jp
# @Language: python 3.7
"""
"""
# traverse, Time O(2^n), Space O(n)
class Solution1:
def minimumTotal(self, triangle: List[List[int]]) -> int:
self.mini = sys.maxsize
self.dfs(triangle, ... |
0ad53a628e1cbabd4bca61f30719ccecec1f648c | grg909/LCtrip | /Binary_Tree/104.Maximum_Depth_of_Binary_Tree.py | 1,147 | 4.0625 | 4 | # -*- coding: UTF-8 -*-
# @Date : 2019/12/20
# @Author : WANG JINGE
# @Email : wang.j.au@m.titech.ac.jp
# @Language: python 3.7
"""
解题报告: 分治更简单直接,traverse需要维护全局变量
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# ... |
d8ebea801fdf0848fb67c4e2ac0f2af3f364909e | grg909/LCtrip | /Binary_Tree/LintCode.95.Validate_Binary_Search_Tree.py | 2,671 | 3.96875 | 4 | # -*- coding: UTF-8 -*-
# @Date : 2020/1/3
# @Author : WANG JINGE
# @Email : wang.j.au@m.titech.ac.jp
# @Language: python 3.7
"""
"""
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
# dfs
class Solution1:
"""
... |
ff579e7e45cc51855abc871ff00b3a070dd6f24c | grg909/LCtrip | /Binary_Tree/257.Binary_Tree_Paths.py | 2,411 | 3.984375 | 4 | # -*- coding: UTF-8 -*-
# @Date : 2019/12/20
# @Author : WANG JINGE
# @Email : wang.j.au@m.titech.ac.jp
# @Language: python 3.7
"""
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Definition... |
4723eb3ac33cc59a6b29e932249d0b9d77673aaf | grg909/LCtrip | /Letian2020/OA1.py | 1,459 | 3.875 | 4 | # -*- coding: UTF-8 -*-
# @Date : 2020/1/20
# @Author : WANG JINGE
# @Email : wang.j.au@m.titech.ac.jp
# @Language: python 3.7
"""
解题报告:https://www.1point3acres.com/bbs/thread-564350-1-1.html 第二题
解法1,树上的BFS + priority queue
解法2,https://stackoverflow.com/questions/25344313/generating-ascending-sequenc... |
3154a8c072b3ce4d22d947347563d1e1b9414e9a | grg909/LCtrip | /Yama2020/240.Search_a_2D_Matrix_II.py | 650 | 3.8125 | 4 | # -*- coding: UTF-8 -*-
# @Date : 2020/3/1
# @Author : WANG JINGE
# @Email : wang.j.au@m.titech.ac.jp
# @Language: python 3.7
"""
"""
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
... |
2fc79153ccded32d57a9161d3d7d2caf6a6f67a5 | grg909/LCtrip | /Yama2020/LintCode.425.Letter_Combinations_of_a_Phone_Number.py | 996 | 3.734375 | 4 | # -*- coding: UTF-8 -*-
# @Date : 2020/1/18
# @Author : WANG JINGE
# @Email : wang.j.au@m.titech.ac.jp
# @Language: python 3.7
"""
"""
KEYBOARD = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz',
}
class Solution:
"""
@... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.