blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
8382fbbb57e19623ef9ad509ab2a318a849ae2e8
ChenJinGit/test001
/login.py
446
3.75
4
class Anilam(object): def __init__(self, name, age, num): self.name = name self.age = age self.num = num def drink(self): print('----喝------') def say(self): print('-----看-----') print('----张三增加的-----') print('----陈金增加的-----') print() def main(): dog ...
0b056f9ee07467142df86d4e5d52dbc9cb343f44
dgquintero/holbertonschool-interview
/0x19-making_change/0-making_change.py
592
4.0625
4
#!/usr/bin/python3 """Program that Given a pile of coins of different values, determine the fewest number of coins needed to meet a given amount total""" def makeChange(coins, total): """Function that Given a pile of coins of different values, determine the fewest number of coins needed to meet a given amount...
f8ca74e03e4ac6be03a1637767293a80f7c2132f
inspectorcat08/OOP_module_game
/models.py
2,157
3.765625
4
from exceptions import * from settings import player_lives from random import randint from datetime import datetime class Enemy: def __init__(self, lives, level = 1): self.level = level self.lives = lives @staticmethod def select_attack(): return randint(1, 3) def decrease_...
c3162aa42d89c6ce79d092cb20bd3f2f49e0b145
codeankit10/Hacktoberfest-2021
/Python-Practice.Program/p3.py
310
4
4
#Write a program to find the sum of charecters ascii values in string List. def asciiSum(li): l = [] for i in range(len(li)): summ = 0 for i in li[i]: summ += ord(i) l.append(summ) return l li = ['HELLOW', 'hellow'] print(li) print(asciiSum(li))
c23e2eeedccca7fa50b89f749afac3b207f39b9e
cmcunningham27/python-newsfeed
/app/models/User.py
1,633
3.53125
4
from app.db import Base #import classes from sqlalchemy module to define table columns and their data types from sqlalchemy import Column, Integer, String from sqlalchemy.orm import validates import bcrypt # create a salt to hash passwords against salt = bcrypt.gensalt() # User class inherits from Base class which wa...
32e5ca3a712202b14ce3838cb023ff400f4048a2
srikanthnekkanti1/hello-world
/numRev.py
171
3.90625
4
//This returns an input number by reversing the digits def numRev(n): //using the string slicing technique print(str(n)[::-1]) if __name__ == '__main__': numRev(1234)
31c02bd2168bde17ce518a6a44215d6ab74807a4
worasit/python-learning
/mastering/decorators/decorating_functions_03_optional_args.py
356
4.0625
4
""" Decorators with (optional) arguments """ import functools def add(extra_n): def _add(function): @functools.wraps(function) def __add(n): return function(n + extra_n) return __add return _add @add(extra_n=1) def eggs(n): return 'eggs' * n print(eggs(1)) # resu...
9153287b7c8ea273e3fd11a48c9e5b470659293b
worasit/python-learning
/mastering/async_io/single_threaded_parallel.py
965
3.859375
4
import asyncio async def sleeper(delay): await asyncio.sleep(delay) print('Finished sleeper with delay: %d' % delay) print('Start program') loop = asyncio.get_event_loop() tasks = (sleeper(1), sleeper(3), sleeper(2)) results = loop.run_until_complete(asyncio.wait(tasks)) print('End program') # Finished sl...
01b8496d29a0a14957447204d655e441254aeb75
worasit/python-learning
/mastering/generators/__init__.py
1,836
4.375
4
""" `A generator` is a specific type of iterator taht generates values through a function. While traditional methods build and return a `list` of iterms, ad generator will simply `yield` every value separately at the moment when they are requested by the caller. Pros: - Generators pause execution completely u...
5ee0c1868b77a32371ff38588047bf9db2145ba3
worasit/python-learning
/mastering/functional_programming/functools.py
2,225
3.84375
4
""" The 'functools' library is a collection of functions that return callable objects. Some of these functions are used as decorators. partial - no need to repeat all arguments every time reduce - combining pairs into a single result(Mostly use in the recursive function) """ # ========================= Partial ======...
6a874b6e76c72d0e8db19246452e1fe78b0b960e
vvkvivekl/Logs-Analysis-Project
/news/newsdb.py
3,117
3.625
4
#!/usr/bin/env python import os import sys import psycopg2 DBNAME = "news" def connect(database_name): """Connect to the database. Returns a database connection.""" try: db = psycopg2.connect(dbname=database_name) return db except psycopg2.Error as e: # THEN you could print an e...
f69d9f6aad1a09883da18e2d210c4cc416aa4586
demetriusengdados/Python-POO
/Doc String 3(Função).py
378
3.9375
4
"""Documetação oficial""" variavel_1 = 'valor 1' def soma(x, y): #soma x e y return x + y def multiplica(x, y, z=None): """Soma x, y, z Multiplica x, y, z o programador por omitir a variavel z caso não tenha necessidade de usa-la """ if z: return x * y else: return x * y * z variavel_2 = ...
2304ff6c6226d6cff5eabd2297d6dbbcbcaa2da0
demetriusengdados/Python-POO
/python_enum.py
556
3.671875
4
from enum import Enum, auto class Directions(Enum): right = auto() left = auto() up = auto() down = auto() def move(direction): if not isinstance(direction, Directions): raise ValueError('Cannot move in this direction') return f'Moving {direction.name}' if __name__ == "__main__": ...
4f44c38e53adc3dadb8323aec0e1f28436f58b43
demetriusengdados/Python-POO
/Encapsulamento.py
899
4.09375
4
""" public = metodos e atributos que podem ser acessados dentro e fora da classe protected = atributos de dentro da classe ou das filhas private = atributos e metodos so podem acessados de dentro da classe """ class BaseDeDados: def __init__(self): self.dados = {} def inserir_clientes(self, id, nome): ...
4cab6e70026d477d7742fce2c63afc609c07a1ab
demetriusengdados/Python-POO
/Função def .py
327
3.78125
4
def divisao(n1, n2): if n2 == 0: return return n1 / n2 divide = divisao(8,2) if divide: print(divide) else: print('Conta Invalida') def divisao(n1, n2): if n2 == 0: return return n1 / n2 divide = divisao(60,4) if divide: print(divide) else: print('Conta Invalida...
ad31329f701c1efcede6f0548aa977238b3311c0
demetriusengdados/Python-POO
/Classes.py
487
3.828125
4
class Pessoa: ano_atual = 2020 def __init__(self, nome, idade): self.nome = nome self.idade = idade def get_ano_nascimento(self): print(self.ano_atual - self.idade) @classmethod def por_ano_nascimento(cls, nome, ano_nascimento): idade = cls.ano_atual - ano_nascimento ...
d845686cceccecd19e1d767f4619618d92a49c41
demetriusengdados/Python-POO
/Operação ternaria.py
252
3.796875
4
idade = input('Qual sua idade: ') if not idade.isnumeric(): print('Voce precisa apenas numeros.') else: idade = int(idade) e_de_maior = ( idade >= 18) msg = 'Pode acessar' if e_de_maior else 'Não pode acessar.' print(msg)
c9ed5680603ef90330cae0b28b90ae0a9eeb4ab6
OpenR00t/Collatz_conjecture
/collatz.py
1,114
3.703125
4
from datetime import datetime today = datetime.now() fileDate = today.strftime('%Y-%m-%d-%H-%M-%S') print("Select starting integer: ", end = '') start = input() start = int(start) num = 0 calculating = True log = open("{0}_working.log".format(fileDate), "w") while True: now = datetime.now() timeCode = now.st...
18292a4d4a250dd03785ff49050da35d005e700e
CLA-GITHUB/password-manger
/passmang_back.py
1,941
3.5625
4
from functions import create_new_passwords, view_passwords, random_password, logout, get_user_id class Password_manager: def __init__(self): self.username = '' self.id = 0 def menue(self): print('1. Add new site and password') print('2. View existing sites and password...
e76c40b7b7dde026c00ddb3bce0e523cb132ee33
onahte/learningPython
/RandomWalk.py
411
3.78125
4
from turtle import Turtle, Screen from random import choice, randint drawer = Turtle(shape ='circle') drawer.color('red') drawer.width(10) drawer.speed(15) screen = Screen() color = ['cornsilk', 'aquamarine2', 'firebrick2', 'DodgerBlue4', 'green3', 'DeepPink4', 'orange', 'DeepSkyBlue4', 'gold1'] for x in range(3000):...
5a20f79e994cb6ad49db479688574eacc619b586
onahte/learningPython
/ShapeDraw.py
438
3.953125
4
from turtle import Turtle, Screen from random import choice drawer = Turtle(shape ='circle') drawer.color('red') drawer.width(3) screen = Screen() drawer.up() drawer.goto(0, -200) drawer.down() color = ['black', 'red', 'blue', 'green', 'purple', 'orange', 'darkblue'] for x in range(3, 40): drawer.color(choice(col...
f0b2ccb0693dd629321c36b864fc73ae80c26713
lfvelascot/Analysis-and-design-of-algorithms
/PYTHON LOG/graficos/ejemploEntry.py
1,564
3.5625
4
from tkinter import * raiz = Tk() frame1 = Frame(raiz,width = 400, height = 400) frame1.pack() minombre = StringVar() cuadro1 = Entry(frame1,textvariable=minombre) cuadro1.grid(row = 0,column =1,padx=10, pady = 10) cuadro1.config(fg = "red", justify = "center") label1 = Label(frame1, text = "Nombre:") ...
b0b33bc7fb0b5f7ea3ebae34bd7f380ee0135088
lfvelascot/Analysis-and-design-of-algorithms
/PYTHON LOG/calculos/basicos/operaciones_basicas.py
382
3.515625
4
def sumar(op1,op2): print ("El resultado de la suma : ",op1," + ",op2," = ",op1+op2) def restar(op1,op2): print ("El resultado de la resta : ",op1," - ",op2," = ",op1-op2) def multiplicar(op1,op2): print ("El resultado de la multiplicacion : ",op1," x ",op2," = ",op1*op2) def dividir(op1,op2): print ("...
befff9285fbb97a84b0184cadee4176a20478977
lfvelascot/Analysis-and-design-of-algorithms
/PYTHON LOG/PYTHON ADVANGE/ARBOLES BINARIOS/huffman.py
5,741
3.640625
4
import six ############################# # Definir una clase de nodo huffman ############################# class Node: def __init__(self,freq): self.left = None self.right = None self.father = None self.freq = freq def is_left(self): return self.father.left == self ###...
b3c14db3a26d5d6e122e96fc736c8266e907ed97
lfvelascot/Analysis-and-design-of-algorithms
/PYTHON LOG/tuplas.py
1,022
4.125
4
tupla1=("Hola","Mi",25,"nombre",25) print("Elemento en la posicion 2 : ",tupla1[2]) print("///////") #Convertir una tupla a lista lista=list(tupla1) print("Tupla convertirda en lista\n",lista) print("///////") ##Convetir una lista a tupla tuplar=tuple(lista) print("Lista convertida en tupla\n",tuplar) print("...
47f4f9d48d55831b9da7dc5d050eefede7d34fa4
lfvelascot/Analysis-and-design-of-algorithms
/PYTHON LOG/PYTHON ADVANGE/ORDENAMIENTO/mergeSort.py
1,095
3.859375
4
def mergeSort(lista): if len(lista) <= 1: return lista medio = len(lista) / 2 izquierda = lista[:medio] derecha = lista[medio:] izquierda = mergeSort(izquierda) derecha = mergeSort(derecha) return merge(izquierda, derecha) def merge(listaA, listaB): lista_nueva = [] a = 0...
168977591620a2a67e99ac79f603e2daaaff7633
HelloRicky/UNSW-MIT
/COMP9021/Quiz/q6/quiz_6.py
6,650
4.03125
4
# Creates 3 classes, Point, Line and Parallelogram. # A point is determined by 2 coordinates (int or float). # A line is determined by 2 distinct points. # A parallelogram is determined by 4 distint lines, # two of which having the same slope, the other two having the same slope too. # The Parallelogram has a method, d...
19387cc438d3caec2b11b0b7d41266e66dabe012
xjqd/codes
/python/sort/lambda.py
212
3.859375
4
#!/bin/python f1 = lambda x, y : x+y print f1(3,5) # 三元表达式 a, b = 1, 2 h1 = a if a>b else b h2 = (a if a>b else b) h3 = a > b and [a] or [b] h4 = (a < b and a or b) print h1 print h2 print h3 print h4
65b7ec724b4efc4779c1440c472f976fb87dc355
xjqd/codes
/python/pattern/singlton/sloution3.py
489
3.71875
4
#!/bin/python class OnlyOne(object): __instance = None def __init__(self ): pass #看到cls做为参数的好处了吧 @classmethod def getinstance(cls): print cls print dir(cls) if not cls.__instance: cls.__instance=OnlyOne() return cls.__instance def __str__(self)...
c03dd868f24eec310e537c5c224b9627b469a811
rileyworstell/PythonAlgoExpert
/twoNumSum.py
900
4.21875
4
""" Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return them in an array, in any order. If not two numbers sum up to the target sum, the function should return an empty...
993e6e978b107490a59cbdc9e4c66b075d5c4883
dandan224/Tree
/Search_In_Binary_Search_Tree.py
524
3.890625
4
Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def search(self, root, key): """ input: TreeNode root, int key return: TreeNode """ # write your solution ...
3abbc619538d04605ad59d5c33d0de52254226a0
dandan224/Tree
/Identical_Binary_Tree.py
567
3.96875
4
Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isIdentical(self, one, two): """ input: TreeNode one, TreeNode two return: boolean """ # write your so...
36185161c7c5053f8436f25e5a0248c2653a77f0
dandan224/Tree
/Minimum_Depth_of_Binary_Tree.py
891
3.90625
4
Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDepth(self, root): """ input: TreeNode root return: int """ # write your solution here if not ...
1fc99f9744b09f5bbf5292a60e5556d7000c6bd6
brian-hernandez/PyGame-Project
/src/platformer/platform_scroller.py
13,625
3.59375
4
"""Module that defines basic parts of game like: - Player Stats - Player Score - Pause - Death Screen - intro - main() """ import pygame import platformer.constants as constants import platformer.levels as levels import platformer.messages as messages from random import randint fr...
c79ba3a6834fbb5a0f8d5c2ebabe0d4f6f790452
mwongeraE/python
/spellcheck-with-inputfile.py
904
4.15625
4
def spellcheck(inputfile): filebeingchecked=open(inputfile,'r') spellcheckfile=open("words.txt",'r') dictionary=spellcheckfile.read().split() checkedwords=filebeingchecked.read().split() for word in checkedwords: low = 0; high=len(dictionary)-1 while low <= high: ...
47feb5aa5e772caaf5384049b0f2b9df85af749e
mwongeraE/python
/strings.py
169
3.765625
4
def main(): n = 42 s = "This is a %s string" % n #'''this is a string #after line #and line of text''' print (s) if __name__ == '__main__': main()
399fdf58b183409d88c8264140602076b007ec1d
SachinHg/python-exercises
/catalan.py
443
3.609375
4
# recursive function def catalan(n): if n <=1: return 1 ress = 0 for i in range(0,n): # for j in range(i): ress+=catalan(i)*catalan(n-i-1) return ress ### dynamic solution def catalan_dynamic(n,res): for i in range(2,n): res[i] = 0 for j in range(0,i): res[i]+=res[j]*res[i-j-1] return res[n-1] n =...
5552c253e787a0bb269ffc9e188831959d852a35
SachinHg/python-exercises
/max_no_consec.py
508
3.640625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT def max_sum(array,n): till_this = 0 except_this = 0 for i in array: new_except = except_this if except_this > till_this else till_this till_this = except_this+i except_this = new_except return(except_this if except_this > till_this else til...
f40532776e6ce34f564a9f2597cadf18c1fbaa13
SachinHg/python-exercises
/palin_idx.py
641
3.75
4
def palindromeIndex(s): s_r = s[::-1] len1 = len(s) if s == s_r: return -1 else: i = 0 s_ar = list(s) while i < len1//2: if s_ar[i] != s_ar[len1-1-i] : if s_ar[i+1] == s_ar[len1-1-i] and s_ar[i+2]==s_ar[len1-1-i]: return i ...
89038721966e0c3974e91a3c58db4c6245ffa354
robwalker2106/100-Days
/day-18-start/main.py
1,677
4.1875
4
from turtle import Turtle, Screen from random import randint, choice don = Turtle() #don.shape('turtle') don.color('purple3') #don.width(10) don.speed('fastest') screen = Screen() screen.colormode(255) def random_color(): """ Returns a random R, G, B color. :return: Three integers. """ r = randi...
570095afbe9ec387c3e925bb2af56148d21e4e22
robwalker2106/100-Days
/US-State-Quiz/score.py
512
3.515625
4
from turtle import Turtle FONT = ('Courier', 24, 'normal') class Score(Turtle): def __init__(self): super().__init__() self.penup() self.pencolor('black') self.hideturtle() self.score = 0 self.score_print() def score_print(self): self.goto(0, 300) ...
ea5126131b60a84358910b22b4ff4204e2d96da6
robwalker2106/100-Days
/Day-15-Coffee-Machine/main.py
2,689
4.03125
4
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { ...
516573693260ec6acd1cc3de931a73d14f9bbccd
robwalker2106/100-Days
/US-State-Quiz/main.py
634
3.703125
4
from turtle import Turtle, Screen from states import States from score import Score screen = Screen() screen.title("U.S. State Game") image = 'blank_states_img.gif' screen.addshape(image) screen.tracer(0) screen.setup(width=900, height=900) states_map = Turtle(image) states = States() score = Score() while score.sco...
7ced80b9eebbbd05c9dfed8b36c725e4b4556a41
tsonict/Actividad4
/zodiaco.py
2,974
3.9375
4
def signo(dia:int, mes:int): if mes == 1: if dia>=1 and dia<=20: print("Tu signo es capricornio.") elif dia>=21 and dia<=31: print("Tu signo es acuario.") else: print("Introduce un dia valido para este mes.") elif mes == 2: if dia>=1 and dia<=...
332c3853fb99eb1b3c8a0a0ee6c50c6cd4b8c5fd
wko1375/Data-Structures
/Homework 5/wk700_hw5_q2.py
4,906
3.890625
4
class EmptyCollection(Exception): pass class ArrayStack: def __init__(self): self.data = [] def __len__(self): return len(self.data) def is_empty(self): return len(self) == 0 def push(self, val): self.data.append(val) def top(self): if ...
be6bb56af000533af1db9f66491bece5475e3608
wko1375/Data-Structures
/Homework 1/wk700_hw1_q6.py
1,759
3.765625
4
class Vector: def __init__(self, d): if isinstance(d, int): self.coords = [0]*d if isinstance(d, list): self.coords = d def __len__(self): return len(self.coords) def __getitem__(self, j): return self.coords[j] def __setitem__(self,...
0598dccc07953e3eda30e23574c5414164c9cc9a
wko1375/Data-Structures
/Homework 9/wk700_hw9.q4.py
397
3.640625
4
def intersection_list(lst1, lst2): maximum_len = max(max(lst1), max(lst2)) length = maximum_len + 1 lst = [None] * length for index in range(len(lst1)): lst[lst1[index]] = lst1[index] intersection_list = [] for index in range(len(lst2)): if lst[lst2[index]] != None: ...
2396ec9d857ad66b55468a15fc91a02f133b76bd
wko1375/Data-Structures
/Homework 5/wk700_hw5_q3.py
3,062
3.65625
4
class ArrayStack: def __init__(self): self.data = [] def __len__(self): return len(self.data) def is_empty(self): return len(self) == 0 def push(self, val): self.data.append(val) def top(self): if (self.is_empty()): raise Empty("...
5e58f62fe8747ac7ba649630108b6538ab5a32a3
Daniel-Schroeder15/Election-Analysis
/PyPoll.py
3,914
4.125
4
# The data we need to retrieve # 1. The total number of votes cast # 2. A complete list of candidates who received votes # 3. The percentage of votes each candidate won # 4. The total number of votes each candidate won # 5. The winner of the election based on popular vote # First we'll import the os module # This will...
82846979d1b90e04ae4a3e9ca561ca955d1af46d
MuchesiaKe/-100DaysOfCode
/tryexcept.py
205
3.765625
4
try: value = 10/0 number = int(input("Enter a number: ")) print(number) except ValueError as err: print(err) except ZeroDivisionError as zero: #store the error in a variable print(zero)
bed6e8db7b459ee9818f4c9bf567ac3837c1bb08
hellomuyi/cars-sales-forecast
/all data/cyj-quchong10000.py
1,770
3.59375
4
""" 数据去重 例如:共有十列,若有多行数据的前九列数据相同,则将第十行数据用均值代替,再使用excel去掉重复行 """ import pandas as pd ThePath = r"./quchong_prepare_input.xlsx" df = pd.read_excel(ThePath) # print(df) print("-"*100) print(len(df)) # 18911 list = [] dict = {} if "color2" in dict.keys(): print("ok") for i in range(len(df)): # 前九列组成字符串 name = s...
38dba16f475d865e3420f08a16b5f18a750fe609
aemann01/pythonMisc
/DNA_seq_functions.py
774
4.03125
4
def validate_base_sequence(base_sequence, RNAflag): """Return TRUE if the string base_sequence contains only upper- or lowercase T (or U if RNAflag), C, A, and G characters, otherwise FALSE""" seq = base_sequence.upper() return len(seq) == (seq.count('U' if RNAflag else 'T') + seq.count('C') + seq.count('A') + ...
426ec8d10284961fd01032b06a480f435cb785b1
aemann01/pythonMisc
/median_rarefied_counts_from_otu_table.py
1,086
3.515625
4
#!/usr/local/bin/python import pandas as pd import glob """Reads in all *.txt files in a directory (OTU tables tab deliniated), merges them on the column headers and then finds median counts for each taxa. Usage: python median_rarefied_counts_from_otu_table.py """ class colors: COMPLETE = '\033[92m' ENDC = '033[0m...
174fc8b9b9050c623588db26f69ece19b8589aee
shawnrivers/bezier
/playground.py
2,140
3.5625
4
from graphics import * import random # Generate random points def genRandomPoints(amount, winWid, winLen): pointsSet = [] for i in range(amount): x = random.randint(0, winWid) y = random.randint(0, winLen) point = {"x": x, "y": y} pointsSet.append(point) return pointsSet # Draw points from the p...
f48d541663c5fbbc5d43f0fe494b90e8bad4d7e0
clacroi/Datum
/datum/readers/reader.py
8,684
3.515625
4
""" Abstract class to represent a database reader used to populate a Dataset object. """ from abc import ABC, abstractmethod from pathlib import Path from typing import List, Tuple, Dict, Any, Optional from datum.utils.annotations_utils import get_dict_value from datum.datasets import Dataset class AttributeConstru...
4378ab68cbeb7f56cf6e12e54c3d5f7cdc7334bb
sudouc/iwomm
/unit_testing/fizzbuzz.py
401
3.984375
4
def get_output(number: int) -> str: """ Return the correct string to print for the number, following FizzBang rules """ output = "" if number % 3 == 0: output += "Fizz" if number % 5 == 0: output += "Buzz" if not output: output = str(number) return output if ...
a3337bde5cf7d0b0712a15f23d2ab63fed289c2f
nickdurbin/iterative-sorting
/src/searching/searching.py
1,860
4.3125
4
def linear_search(arr, target): # Your code here # We simply loop over an array # from 0 to the end or len(arr) for item in range(0, len(arr)): # We simply check if the item is equal # to our target value # If so, then simply return the item if arr[item] == target: ...
11ed7a05da31e7f377e43ff39a6079aabaf7c1d4
NikitaInozemtsev/python-practice
/Additional tasks/practice_1/fast_mul/fast_mul.py
551
3.59375
4
def fast_mul(x,y): if (x == 0 and y == 0): return 0 xlist = div2(x) ylist = mul2(y, len(xlist)) sum = 0 for i in range(len(xlist)): if (xlist[i] % 2 != 0): sum += ylist[i] return sum def div2(num): resList = [num] while num > 0: temp = num // 2 ...
27621b513e4265505d349173cf3f9e882dd3bfa9
NikitaInozemtsev/python-practice
/Additional tasks/practice_2/task3/f.py
116
3.9375
4
def transpose(x): return [list(i) for i in zip(*x)] a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(transpose(a))
aad2c2448632a991832ce917a03261998f6fd930
a3539a/Python
/Ch03/3_3_For.py
1,599
3.671875
4
""" 날짜 : 2021/04/28 이름 : 김승용 내용 : 파이썬 반복문 For 실습 교재 p70 """ # for for i in range(5): print('i : ', i) for j in range(10, 20): print('j : ', j) for k in range(10, 0, -1): # range( start, end, step ) print('k : ', k) # 1 부터 10 까지 합 sum1 = 0 for k in range(11): sum1 += k print('1부터 10까지 합 : ', sum1) ...
681d09a2e30d02bb52cec33e98e2499383eb9c5f
a3539a/Python
/Exam01/Ex1_8.py
329
3.609375
4
""" 날찌 : 2021/04/30 이름 : 김승용 내용 : 파이썬 최대값 / 최소값 연습문제 """ scores = [62, 82, 76, 88, 54, 92] max = scores[0] min = scores[0] for score in scores: if max < score: max = score if min > score: min = score print('최대 값 : ', max) print('최소 값 : ', min)
6c1d494ed4c41dc6735916ab8d68507c18ccc2ce
a3539a/Python
/CodingTest/Test02.py
455
3.640625
4
""" 날짜 : 2021/05/13 이름 : 김승용 내용 : 코딩 테스트 - 숫자 카드 게임 """ # n, m 을 공백으로 구분하여 입력 받기 n, m = map(int, input('입력 :').split()) nums = [] result = 0 for i in range(n): data = list(map(int, input('입력 :').split())) # data에서 가장 작은 수 구하기 data.sort() num = data[0] nums.append(num) # nums 에서 가장 큰 값 구하기 nums.sort() result = ...
25b6f7684ec7186a99f2dcfe5ac8f47e8a5059ae
a3539a/Python
/Ch02/p52.py
804
3.796875
4
""" 날짜 : 2021/04/27 이름 : 김승용 내용 : 교재 실습 p52 """ # 문자열 처리 함수 # 1) 특정 글자 수 반환 oneLine = 'this is one line string' print('t 글자 수 : ', oneLine.count('t')) # 2) 접두어 문자 비교 판단 print(oneLine.startswith('this')) print(oneLine.startswith('that')) # 3) 문자열 교체 print(oneLine.replace('this', 'that')) # 4) 문자열 분리(split) : 문단 ...
2a100f31956f9105be15ee9dea8fb35faa864621
a3539a/Python
/Exam02/ex2_1.py
401
3.90625
4
""" 날짜 : 2021/05/13 이름 : 김승용 내용 : 사전평가 """ scores = [] while True: print('0 : 종료', '1 : 입력') result = input('입력 : ') if result == '0': break score = int(input('점수입력 : ')) scores.append(score) print('입력한 점수 확인') print(scores) sum = 0 for score in scores: sum += score print('리스트 총...
72efdcea2b485a568e207a9334fe188bc8251d4a
a3539a/Python
/Ch03/Chap03Exam.py
1,855
3.90625
4
""" 날짜 : 2021/04/28 이름 : 김승용 내용 : Chap03 연습문제 풀이 p77 """ # 문제 1)a형 p 77 참조 jim = int(input('짐의 무게는 얼마입니까? : ')) if jim < 10: print('수수료는 없습니다.') else: print('수수료는 10000원 입니다.') # 문제 1)b형 p77 참조 jim = int(input('짐의 무게는 얼마입니까? : ')) if jim >= 10: price = (jim // 10) * 10000 print('수수료는 {}원 입니다.'.format(...
05a3169ef5edfea132705abfd0ee61204f8219e1
cristinaedt/python2018
/ejercicio-edad-1.py
122
3.8125
4
# coding: utf­8 edad=input("escribe un numero:") if(edad>=15 and edad<=17): print "puede entrar sesión de tarde"
c7fb773cfc1cddcecfb8dd3ed5cae925b76699e8
bhishan/cryptography
/ceasarattack.py
1,401
3.578125
4
valid_words = ["hello", "world"] alphabets = "abcdefghijklmnopqrstuvwxyz" frequencies = [0.080, 0.015, 0.030, 0.040, 0.130, 0.020, 0.015, 0.060, 0.065, 0.005, 0.005, 0.035, 0.030, 0.070, 0.080, 0.020, 0.002, 0.065, 0.060, 0.090, 0.030, 0.010, 0.015, 0.005, 0.020, 0.002] freq = [] sai_values = [] cipher_text = raw_i...
3de6280127975e6078a90293ccb2fcc915329d9a
blackozone/pynet-ons-feb19
/day1/str_ex1lee.py
186
3.6875
4
name1 = "Lee" name2 = "Greg" name3 = "Rudy" print("{:>30}{:>30}{:>30}".format(name1, name2, name3)) name4 = input("Submit another for the sacrifice: ") print("{:>30}".format (name4))
584ef2d6f95c1132c140334967b75cd6d1e52523
holmesr19/Classics_scraper
/Latin_text_analyzer.py
684
3.890625
4
''' Author: bancks holmes File: Latin_text_analyzer.py Purpose: This program integrates the parsing engine from whitaker's words with a text analysis component similar to one like that employed by voyant tools. A parsing engine assists the operation of the text analyzer in a language such as latin because it is so mu...
133d43194763c2768496f6e3f5f3d9d4c7fb47c2
vijaykumar250/Final_rmse_r2_mse
/test final regression_all.py
2,433
3.6875
4
import numpy as np import pandas as pd import pandas import matplotlib.pyplot as plt data = pandas.read_excel('sampledata.xlsx') print(data.shape) data.head() # Collecting X and Y X = data['lift1_True'].values Y = data['lift2_Predict'].values # Mean X and Y mean_x = np.mean(X) mean_y = np.mean(Y) # ...
c346a76f33f96248e4782304636a32c12238c6aa
adilawt/Tutorial_2
/1_simpsons_rule.py
672
4.15625
4
# ## Tutorial2 Question3 ## a) Write a python function to integrate the vector(in question #2) using ## Simpson's Rule # import numpy as np def simpsonsrule(f, x0, xf, n): if n & 1: print ("Error: n is not a even number.") return 0.0 h = float(xf - x0) / n integral = 0.0 x = float...
91d5de9694330211c783624fda58cd9585cddcff
OleksPo/GLBasecamp
/Python/count_holes.py
800
4
4
#!/usr/bin/env python3 # Global array for hole values hole = [ 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 ] # Function to return the count of holes in num def count_holes(num): try: int(num) except (TypeError, ValueError): #catch incorrect input of an integer return print ('error') else: str(num...
c2c554cd8ac9d0aa8ffb31f74a1020273aabd8f9
Amber-Chaeeunk/Datacrawling
/week2/homework.py
554
3.875
4
print("일반계산기 프로그램입니다!") first = input("계산할 첫번째 값을 입력해주세요: ") first = int(first) second = input("계산할 두번째 값을 입력해주세요: ") second = int(second) print("두개의 값 :", first,"와", second) print("더하기 값 (a+b) :" , first+second) print("빼기 값 (a-b) :" , first-second) print("곱하기 값 (a*b) :" , first*second) print("정수 나누기 값 (a//b) :" , fir...
648d2def58d3afd15ba4fef35b83a8a681144ef2
mimiyang/cs583-project1
/msapriori_Algorithm.py
7,670
3.75
4
import sys import operator mis_data = {} # MIS data will be stored in dictionary. process_data = [] # input data will be stored in a list. constraint = [] # constraints such as must-have and no-together will be stored in a list. # process the input data from input file and store all sequences into process_data li...
ab1a0c5e0f29e91a4d2c49a662e3176f4aa158f5
salihbaltali/nht
/check_if_power_of_two.py
930
4.1875
4
""" Write a Python program to check if a given positive integer is a power of two """ def isInt(x): x = abs(x) if x > int(x): return False else: return True def check_if_power_of_two(value): if value >= 1: if value == 1 or value == 2: return True el...
53094b11262e79430ddac42ba7d8ef7c54c448e4
ollyvergithub/CursoAluraPython1
/jogos/06_a_condicao_elif.py
609
3.953125
4
print("********************************") print('A condicção elif') print("********************************") numero_secreto = 42 chute_str = input("Digite o seu número: ") print("Você digitou ", chute_str) chute = int(chute_str) acertou = chute == numero_secreto chute_maior = chute > numero_secreto chute_menor = ...
fbfcac499c31339d324356c0c3e039ac4dea8ffa
ollyvergithub/CursoAluraPython1
/jogos/jogos_index.py
431
3.734375
4
import forca import adivinhacao print("********************************") print('Jogos Index') print("********************************") print("Escolha o jogo que deseja: (1)Forca (2)Adivinhação ") jogo = int(input("Qual jogo? ")) if(jogo == 1): print("Jogar o Forca") forca.jogar() elif(jogo == 2): pri...
1405849a70414a9040e7ecc24727e508403f602f
vfpimenta/corruption-profiler
/src/util.py
1,883
3.578125
4
import time import datetime import calendar def timing(f): def wrap(*args): time1 = time.time() ret = f(*args) time2 = time.time() print('{} function took {} ms'.format(f.__name__, (time2-time1)*1000.0)) return ret return wrap def printProgressBar (iteration, total, pre...
da506bfcd96313fb72d0977abb91738029442c6a
gzchub/python
/python0/python3.py
96
3.578125
4
#!/usr/bin/python print("hello") a = 1 print("a = %d"%a) a = 1 print("a = %d"%a,end="") a = 1
625a7276be836efc731d45d89e7bfa0ad1b34bea
hu279318344/Python-work
/PycharmProjects/hello/class.py
1,789
4.09375
4
#!/usr/bin/env python # encoding: utf-8 """ @version: Python 3.6 @author: Admin @license: Apache Licence @contact: yang.hu@live.com @software: PyCharm @file: class.py @time: 2017/3/7 10:07 类的初始化 """ """ class dog: def __init__(self,name): print("Hello Dog!") self.Name = name def sayname(sel...
bc1eae56ed6d7304c0526dfaf1987d76b411993a
hu279318344/Python-work
/PycharmProjects/hello/Querying Data mysql.py
1,446
3.671875
4
#!/usr/bin/env python # encoding: utf-8 """ @version: Python 2.7 @author: Admin @license: Apache Licence @contact: yang.hu@live.com @software: PyCharm @file: Querying Data mysql.py @time: 2017/1/17 14:10 """ import datetime import mysql.connector config = { 'user': 'root', 'password': '123456', 'host': '127....
46d45e0348daaf7ba29b54af3a2bfb3cc53a1b51
jiadebin/Mine_LeetCode
/Combination Sum II/test.py
2,850
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Tags: Array Backtracking Combination Sum II Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. Note: All numbers (...
89994b56da945167c927ad2617a5b9cbfc2d4a6b
rkovrigin/crypto
/week2.py
2,872
4.25
4
""" In this project you will implement two encryption/decryption systems, one using AES in CBC mode and another using AES in counter mode (CTR). In both cases the 16-byte encryption IV is chosen at random and is prepended to the ciphertext. For CBC encryption we use the PKCS5 padding scheme discussed in the lecture (1...
7e6d9daeb5b111b34accc02509fcb5b2a5217d81
heesuh98/Korea_Bio
/triangle.py
361
3.6875
4
#! /usr/bin/env python #while문을 이용한 삼각형 출력하기 i=0 while i<7: print('*'*i) i += 1 #####답 i = 1 while True : print('*' * i) i += 1 if 7<i : break #####sol2 #덧셈 이용하기 star = '' while True : print(star) star += * #*을 하나씩 star라는 변수에 더함 if 7 < i: break
dd322537f6368b99181c8ac76e85905c5bf9ab68
mali2005/sin
/sin.py
652
3.8125
4
import math def net_degree(degree): net = degree%360 return net def degree_to_radian(degree): tt = 180/degree radian = math.pi/tt return radian def sin(degree,count): degree = net_degree(degree) radian = degree_to_radian(degree) alpha = 1 test = 1 result = 0 ...
c3242cd16189ee8d23b696132b202f2bb97c3f93
Wintus/MyPythonCodes
/NegativeBase.py
3,367
3.90625
4
'''Negative base''' class NegativeBase(): '''Super class for negative bases base <= -2''' str_digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" def __init__(self, base, n): if not base < -1: raise ValueError('Base should be "base <= -2"') self.base = base self.num =...
0c40f14af82893bc8ccce60259424a98aaf28574
Wintus/MyPythonCodes
/PrimeChecker.py
608
4.15625
4
'''Prime Checker''' def is_prime(n): '''check if interger n is a prime''' n = abs(int(n)) # n is a pesitive integer if n < 2: return False elif n == 2: return True # all even ns aren't primes elif not n & 1: # bit and return False else: # for all odd ns ...
a128c820964fd5e88fdd6a17556514774b518f31
Wintus/MyPythonCodes
/TailCall.py
384
3.84375
4
'''recursion to tail call''' # seems impossible from functools import wraps def tail_call(func): '''decorate function to tail call form''' def _tail_call(*args, **key): nonlocal = func return _tail_call @tail_call def frac(n): return 1 if n == 0 else n * frac(n - 1) # => def frac_T...
4dfad2ec527357f9654b531f2f4558bcd9651f47
Wintus/MyPythonCodes
/ZhangYiwuHomework05Sec01.py
3,872
3.703125
4
# Project: Throw dice(ZhangYiwuHomework05Sec01.py) # Name: Yiwu Zhang # Date: 06/03/14 # Description: This program will let user throw five dices from graphics import * from random import randint def textbox(center, text, width, height, win): #calculate the p1, p2 from the center, width, he...
a82bdb9e0db4c1cd43b6ab4541abfa81b0b01cc2
Baqirh/automate-boring-stuff-with-python-projects
/regexOps1.py
4,462
4.21875
4
import re ''' creating a regex object. ''' phoneNumRegex = re.compile(r"\d{3}-\d{3}-\d{4}") # raw string ''' searching the string for any regex object match ''' mo = phoneNumRegex.search('My number is 415-555-4242 , 415-555-4244, 415-555-4222.') ''' returning the actual matched regex. ''' print("The ...
cf6ce8aa0d9eee7822ba65609651945c2019fcd5
Baqirh/automate-boring-stuff-with-python-projects
/ChessDictionaryValidator.py
2,288
3.84375
4
''' Checking weather a chess board is valid or not. Created: May 30, 2021 Creator: Nishkant ''' goats = ["pawn", "rook", "bishop", "king", "queen", "knight"] #valid names of goats piece_names = ["bpawn", "brook", "bbishop", "bking", "bqueen", "bknight" , "wpawn", "wrook", "wbish...
366e5c14d334d22f19ccad6dc78fa6276eb56dc2
Baqirh/automate-boring-stuff-with-python-projects
/CoinFlipStreaks.py
2,530
3.921875
4
''' How often does a streak of 6 heads/tails occur in flipping a coin 100 times ??? Code to calculate the number of streaks in an experiment of flipping a coin 100 times and repeating it 10000 times to calculate a decent average of percentage of streaks. Created: 27 may, 2021 Some commen...
1c6cd5037b87166c3d43bf4f3d6f8db79d8bcdc1
FrancisJaGlez/Mision_02
/extraGalletas.py
596
3.59375
4
#Francisco Javier González Molina A01748636 #Cuanto de ingredientes uso para "x" cantidad de galletas galletasdeseadas=int (input("¿Cuantas galletas deseas preparar? : ")) azucargalleta=(1*1.5)/48 mantequillagalleta= (1*1)/48 harinagalleta=(1*2.75)/48 azucarnecesaria=azucargalleta*galletasdeseadas mantequi...
88393b0337bbdc9f11912f61478be500e465c644
leonskim/webdnn
/src/graph_transpiler/webdnn/graph/operators/util.py
283
3.765625
4
from collections import Collection from typing import Union, Tuple def to_tuple(x, length=2): if isinstance(x, Collection): assert len(x) == length return tuple(x) else: return (x,) * length IntOrTuple = Union['IntOrTuple', int, Tuple[int, int]]
1350fcd3baa866a02f5db2c066420eaa77e00892
BrasilP/PythonOop
/CreatingFunctions.py
1,404
4.65625
5
# Creating Functions # In this exercise, we will review functions, as they are key building blocks of object-oriented programs. # Create a function average_numbers(), which takes a list num_list as input and then returns avg as output. # Inside the function, create a variable, avg, that takes the average of all th...
31699bbcc298caa16eb2bb2afed55ce746784c89
iskskskska/py4e
/temperature_exercise.py
83
3.734375
4
C=input("Enter the temperature in Celsius:") F=9/5*float(C)+32 print (str("F="),F)
513d47178f663f7a785302c5e0612cad755954c5
nstflecher/pythonlearningprocess
/print_max.py
370
4
4
# -*- coding: utf-8 -*- """ Created on Thu May 31 22:28:29 2018 @author: perso """ def print_max(a,b): if a>b: print(a, 'is maximum') elif a==b: print(a, 'is equal to', b) else: print(b, 'is maximum') #直接传递字面值 print_max(3,4) x=5 y=7 #以参数的形式传递变量 prin...
ff83e6fa161366cdaa83441c63d7ccb23073a92f
nstflecher/pythonlearningprocess
/convert_from_decimal.py
547
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 2 21:03:49 2018 @author: perso """ def convert_from_decimal (number, base): multiplier, result = 1,0 while number > 0: result += number%base*multiplier multiplier *= 10 number = number//base return result def ...
e60d5751c9ea27ad29b8566b2955d8fec5c5b8ec
TCS-Class-of-2019/New-Game
/Example Code/Tower-Defense-Prototype.py
8,148
3.75
4
# code based of of the code from the pygame tutorial at pythonprogramming.net. import pygame # these import the needed modules import random import math pygame.init() # this initializes the pygame module gameDisplay = pygame.display.set_mode((800,600)) # makes a window pygame.display.set_caption("TOWER DEFENSE") # s...
33b7212967b80f58777109bcb9c9acce7f1939a4
aeakoski/todo
/native_python_app/DragDropListbox.py
1,668
3.6875
4
try: import Tkinter as tk # Tkinter for python 2 except ImportError: import tkinter as tk # tkinter for python 3 class DragDropListbox(tk.Listbox): """ A Tkinter listbox with drag'n'drop reordering of entries. """ def __init__(self, master, brain, li, **kw): self.brain = brain self.mad...