blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
08700e20251e1cfe34298e480c6146a40fa31a0c
prompt-toolkit/python-prompt-toolkit
/examples/progress-bar/a-lot-of-parallel-tasks.py
1,903
3.53125
4
#!/usr/bin/env python """ More complex demonstration of what's possible with the progress bar. """ import random import threading import time from prompt_toolkit import HTML from prompt_toolkit.shortcuts import ProgressBar def main(): with ProgressBar( title=HTML("<b>Example of many parallel tasks.</b>")...
0c5e46763def0d6a5dd3c01f11800bb4bf7550d6
prompt-toolkit/python-prompt-toolkit
/examples/prompts/get-password-with-toggle-display-shortcut.py
768
3.921875
4
#!/usr/bin/env python """ get_password function that displays asterisks instead of the actual characters. With the addition of a ControlT shortcut to hide/show the input. """ from prompt_toolkit import prompt from prompt_toolkit.filters import Condition from prompt_toolkit.key_binding import KeyBindings def main(): ...
5870d2050fd949016a93c2dc3c044907bb97f77e
prompt-toolkit/python-prompt-toolkit
/examples/prompts/get-multiline-input.py
1,007
4
4
#!/usr/bin/env python from prompt_toolkit import prompt from prompt_toolkit.formatted_text import HTML def prompt_continuation(width, line_number, wrap_count): """ The continuation: display line numbers and '->' before soft wraps. Notice that we can return any kind of formatted text from here. The p...
dac24e601f09a5d4273af5af8e41a47ad22aa346
starfreck/Python-Practicals
/Practical -2/1.py
142
4.03125
4
#Q-1 : Define a function that can convert a integer into a string and print it in console. def printValue(n): print (str(n)) printValue(3)
2ff6e00112d01747c6a7b9759b353996ff2d4482
starfreck/Python-Practicals
/Practical -2/5.py
317
4.1875
4
# Q-5 : Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only. def printDict(): d=dict() for i in range(1,21): d[i]=i**2 for (k,v) in d.items(): print(v) printDict()
b4ef47b2f0ab35a63196a9b32cfd253a6af4ce2b
starfreck/Python-Practicals
/Practical -2/3.py
387
4.25
4
# Q-3 : Define a function that can accept two strings as input and print the string with maximum length in console. If two strings have the same length, then the function should print al l strings line by line. def printValue(s1,s2): len1 = len(s1) len2 = len(s2) if len1>len2: print(s1) elif len2>len1: print ...
abbcd76f246922247bbadd9fa3212e8b37efbff0
kaspersky43/15puzzle
/MyFifteenPuzzle.py
1,876
3.984375
4
from FifteenPuzzle import * class MyFifteenPuzzle(FifteenPuzzle): def __init__(self, initial=None): """Do precomputations for puzzle heuristics.""" FifteenPuzzle.__init__(self, initial) # Put any initialization code here. def heuristic(self, state): """A heuristic to aid in searching the solution space...
a0910df1d1fbbccf3cb3743e799e922ce2bac984
imanolas/Python
/2/file.py
177
3.59375
4
year = int(input('Year= ')) if (( year%400 == 0) or (( year%4 == 0 ) and ( year%100 != 0))): disekto = True print(disekto) else: disekto = False print(disekto)
a2fb2b4626ac32ef586f00bb2850dc6bebc0cbd0
laerreal/gic
/common/antiset.py
877
4.15625
4
__all__ = [ "antiset" ] class antiset(object): """ Anti-set contains anything you ask except for explicitly removed items. """ __slots__ = ["__removed"] def __init__(self): self.__removed = set() def remove(self, item): # remember explicitly removed items self.__remov...
f4e42e3a96ffc6835024058b82bd8d95f43c8a2b
Vinke-dev/p3
/hero.py
887
3.578125
4
class Hero: def __init__(self, labyrinth): self.labyrinth = labyrinth self.position = None self.inventory = [] def move(self, direction): # nouvelle_position <- demander à l'objet self.position de renvoyer la position dans direction new_position = self.po...
81275aa998304d58b9b81bb90131fca5e03fca62
IcyNoctiluca/TSPSearchAlgorithms
/gen.py
9,166
3.8125
4
''' Genetic Algorithm ''' ''' importing the libs & pkgs ''' import copy import numpy as np import random import rec import sys import time ''' main flow ''' def run(map, totalPopulation): # set up vars for iteration totalCities = np.shape(map)[0] - 1 bestPathLength = np.inf bestPath = None ...
160400fe8de8d3db1dce921a73452f0bd4c9cefc
CommissarMa/PythonTutorCMa
/4程序流程控制/4_3迭代和列表解析/4_3_1迭代.py
1,196
4.25
4
#Python中的各种序列(字符串、列表、元组、字典以及文件等) # 均可作为可迭代对象,可迭代对象可以使用迭代器来遍历包含的元素。 #字符串、列表、元组以及字典等对象虽然是可迭代对象, # 但它们没有自己的迭代器。 #Python使用iter()函数来生成可迭代对象的迭代器, # 然后对迭代器调用next()函数来遍历对象。 # next()函数依次返回可迭代对象的一个元素, # 无元素返回时,会产生一个StopIteration异常。 d=iter([1,2,3])#为列表生成迭代器 next(d)#返回第一个元素 next(d)#返回第二个元素 next(d)#返回第三个元素 next(d)#当无元素返回时,产生异常 d=i...
53b7b70fee54a50fc5f943b89d92c8a4ef6bdccb
CommissarMa/PythonTutorCMa
/2Python基础知识/2_1Python程序基本结构/2_1_4语句分隔.py
338
4.3125
4
# Python使用分号分隔语句,从而将多条语句写在一行 print(100);print(2+3) # 如果冒号之后的语句块只有一条语句, # Python允许将语句写在冒号之后。 # 冒号之后也可以使分号分隔的多条语句。 x=90 if x<100 and x>10: print("x大于10小于100") else:print("x小于10或者大于100")
c9e1439f796357a1414a5bc1eefcd2685af01dbb
CommissarMa/PythonTutorCMa
/2Python基础知识/2_3数字常量/2_3_1整数常量.py
685
4.03125
4
#2的10次方 print(2**10) #二进制以0b或0B开头,后面跟二进制数字 print(0b101) #八进制以0o或0O开头,后面跟八进制数字 print(0o15) #十六进制以0x或0X开头,后面跟十六进制数字 print(0x12AB) #注意:不同进制只是整数的不同书写形式,程序运行时都会处理为十进制数。 #可以使用int函数将一个字符串按指定进制转换为整数 #注意:参数只能是整数字符串 int('111')#默认按十进制 int('111',2)#按二进制 int('111',8)#按八进制 int('111',16)#按十六进制 #Python提供内置函数bin(x),oct(x),hex(x)用...
3c481b63f52ca32f0aa1942b43a80140b49c3c8e
CommissarMa/PythonTutorCMa
/2Python基础知识/2_5小数分数/2_5_4分数.py
223
4.125
4
#使用fractions模块中的Fraction函数来创建 #使用分数可以有效避免浮点数的不精确性 from fractions import Fraction x=Fraction(2,8) print(x+2) #浮点数转分数 x=Fraction.from_float(1.25) print(x)
883347f5c20132e708c684739cc9eb7f3ef53f6a
CommissarMa/PythonTutorCMa
/2Python基础知识/2_1Python程序基本结构/2_1_1用缩进表示代码块.py
327
4.25
4
# Python使用缩进(空格)来表示代码块 # 通常、语句末尾的冒号表示代码块的开始 x=1 if x>0: print("yes") else: print("no") # 在包含代码嵌套时,应注意同级代码块的缩进量应保持相同 x=-1 if x>0: print("x>0") if x>2: print("x>2") else: print("x<=0")
449c2320987c96a5f85656ea0a0fa3faa7cd880b
CommissarMa/PythonTutorCMa
/5函数与模块/5_1函数/5_1_1定义函数.py
312
3.90625
4
#Python使用def语句来定义函数,基本格式如下: #def 函数名(参数表): # 函数语句 # return 返回值 #参数和返回值都不是必须的。 def hello():#定义函数 print("Hello Python!") hello()#调用函数 def add(a,b):#定义函数 return a+b add(1,2)#调用函数
b7dbb93e3362bd7131b4216ddf696ad661a6db34
CommissarMa/PythonTutorCMa
/3Python重要数据类型/3_4元组/3_4_4元组方法.py
401
3.546875
4
#count方法用于返回指定值在元组出现的次数。 x=(1,2)*3 x.count(1)#返回1在元组中出现的次数 x.count(3)#元组不包含指定值时,返回0 x.index(2)#从索引0到末尾查找2第一次出现的索引 #如果没有找到,则报错ValueError x.index(2,3)#从索引3到末尾查找2第一次出现的索引 x.index(2,3,5)#从索引3到索引5查找2第一次出现的索引
267c1337c8e38e02b591aa18cf28920895d2c774
CommissarMa/PythonTutorCMa
/2Python基础知识/2_5小数分数/2_5_1小数对象.py
338
4.40625
4
#小数对象使用decimal模块中的Decimal函数来创建 #使用时应先导入函数 from decimal import Decimal result=Decimal('0.3')+Decimal('0.3')+Decimal('0.3')+Decimal('0.1') print(result)#小数对象是带精度的,因此输出结果为1 result=0.3+0.3+0.3+0.1 print(result)#由于浮点数的误差,输出结果并不为1
67a8b069ca4f898e787e047042ed3f611be38231
Oleksandr-Korol/My_Python3_lab
/HomeWork1.py
228
3.875
4
number = input ("Введіть Ваш вік >>> ") number = int (number) if number < 16 : print ("Привіт;") elif number < 30 : print ("Вітання;") else: number > 30 print ("Добрий день.")
576800291e590b43dfb06949ce31445756a3c075
carbonblack/cb-response-bigfix-connector
/test/t_tools/deep_compare.py
732
3.640625
4
def deep_compare(alpha, beta): # hackish way to compare unicode strings to ascii strings if type(alpha) is str: alpha = unicode(alpha) if type(beta) is str: beta = unicode(alpha) if type(alpha) is not type(beta): return False if type(alpha) is dict: try: ...
d9feef32a3af1498bd3c2dd07b89293702f41074
ljxiaoBU/EC602
/602HW2/integer_limits.py
245
3.546875
4
#Copyright 2017 Lijun Xiao ljxiao@bu.edu Table="{:<6} {:<22} {:<22} {:<22}" print(Table.format('Bytes','Largest Unsigned Int','Minimum Signed Int','Maximum Signed Int')) i=1 while i<=8: print(Table.format(i, 2**(i*8)-1, -2**(i*8-1), 2**(i*8-1)-1)) i=i+1
ee59d3fb40d10b1899aea5ac2692fde9804b4361
caipre/advent
/2015/three.py
806
3.828125
4
#!/usr/bin/env python3 with open('three.in', 'r') as f: directions = f.read() class Sleigh(object): def __init__(self, x, y): self.x = x self.y = y self.deliveries = set([(x, y)]) def move(self, dir): if dir == '^': self.y -= 1 elif dir == '>': ...
0a874d72ba47cc5527ab7f8642a323667c2ea038
farcry6/hola_mundo
/test.py
68
3.578125
4
name = input ("introducza tu nombre") print("hola" + name + "!")
64090060bf37aae50283ed47d07961e04821cef2
MicGiordano/Optimal_Advertising_Volterra
/controlled_Volterra_OU.py
10,819
4.125
4
import math as math from scipy.stats import norm import numpy as np import scipy.special as sy import scipy as sp import matplotlib.pyplot as plt from r8_choose import r8_choose from r8_mop import r8_mop def brownian(x0, n, dt, delta, out=None): """ Generate an instance of Brownian motion (i.e. th...
21ba2cbfe012762cb6206e520b9fbac231c24e68
fcdennis/CursoPython
/mundo2/parte3/partea/ex059.py
977
3.953125
4
from time import sleep n1 = int(input('Primeiro valor: ')) n2 = int(input('Segundo valor: ')) fim = True while fim: print('[ 1 ] somar') print('[ 2 ] multiplicar') print('[ 3 ] maior') print('[ 4 ] novos números') print('[ 5 ] sair do programa') opc = int(input('Qual é a sua opção? ')) sleep...
24d6096f163b8adc7d919fc17f056d1c58fae74e
fcdennis/CursoPython
/mundo1/parte4/ex030.py
145
3.9375
4
n1 = int(input("Digite um número inteiro: ")) if n1 % 2 == 0: print(f"O número {n1} é PAR!") else: print(f"O número {n1} é IMPAR!")
74288c95f9c9e1528237b17c4473c8de9d5abd7d
fcdennis/CursoPython
/mundo1/parte3/ex023.py
204
3.859375
4
n1 = int(input("Informe um número: ")) n2 = n1 // 10 u = n1 % 10 n3 = n2 // 10 d = n2 % 10 c = n3 % 10 m = n3 // 10 print(f"Unidade {u}") print(f"Dezena {d}") print(f"Centena {c}") print(f"Milhar {m}")
3b61fe1a8a96ac180efcfa074dc351839f974a63
fcdennis/CursoPython
/mundo1/parte3/ex025.py
71
3.625
4
name = input("Digite o nome: ").upper().strip() print('SILVA' in name)
2fadcb32e1dd87aedbd342f9a80d3a53ea9c482e
fcdennis/CursoPython
/mundo3/parte1/ex074.py
273
4.0625
4
from random import randint numeros = randint(1, 9), randint(1, 9), randint(1, 9), randint(1, 9), randint(1, 9) print('Os números sorteados foram:', end=' ') for n in numeros: print(n, end=' ') print(f'\nO maior é {max(numeros)}') print(f'O menor é {min(numeros)}')
bc2e8744c00b6e0b4831bda6dd7080944f07b957
fcdennis/CursoPython
/mundo1/parte3/ex024.py
89
3.875
4
city = input("Digite o nome de uma cidade: ").upper().strip() print('SANTO' in city[:5])
c828ed90b3f2863af4eb6f992a0cb735e244d2e0
fcdennis/CursoPython
/mundo1/parte3/ex018.py
262
3.9375
4
import math angulo = math.radians(float(input("Digite o ângulo que você deseja: "))) print(f"O seno de {angulo} é {math.sin(angulo):.2f}.") print(f"O cosseno de {angulo} é {math.cos(angulo):.2f}.") print(f"A tangente de {angulo} é {math.tan(angulo):.2f}.")
998114a8aa6c86da61a885775e26167092a4de3b
fcdennis/CursoPython
/mundo1/parte2/ex010.py
132
3.5625
4
real = float(input("Quanto dinheiro você tem na carteira? ")) print(f"Com R${real:.2f} você pode comprar US${(real / 5.35):.2f}")
150fba597a370093a9666e3ba5270e7fdf9bd58f
fcdennis/CursoPython
/mundo1/parte2/ex009.py
159
4.03125
4
base = int(input("Digite um número para ver sua tabuada: ")) print('-' * 20) for c in range(1, 11): print(f"{base:2} X {c:2} = {c*base:3}") print('-'*20)
a68bfeae79c20c662a425d43740db17fcbf68cd9
fcdennis/CursoPython
/mundo2/parte1/ex043.py
424
3.8125
4
peso = float(input("Qual é o seu peso? (Kg) ")) altura = float(input("Qual é sua altura? (m) ")) imc = peso / (altura ** 2) print(f"O IMC dessa pessoa é de {imc:.1f}") print('Você está em ', end='') if imc < 18.5: print('ABAIXO DO PESO.') elif imc < 25: print('PESO IDEAL. PARABÉNS!') elif imc < 30: print('...
3d52eccea73c2a361e3dedeb752dd8a03ffde59e
HarshitGH/Simple_Calculator_Tkinter
/learner.py
4,300
3.859375
4
# p = int(input('enter value of p')) # r = int(input('enter value of r')) # t = int(input('enter value of t')) # # SI = (p*r*t)/100 # # print("The simple interest is {}".format(SI)) # age = int(input("Enter your age ")) # # if age < 18: # print('Applicant is a Minor') # elif 18 < age < 50: # print('Applicant i...
f99b79467028aa25e92e3ce8baa661afd7657933
mantripat/python_programs
/oct_to_dec.py
225
3.90625
4
num=(input("enter any oct number")) i=0 j=0 print("entered str is: ",num ) l=len(num) s=num[::-1] st=[] print("reverse of string is", s) while(i<l): j=j+(int(s[i])*(8**i)) i=i+1 print("Decimal equivalent", j)
03a7d8a499989b737eadbff04b5c7e606faf8c4d
mantripat/python_programs
/string11.py
296
3.671875
4
a="I love python, python is an easy,python is base for ML" loc=-1 f={-1} x=0 for i in range(loc+1,len(a)): loc=a.find("python",loc+1,i) if(loc!=-1): f.add(loc) x+=1 elif loc==-1: x=0 if x!=0: f.remove(-1) print("Item found at loc:\t",f) else: print("item not find")
91a56a63e18a90190b32636db61dfc25d8acb777
mantripat/python_programs
/clean_string - Copy.py
154
3.578125
4
## clean this list and result should be double of the integers in list x="10,20,30" y='' for i in x: if i in '0123456789': y+=i print(int(y)*2)
764365f3448efbf9bcee1ff867afbfd837521386
zyzfred/BU-CS-521
/HW10/HW-Problem-5.py
309
3.671875
4
x = [2, -6, -3, 1, 19] minor_count = 0 print("List before sort:", x) for e in x: if e < 0: minor_count += 1 for i in range(len(x) - 1): for j in range(i, len(x)): if x[i] > x[j]: x[i], x[j] = x[j], x[i] x[:] = x[minor_count:] + x[:minor_count] print("List after sort:", x)
ab82a6f5fc5b953b59594a34d10c2baf03a12bae
zyzfred/BU-CS-521
/HW2/HW2-2.3.py
112
3.71875
4
feet = eval(input('Enter a value for feet: ')) meters = feet * 0.305 print(feet, "feet is" , meters, "meters")
bc3dadedcedc563ced293f35303bd2b5e78b5181
zyzfred/BU-CS-521
/HW10/HW-6-5.py
391
4.125
4
def displaySortedNumbers(num1, num2, num3): l = [] l.append(num1) l.append(num2) l.append(num3) l = sorted(l) print('The sorted numbers are:',' '.join(l)) def main(): user_input_s = input('Please enter three numbers separated by \', \': ') user_input_l = user_input_s.split(', ') displaySor...
9d005488a8e09b439ed92e318cf8dec715e01ac4
zyzfred/BU-CS-521
/HW4/HW4-11.1.py
839
3.890625
4
ROW_NUM = 3 COLUMN_NUM = 4 def get_matrix(): matrix = [] s1 = input('Enter a 3-by-4 matrix row for row 0: ') s2 = input('Enter a 3-by-4 matrix row for row 0: ') s3 = input('Enter a 3-by-4 matrix row for row 0: ') s1_list = s1.split(' ') s2_list = s2.split(' ') s3_list = s3.split(' ') r...
db60c793a82d846fbc8234ec0ad5e5bd20759d80
zyzfred/BU-CS-521
/HW5/HW5-5.19.py
560
3.5
4
# get a number lines = eval(input("Enter the number of lines: ")) space = ' ' for i in range(lines): # initial a list x = i + 1 list_a = [] # append each number for n in range(x): list_a.append(str(n + 1)) # reverse list_b = list_a[:0:-1] list_c = list_b + list_a if lines >= 1...
6abacd66dbe5e00a2320401956655c616dd0411b
cindy-cho/University-Lectures
/컴퓨팅 사고력/final 대비/리스트 합치고 정렬.py
190
3.625
4
'''sorted''' A = [71,23,31] B = [54,1] A.extend(B) print("extend 함수를 이용하여 합친 리스트:",A) A = sorted(A,reverse=True) print("내림차순으로 정렬한 리스트:",A)
5b231da3523b6381da32edf49b5758d1bcd53d67
cindy-cho/University-Lectures
/컴퓨팅 사고력/final 대비/turtle practice.py
849
3.828125
4
from turtle import* ##pencolor("red") ##fd(100) ##rt(90) ##fd(100) ##rt(90) ##fd(100) ##rt(90) ##fd(100) ##rt(90) ##pencolor("blue") ##for count in range(6): ## circle(100) ## left(360/6) ## ## ##pencolor("black") ##shape("turtle") ## ##for i in range(3): ## forward(100) ## left(360/3) ## ##pencolor("pu...
c5635696513f130ffae10878464a55ab7f93ebda
cindy-cho/University-Lectures
/컴퓨팅 사고력/ch6/ch6_hw4_20151610.py
241
3.59375
4
'''실습 4''' import math as m a, b, c= input("Enter a, b, c : ").split() a = float(a) b = float(b) c = float(c) D = b*b - 4*a*c D = m.sqrt(D) root1 = (-b + D)/2*a root2 = (-b - D)/2*a print("root1 = %.4f and root2 = %.4f." %(root1,root2))
00511707313755de4dfbc134269bf6d6622026fa
cindy-cho/University-Lectures
/컴퓨팅 사고력/final 대비/크리스마스트리.py
308
3.828125
4
'''크리스마스트리''' for i in range(5): for j in range(6-i): print(" ",end='') for j in range((i+1)*2-1): print("*",end='') print() for i in range(5): for j in range(4-i): print(" ",end='') for j in range((i+2)*2+1): print("*",end='') print()
2e0e1226d8845a1aca6f68a48ea5035e83082060
minghzhang007/python-learn
/pythondemo1/exceptionerror.py
1,878
3.90625
4
def test1(): while True: try: x = int(input("please enter a number:")) print('i got the number:', x) break except ValueError: print("Oops! That was no valid number.Try again ") import sys def test2(): try: f = open('myfile.txt') ...
404826ca4ba9e66e657bf03611769e127e186a8b
31chethana/Python-Programming
/Basic-Python-Programs/lcm.py
342
4.125
4
def lcm(num1, num2): if num1 > num2: max = num1 else: max = num2 while(True): if ((max % num1 == 0) and (max % num2 == 0)): lcm=max break max= max+ 1 return lcm x = int(input("Enter 1st number: ")) y = int(input("Enter 2nd number: ")) print "The lcm of ",x," and...
ec54cebc568e45034e68b3a72daaed4cd61da89e
st2257st2257/mipt_inf
/lab2/task14.py
492
3.546875
4
import numpy as np import turtle turtle.speed(10) turtle.left(90) def smile(n,s=1): #face_big b = 180 - 180*(n-2)/n a = 180 - 2*b for i in range(n): turtle.forward(100) if s>0: turtle.right(180 - a) else: turtle.left(180 - a) if (n%2==0): ...
85a4c22a22c6825120b8b7549e304dba0422d2aa
BK-notburgerking/Algorithm
/Baekjoon/11586.py
816
3.71875
4
mirror = [] #거울에 비치는 모양을 담을 리스트 초기화 size = int(input()) # 사이즈 입력 for i in range(size): mirror += [list(map(str, input()))] #입력을 한줄씩 리스트로 받고, 초기화한 리스트에 2차원 리스트로 담음 feelings = int(input()) # 1:그대로 / 2:좌우반전 / 3:상하반전 if feelings == 1: #그대로 for princess in mirror: #리스트 앞에서부터 하나씩 꺼내서 print(''.join(prince...
28e716ba32cd9b219fc7ad7c72872d73627ea372
kobitoko/cmput404lab2
/clientSocketDemo.py
675
3.5625
4
import socket # Using Sockets from the OS to make clients. # socket.AF_INET means use this socket to communicate to the internet # socket.SOCK_STREAM means we want to use TCP! clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # this function tries to do C, hence 1 tuple as argument. clientSocket.connect...
b48d58825b5520e92ebc81f94c2183f9b0d6f006
dchannah/python_fun
/eastbaycrawler/scraper_tools.py
1,815
3.6875
4
# -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup """A collection of methods useful for scraping pages on the East Bay News site. This is just a bunch of cleaned-up soup routines, more or less; I'm still deciding on final formats for all that stuff. """ __author__ = "Daniel Hannah" __email__ = "...
acebb18bf5309ae0f3e5e7d7a2bb8749f9939308
9Ned/Excercise11_Nawapon_P
/Excercise11_LoopInLoop.py
239
4.125
4
numStep = int(input("Enter Number: ")) for x in range(numStep): for y in range(x+1): text = "" space = "" space = space + str(" "*(numStep-y-1)) text = text + "*" * ((2*y)+1) print(space+text)
67ea58fb29e83776277373a6cbbdfcfe403c3926
mtaiuit/pythonfs
/parser.py
235
3.515625
4
import requests from bs4 import BeautifulSoup req = requests.get('https://en.wikipedia.org/wiki/Python_(programming_language)') soup = BeautifulSoup(req.text, "lxml") for sub_heading in soup.find_all('h2'): print(sub_heading.text)
712fab40fd0e8078b95542f8f60856f84dc84714
skanin/NTNU
/Informatikk/Bachelor/Pythonkurs/Prime.py
230
4.03125
4
from math import sqrt def isPrime(n): if n<2: return False if n==2: return True i = 3 while i<= sqrt(n): if n%i==0: return False i+=1 return True print(isPrime(9))
1e712595b9c0cc762aa83010a881a8089302c930
skanin/NTNU
/Informatikk/Bachelor/H2017/ITGK/Øvinger/Øving 3/Tegne figurer med løkker/d.py
260
3.671875
4
from turtle import * print("Jeg kan tegne et regulært polygon!") sider = int(input("Hvor mange sider?: ")) omkrets = int(input("Velg omkrets: ")) vinkel = 360/sider piksler = omkrets/sider for i in range(sider): forward(piksler) left(vinkel) done()
c8b74962700ee1e06f00b655a42598f44d135806
skanin/NTNU
/Informatikk/Bachelor/H2018/Studass/Øvinger/Øving 7/Aksessering av karakterer i en streng/Aksessering_av_karakterer_i_en_streng.py
516
4.03125
4
print("A--------------------------------------") def print_char_str(st): for ch in st: print(ch) print_char_str("Hei på deg") print() print("B--------------------------------------") def return_third(st): if len(st) < 3: return 'q' return st[2] print(return_third("Mistborn")) print(...
291ddd2965d40c0547dbeec5646a02cdf1d8d0b3
skanin/NTNU
/Informatikk/Bachelor/H2017/ITGK/Øvinger/Øving 6/vektorer/oppgave.py
1,384
3.515625
4
import math # a: def lag_vektor(komp1, komp2, komp3): vektor = [komp1, komp2, komp3] return vektor # b: def print_vektor(vec1): return print("Vec1: ", vec1) # c: def skalar(vec, skal): vec2 = [None, None, None] for i in range(len(vec)): vec2[i] = skal*vec[i] return vec2 # d:...
66d20292d64c551bd9468a91881725a482df739e
skanin/NTNU
/Informatikk/Bachelor/H2017/ITGK/Øvinger/Øving 7/Innebygde funksjoner og lister/oppgave_innebygde.py
816
3.609375
4
import random import statistics # a random_numbers = [random.randint(0, 100) for i in range(0, 100)] print(random_numbers) # b count = 0 for num in random_numbers: if num == 2: count += 1 if count == 1: print("Det er 1 2er i listen") else: print("Det er " + str(count) + " 2ere i listen") # c ...
f1e7c420937918c42fd3072fdd7444a9fdf372c2
skanin/NTNU
/Informatikk/Bachelor/H2018/Studass/Øvinger/Øving 9/Bursdagsdatabasen/bursdagsdatabasen.py
537
3.65625
4
birthdays = { "22 nov": ["Bob Bernt", "Mathias"], "10 des": "Elle", "31 okt": ["Aragusta", "Carina"], "12 jan": "Silje", "23 okt": "Willy", "5 jul": ["Martin", "Øystein"], "11 mar": "Miriam" } def add_birthday_to_date(date, name): try: birthdays[date].append(name) except At...
70e02c83426c1cf999d0daea7aff2ec664c5668c
skanin/NTNU
/Informatikk/Bachelor/H2017/ITGK/Øvinger/Øving 2/Karaktergrense/oppgave.py
488
3.828125
4
poeng = int(input("Skriv inn antall poeng: ")) if poeng == 100 or poeng > 89: print("Du fikk A!") elif poeng == 88 or poeng > 77: print("Du fikk B!") elif poeng == 76 or poeng > 65: print("Du fikk C!") elif poeng == 64 or poeng > 53: print("Du fikk D!") elif poeng == 52 or poeng > 41: print("Du fik...
c7274aa98a0f4f470dd8807e45dfdc2ae36a6499
skanin/NTNU
/Informatikk/Bachelor/H2017/ITGK/Eksamensøving/Øving 5/Arbeidsdager.py
1,164
3.828125
4
def is_leap_year (year): if year % 400 == 0: return True elif year % 100 == 0: return False elif year % 4 == 0: return True return False def weekday_newyear(year): if year == 1900: return str(year) + " man" else: day = 0 for i in range(1901, year...
4d9d162de7e55ab46cad3d09b3f48ebb9f57a862
skanin/NTNU
/Informatikk/Bachelor/Codewars/consecutive_fib.py
319
3.546875
4
memo = {} def test(prod): memo[0] = 1 memo[1] = 1 n = 2 while True: for i in range(n, -1, -1): memo[n] = memo[n-1] + memo[n-2] if memo[n-1] * memo[n-2] == prod: return [memo[n-2], memo[n-1], True] elif memo[n-1] * memo[n-2] > prod: return [memo[n-2], memo[n-1], False] n += 1 print(test(4895))
1c239f0729222e44e7bacd9b4e7767baac768cc5
skanin/NTNU
/Informatikk/Bachelor/H2018/Studass/Øvinger/Øving 2/Andregradsligning/Andregradsligning.py
553
3.734375
4
from math import sqrt as rot a = int(input("A: ")) b = int(input("B: ")) c = int(input("C: ")) d = (b**2 - 4*a*c) likning = "Andregradsligningen " + str(a) + "x^2 + " + str(b) + "x + " + str(c) + " har " if d < 0: print(likning + "to imaginære løsninger") else: likningPluss = (-b + rot(d)) / (2 * a) li...
6645355c080743dca38d697b92913ca48c1b1dad
delturge/Polyglot
/Python/Griddy/Converters/Converter.py
1,000
3.828125
4
# A base class that centralizes conversion logic. class Converter: def __init__(self, validator): self.validator = validator #A method that strips parenthesis from the beginning and ending of a list of strings. def stripParenthesis(self, listOfParenStings): parenFreeStrings = [] ...
4926ac5e4a4e923a1d4d93aedb2c04a2aca3ede9
C-SON-TC1028-001-2113/funciones-t2-AllanBa17
/assignments/02CalculaGrado/src/exercise.py
489
3.921875
4
def calcula_grado(x): if x>0.9 and x<=1: print ("A" ) elif x<=0.9 and x>0.8: print ("B" ) elif x<=0.8 and x>0.7: print ("C" ) elif x<=0.7 and x>0.6: print ("D" ) elif x<=0.6 and x>=0.0: print ("F" ) else: print ("score incorrecto" ) def main(): ...
1783d484c6ddab2399743b84aae31bf1b1073b32
rapgame/euler
/problem_2.py
978
3.84375
4
#! /usr/bin/env python """ https://projecteuler.net/problem=2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not excee...
e8090acfcc404f44bcf8993be0446f694bde4cba
sunyeongchoi/python
/mycode/2_dataType/operation.py
617
4.125
4
# 한줄주석 ''' block주석 사칙연산 실행 : ctrl + shift + f10 주석 : 범위잡고(shift + 방향키) + ctrl + / ''' # 자바에서 + 는 연결 BUT 파이썬 에서는 연산 n1 = 100 n2 = 200 print('n1 = ', n1, n2) # 결과 : n1 = 100 200 print(n1+n2) # 결과 : 300 mystr = 'hello' mystr2 = "hello" print(mystr, mystr2) # 결과 : hello hello print(mystr + mystr2) # 결과 : hellohello my_...
7fc00c41a3ed056d752e6738c2071a27ad1a4a23
sunyeongchoi/python
/teacher/0717/polymorphism_test.py
618
3.96875
4
# abstract method를 가진 부모 클래스 선언 class Animal(object): def __init__(self, name): self.name = name # abstract method def talk(self): raise NotImplementedError('자식클래스에서 반드시 구현해야 함') class Cat(Animal): def talk(self): return 'Meow' class Dog(Animal): def talk(self): ret...
0485eb55ea815d96e61fb4ba6662e9b6593bfe58
sunyeongchoi/python
/mycode/4_list/list_index.py
1,062
3.796875
4
colors = ["red", "blue", "green"] print(colors[0]) print(colors[2]) print(len(colors)) # lsit 0번째 엘리먼트 값을 변경하기 colors[0] = 'Yellow' print(colors) # list에 엘리먼트를 1개씩 추가하기 colors.append('black') print(colors) # list에 엘리만트를 여러개 추가하기 colors.extend(['orange', 'red']) print(colors) # list의 엘리먼트 삭제하기 # remove('값'), del col...
a8b9fce1ab9efba0e899995d110d54423096cc08
sanandita001/Chess-Replay
/piece.py
2,110
3.515625
4
import checkmove SPACE = " " def castle(move, board_view, piece_view): home_rank, king, rook = "1", "K", "R" if move[0] == "O" else "8", "k", "r" king_before = "e" + home rook_after = ("a" if move == "OOO" else "h") + home_rank king_after = ("c" if move == "OOO" else "g") + home_rank rook_after ...
60c0774e4f78467af11167483d91fe6f4a9172f1
rakshanavale24092000/Python-Basics
/CountingWords.py
391
4.25
4
#split() method splits string into list. You can specify the seperator, if not specified the default seperator is taken as white space. #x="Hi this is a string" then x.split("i") splits x as ['H',' th','s ','s a str','ng'] myString = "Hello, this is a string" words = myString.split() length = len(words) pri...
0aa3c5c7b8e52a5bd5b642140a99d4377004ce36
Ronik22/Codes-and-Scripts
/Image_In_Terminal/img_in_terminal.py
566
3.75
4
# pip install color-it # pip install pillow from PIL import Image from colorit import init_colorit, background init_colorit() image = Image.open(input("Enter image path: ")) fixed_height = int(input("Enter height to resize the image: ")) height_percent = (fixed_height / float(image.size[1])) width_size = int((float(...
3ff13c9ee66572d7869288a35104694d7349e926
Marsovi4/Python_lessons_basic
/lesson02/home_work/hw02_normal.py
4,117
4.03125
4
# Задача-1: # Дан список, заполненный произвольными целыми числами, получите новый список, # элементами которого будут квадратные корни элементов исходного списка, # но только если результаты извлечения корня не имеют десятичной части и # если такой корень вообще можно извлечь # Пример: Дано: [2, -5, 8, 9, -25, 25, 4] ...
b601729d41afd6f10e9d15dbbe6c75b00a9f6c8b
sampath97/Python_Practice
/Day1/getascii.py
93
4.21875
4
#Program to print ASCII value of given character x=input("Enter character: ") print(ord(x))
0d14432b432fcfda586b2f581635b174611afd0e
Dwizpa/PythonProject
/Homework/Week1/Fibonacci.py
764
3.96875
4
def fibo(n): """ Digunakan sebuah fungsi fibo yang berfungsi untuk menghitung bilangan fibonacci dari sebuah angka yang sudah ditetapkan. Terdapat 1 parameter pada fungsi ini: n : sebagai penampung sebuah integer dari main method """ if n <= 1: return n else: ...
70202fdb216dcff6c559177284482033d01e0289
valeriofarias/code
/easy/fizzbuzz/fizzbuzz.py
407
4.03125
4
""" FizzBuzz rules 1. If position is multiple of 3 say fizz 2. If position is multiple of 5 say buzz 3. If position is multiple of 3 and 5 say fizzbuzz 4. For any other position say the number """ def robot(pos): say = str(pos) if pos % 3 == 0: say = 'fizz' if pos % 5 == 0: say =...
cee65d84d42b36167ce2420acec0d8ef53153208
haree09/python.py
/New folder/fun.py
358
3.828125
4
def add(x,y): return x+y def sub(x,y): return x-y def mul(x,y): return x*y def div(x,y): return x//y def modl(x,y): return x%5 n1=int(input("enter n1=")) n2=int(input("enter n2=")) print("add=",add(n1,n2)) print("mul=",mul(n1,n2)) print("sub=",sub(n1,n2)) print("div=", div...
b9baa80d35b7361b711a9b226975bd579ad86e99
gauravkatkar1000/p1
/asa.py
310
3.640625
4
a=[2,3,1] b=[1,2,3] c=b.copy() k=0 for i in a: e=0 for j in range(0,len(b)): if(i==b[j]): e=1 b[j]=-1 break if(e==0): print("not equal") k=1; break if(k==0): print("equal") print(a) print(b) print(c)
093b7947503af45da305ca56ecd8fd6d2402f06c
ktb5891/Bigdata_lecture
/두근두근_파이썬_실습코드_1~7/chap04/lab6.py
1,092
3.84375
4
import turtle t = turtle.Turtle() t.shape("turtle") # 리스트를 사용하여 색상을 문자열로 저장한다. color_list = [ "yellow", "red", "blue", "green" ] t.fillcolor(color_list[0]) # 채우기 색상을 설정한다. t.begin_fill() # 채우기를 시작한다. t.circle(100) # 속이 채워진 원이 그려진다. t.end_fill() # 채우기를 종료한다. t.forward(50) t.fillcolor(color_l...
c41839d048329042b9e60c7bb47812f73ea33169
ktb5891/Bigdata_lecture
/두근두근_파이썬_실습코드_8~14/chap08/proj5.py
3,598
3.8125
4
import turtle from random import randint # (x, y) 위치에 반지름 radius로 원을 그리는 함수 def draw_circle(turtle, color, x, y, radius): turtle.penup() # 펜을 올린다. turtle.fillcolor(color) # 채우기 색상을 설정한다. turtle.goto(x,y) # 거북이를 (x, y) 위치로 이동한다. turtle.pend...
c5012fa076f1c7302b8da32dacf99a4a622e1a30
ktb5891/Bigdata_lecture
/두근두근_파이썬_실습코드_1~7/chap02/lab2.py
1,153
3.515625
4
# 터틀 그래픽을 사용하여야 하므로 다음과 같은 코드를 소스 파일에 입력한다. import turtle t = turtle.Turtle() t.shape("turtle") # 사용자로부터 집의 크기를 받아서 size라는 변수에 저장한다. # 집의 크기는 정수이므로 input()이 반환하는 문자열을 int()를 통하여 정수로 변환하였다. size = int(input("집의 크기는 얼마로 할까요? ")) # 집을 그릴 차례이다. 사각형을 다음과 같은 코드로 그린다. 이때 변수 size를 사용하자. # 사각형을 그린다. t.forward(...
13843368e5906a13dfaf512ff9e69510765af329
ktb5891/Bigdata_lecture
/두근두근_파이썬_실습코드_1~7/chap03/lab5.py
458
3.75
4
money = int(input("투입한 돈: ")) price = int(input("물건값: ")) change = money-price print("거스름돈: ", change) coin500s = change // 500 # 500으로 나누어서 몫이 500원짜리의 개수 change = change % 500 # 500으로 나눈 나머지를 계산한다. coin100s = change // 100 # 100으로 나누어서 몫이 100원짜리의 개수 print("500원 동전의 개수:", coin500s) print("100원 동전의 개수:",...
4a3cb3f002cd808a199d29d4ed77679b71dbaf02
jmnich/UFP_Regulator_Simulations
/FUZZY/FUZMain.py
1,183
3.609375
4
# -*- coding: utf-8 -*- """ FUZZY REGULATOR 1. Create an instance of the balanced arm 2. Set initial conditions 3. Prepare a fuzzy regulator 4. Begin iterating: a) 5. Visualize results note: all values are scaled in standard metric units note: input params: angle, angular_velocity note: output...
958e3ca5bd6d18e0abcbe9f460765dc192145ee8
python-elective-2-spring-2019/Lesson-11-Unit-Test
/code_from_today/print_debug.py
198
3.65625
4
def add_number_x_times(num, x): print('Im in the function') for i in range(x): print(i) num += num print(num) return num add_number_x_times(10, 90)
86ff61201cd9f89c2f376c6f8701a3af233c505d
AteCastillo/AirBnB_clone
/console.py
7,474
3.671875
4
#!/usr/bin/python3 """Console File to handle objects""" import cmd import json from models import storage from models.base_model import BaseModel from models.user import User from models.state import State from models.city import City from models.place import Place from models.amenity import Amenity from models.review ...
2ac64654a1abdf6bf8e1e2ba04d86ff29452b880
chearasmey/python_tutorials
/loops.py
133
4.09375
4
names = ["Harry", "Ron", "Mike"] #simple loop # for name in names: # print(name) #loop by range for i in range(10): print(i)
3dfa3414a68e072b418f00e60222c11c122c7bef
stephenykk/coolfe
/python-lm/abs.py
124
3.953125
4
# print absolute value val = input('input a numver: ') val = int(val) if val >= 0: print(val) else: print(-val)
739f406cb95b7261026195f53795cbeee9fdac82
lkloh/USArray-lkloh
/BasicsOfCoding/unit_test_demo/programs/simple_calculator.py
249
3.59375
4
import sys, os, matplotlib import matplotlib.pyplot as py def add(num1, num2): return num1+num2 def subtract(num1, num2): return num1-num2 def times(num1, num2): return num1 * num2 def divide(num1, num2): return num1/float(num2)
8b9db69b4c42c65a6babc414a6a3d140bcaedc36
NeilKleistGao/Dejavu
/dm/preprocessing/step3.py
869
3.546875
4
import pandas as pd # 重新处理时间数据,使得时间可以被量化 if __name__ == '__main__': df = pd.read_csv("../dataset/temp2.csv") reg = df["regDate"] create = df["creatDate"] reg_y = reg.map(lambda x: int(str(x)[0: 4])) reg_m = reg.map(lambda x: int(str(x)[4: 6])) reg_d = reg.map(lambda x: int(str(x)[6: 8])) ...
6032a3299ed54ec4f131f4a3ec0b44987850b41f
Pikasu12/lotto_number_generator
/run.py
2,250
4.1875
4
import pyfiglet from LuckyNumber import LuckyNumbers from resources.game_rule import games # Define a variable which contains the instruction to use. init_question = ''' Please choose the game you want to generate number from. [1] Lotto 6/42 [2] Mega Lotto 6/45 [3] Super Lotto 6/49 [4] Grand Lotto 6/55 [5] Ultra Lott...
7a848c7a971f6ff901b43c14543a0222662f09d2
polegarh/Python-programs
/calculator.py
1,264
3.890625
4
#calculator ''' want a calculator to be a wisget give it a parent and pack it (or grid it) inherit from Frame all the time - like a window but doesnt have to be top level, can be packed/gridded ''' from math import * from tkinter import * class Calculator(Frame): #have to accept a parent argument def __init__...
b454604fcc5ed0c864b446a3667fbc3d87ebf982
gnavink/Python
/3_OOP/oop5.py
2,115
4
4
#oop5.py #Illustrates : # i) Inheritance with Manager Class # ii) Add/Remove/Print Employee methods # iii) isinstance, issubclass methods class Employee: raise_amount = 1.04 num_employees = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.email...
82da16a5ff5a95107dbad97b801e6c98b543eeb0
gnavink/Python
/1_Fundamentals/age.py
389
3.890625
4
#age.py # This program keeps prompting the user to enter a valid age. # If a valid integer is enter, it prints and exits the function def get_int(msg): while(True): try: i = int(input(msg)) return i except ValueError as err: print(err) if __name__ == '__ma...
d58c471c3fbffa06206d3060e47802f816e8f440
gnavink/Python
/3_OOP/oop2.py
1,284
4.375
4
#oop2.py #Illustrates: # i) Class variables # ii) How are class variables accessed? class Employee: raise_amount = 1.04 num_employees = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.email = first + '.' + last + '@email.com' ...
8d2e41931c732e004eb3ae5784e93827542237a5
NikosAvg/AdventOfCode20
/day2/day2_1.py
631
3.609375
4
with open('input.txt') as f: data = f.readlines() for i in range(len(data)): data[i] = data[i].split(' ') #Split each data point at the space #Extract numbers letter and password def extract_and_validate(data): count=0 for i in data[2].split('\n')[0]: if i==data[1].split(':')[0]: count+=1 i...
61efe39ca12cfd7e02bfb8e617c293847c3647ae
stepan20000/MITx-6-00-1
/week2/Pset2_3Rec.py
829
3.765625
4
balance = 87169 annualInterestRate = 0.18 low = balance / 12 high = (balance * (1 + annualInterestRate / 12)**12) / 12.0 def findMinPay(balance, low, high, last): import math def PayDebtYear(bal, ann, mon): b = bal - mon + (ann/12) * (bal - mon) for i in range(11): b = b - mon ...
7155cb6464dc69fa7ec0e92869fad5590ceba165
w40141/atcoder
/abc_251/c.py
325
3.5
4
from typing import Dict, Tuple n = int(input()) d: Dict[str, int] = {} award: Tuple[int, int] = (10 ** 6, -10 ** 6) for i in range(1, n + 1): s, t = input().split() point = int(t) if s in d: pass else: d[s] = point if point > award[1]: award = (i, point) print(award...