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
6bd22bd42961fa6af7314a7d77510f2c35239071
PRIYANSHUSHARMAPHULERA/program
/exception handling.py
295
3.9375
4
try: num1,num2=eval(input("enter two numbers,separated:")) result=num1/num2 print("result is",result) except(ZeroDivisionError,syntaxerror) as e: print("Inside ZeroDivisionError,syntaxerror",e) except: print("wrong input") else: print("no exception") finally: print("done")
728217568061ad1570ef5ef3ce1d4a6a79d7306c
patrickayoup/untangling_changes
/src/merger.py
2,506
3.703125
4
import change def merge(change_matrix, threshold): """ Merges changes with values below the threshold. :param change_matrix: Matrix of changes with convidence voter values. :type change_matrix: dict[change.Change, dict[change.Change, double]] :param threshold: The threshold to discriminate whether ...
ca6bd0af267f78a56abff0b41cea92da1969021d
RadhikaRadhi/python-programming
/prime.py
113
3.640625
4
num=int(input()) k=0 for i in range(2,num): if(num%i==0): k+=1 if(k>0): print("no") else: print("yes")
11bd6d3d9139faee4ef23336f3ac432c954501bf
gauravowlcity/GeeksForGeeks
/consecutivebinary1.py
456
3.671875
4
''' Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s. ''' def count(n): a = [0]*n b = [0]*n a[0] = 1 b[0] = 1 for i in range(1,n): a[i] = a[i-1] + b[i-1] b[i] = a[i-1] return a[n-1] + b[n-1] def countSim...
123ccd623c8a2e1f1264cc4250eb1c9262ace418
gauravowlcity/GeeksForGeeks
/satisfyString.py
580
4.0625
4
''' Given n and an array of strings, print the string that contains the digits (1, 2, 3), if there are multiple strings that satisfies the conditions, print them in ascending order. Input : 5 1395 1721298 102030 3215 123 Output : 123 3215 102030 ''' n =...
8116ad8e00d374a2c44cb195897d7dbab5b77583
maciek-nowak/ccms-system
/views/assignment_view.py
844
3.625
4
def print_assignment_details(assignment): """ Function prints assignment details Args: assignment (Assignment): object represents single assignment added by mentor Returns: None """ ornament = 30 * '=' print(ornament) print('Assignment id:', assignment.assignment_id) ...
38395f1c4e4a31e0c35e9e4487af42764b7910dc
faisalkhan91/Backtracking-Search
/BacktrackingSearch.py
3,313
4.21875
4
#!/usr/bin/python3 ############################################################################################# # Program by Mohammed Faisal Khan # # Email: faisalkhan91@outlook.com # # ...
bcca1e7dc3c2ded6e2438b34a8a58ebc5ac49252
jaimevalero/learning-machine-learning
/best-practices/1-pipeline.py
1,250
3.5
4
import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline df = pd.read_csv('wdbc.data', header=None) from sklearn.preprocessing import LabelEncoder # We assign the 30 ...
e42133e88f5c11917a81a43fe648e4006a76e3c0
alwaysactivo/hacktoberfest2020-1
/Primsalgo.py
1,898
3.96875
4
# Python3 implementation to find minimum # spanning tree for adjacency representation. from sys import maxsize INT_MAX = maxsize V = 5 # Returns true if edge u-v is a valid edge to be # include in MST. An edge is valid if one end is # already included in MST and other is not in MST. def isValidEdge(u, v, i...
f09acf79422634e45e7c507050c0f47663e2ddc5
XieDake/codejam
/binsearch.py
336
3.953125
4
#!/usr/bin/env python3 def binsearch(array, t): l, r = 0, len(array) - 1 while l <= r: m = (l + r) // 2 if array[m] < t: l = m + 1 elif array[m] > t: r = m - 1 else: return m return -1 if __name__ == '__main__': print(binsearch(list...
1c132cd8d307833a17f4860c3d0267c89e0f83c6
Sridevi333/Python-Deep-Learning-Programming
/ICP2/wordsperline.py
355
4.125
4
fileName = input("Enter file name: ") f = open(fileName, "r") # Open file for input lines=0 mostWordsInLine = 0 for lineOfText in f.readlines(): wordCount = 0 lines += 1 f1=lineOfText.split() wordCount=wordCount+len(f1) if len(f1) > mostWordsInLine: mostWordsInLine = len(f1) print ...
2e74b6075f5d69a08959ab25087be6373d50e9f4
mrzhang638993/python-basis
/exer10.py
476
4
4
# 语法错误 #print(3 == not 5) # 运算符的优先级,and的优先级高于or print(3 or 5 and 0) # 6 print(3 and 5 + True or False) #not的优先级高于and print(0 and not 1 or not 2 and 3 or 4 and not 5) #False print(1 == 2 < 3) #False print(1 < 2 > 3 < 4 < 5) #编程题目 #x%2==1 #x%3==2 #x%5==4 #x%6==5 #x%7==0 # 119 i=0 while True: if i%2==1 and i%3==2 a...
ec79fbf6c6334667e4604b67cf4718304c5be637
mrzhang638993/python-basis
/object_excercise.py
1,525
4.1875
4
# python 对象的课后习题的训练 import math class Point: def __init__(self, x, y): self.x = x self.y = y class Line: def __init__(self, z, r): self.z = z self.r = r def getLen(self): return math.sqrt(math.pow((self.z.x - self.r.x), 2) + math.pow((self.z.y - self.r.y), 2)) ...
12c316d485a31bdf8e4d471cf031d6b34f2fe1b2
mrzhang638993/python-basis
/生成器.py
1,102
3.953125
4
# 生成器对应的是迭代器的一种实现,所以可以使用迭代器的方式实现迭代操作的 def myGen(): print("生成器被执行") yield 1 yield 2 myG = myGen() print(next(myG)) print(next(myG)) # 定义斐波拉切数列 def fibs(): a = 0 b = 1 while True: a, b = b, a + b yield a # 不要丢掉了a,否则下面的会报错的 for each in fibs(): if each > 100: break...
be35a837d21b2fe82483d9485745b9be44602816
mrzhang638993/python-basis
/object.py
7,883
4.34375
4
# 类对象 # 实例化对象 # 面向对象编程的特点和概念,需要进行关注 # 蓝猫,白猫,黑猫。 # 长,宽,面积,周长, # 类是一个抽象的概念。类的抽象需要根据具体的实际的需要进行抽象的 # 封装: 对应的是实现将对象的行为和属性进行封装操作,继承:对应的体现的是子类用于父类所有的行为和属性 # 多态:对应的是不同的类对于同样的一个行为提供了不同的实现操作 # 函数和方法的区别:函数和方法没有任何本质的区别。 class Person: name = "小甲鱼" def printSelf(self, name): self.name = name print(self...
d1f6b7f2192bbd7c650dca043c403264af0fdce4
mrzhang638993/python-basis
/module_exercise.py
1,485
4.40625
4
# python中的模块对应的是一个python文件 """ 1.我们现在有一个 hello.py 的文件,里边有一个 hi() 函数:.&ymiM?t def hi(): print("Hi everyone, I love FishC.com!") 复制代码 请问我如何在另外一个源文件 test.py 里边使用 hello.py 的 hi() 函数呢? 答案:对应的引用方式是如下的: import hello_1 as hello hello.hi() 2.模块对应的引入方式主要包括如下的3中引入方式的: 导入方式之一:import 模块导入操作 导入方式之二:from 模块名称 import 函数名称 可以只引...
98f2a515844083826503ee03d9420d36aa90ca19
mrzhang638993/python-basis
/game.py
447
4.28125
4
"""使用python 设计第一个游戏""" temp=input("不妨猜猜小甲鱼现在心里想的是那个数字: ") #接收用户的输入,赋值给temp guess=int(temp); if guess==8: #注意缩进的位置的,python非常注重缩进操作的 print("你是小甲鱼心里的蛔虫嘛?!") print("哼,猜中了也没有奖励!") else: print("猜错了,小甲鱼现在心里想的是8!") print("游戏结束,不玩了")
8ec6d74ebdd807d93bbbc3f456b0b9401a1d86f5
mrzhang638993/python-basis
/exception.py
2,144
3.8125
4
# 编程的话,永远不要相信你的用户。他们永远不懂程序的 # 程序的exception # 异常检测和体现处理,使用try-----except 以及 try------finally import os try: f=open('我为什么是一个文件.txt') print(f.read()) f.close() except (OSError, TypeError) as reason: print("文件出错了",str(reason)) except TypeError as reason: print('类型出错了',reason) # 捕捉任何的异常 except: pri...
3614869226a4c32371ee49561b2967f83360856e
thaiscardia/ex-python
/Guanabara/Mundo2/ex68-parImpar.py
1,274
4
4
"""Faça um programa que jogue par ou impar com o computador. O jogo só será interrompido quando o jogador PERDER, mostrando o total de vitórias consecutivas que ele conquistou no final do jogo. """ from random import randint contador = 0 while True: numero = int(input("Insira um número: ")) p...
88f78c2b5688b503606286102c9ffa79129d5501
thaiscardia/ex-python
/Guanabara/Mundo1/ex11-areaVSlitro.py
416
3.96875
4
'''Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a qtd de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2m²''' larg = float(input("Digite a largura em metros:")) alt = float(input("Digite a altura em metros: ")) a = larg * alt t = a / 2 ...
7af3b6b3a8cf63f64ad0527790de8e75d4ae9c1c
thaiscardia/ex-python
/project-euler/problem1-multiples3and5.py.py
310
4.125
4
"""definir o limite para 1000 %5 == 0 -> uma função or %3 == 0 se o num for divisivel, lista; soma a lista """ def calculo(): lista = [] for num in range(1, 1000): if num %5 == 0 or num %3 == 0: lista.append(num) soma = sum(lista) print(soma) calculo()
6342d3d62acbbd784b0433b985f4e8c140fbffa5
thaiscardia/ex-python
/Guanabara/Mundo2/ex56-mediaSexName.py
1,176
4
4
""" Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: - a média de idade do grupo. - Qual é o nome do homem mais velho. - quantas mulheres tem menos de 20 anos """ def leitor(): somaIdade = 0 nomeH = '' velhoH = 0 mulher = 0 for dados in rang...
3fe3c7b31f3dd81cc5d45896ae728f7a05f524ed
thaiscardia/ex-python
/Guanabara/Mundo1/ex26-ocorrenciaString.py
417
4.1875
4
"""Faça um programa que leia uma frase pelo teclado e mostre: - quantas vezes aparece a letra "A"; - em que posição ela aparece a primeira vez; - em que posição ela aparece a última vez;""" f = input("Digite a frase aqui: ") f = f.upper() print("Esta frase possui {} letra(s) A".format(f.count("A"))) print("O primeiro ...
20607ff23466bd2070330596910fa56ea0c8cea3
thaiscardia/ex-python
/Guanabara/Mundo2/ex52-primo.py
362
4.03125
4
"""Faça um programa que leia um número inteiro e diga se ele é ou não um número primo""" pr = int(input("Insira um número inteiro: ")) if pr > 2 and pr % 2 == 0 or pr > 3 and pr % 3 == 0 or pr > 5 and pr % 5 == 0 or pr > 7 and pr % 7 == 0: print("Não é número primo") elif pr == 1: print("Não é número primo") else:...
dff9c4c18bec1c47e11d778818cc20eb3fc93367
thaiscardia/ex-python
/Guanabara/Mundo2/ex61-progressaoWhile.py
382
3.75
4
"""Refaça o DESAFIO 51 lendo o primeiro termo e a razão de uma PA, mostrando os 10 primeiros termos da progressão usando a estrutura while.""" ter = int(input("Insira primeiro termo da P.A: ")) ra = int(input("Insira a razão: ")) lista = [] limite = 0 while limite is not 11: calc = ter + (limite - 1) * ra li...
e8ffcd17986adaee333eb21328f08ccf79dfa2b5
thaiscardia/ex-python
/Guanabara/Mundo3/ex77-vogais.py
498
3.796875
4
"""Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são suas vogais. """ tupla = ("crie", "um", "programa", "que", "tenha", "uma", "tupla", "com", "depois", "disso", "deve", "mostrar", "para", "cada", "palavra", "quais", "suas", "vo...
65b3ce0977798ad16c430219e50648075d740827
thaiscardia/ex-python
/Guanabara/Mundo1/ex38-maxEmin.py
361
4.03125
4
#Faça um programa que leia três números e mostre qual é o maior e qual é o menor. n1 = float(input("Digite primeiro número: ")) n2 = float(input("Digite segundo número: ")) n3 = float(input("Digite terceiro número: ")) l = [n1, n2, n3] print("O \033[0;33;41mmaior\033[m número é {} e o \033[7;30;46mmenor\033[m número ...
81628899f7be10b11d5198464b56849ac419bbf8
Chuukwudi/Think-python
/chapter11.py
3,590
3.546875
4
def histogram(s): d = dict() for c in s: d[c] = d.get(c, 0) d[c] += 1 return d print(histogram('assdddffffggggg')) '''Exercise 11-1''' def create_dic(): offen = open('words.txt') counter = 0 dictionairy = {} for line in offen: word = line.strip('\n'...
1a0e41d3b08f4c98db46d0f7e01e7ae247b21298
Chuukwudi/Think-python
/chapter8_exercise8_5.py
2,544
4.28125
4
''' str.islower() Return True if all cased characters in the string are lowercase and there is at least one cased character, False otherwise. ''' def any_lowercase1(s): for c in s: if c.islower(): return True else: return False '''Here, the funtion takes th...
0a78c6d040d7c5b7089567fab7d2182240022f62
gurhanPro/python-data-structures
/Array-Sequences/array_max_sort.py
342
3.515625
4
#given array, and max integer in array, sort the array import timeit arr = [1,2,3,5,2,3,1,5,4,8,8,9] def a(a): b = [0] * (9+1) for i in a: b[i]+=1 s = [] print a print b for p,c in enumerate(b): print p , c for t in range(c): s.append(p) ...
65778169153ffb7dcd8f0aad2cdf11fc43a54e90
girrig/llamagamePy
/_deprecated/OldGame/Grid.py
2,517
3.5
4
''' Created on Aug 9, 2012 @author: Brandon ''' from Cell import * import math class Grid: #grid is z*z def __init__(self, z): #Length of cells array is the number of cells self.cells = [] #dictionary of all the x and y coordinates self.cell_lookup = {} self...
0fc1e90b20be10d3f33ef54b80776116362d9710
fosterj096/CS449_Project
/gameTest.py
1,697
3.734375
4
import newGameboard import unittest boardSize = 3 gameboard = [[" " for x in range (boardSize)] for y in range(boardSize)] gameboard1 = [["S" for x in range (boardSize)] for y in range(boardSize)] gameBoardTrue = [[" " for x in range (boardSize)] for y in range(boardSize)] gameBoardTrue[0][0] = "S" gameBoardTr...
7783f793664c77640e328a30721a8c28b06e7a07
anandaviamianni/Pengkondisian-Modul-2-
/Studi Kasus.py
717
4.1875
4
# Kiki dan Titis adalah seorang programmer di PT Daspro, kemudian mereka diminta oleh atasannya # untuk membuat sebuah program untuk menentukkan kategori umur, dengan ketentuan umur seperti di bawah. print("==== KATEGORI UMUR ====") umur = int(input("Masukkan umur anda = ")) print("\nAnda Berada pada : ") pri...
b3ab5b8a8744c748158bb3f5d41a32efb9bd19ae
Teddy2M6/RST---Part-2
/mastermind (colour).py
2,047
3.890625
4
import random def mastermind(): colour1 = ['R', 'B', 'G', 'W', 'B', 'P'] colour2 = ['R', 'B', 'G', 'W', 'B', 'P'] colour3 = ['R', 'B', 'G', 'W', 'B', 'P'] colour4 = ['R', 'B', 'G', 'W', 'B', 'P'] c1 = random.choice(colour1) c2 = random.choice(colour2) c3 = random.choice(colour3...
d600ba01a3c2015760ae76345c633dee937c76db
sshuster/ChaiWithJai-Chatbot_That_Talks_Like_Me
/Whatsapp Chat Data Processing/whatsapp_messages_processor.py
2,995
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 4 17:43:26 2019 @author: jai """ import pandas as pd import re import numpy as np messageDictionary = {} myName = 'Jai Kotia' friendName = 'Rishika' data = pd.read_csv('WhatsApp Chat with ' + friendName + '.txt', sep="m - ", header=None, engine...
5d7e6458c2f4d28d09a118fb37587f850f2d8854
OperationalResearchProject/Client-Knapsack
/KnapSack.py
2,483
3.53125
4
import random class KnapSack: def __init__(self, filename): with open(filename, "r") as f: lines = f.readlines() self.nbObject = int(lines[0]) self.profits = lines[1].split() self.weights = lines[2].split() self.weightMax = lines[3] ...
d4e91e5be16caa28373a7b0f63e3fa4f609a6f60
katiezzzzz/Month-of-ML
/Day 3 Models.py
3,651
4.25
4
""" Most generally, we use models to map some input to some output, these inputs can take any form: - text to its overall sentiment - images to the boxes that bound specific objects within them Models are usually mathematical functions: they can be wavy, high-dimensional (like images), probability distribution and...
fbe275e46d86c84b2245658b0feca942794b404b
hannahhall/classes
/examples.py
1,890
3.9375
4
from classes import living_room from classes.kitchen import Kitchen from classes import Room, Kitchen, LivingRoom, BathRoom, Studio room1 = Room(10, 12, 4) room2 = Room(30, 40, 2) print(room2.length, room2.width, room2.number_of_windows) # # Class variables can be accessed by the instance or the class print(f'Does r...
50bfc824c8d3e8b8614753ef7ad7dfa5a73d6ce5
shawn11ZX/CodingPractices
/python/idioms/subsets.py
509
3.546875
4
def subsets(candidates, offset, prefix, action): if offset == len(candidates): action(prefix) else: prefix.append(candidates[offset]) subsets(candidates, offset+1, prefix, action) prefix.pop() subsets(candidates, offset+1, prefix, action) import unittest class Test0(uni...
f6cb2c4fad51dd32614d2a845d76710ee6f25409
cernat-catalin/advent_of_code_2019
/day14/main.py
2,245
3.515625
4
import re, math from typing import NamedTuple, List, Tuple from collections import defaultdict class Reaction(NamedTuple): left: List[Tuple[int, str]] right: Tuple[int, str] def create_reaction(unparsed_reaction: List[str]) -> Reaction: parse_element = lambda x: (int(x.split(' ')[0]), x.split(' ')[1]) ...
2ec7e530e13a64d91665dea3e77b28c3b41371fa
gustycooper/cpsc110
/code/ch6average.py
231
3.71875
4
def avg(numbers): s = 0 for n in numbers: s = s + n a = s / len(numbers) return a def main(): lst = [90, 95, 78,82] ave = avg(lst) print(avg([90, 95, 78, 82]), ave) if __name__ == '__main__': main()
dd2c603bce376a4e9676c1d1664a0b62fe94e9ab
gustycooper/cpsc110
/code/ch3collegeclass.py
462
4.03125
4
# collegeClass.py # Determine the college class by number of credits def main(): print("Determin the college class by the number of credits.\n") credit = eval(input("Enter the number of credits: ")) if credit < 7: clas = "Freshman" elif credit >= 7 and credit < 16: clas = "Sophomore" ...
9c8c7a0e1f590e6807f989df71cafcd3e266a7bf
gustycooper/cpsc110
/code/ch8entrybutton.py
597
3.703125
4
from graphics import * from button import * def main(): w = GraphWin("Entry Examples", 200, 150) t = Text(Point(40,20), "Name") t.draw(w) e = Entry(Point(100,20), 10) e.draw(w) b = Button(w, Point(100, 90), 40, 40, "Enter") b.activate() ot = Text(Point(100, 50), "") ot.draw(w) ...
4da36c934c9e9d0e0214d88da1572e10e396581b
kardotinambunan12/python-dasar
/kondisi.py
686
3.796875
4
# penggunaan fungsi IF # variabel1 = 13 # variabel2 = 20 # if(variabel1 < variabel2) : # print("nialai varriabel1 lebih kecil dari nilai variabel2") # Penggunaan Fungsi elseif # var_a = 20 # var_b = 15 # if(var_a < var_b) : # print("nilai vara lebih kecil dari nilai varb") # else : # print("nilai vara...
7d0fb7c8f5d84cfede10fb3164117ff555607d9a
abel968/MachineLearning
/Week2/ex1.py
2,497
3.796875
4
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter def computeCost(X, y, theta): return ((X.dot(theta) - y)**2).sum() / (2*len(X)) def pradientDescent(X, y, theta, alpha, iterations):...
a5c2a54b5cb4b13cd4633e5134f09e1c6acdd2d8
Nild18/Python
/bookenizer.py
2,722
3.828125
4
# Copyright (C) 2021 by # Nicklas Lindroth <nicklas.lindroth@ibuildit.nu> # All rights reserved. # BSD license. """This is a application that take booking items and store them in the right row dependent on the size of the item and the reachability of the row and if there is suitable rows fore the item. ...
70f3c1a1dedaa36563b6f5f0f5f0777c208251af
ZhuZean/bookkeeping-demo
/bill/app/helper/paginator.py
1,946
3.765625
4
""" Paginator """ from math import ceil class InvalidParameterError(ValueError): """ Raised when page or limit is invalid """ class Paginator: # pragma: no cover """ Handles pagination """ def __init__(self, limit=5, page=1): try: if not page: page = 1 ...
89d6f51bd7734c6d3d42d150e439199ac09e21ec
BinkBoinkBonk/SpanishConjugations
/SpanishConjugations.py
3,317
3.546875
4
import webbrowser, sys #12:30 am 11/5/2020 Lets do this! def main(): def preterite(): preteriteverb = input("Whats your spanish verb?\n") webbrowser.open_new('https://www.livelingua.com/spanish/verbs/tenses/preterite/' + preteriteverb) again = input("Stay in this tense?(y/n)\n") ...
e1ff194e4a4dc04908079b1059679c44001d3454
LordBH/python
/3.5/cookbook/cookbook.py
4,848
3.65625
4
""" =================== - Using deque(maxlen=N) creates a fixed-sized queue. from collections import deque =================== import heapq # nlargest, nsmallest | args (nums, arr) >> heapq.nsmallest(3, portfolio, key=lambda s: s['price']) The nlargest() and nsmallest() functions are most appropriate if you are tryin...
3e6ce0eda572bbc2fea15adc4deb249ab9bc3865
zhangquanyue/hello-world
/calculator.py
1,911
3.53125
4
#!/usr/bin/env python3 import sys def Income(income): Wages = income shebao = Wages*0.165 taxable_income = Wages - shebao - 3500 if 0 < taxable_income < 1500: tax_rate = 0.03 tax_amount_payable = taxable_income * tax_rate - 0 remain = Wages - tax_amount_payable - shebao r...
9788622e7b501227e639ecfd1020bd244039e858
niqwilk/Data-Science
/Homework-Projects/MAT456 Python HW/homework 3/Homework 3.py
895
3.734375
4
#Homework 3 Nicholas Wilk import csv import numpy as np import matplotlib.pyplot as plt def main(): with open('NYPD_Motor_Vehicle_Collisions.csv', 'rb') as f: reader = csv.DictReader(f) time = [row['TIME'] for row in reader] hourCount = {} print time for timeString in tim...
e68d04b5cd68f42732c81299aca564badff14209
dondon17/PYTHON
/ch04/func.py
1,947
3.796875
4
# 매개변수가 있는 함수 def add(a,b): return a+b # 매개변수가 없는 함수 def say(): return 'hi' # 리턴값이 없는 함수 def add2(a,b): print("%d + %d = %d" %(a,b,a+b)) # 매개변수, 리턴값이 없는 함수 def say2(): print("hello~") print(add(1,2)) print(say()) add2(1,5) say2() # 이와같이 매개변수를 미리 지정하지 않고 전달할때 지정할 수도 있음 res = add(a=5, b=1) print(res)...
24fa2455c88f607af532934b31c052e4f1d24224
dondon17/PYTHON
/ch03/for.py
1,601
3.859375
4
# 다른 언어들 보다 for문의 작성이 간단하다 # 1. 전형적인 for문 print("(1) 전형적인 for문") list_ = ['one', 'two', 'three'] for i in list_: print(i) # 2. for문 응용 print("(2) for문 응용1") list_ = [(1,2), (3,4), (5,6)] for (a,b) in list_: # 이와같이 form을 맞춰주면 된다. print(a+b) # 3. for문 응용 print("(3) for문 응용2") score_ = [90, 30, 66, 44, 85] cnt ...
a2b67a83a02b94a109686cf912cd441d17a95ca5
dondon17/PYTHON
/코딩도장/Unit09/string.py
278
3.890625
4
# 변수로 문자열 사용 hello = "hello world" print(hello) # 여러 줄로 된 문자열 hello = '''Python C++ C JAVA''' print(hello) hello = """big quote same""" print(hello) # 따옴표 안에 따옴표 hello = 'He said "hello"' print(hello) print('he is \'monster\'')
cd811a11f53c75758bbf5c6f5a72f74eaf725bc6
dondon17/PYTHON
/examples/02/question8.py
129
3.53125
4
t1 = (1,2,3) t2 = (4, ) print("t1 = {}".format(t1)) print("t2 = {}".format(t1)) print("="*14) print("t1 + t2 = {}".format(t1+t2))
9915f35fbf0a364a046a797e3c2c44267b213ee6
aaaaaaason/codeforces
/DiceRolling.py
151
3.65625
4
n = int(input()) for i in range(n): want = int(input()) if want % 2 == 0: print(want//2) else: print(str(1 + (want-3)//2))
e2576e6b616d9e0191f97284745288b1f691db97
giri-2452/Python-excersises
/venv/FirstProgram.py
178
3.75
4
""" Demonstartion of .format() function, how to print two variable in a single line""" name = "Giridhar" Company = "Mindtickle" print("{} works at {}".format(name,Company))
d24613b7810cab484626991bd623db1c44467582
sugonedu-moyi/pyedu
/guess/sugon/edu/guess.py
1,539
3.890625
4
# -*- coding: utf-8 -*- import random def is_valid_number(s): """判断字符串s是否表示有效的数字。 返回Boolean类型""" '*** 在这里补充你的代码 ***' '*** 首先判断字符串s是否表示数字 ***' '*** 如果是数字,转为int类型,并进一步判断是否在1-100之间 ***' '*** 提示:使用字符串的isdigit()方法 ***' return s.isdigit() and 1 <= int(s) <= 100 def main(): # 生成要猜的数字 ...
a687a62ebc6d9732249a7cfc9b84a94fd9449c30
gomezarg/itedes
/modulo1/segmento3/apunte7/ejercicio1.py
260
3.828125
4
def divisores(number): quantity = 0 for i in range(1,number+1): if number%i==0 : quantity += 1 return quantity number=int(input('Ingrese un numero : ')) quantity = divisores(number) print("La cantidad de divisores de " , number , " es : " , quantity)
4f608e3913498a21c8059ea860c53ab71a0adafe
gomezarg/itedes
/modulo1/segmento3/apunte3/ejercicio2.py
361
3.796875
4
num = int(input("Ingrese un numero y se devovera un dia de semana: ")) if num == 1 : print("Lunes") elif num == 2 : print("Martes") elif num == 3 : print("Miercoles") elif num == 4 : print("Jueves") elif num == 5 : print("Viernes") elif num == 6 : print("Sabado") elif num == 7 : print("Domi...
cb5768418ce59348ee4dd85c5f1a031909670e93
gomezarg/itedes
/modulo1/segmento3/apunte7/ejercicio2.py
713
4.0625
4
def multiplos(): print() if number1%number2 == 0 and number2%number1 == 0: multiplos = print('Ambos numeros son multiplos!') elif number2%number1 == 0: multiplos = print('El segundo numero (', number2 , ') es multiplo del primer numero (', number1 , ')!') elif number1%number2 == 0: multiplos = print('El prime...
01920fb76316be4707d05fb5e7f4659c80db9633
gomezarg/itedes
/modulo1/segmento3/apunte1/ejercicio4.py
321
3.84375
4
num1 = int(input("Ingrese primer numero: ")) num2 = int(input("Ingrese segundo numero: ")) num3 = int(input("Ingrese tercer numero: ")) num4 = int(input("Ingrese cuarto numero: ")) if num1 == num2 and num3 == num4: print("Los numeros ingresados son iguales") else: print("Los numero ingresados NO son iguales!")...
3a1282e2cbbc3c579dd332c46cb7d9a3131828ef
ThuanK42/HocPython
/Chapter03/Split&JoinString.py
637
3.75
4
''' Thao tac noi va cat chuoi''' chuoi = 'Bảo đao đồ long hiệu lệnh thiên hạ, Ỷ thiên kiếm diệt sát quần hùng' # chuoi.split(): Cat chuoi dua vao khoan trang => result: mảng các chuỗi đã loại bỏ khoản trắng print(chuoi.split()) # chuoi.split('a'): Cat chuoi dua vao ky tu a print(chuoi.split('a')) # chuoi.split('',n...
f50d08b5f3ff7fb577b675f5a976e35715598b2d
ThuanK42/HocPython
/Chapter03/String_Object_Basic.py
801
3.5
4
"""" Bai hoc co ban ve String trong Python""" say='I love you,Trinh Trinh!' #type(a) : xac dinh kieu du lieu print(type(say)) #id(a): xac dinh id cua gia tri a print(id(say)) #len(a): lay do dai chuoi a print(len(say)) #tenchuoi[index]: lay chu o vi tri thu index trong ten chuoi '''chu y: Python no cung coi 1 chuo...
014a27cc6930befa1332dba1f959f7cd0560bc20
ThuanK42/HocPython
/Chapter02/Rangee.py
465
3.71875
4
''' Ham Range tao ra 1 day so''' # Range(n), n la so phan tu cua day so tu nhien bat dau tu 0 x = range(15) '''x la mang chua gia tri tu 0->14''' print(type(x)) ''' in x ra co nhieu cach: cach1: gan no cho list''' print(list(x)) '''cach 2 dung vong lap for''' for item in x: print(item) # range(a,b) -> in ra gia t...
ec835da60ab44183c36c920bd4c507c92fc84a7d
xutu10/python
/basic/bayes_test/dic_init.py
490
3.953125
4
class dic: def __init__(self): self.data = {'1':'arts', '2': 'business', '3':'sports', '4': 'politic' } def show(self): print self.data.items() for key, value in self.data.items(): # print in one line with ',' af...
6b9f78ec3e72c88415579e01b935104e6528914d
xutu10/python
/basic/function.py
291
3.8125
4
def hey(x): return "hey " + x #x = "xutu" print hey("hony") print "---------" def name(one="hey", two="xu"): print "%s,%s" % (one, two) name("xutu","wang") name() print "---------" def profile(name, *ages): #indicate a tuple print name print ages profile("xu",12,13,14)
e2ffe256c5a827cb9b26175e2f1d7f9967687378
Zachary-Greene/GUI-Calculator
/GUI Based Calculator.py
5,679
4.21875
4
# importing all the necessary libraries from tkinter import * import tkinter as tk import sys # defining and the answer to call back answer = [] # creating the Window object class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.myText_Box = None ...
67f7339adfc3d52ebef1df5c5564ecdb1f23a40e
KajalTomar/tamagotchi
/tamagotchi.py
7,185
4.09375
4
from microbit import * import random # ---------------------------------------------------------- # FILE: tamagotchi.py # Author: Kajal Tomar # REMARKS: This is a much simplified implementation of a # tamagotchi. The player can shake the micro:bit # to view the pet's mood. If the pet is ...
54e4a2eb2c011b846beb37896e1d1312a47c754c
justnishad/HackerRank-Problemsolving
/BonAppetit.py
565
3.5625
4
#link to prob:https://www.hackerrank.com/challenges/bon-appetit/problem # Complete the bonAppetit function below. def bonAppetit(bill, k, b): n=len(bill) sums=0 actual=0 for i in range (n): if(i!=k): sums=sums+bill[i] actual=sums/2 final=b-actual if(final!=0): ...
c33893769b06dc2219b96c697b71263bfdafe604
justnishad/HackerRank-Problemsolving
/migratoryBirds.py
597
3.765625
4
#link to problem:https://www.hackerrank.com/challenges/migratory-birds/problem # Complete the migratoryBirds function below. def migratoryBirds(arr): n=len(arr) second=[] third=[] for i in range(n): temp=arr[i] if(temp not in second): second.append(temp) second....
d42909ba1c26edd0d518707f8162cd0f1aa182e5
jack-skerrett-bluefruit/pythonSession2
/1 functions/functions.py
1,633
4.03125
4
score = 0 input("Hello and welcome to my quiz!") input("\nI'm going to say a series of statements. Your job is to guess true or false.") input("\nGet them right, and you are a very smart person, well done.") input("\nGet them wrong and I don't care.") input("\nPlease answer all questions with a 't' for true or an 'f' ...
30092cabb0cba8b4590c19de65396a3cecafc62c
joshjin/shortest_path_on_Brandeis_campus_map
/Map.py
3,552
3.5
4
import DijkstraAlgorithm import PrimAlgorithm from UtilTool import UtilTool # main method if __name__ == '__main__': # read data from the raw text files vertex_list = UtilTool.read_from_vertex('Raw_Data/MapDataVertices.txt') edge_list = UtilTool.read_from_edge('Raw_Data/MapDataEdges.txt') # adjacency_m...
0b2cae01c7b42248fe64d07cecfd429b576a00be
SoongsilShooteam/gameBox
/source/vector.py
987
3.734375
4
import math class Vector2: x = 0.0 y = 0.0 def __init__(self): self.x = 0.0 self.y = 0.0 def __init__(self, x, y): self.x = x self.y = y # 두 벡터의 내적 구하기 def dot(self, v2): return (self.x * v2.x) + (self.y * v2.y) # 두 벡터 사이각 구하기 def angle(self,...
a12543e90095726b5bd8a96463da4311462fb58e
LeeGing/Python_Exercises
/8_ball.py
835
4.3125
4
#Magic 8 Ball def shake(): import random print ("======================================================") print ("==================== MAGIC 8 BALL ====================") print ("======================================================") user_input = input("ASK THE 8 BALL YOUR QUESTION: ") ans = random.randint(1,5...
20019092e2bb33010e2d0ef207bb3e30fe5fa04b
tangmin1234/kdd-17
/utils.py
3,610
3.578125
4
import numpy as np from datetime import timedelta, datetime def pprint(dictionay): keys = dictionay.keys() keys.sort() for i in range(len(keys)): print keys[i], dictionay[keys[i]] def convert_to_interval_number(datetime): return datetime.hour * 3 + datetime.minute / 20 def convert_to_time_window(time, interval...
46829099c1c9857e06ff9bb661ab81e53c626ed6
cchio/hackerrank
/crossword-puzzle.py
3,330
3.703125
4
#!/bin/python3 # https://www.hackerrank.com/challenges/crossword-puzzle import math import os import random import re import sys def fill_word(crossword, x, y, s, isHorizontal=True): c = crossword[:] for i in range(len(s)): if isHorizontal: if c[y][x+i] == s[i] or c[y][x+i] == "-": ...
b3f929357e2a93c9ef37295ab596050b34a15386
nneiros/python-learning
/python33/listes_kai_diaxeirisi/lista_sort_me_def.py
3,447
3.84375
4
#φτιαχνει λεξικο με επικεφαλιδα το πρωτο γραμμα from itertools import groupby from operator import itemgetter somelist = ['About', 'Absolutely','Βοδι', 'Alabama', 'Aunt', 'Behind', 'Biblical', 'Ωραιος','Αρχειο'] for letter, words in groupby(sorted(somelist), key=itemgetter(0)): print('-',letter,'-') ...
47b0aade8ee0303588b79efacd6ad600231aa16f
nneiros/python-learning
/python33/arxeia_diaxeirisi/arxeio_listas_pickle_filename.py
300
3.5625
4
import pickle picklelist = ['one',2,'three','four',5,'can you count?'] file = open('filename', 'wb') pickle.dump(picklelist,file) file.close() unpicklefile = open('filename', 'rb') unpickledlist = pickle.load(unpicklefile) unpicklefile.close() for item in unpickledlist: print (item)
8de9b7f02c4010a1c549002fc3c284b8b3d71bb6
nneiros/python-learning
/python33/erotiseis_diafores/erotisi_ilikia_name_tilefono.py
1,464
3.890625
4
#rotaei kai ektiponei onoma kai ilikia name=input("Πως σε λενε? ") age=int(input("Ποια ειναι η ηλικια σου? ")) print ("Χαρηκα που σε γνωρισα ",name) print (age, "χρονων δεν ειναι καθολου ασχημα!") print ('*********************************************************') #rotaei kai ektiponei ilikia me diki tou protasi ...
98810cf65066a038891dcbbe02bb0bd0562ee913
nneiros/python-learning
/python33/password_pin/password1.py
329
4.03125
4
x=1 while x <= 3: password=input('Δωσε κωδικο:') if password.endswith('1234'): print ('Καλως ορισες') break else: print ('Ο κωδικος ειναι λαθος') x=x+1 else: print ('Εκανες λαθος τρεις φορες αντε γεια.')
451c1243f07dc6cfc0294476665ea4aa79b39173
nneiros/python-learning
/python33/pickle/pickle1.py
570
3.78125
4
import pickle def main(): # Creating objects we want to pickle, write, to a file. pickleObjects = ["home", "library", "garage", "garden", "pool", "car"] print (pickleObjects) # Pickling, writing, to a file. outFile = open('pickleExample.txt', 'wb') pickle.dump(pickleObjects, outFile...
a8babd3ea2e833f166eaff61459b134ce6e8e75f
nneiros/python-learning
/python33/trapeza_vathmologia_pithagorio_emvadon/menu_vathmologias.py
1,582
3.515625
4
vathmoi=[]#kataskeyh listas(vathmologia) def print_menu(): print ()#kataskeyh menu print ('--------------------Vathmologia Theologikou-------------------') print () print ('---------1.Dose vathmo mathimatos pou perases--------') print ('---------2.Ektipose sinolo mathimaton pou perases----')...
773dc422a4d97c471b7b920beb777b79a25dceeb
nneiros/python-learning
/python33/evresi_arithmou_kai_metaf_ikanotitas/evresi_arithmou_me_mpravo.py
664
3.609375
4
import random thenumber = random.randint(1,50) name = input("Δωσε το ονομα σου:") print ("Εχω σκεφτει ενα αριθμο απο το 1 εως το 50.") print ("Μπορεις να τον βρεις?") guess = 0 tries = 0 while guess != thenumber: tries=tries + 1 guess = int(input("Δωσε τον αριθμο: ")) if guess > thenumber: print ("...
edc2910119ede33901f147c436087fbf14ed99c2
nneiros/python-learning
/python33/evresi_arithmou_kai_metaf_ikanotitas/evresi_symbol_kai_hlikias.py
3,428
4.3125
4
# search a dictionary for key or value # using named functions or a class def find_key(dic, val): """return the key of dictionary dic given the value""" return (k for k, v in dic.iteritems() if v == val)[0] def find_value(dic, key): """return the value of dictionary dic given the key""" return ...
97b336f7a98c70a5dcd0e449ba3cde39687067a2
blade-sensei/bts-sio-courses
/Math/COYLA_exercice_8.py
239
3.53125
4
#COYLA from math import * def Diviseur(nbr): div=[] i=1 while i<=nbr: if nbr%i==0: div.append(i) i=i+1 if len(div)==2: print(nbr,"est un nombre premier") else: print(div)
7b659166ca9845366521da6132889c30e7de2849
makaiolam/final-day-1
/main.py
1,796
4.21875
4
import turtle # turtle = turtle.Turtle() # shape = input("choose shape triangle square or circle") # if shape == ("triangle"): # def triangle(length,color): # turtle.speed(1) # turtle.color(color) # turtle.forward(length) # turtle.left(120) # turtle.forward(length) # turtle.left(120) # t...
fd42c738d4413924bdd77efe9b01e7d98555e8dc
JorgeAvilaG/advent-of-code-2017
/day9.py
667
3.921875
4
# Part 1 and 2 groups = 0 garbage = False ignore_next = False characters = 0 score = 0 for n in data: if n == "!" and not ignore_next: ignore_next = True elif n == "<" and not garbage and not ignore_next: garbage = True elif n == ">" and not ignore_next: garbage = False elif n =...
bc6c488f78064e2a00255460c167d5f48ca92146
JorgeAvilaG/advent-of-code-2017
/day19.py
3,015
3.515625
4
import numpy as np data = [list(line) for line in imput_data.split("\n")] matrix = np.matrix(data) letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Part 1 for n in range(matrix[0].size): if matrix[0, n] == "|": position = np.array([0, n]) direction = "down" last_letter = "Q" solution = "" valor = matrix[tuple(p...
1c73c8cbe01ea64a5d54012dd9985a3aeb04c9d4
evalinghan/Spectral-Processing
/MakeTernaryPlots.py
4,544
3.59375
4
""" Created March 12 2020 This program helps you plot a heat map in a ternary diagram You will need the following python modules: matplotlib and ternary installed Visit https://github.com/marcharper/python-ternary to install and use ternary Creator: Eva L. Scheller, Email: eschelle@caltech.edu """ import matplotli...
a1af47bd51c847b5ec8815835a24f13e89aa3053
ckaydevs/learning_python
/class/draw art/squre.py
924
4.3125
4
import turtle def draw_square(some_turtle): for i in range(1,5): some_turtle.forward(100) some_turtle.right(90) def draw_art(): window=turtle.Screen() window.bgcolor("red") #Create the turtle brad- Draws a square brad=turtle.Turtle() brad.shape("turtle") brad.color("yellow"...
795edfa33a08873ab8126c14e3345254fa78a99a
KodakBrax/CS50
/pset7/houses/import.py
800
3.953125
4
from sys import argv, exit import csv from cs50 import SQL def main(): # check for command line arguments if len(argv) != 2: print('Incorrect number of arguments') exit(1) # open csv file info = csv.DictReader(open(argv[1])) # open sql database db = SQL("sqlite:///students...
41f18765b7ef3045990c079ddc3b2838707eca56
RAIS14/labpy1
/praktikum1.py
188
3.953125
4
a=int (input ('bilangan a : ')) b=int (input ('bilangan b : ')) c=int (input ('bilangan c : ')) if a>b : if a>c : print(a) else : print (c) elif b>c : print(b) else : print (c)
ab151524e7823fa8d8cea54e810081d78b60deec
eebrandt/male_vib
/not_used/old_viban_functions.py
3,544
3.59375
4
def ratecalcs (durationinfo, srfile): """ This function takes in information about the duration of a given feature (usually scrape-rate regions), and the path of a file that lists each scrape-rate region and the number of scrapes found in that region. It plots the rates/length of the song (normalized to 1), and retu...
806767c27830db7b0df2f390dbecac4ca9da1f05
fortunee/Learn-Python-The-Hardway-
/ex13.py
385
3.828125
4
from sys import argv """ script = raw_input('what script is this?') first = raw_input('what is first?') second = raw_input('what is the second') third = raw_input('what is the third') """ script, first, second, third = argv print "The script is called:", script print "Your first variable is:", first print "Your seco...
8cd8fe16d90e29486bd87e97f2c1c7f3617f372c
cyru8/practicesnippets
/snippet02.py
922
3.59375
4
#! /usr/bin/env python """ This is another practice snippet """ __author__ = "O.A" __author_email__ = "oa@live.com" from datetime import datetime log_file = "snippet02.log" def read_log(log): """ Open the log file in the working directory and print on the terminal """ with open(log, "r") as f: ...
e3dd3b37d8b03ae0845218c39e5e5b8c4ca986bc
cyru8/practicesnippets
/filterlist.py
157
4.0625
4
print("Before",) my_list = [9,41,12,3,74,15,75] for value in my_list: if value > 20: print("The largest number is: ", value) print("After")
322570b3e3b5f45fb5de964805d4c9b7cae2a981
cyru8/practicesnippets
/findall.py
127
3.640625
4
import re x = "This is my study cave time with my other half from 20:00 to 23:59 and 04:00" y = re.findall("[0-9]+",x) print(y)
1a9e751f753eb6257ecabcde63d0cdf02b35eb03
bettazzoni/unittest_isolation_python
/addsome/adder.py
279
3.53125
4
add = lambda a,b: (a+b) _sum_total = 0 def summatory(x): _sum_total += x return _sum_total class Adder(object): def __init__(self, sum_start = 0): self.sum = sum_start def add(self, value): self.sum += value return self.sum
6b63b2b973e06ccf053edfb12ceb1f91d316be63
esthermanthi/text-analyzer
/text.py
625
3.796875
4
def count_char(text, char): count = 0 for c in text: if c == char: count += 1 return count file = open("newfile.txt", "w") file.write("""the world is looking for girls and women who can code to solve their problems.coding is advantageous to learn and its fun, programmers love to code day...