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 |
|---|---|---|---|---|---|---|
df273e0b1a4ec97f7884e64e0fe1979623236fb2 | bdjilka/algorithms_on_graphs | /week2/acyclicity.py | 2,108 | 4.125 | 4 | # Uses python3
import sys
class Graph:
"""
Class representing directed graph defined with the help of adjacency list.
"""
def __init__(self, adj, n):
"""
Initialization.
:param adj: list of adjacency
:param n: number of vertices
"""
self.adj = adj
... |
16753f583825a4a04c044a314ade735202b7076d | ggrecco/python | /basico/zumbis/surfSplitNomeNotas.py | 310 | 3.59375 | 4 | f = open("surf.txt")
#maior = 0
notas = []
for linha in f:
nome, pontos = linha.split()
notas.append(float(pontos))
#if float(pontos) > maior:
#maior = float(pontos)
f.close()
#print(maior)
notas.sort(reverse = True)
print("1º - {}\n2º - {}\n3º - {}".format(notas[0],notas[1],notas[2]))
|
e3161b35c014b11888d835507c3eb8de8105b426 | ggrecco/python | /basico/zumbis/imprimeParSemIF.py | 135 | 3.953125 | 4 | #imprimir pares de 0 ao digitado sem o if
n = int(input("Digite um número: "))
x = 0
while x <= n:
print(x, end = " ")
x += 2
|
d8fe9b832e0927a1fe6d869bb10854b4c2d53bee | ggrecco/python | /basico/coursera/verifica_ordenamento_lista.py | 198 | 3.78125 | 4 | def ordenada(lista):
b = sorted(lista)
print(lista)
print(b)
if b == lista:
return True
#print("Iguais")
else:
return False
#print("Diferente")
|
8c35008e3eafc6f0877dd65325ee051cea3afaf3 | ggrecco/python | /basico/zumbis/jogo_2.py | 291 | 3.734375 | 4 | from random import randint
secreta = randint(1, 100)
while True:
chute = int(input("Chute:"))
if chute == secreta:
print("parabéns, vc acertou o número {}".format(secreta))
break
else:
print("Alto" if chute > secreta else "Baixo")
print("Fim do jogo")
|
e3d7c97584d737e341caae29dc639be446b80159 | ggrecco/python | /basico/zumbis/trocandoLetras.py | 311 | 3.75 | 4 | #ler uma palavra e trocar as vogais por "*"
i = 0
troca = ""
palavra = input("Palavra: ")
j = input("Letra: ")
t = input("trocar por: ")
while i < len(palavra):
if palavra[i] in str(j):
troca += t
else:
troca += palavra[i]
i += 1
print("Nova: {}\nAntiga:{}".format(troca,palavra))
|
3542c66b49e08f505395c9f76b2bbee070677991 | ggrecco/python | /basico/coursera/calculadoraVelocidadeDownload_importando_funcao_tempo.py | 401 | 3.75 | 4 | import fun_Tempo
def calcVel(k):
return k/8
i = 1
while i != 0:
n = int(input("Velocidade contratada[(zero) para sair]: "))
t = (float(input("Tamanho do arquivo em MegaBytes: ")))
segundos = t / calcVel(n)
fun_Tempo.calcTempo(segundos)
print("Velocidade máxima de Download {} MB/s\... |
b49c3aaa2c6ba16a47729c07471b6ca18795fa56 | ggrecco/python | /basico/zumbis/latasNecessarias.py | 526 | 3.828125 | 4 | '''
usuário informa o tamanho em metros quadrados a ser pintado
Cada litro de tinta pinta 3 metros quadrados e a tinta
é vendida em latas de 18 litros, que custam R$ 80,00
devolver para o usuário o numero de latas necessárias
e o preço total.
Somente são vendidas nº inteiro de latas
'''
m = float(input("Metros²: "))
if... |
bd2dbd08dfd85e478fd10e6416536ac6490bdf62 | ggrecco/python | /basico/coursera/imprime_retangulo_vazado.py | 317 | 4.03125 | 4 | n = int(input("digite a largura: "))
j = int(input("digite a altura: "))
x = 1
while x <= j:
print("#", end="")
coluna = 0
while coluna < (n - 2):
if x == 1 or x == j:
print("#", end="")
else:
print(end=" ")
coluna = coluna + 1
print("#")
x = x + 1
|
59d1bf3ee1afee7ebd9c03797a779f4beae41c18 | sohanur-it/programming-solve-in-python3 | /cricket-problem.py | 476 | 3.640625 | 4 | #!/usr/bin/python3
T=int(input("Enter the inputs:"))
for i in range(1,T+1):
RR,CR,RB=input("<required run> <current run> <remaining balls> :").split(" ")
RR,CR=[int(RR),int(CR)]
RB=int(RB)
balls_played=300-RB
current_run_rate=(CR/balls_played)*6
current_run_rate=round(current_run_rate,2)
print("current run rate:... |
7971c61b321c45254f4d74d20494dba9b172c5b2 | uchicagotechteam/HourVoice | /workbench/data_collection/combine_data.py | 2,335 | 3.71875 | 4 | import json
from collections import defaultdict
def combine_databases(databases, compared_keys, equality_functions, database_names):
'''
@param databases: a list of dicts, where each dict's values should be
dictionaries mapping headers to individual data points. For example, [db1, db2] with db1 = {'1': , '... |
9390fdf52e3768a4828ded73fefccd059537eb22 | nguyenl1/evening_class | /python/notes/python0305.py | 1,088 | 4.03125 | 4 | """
Dictionaries
Key-values pairs
dict literals (bracket to bracket)
{'key': 'value' }
[ array: list of strings ]
Immutable value (int, float, string, tuple)
List and dicts cannot be keys
"""
product_to_price = {'apple': 1.0, "pear": 1.5, "grapes": 0.75}
print(product_to_price['apple'])
# print(product_to_price... |
a90e7646813c7645935894105d63434178909703 | nguyenl1/evening_class | /python/labs/lab15.py | 1,779 | 3.9375 | 4 | """
Convert a given number into its english representation. For example: 67 becomes 'sixty-seven'. Handle numbers from 0-99.
Hint: you can use modulus to extract the ones and tens digit.
x = 67
tens_digit = x//10
ones_digit = x%10
Hint 2: use the digit as an index for a list of strings.
"""
noindex = [0,1,2,3,4,5,... |
e39edeb39458969cef046410d03535f2f5d8a64a | nguyenl1/evening_class | /python/notes/python0225.py | 851 | 4.0625 | 4 | '''
def my_add(num_1, num_2):
a_sum = num_1 + num_2
return a_sum
sum = my_add(5, 6) #the contract between the users and the function
print(sum)
'''
"""
#variables
x = 5
print (x)
greeting = "hello"
print (greeting)
bool = 5 > 10
print (bool)
"""
'''
# my_string = "ThIs Is A StRiNG"
# print(my_string.lo... |
4b3922cdedf4f4c7af87235b94af0f763977b191 | nguyenl1/evening_class | /python/labs/lab23final.py | 2,971 | 4.25 | 4 | import csv
#version 1
# phonebook = []
# with open('lab23.csv') as file:
# read = csv.DictReader(file, delimiter=',')
# for row in read:
# phonebook.append(row)
# print(phonebook)
#version2
"""Create a record: ask the user for each attribute, add a new contact to your contact list with the attr... |
6e52d2a6e99a95375e37dace8a996a9f10ca87cd | nguyenl1/evening_class | /python/notes/python0227.py | 647 | 3.796875 | 4 | # x = 5
# y = 5
# print(x is y)
# print(id(x)) #returns ID of an object
# truthy falsey
# empty lists, strings, None is a falsey value
x = []
y = [1,2,3]
i = ""
j = "qwerty"
z = None
if x:
print(x)
if y:
print(y) # [1,2,3]
if i:
print(i)
if j:
print(j) # qwerty
if z:
print(z)
#
my_flag = Tru... |
3bd0c70f91a87d98797984bb0b17502eac466972 | nguyenl1/evening_class | /python/labs/lab18.py | 2,044 | 4.40625 | 4 | """
peaks - Returns the indices of peaks. A peak has a lower number on both the left and the right.
valleys - Returns the indices of 'valleys'. A valley is a number with a higher number on both the left and the right.
peaks_and_valleys - uses the above two functions to compile a single list of the peaks and valleys i... |
208f0481f2b86a5487202000de30700f754ad873 | rxbook/study-python | /06/12.py | 125 | 3.796875 | 4 | def power(x,n):
if n == 0:
return 1
else:
return x * power(x,n-1)
print power(2,3)
print power(2,5)
print power(3,4)
|
ca672ad960d02bc62c952f5d8bab44670fa03c24 | rxbook/study-python | /05/t02.py | 115 | 3.75 | 4 | score = input('Enter your score:')
if score >= 85:
print 'Good'
elif score < 60:
print 'xxxxx'
else:
print 'OK'
|
530effec6984850539b440dc14870a2bd4af2f71 | rxbook/study-python | /05/t13.py | 133 | 3.796875 | 4 | names = ['zhang','wang','zhao','li']
ages = [12,46,32,19]
zip(names,ages)
#for name,age in zip(names,ages):
# print name,'-----',age
|
5dc0ca50f55cc6967821f52336deffda5530ad04 | airuchen/python_practice | /raise_error.py | 444 | 3.8125 | 4 | import sys
def displaySalary(salary):
if salary<0:
raise ValueError('positive')
print('Salary = '+str(salary))
while True:
try:
Salary = float(input('enter Salary:'))
displaySalary(Salary)
break
except OSError as err:
print('OS Error: {0}'.format(err))
except... |
feefbfb35b341b204fddcbe7dbd8d31acbc13b89 | adpoe/CupAndChaucerSim | /INITIAL_EXPERIMENT/time_advance_mechanisms.py | 28,390 | 3.8125 | 4 | import Queue as q
import cupAndChaucArrivs as cc
"""
Discrete time advance mechanisms for airport simulation project.
This class will generate 6 hours worth of passenger arrivals, and store the data in two arrays:
- One for commuters passengers
- One for international passengers
For each passenger, also need to gener... |
261a80f5080e6ad40aacc3f4921d7e140d19fedd | imran436/Projects-Portfolio-master | /Tech Academy/python projects/#13.py | 555 | 3.9375 | 4 | import time
X = 5
print(X)
X = X**5
print(X)
if X<10:
print("our number X is a small value")
elif X<100:
print("The number is an average value")
else:
print("the number holds a big value")
counter = 0
for counter in range(0, 100,5):
print(counter)
time.sleep(.25)
counter = 0
while counter < X:
p... |
70c66c6ddb26d1ddad9409d84c4932e7dfd718af | Sasithorn04/Python | /ตารางหมากฮอส.py | 604 | 3.9375 | 4 | #โปรแกรมจำลองตารางหมากฮอส
#ปรับจากสร้างภาพวาด4เหลี่ยมจตุรัส
number = int(input("ป้อนขนาด :"))
for row in range(1,number+1) :
for column in range(1,number+1) :
if (column%2 == 0) & (row%2 == 0) :
print("o",end='')
elif (column%2 != 0) & (row%2 != 0):
print("o",end='')
... |
ebcd50508c0690db480ba215a31c764c84db3988 | harshit-tiwari/Python-Codes | /Simple Calculator/addition.py | 689 | 4.09375 | 4 | import calculate
def addFunc():
print("You have chosen Addition")
operands = []
number = 0
while True:
try:
number = int(input("How many numbers do you want to add? : "))
break
except ValueError:
print("Please enter a number as your input")
for i... |
e978a7977ddfd0f0e7559618d3aa1f5282f8ab91 | chrissowden14/bank | /FileStore.py | 1,592 | 3.90625 | 4 | class FileStore:
def __init__(self):
# This creates an open list everytime the program is opened
self.cusnames = []
self.cusspaswords = []
self.cusbalance = []
# opening the stored file that collects the old data from customer
self.namefile = open("cusnamesfile.txt",... |
b58ef87371085284143fbb0d28d9251d8d97b01f | Subhashriy/python | /11-07-19/substitute.py | 200 | 3.5 | 4 | import re
n=int(input("Enter no. of lines:"))
a=[]
for i in range(n):
a.append(input())
str1=re.sub(r'&&','and',a[i])
str1=re.sub(r'\|\|','or',a[i])
|
0de46d21ae522160a24e89e11919f60365b32288 | Subhashriy/python | /17-07-19/tcpclient.py | 752 | 3.5625 | 4 | import socket
def main():
host='127.0.0.1'
port=5000
#Creting a socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print("Socket Created.")
#connect to the server
s.connect((host,port))
print('Connected to server.')
#send msg to the server
data=input... |
07617bf9783632e43ce3e5e585bc5d844e29f8e1 | Subhashriy/python | /17-07-19/avg.py | 128 | 3.90625 | 4 | lst=[int(x) for x in input('Enter the list: ').split(' ')]
print('The average of the list is : {}'.format((sum(lst)/len(lst)))) |
1687e6c73055cb78bb5399468addc38065edfc4f | Subhashriy/python | /17-07-19/random.py | 199 | 3.75 | 4 | import random
def randomnum(i,n):
print(random.randint(i,n+1))
#print(random.randint(1,100))
i=int(input('Enter the start range:'))
n=int(input('Enter the end range:'))
randomnum(i,n) |
70b744b963b558041e7e60fb910eaa3260c619e9 | zacharymollenhour/Fitness_Tracker | /test.py | 2,323 | 3.984375 | 4 | import numpy as np
import pandas as pd
import csv
from datetime import date
#Get User Name
class Person:
"This is a persons data class"
def __init__(self):
self.userData = []
self.name = ''
self.age = 0
self.weight = 0
#Greet User for data about the individual
def gree... |
ce0dada2eadce554808ced1d97e1c8b88e2a9b7e | devsben/Neopets-Multi-Tool | /classes/__init__.py | 288 | 3.5 | 4 | import sys
if sys.version_info[0] < 3:
"""
If a Python version less than 3 is detected prevent the user from running this program.
This will be removed once the final tweaking is completed for Python 2.
"""
raise Exception("Python 3 is required to run this program.") |
39c5729b31befc2a988a0b3ac2672454ae99ea9a | krsatyam20/PythonRishabh | /cunstructor.py | 1,644 | 4.625 | 5 | '''
Constructors can be of two types.
Parameterized/arguments Constructor
Non-parameterized/no any arguments Constructor
__init__
Constructors:self calling function
when we will call class function auto call
'''
#create class and define function
class aClass:
# Constructor with arguments
def... |
bcde27b2f96aff6d73cf8cb2836416b57c3e0e56 | krsatyam20/PythonRishabh | /filehandling.py | 1,001 | 3.734375 | 4 | '''
open(mode,path)
mode
r :read
read() => read all file at a time
readline() => line by line read
readlines() => line by line read, but line convert into list
w :write
write()
a :append
open(path,'a')
write()
... |
5be464d262f21413b369dc140cae381540470ef0 | krsatyam20/PythonRishabh | /forloop.py | 590 | 4.09375 | 4 | ''' loop : loop is a reserved keyword it`s used for repetaion of any task
types of loop
1. For loop
2.while loop
'''
for i in range(0,10):
print("Rishab %d " %(i))
for i in range(1,21):
print(i)
#use break keyword
print("===========break keyword=================")
for i in ran... |
fa517e9e021b1d701a23211c569e6fd201bdb42c | gsingh84/Adventure-Game | /Adventure-game.py | 10,666 | 4.25 | 4 | #All functions call at the end of this program
import random
treasure = ['pieces of gold!', 'bars of silver!', 'Diamonds!', 'bottles of aged Rum!']
bag = ['Provisions']
#yorn function allow user to enter yes or no.
def yorn():
yinput = ""
while True:
yinput = input("Please Enter Yes or No (Y/N): ")
... |
34f5750734878b8d0d100a5882e2b4a70fbb13f9 | nicklip/Google_Python_Developers_Course | /copyspecial.py | 4,485 | 3.828125 | 4 | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import commands
"""Copy Special exercise
The c... |
5bd5df1910a6c6765dfeff536eba03ca4878dc6e | TiwariSimona/Hacktoberfest-2021 | /g-animesh02/cartoon3.py | 2,243 | 4.0625 | 4 | import cv2
class Cartoonizer:
"""Cartoonizer effect
A class that applies a cartoon effect to an image.
The class uses a bilateral filter and adaptive thresholding to create
a cartoon effect.
"""
def __init__(self):
pass
def render(self, img_rgb):
img_rgb = cv2... |
5152927f8f259d1d78645fdec94330753225833a | TiwariSimona/Hacktoberfest-2021 | /Aryan810/new_search_algorithm.py | 1,268 | 3.71875 | 4 | from threading import Thread
import time
class SearchAlgorithm1:
def __init__(self, list_data: list, element):
self.element = element
self.list = list_data
self.searching = True
self.index = None
def search(self):
Thread(self.forward())
self.reverse()
... |
f2744631653064a83857180583c831b187a8f53c | TiwariSimona/Hacktoberfest-2021 | /ajaydhoble/euler_1.py | 209 | 4.125 | 4 | # List for storing multiplies
multiplies = []
for i in range(10):
if i % 3 == 0 or i % 5 == 0:
multiplies.append(i)
print("The sum of all the multiples of 3 or 5 below 1000 is", sum(multiplies))
|
bbfe214cd8be2137032f9f2fa056302865a9ada2 | TiwariSimona/Hacktoberfest-2021 | /akashrajput25/Some_py_prog/count_alphabet.py | 178 | 3.671875 | 4 | name=input("Enter your name\n")
x=len(name)
i=0
temp=""
for i in range(x) :
if name[i] not in temp:
temp+=name[i]
print(f"{name[i]}:{name.count(name[i])}")
|
16ad6fbbb5ab3f9a0e638a1d8fd7c4469d349c11 | TiwariSimona/Hacktoberfest-2021 | /parisheelan/bmi.py | 957 | 4.15625 | 4 | while True:
print("1. Metric")
print("2. Imperial")
print("3. Exit")
x=int(input("Enter Choice (1/2/3): "))
if x==1:
h=float(input("Enter height(m) : "))
w=float(input("Enter weight(kg) : "))
bmi=w/h**2
print("BMI= ",bmi)
if bmi<=18.5:
print("Under... |
c5a68da4e7ffdc1ddc86d247e3092c5eb7d09699 | TiwariSimona/Hacktoberfest-2021 | /CharalambosIoannou/doubly_linked_list_helper.py | 2,632 | 4 | 4 | class DListNode:
"""
A node in a doubly-linked list.
"""
def __init__(self, data=None, prev=None, next=None):
self.data = data
self.prev = prev
self.next = next
def __repr__(self):
return repr(self.data)
class DoublyLinkedList:
def __init__(self):
"""
... |
1c7ecdea2b8d027f39b67355f76a7b6e9c7fce47 | SiyandzaD/analysehackathon | /tests/test.py | 494 | 3.875 | 4 | from analysehackathon.recursion import sum_array
from analysehackathon.recursion import fibonacci
def test_sum_array():
"""
make sure sum_aray works correctly
"""
assert sum_array([1,2,3]) == 6, 'incorrect'
print(sum_array([1,2,3]))
assert sum_array([1,2,3,4]) == 10, 'incorrect'
... |
932042d87adfba2bdb8d437b2c20d98d2afd7c22 | VinayagamD/PythonBatch3 | /hello.py | 74 | 3.5 | 4 | a = 10
b = 20
sum = a +b
print(sum)
print('Hello to python programming')
|
b6d05ea933a068a2a1716aee977af795764eeaa7 | quirosnv/PROYECTO | /Proyecto Buscador en proceso/Buscador.py | 5,085 | 3.890625 | 4 | data = int(input("ingrese 1 si quiere buscar por cantante, 2 por cancion, 3 por album, 4 por año, -1 SALIR: "))
cantante = ['KALEO', 'kaleo', 'Coldplay', 'COLDPLAY', 'The Beatles', 'beatles']
contador = 0
while data != -1:
if data == 1:
print("Eligio buscar por cantante:")
cant= input("Ingre... |
169e431b852089fcda8a72114582cba0f847afbe | whyalwaysmeee/Machine-Learning-Sklearn-Linear-Model | /Linear Model(Least Square Mothod).py | 1,274 | 4.03125 | 4 | import matplotlib.pyplot as plt
from sklearn import datasets, linear_model
import numpy as np
from sklearn.metrics import mean_squared_error, r2_score
# Load the diabetes dataset
price = datasets.load_boston()
# Use only one feature
price_x = price.data[:,np.newaxis,5]
# Split the data into training/testi... |
08947ee21f916756c6edf64e0f1d1ad5730b59bd | LiangChen204/pythonApi_Test | /runoob/baseException.py | 1,868 | 3.921875 | 4 | #!//usr/local/bin python
# -*- coding:utf-8 -*-
# 走try
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!")
except IOError:
print("Error: 没有找到文件或读取文件失败")
else:
print("内容写入文件成功")
fh.close()
# 捕获异常
try:
fh = open("testfile", "r")
fh.write("这是一个测试文件,用于测试异常!")
except IOError:
print... |
5f285c43fbeb0489a57c0c703201abfb2df3a575 | andfanilo/streamlit-sandbox | /archives/app_styling.py | 567 | 3.734375 | 4 | import pandas as pd
import streamlit as st
# https://stackoverflow.com/questions/43596579/how-to-use-python-pandas-stylers-for-coloring-an-entire-row-based-on-a-given-col
df = pd.read_csv("data/titanic.csv")
def highlight_survived(s):
return ['background-color: green']*len(s) if s.Survived else ['background-col... |
00eb68cef452b9026f89936170f6c21e7ef09e2c | TeenaThmz/List | /list2.py | 64 | 3.5 | 4 | list2=[12,14,-95,3]
list=[i for i in list2 if i>=0]
print(list)
|
18785e22dbae3eed4affb39e74eaf9aaffadf949 | kooose38/pytools_table | /xai/eli5.py | 1,384 | 3.578125 | 4 | from typing import Any, Dict, Union, Tuple
import eli5
from eli5.sklearn import PermutationImportance
import numpy as np
import pandas as pd
class VizPermitaionImportance:
def __doc__(self):
"""
package: eli5 (pip install eli5)
support: sckit-learn xgboost lightboost catboost lighting
purpose: Vi... |
c6ea76ace41ca74098a6562ee75c1e6216cb6fe2 | plukis/merge_sort | /controllers/merge_sort.py | 1,177 | 3.84375 | 4 | # -*- coding: utf-8 -*-
class MergeSort:
a_list = []
def _merge_work(self, alist):
print("delimito ", alist)
if len(alist) > 1:
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
self._merge_work(lefthalf)
self._m... |
42a76e11702d791ddbff3b132710144b3d684323 | qqinxl2015/leetcode | /112. Path Sum.py | 1,036 | 3.859375 | 4 | #https://leetcode.com/problems/path-sum/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int... |
91ac4bcae6d6e1ba52e2145bdc158800e31d5d6e | qqinxl2015/leetcode | /009. Palindrome Number.py | 470 | 3.796875 | 4 | #https://leetcode.com/problems/palindrome-number/
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x ==0:
return True
if x < 0:
return False
if int(x%10) == 0 and x !=0:
return False
... |
0e5abd4e1435664f4b626bc96a4d57fd2b5f2374 | susanpinch/Read-and-Process-Data-Python | /pinchiaroli_susan_assign9_fileioio.py | 1,952 | 3.96875 | 4 | """
file_io_nested.py
Write data from a set of nested lists to a file,
then read it back in.
By: Susan Pinchiaroli
Date: 28 Nov 2018
"""
data = []#empty list
# This is our data
data.append(['Susan','Davis',23,7])#append data
data.append(['Harold','Humperdink',76,9])
data.append(['Lysistrata','Jones',40,12])
data.appe... |
0211584a0d5087701ee07b79328d4eb6c101e962 | pintugorai/python_programming | /Basic/type_conversion.py | 438 | 4.1875 | 4 | '''
Type Conversion:
int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
str(x)
Converts object x to a string representation.
eval(str)
Evaluates a string and returns an object.
tuple(s)
Converts s to a tuple.
list(s)
Converts s to a list.
set(s)
Converts s to a set.
dict(d)
Creates... |
ac7016757e19991066147e75b923b1ef734beb6d | zags4life/tableformatters | /tableformatters/tabledataprovider.py | 776 | 3.75 | 4 | # table_formatters/data_provider.py
from abc import ABC, abstractproperty
class TableFormatterDataProvider(ABC):
'''An ABC that defines the interface for objects to display by a table
formatter. Any object displayed by a TableFormatters must implement this
ABC.
Classes that implement this ABC c... |
22c30808220f095b21eca67c444dc2b46b4026b0 | gmayock/kaggle_titanic_competition | /gs-titanic-7-final-submission-code.py | 11,102 | 3.515625 | 4 | # # Load data
# Ignore warnings to clean up output after all the code was written
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd
import os
print(os.listdir("../input"))
['train.csv', 'gender_submission.csv', 'test.csv']
# Step 1 is to import both data sets
training... |
f172ed025705f196ebe0c394595dee382a415ccf | jaaaaaaaaack/zalgo | /zalgo.py | 1,428 | 3.96875 | 4 | # zalgo.py
# Jack Beal, June 2020
# A small module to give any text a flavor of ancient doom
from random import random
def validCharacter(char, stoplist):
""" Helps to prevent unwanted manipulation of certain characters."""
if char in stoplist:
return False
else:
return True
def uniform... |
cf37344075ac3ebcd091fcfe24de0444742a01be | elliotgreenlee/advent-of-code-2019 | /day10/day10_puzzle1.py | 2,365 | 3.734375 | 4 | import math
def read_puzzle_file(filename):
with open(filename, 'r') as f:
points = set()
for y, line in enumerate(f):
for x, point in enumerate(line):
if point is '#':
points.add((x, y))
return points
def n... |
5976699fa85e8eb7237467f8732bdca6df5d350d | jasoncwells/Test_2 | /scraper.py | 230 | 3.578125 | 4 | myvar = 'What is happening today'
myage = 46
mylist = ['how','now','brown','cow']
mynumlist = [1,2,3,4,5]
print myvar
print myage
print mylist
listlength = len(mylist)
print listlength
stringlength = len(myvar)
print stringlength
|
dd793f5d7f0d88d1a6446c8ce2025904144c2136 | cybera/data-science-for-entrepreneurs-workshops | /helpers/color.py | 820 | 3.640625 | 4 | def hex2rgb(color):
return tuple(int(color.lstrip('#')[i:i+2], 16) for i in (0, 2 ,4))
# Decimal number to HEX str
def dec2hex(n):
n = int(n)
if (n > 16):
return str(hex(n).split('x')[-1])
else:
return "0" + str(hex(n).split('x')[-1])
# Gradient starting at color "start" to color "stop... |
ca8162f61acd25fc40f57615225c78c2d1ad0623 | sambapython/batch53 | /modules/file1.py | 199 | 3.546875 | 4 | print("name:",__name__)
a=100
b=200
c=a+b
d=a-b
def fun():
print("this is fun in file1")
if __name__=="__main__":
def fun1():
print("this is fun1")
print("this is file1")
fun()
print(a,b,c,d)
|
38da743b5276b4924cc7e40aa237daef479aaed8 | sambapython/batch53 | /app.py | 89 | 3.515625 | 4 | a=raw_input("Enter a value:")
b=raw_input("Enter b value:")
a=int(a)
b=int(b)
print (a+b) |
b483de5c6c42f4c9234be3dacd50c8828437b260 | aishraj/slow-learner | /python/pythonchallenge/001.py | 614 | 3.53125 | 4 | import string
import collections
def decrypt(cyphertext):
values = ''
keys = ''
for i in range(ord('a'),ord('z')+1):
keys += chr(i)
j = i - ord('a')
values += chr(ord('a') + (j + 2) % 26)
transtable = string.maketrans(keys,values)
return string.translate(cyphertext,transta... |
cdb57be6cb1e664d937ecc44efcd00095bdb7407 | azbrainiac/PyStudy | /third.py | 702 | 3.953125 | 4 | for item in [1, 3, 7, 4, "qwerty", [1, 2, 4, 6]]:
print(item)
for item in range(5):
print(item ** 2)
wordlist = ["hello", "ass", "new", "year"]
letterlist = []
for aword in wordlist:
for aletter in aword:
if aletter not in letterlist:
letterlist.append(aletter)
print(letterlist)
sqlist = []
for x in range(4,... |
ad94bc21b8b6a213a11e455e666325fdcf95d890 | patpalmerston/Algorithms-1 | /making_change/making_change.py | 2,323 | 4.0625 | 4 | #!/usr/bin/python
import sys
def making_change(amount, denominations=[1, 5, 10, 25, 50]):
# base case
if amount <= 2:
return 1
# starting a cache equal to the size of the amount, plus an initial default of 1 for index of zero
cache = [1] + [0] * amount
# loop through the coins in our li... |
5f89f65fa211fff9288edd96e534a90baaca6919 | hklgit/PythonStudy | /pythonCodes/com/coocaa/study/类/Student.py | 885 | 3.9375 | 4 | class Student(object):
# 把一些我们认为必须绑定的属性强制填写进去。
# 通过定义一个特殊的__init__方法,在创建实例的时候,就把name,score等属性绑上去:
# 特殊方法“__init__”前后分别有两个下划线!!!
# 注意到__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。
# 这个跟构造器很类似
def __init__(self, name, age):
self.name = name
s... |
becc6a966f455b1d32d7633c9f7cfb53e110b033 | kelvinng2017/chat1 | /test2.py | 225 | 3.890625 | 4 |
while True:
print("請輸入密碼:", end='')
password = input()
if int(password) == 1234567:
print("歡迎光臨!敬請指教")
break
else:
print("密碼錯誤!請在重新輸入") |
c538c8864abefaab9f3e97af43283c2bc0efc63f | randeeppr/fun | /desired_days.py | 1,188 | 4.0625 | 4 | #!/usr/bin/python
#
# This program prints the desired day(s) in between start date and end date
#
import datetime,sys,getopts
def getDesiredDay(start_date,end_date,desired_day):
v1 = value_of_start_day = weekdays[start_date.strftime("%a")]
v2 = value_of_desired_day = weekdays[desired_day]
#print(v1)
#print(v2... |
0d261b64fc0fee1629ebb3e24483ea4ecd89ad07 | Jav10/Matplotlib-Plotting | /UNO/backToBackBarCharts.py | 488 | 3.59375 | 4 | #Matplotlib Plotting
#Autor: Javier Arturo Hernández Sosa
#Fecha: 30/Sep/2017
#Descripcion: Ejecicios Matplotlib Plotting - Alexandre Devert - (18)
#Gráficas de barras espalda con espalda
import numpy as np
import matplotlib.pyplot as plt
women_pop=np.array([5., 30., 45., 22.])
men_pop=np.array([5., 25., 50... |
1e618d71d615ae0f419c6d78f9684f028d8f4aa6 | jip174/cs362--Software-Eng-2 | /week4/test/teststring_testme.py | 480 | 3.765625 | 4 | import testme
from unittest import TestCase
import string
class teststring(TestCase):
def test_input_string(self):
ts = testme.inputString()
count = 0
for x in ts:
if x.isalpha() == True or x == '\0':
count += 1
print(x)
el... |
b74c84a5554423d4fcb488945748ebbe64bdd716 | jip174/cs362--Software-Eng-2 | /week4/test/tester_testme.py | 864 | 3.8125 | 4 | import testme
from unittest import TestCase
import string
class testchar(TestCase):
def test_input_char(self):
tc = testme.inputChar()
letters = string.ascii_letters
if (tc.isalpha() == True):
#print(tc)
self.assertTrue(tc.isalpha() == True)
else... |
4891587a4606af3b4d6e284ac033185117abbf14 | peluche/mooc_algo2 | /graphs/dfs_topological_search.py | 1,058 | 3.875 | 4 | #!/usr/bin/env python3
explored = {}
current_label = 0
def is_explored(vertex):
return explored.get(vertex) != None
def explore(vertex):
explored[vertex] = True
def tag(vertex):
global current_label
explored[vertex] = current_label
current_label -= 1
def dfs(graph, vertex):
explore(vertex)
... |
d902702bc0e0c3168d745fdf7dfda52fbff1c3d0 | Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1 | /Programas da 3a week/Tarefa de programação/Exercícios 2 - FizzBuzz parcial, parte 1.py | 100 | 4.1875 | 4 | num = int(input("Digite um número inteiro: "))
if num % 3 == 0:
print ("Fizz")
else:
print (num) |
29781302370b185924aca0e0384ab49f4af4764c | Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1 | /Programas da 7a week/Tarefa de programação Lista de exercícios - 6/Exercício 2 - Retângulos 2.py | 456 | 4 | 4 | larg = int(input("Digite o número da largura do retângulo: "))
alt = int(input("Digite o número da altura do retângulo: "))
x=larg
y=alt
cont=larg
while y > 0:
while x > 0 and x <= larg:
if y==1 or y==alt:
print ("#", end="")
else:
if x==1 or x==cont:
print ... |
1d326577cedbfe93c61026649efd049a720ded66 | Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1 | /Programas da 3a week/Praticar tarefa de programação Exercícios adicionais (opcionais)/Exercício 1 - Distância entre dois pontos.py | 277 | 3.828125 | 4 | import math
x1 = int(input("Digite o primeiro x: "))
y1 = int(input("Digite o primeiro y: "))
x2 = int(input("Digite o segundo x: "))
y2 = int(input("Digite o segundo y: "))
dis = math.sqrt ((x1 - x2)**2 + (y1 - y2)**2)
if dis > 10:
print("longe")
else:
print ("perto")
|
2c6eb6b2fbcc6a1cd440d3c0fff85fdb58e0d72f | maimoonmaimu/codeketa | /set1-5.py | 104 | 3.546875 | 4 | m,a,i=input().split()
if(m>a):
if(m>i):
print(m)
elif(a>i):
print(a)
else:
print(i)
|
91cbaa9c8b92230b76a14a687875b71358fe260f | lx36301766/AtlanLeetCode | /src/pl/atlantischi/leetcode/medium/Medium486.py | 2,964 | 3.78125 | 4 |
"""
给定一个表示分数的非负整数数组。 玩家1从数组任意一端拿取一个分数,随后玩家2继续从剩余数组任意一端拿取分数,然后玩家1拿,……。
每次一个玩家只能拿取一个分数,分数被拿取之后不再可取。直到没有剩余分数可取时游戏结束。最终获得分数总和最多的玩家获胜。
给定一个表示分数的数组,预测玩家1是否会成为赢家。你可以假设每个玩家的玩法都会使他的分数最大化。
示例 1:
输入: [1, 5, 2]
输出: False
解释: 一开始,玩家1可以从1和2中进行选择。
如果他选择2(或者1),那么玩家2可以从1(或者2)和5中进行选择。如果玩家2选择了5,那么玩家1则... |
0b241bfd9a912c87ef304cb43ace9ffb90cce82c | cyro809/trabalho-tesi | /sentimusic/distance_utils.py | 1,284 | 4 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import math
# ---------------------------------------------------------------------------
# Função calculate_distance(): Calcula a distancia euclidiana entre dois pontos
# - vec1: Vetor 1
# - vec2: Vetor 2
# - num: Número de dimensões espaciais
# ------------------------... |
7faefdd7192a19669f3b7a0e73e08b2b769ed15c | chulhee23/today_ps | /hanbit/dfs_bfs/ice_frame.py | 810 | 3.640625 | 4 | # 얼음 틀 모양 주어졌을 때
# 생성되는 최대 아이스크림 수
# 2차원 배열
# 1은 막힘 -> 방문.
# 0은 열림 -> 아직 방문X.
# 0 인접한 0들 묶음 갯수를 파악
def dfs(x, y):
# 범위 벗어나면 종료
if x <= -1 or x >= n or \
y <= -1 or y >= m:
return False
# 방문 전
if graph[x][y] == 0:
# 방문 처리
graph[x][y] = 1
# 상하좌우 재귀 호출
... |
3b05df07dcddc639466ba683231cfeff56ba44d8 | chulhee23/today_ps | /data_structure/stack/stack.py | 547 | 3.921875 | 4 | class Stack:
def __init__(self):
self.top = []
def __len__(self):
return len(self.top)
def __str__(self):
return str(self.top[::1])
def push(self, item):
self.top.append(item)
def pop(self):
if not self.isEmpty():
return self.top.pop(-1... |
101eea3d60903038cf55472c0ef04b5591e0190e | chulhee23/today_ps | /BOJ/15000-19999/17413.py | 1,793 | 3.515625 | 4 | from collections import deque
import sys
word = list(sys.stdin.readline().rstrip())
i = 0
start = 0
while i < len(word):
if word[i] == "<": # 열린 괄호를 만나면
i += 1
while word[i] != ">": # 닫힌 괄호를 만날 때 까지
i += 1
i += 1 # 닫힌 괄호를 만난 후 인덱스를 하나 증가시킨다
elif wor... |
3597f00172708154780a6e83227a7930e034d166 | csu100/LeetCode | /python/leetcoding/LeetCode_225.py | 1,792 | 4.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/31 10:37
# @Author : Zheng guoliang
# @Version : 1.0
# @File : {NAME}.py
# @Software: PyCharm
"""
1.需求功能:
https://leetcode-cn.com/problems/implement-stack-using-queues/
使用队列实现栈的下列操作:
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
... |
0efc9e2b00e3c6ad7251b21c0dbdda5fe5a748ff | csu100/LeetCode | /python/leetcoding/LeetCode_206.py | 994 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/24 14:42
# @Author : Zheng guoliang
# @Site :
# @File : LeetCode_206.py
# @Software: PyCharm
"""
1.需求功能:
https://leetcode.com/problems/reverse-linked-list/description/
2.实现过程:
"""
from leetcoding.ListNode import ListNode
class Solution:
... |
0768a12697cd31a72c3d61ecfa4eda9a1aa0751e | csu100/LeetCode | /python/leetcoding/LeetCode_232.py | 1,528 | 4.46875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/31 17:28
# @Author : Zheng guoliang
# @Version : 1.0
# @File : {NAME}.py
# @Software: PyCharm
"""
1.需求功能:
https://leetcode-cn.com/problems/implement-queue-using-stacks/submissions/
使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
... |
0341229309f1cf0e9add85b69c248e2f13e9f819 | ZhouYzzz/TF-CT-ResCNN | /test/test_decorator.py | 328 | 3.734375 | 4 | def print_args(func):
def wrapped_func(*args, **kwargs):
print(func.__name__, func.__doc__)
for a in args:
print(a)
for k, v in kwargs:
print(k, v)
return func(*args, **kwargs)
return wrapped_func
@print_args
def add(x: int, y: int):
""":Add two integers"""
return x + y
print(add... |
71a23a3ac6f35438be6d943dad386d2f33c01c84 | DenisoDias/python-password-generator | /password_gen.py | 1,181 | 3.734375 | 4 | from random import choice
import argparse
import string
arg = argparse.ArgumentParser(add_help=True)
arg.add_argument('-s', '--size', default=20, nargs="?", type=int, help='Parameter to set size of password you will generate')
arg.add_argument('-q', '--quantity', default=10, nargs="?", type=int, help="Parameter to set... |
ef0de30520dcecfae1031318a469f4202c02091c | jeanjoubert10/Atwood-machine | /atwood machine1.py | 3,357 | 3.5 | 4 |
# Simple atwood machine in python on osX
import turtle
from math import *
import time
win = turtle.Screen()
win.bgcolor('white')
win.setup(500,900)
win.tracer(0)
win.title("Atwood machine simulation")
discA = turtle.Turtle()
discA.shape('circle')
discA.color('red')
discA.shapesize(3,3)
discA.up()
discA.goto(0,30... |
708e40f6392f05d6e0b04e32c600328e052d153e | IracemaLopes/Data_Visualiazation_with_Matplotlib | /annotating_a_plot_of_time_series_data.py | 444 | 3.984375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Read the data from file using read_csv
climate_change = pd.read_csv("climate_change.csv", parse_dates=["date"], index_col=["date"])
# Plot the relative temperature data
ax.plot(climate_change.index, climate_change["relative_temp"])
# Annot... |
995c55f01fcece72677e88b3518bcce98e8f4522 | yassir-23/Algebre-application | /Systemes.py | 1,765 | 3.703125 | 4 | from os import *
from Fonctions import *
def Systemes():
while True:
system('cls')
print(" #-----------------------------# Menu #-----------------------------#")
print(" 1 ==> Système de n équations et n inconnus.")
print(" 0 ==> Quitter.")
print(" #----------------... |
3a9a3220f024406f7120421cb00e17427810bb09 | devdw98/TIL | /Language/Python/파이썬으로 배우는 알고리즘 트레이딩/lesson05.py | 913 | 3.546875 | 4 | #5-1
def myaverage(a,b):
return (a+b)/2
#5-2
def get_max_min(data_list):
return (max(data_list), min(data_list))
#5-3
def get_txt_list(path):
import os
org_list = os.listdir(path)
ret_list = []
for x in org_list:
if x.endswith("txt"):
ret_list.append(x)
return ret_list
#5-4
def BMI(kg,... |
6e42680389e94466abc769aec4e8eba49d9a853d | hexavi42/eye-see-u | /proofOfConcept/grayscale.py | 782 | 3.546875 | 4 | import argparse
from os import path
from PIL import Image
def main():
parser = argparse.ArgumentParser(description='Grayscale an Image')
parser.add_argument('-p', '--path', type=str, default=None, help='filepath of image file to be analyzed')
parser.add_argument('-o', '--outFile', type=str, default=None, h... |
0be7bc8211b56c825d410b76816af2d89eb19f6d | Alb4tr02/holbertonschool-higher_level_programming | /0x03-python-data_structures/10-divisible_by_2.py | 318 | 3.984375 | 4 | #!/usr/bin/python3
def divisible_by_2(my_list=[]):
new_list = []
if my_list is None or len(my_list) == 0:
return (None)
else:
for i in my_list:
if (i % 2) == 0:
new_list.append(True)
else:
new_list.append(False)
return (new_list)
|
c537a01c9337f80af03e9209217d1a7dd25fbad9 | Alb4tr02/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 221 | 3.625 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
if matrix is None:
return
newm = matrix.copy()
for i in range(0, len(newm)):
newm[i] = list(map(lambda x: x*x, newm[i]))
return newm
|
2003141f132187e8281b81d69561fe78131a948a | Alb4tr02/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/6-print_sorted_dictionary.py | 216 | 4.03125 | 4 | #!/usr/bin/python3
def print_sorted_dictionary(a_dictionary):
if a_dictionary is None:
return
list = (sorted(a_dictionary.items()))
for i in list:
print("{}{} {}".format(i[0], ":", i[1]))
|
cc43bddce55b547f89fb76b6636a278204121d0f | Alb4tr02/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 194 | 4.09375 | 4 | #!/usr/bin/python3
def uppercase(str):
for a in str:
c = ord(a)
if c >= ord('a') and c <= ord('z'):
c -= 32
print("{:c}".format(c), end="")
print("")
|
74c99c3b0c9b9bd9adc3d84ec71d466169be8a1f | PuchatekwSzortach/convolutional_network | /examples/mnist.py | 2,112 | 3.546875 | 4 | """
A simple MNIST network with two hidden layers
"""
import tqdm
import numpy as np
import sklearn.utils
import sklearn.datasets
import sklearn.preprocessing
import net.layers
import net.models
def main():
print("Loading data...")
mnist = sklearn.datasets.fetch_mldata('MNIST original')
X_train, y_tra... |
9003c2fc01c18745533b9995186de30fc99f4fc4 | KulaevaNazima/files | /files4.py | 1,348 | 3.859375 | 4 | #Cоздайте текстовый файл python.txt и запишите в него текст #1 из Classroom:
#Затем, считайте его. Пробежитесь по всем его словам, и если слово содержит
#букву “t” или “T”, то запишите его в список t_words = [ ]. После окончания списка,
#выведите на экран все полученные слова. Подсказка: используйте for.
python = open ... |
5cb813598d9e52af2c1f514da781de4d22285190 | singediguess/my-python-note | /using_str/using_str.py | 495 | 4.0625 | 4 | str1 = 'I am {}, I love {}'
str2 = str1.format('k1vin', 'coding')
print (str2)
print('---')
#using index
str3 = '{0:10} : {1:3d}'
table = {'c++':16, 'html':15, 'python':17}
for name, nmb in table.items():
print (str3.format(name, nmb))
print('---')
#using '%'
import math
print ('pi = %6.4f' % math.pi)
print('---')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.