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
706c930643ef182f32daf80f8b6fbc3f50684593
maktweet/Python_Training
/Day 1/Day1.py
336
4.03125
4
# Print to the console in Python print("Day 1 - Python Print Function") print("The function is declared like this:") print("print('what to print')") print("====================================") # Strin in a single line of above text print("Day 1 - Python Print Function\nThe function is declared like this:\nprint('wh...
05e5cfd09667d7120e264b9b071108e19cdcb9b3
maktweet/Python_Training
/Day 2/life_in_weeks.py
235
3.78125
4
age = input("What is your current age: \n") years_remaining = 90 - int(age) days = years_remaining * 365 months = years_remaining * 12 weeks = years_remaining * 52 print(f"You have {days} days and {weeks} weeks and {months} months")
6930bf6d11c747c437aad99055a53d1b19c0a829
satyen-d/Python-Concepts
/bubblesort.py
245
3.6875
4
def BubbleSort(L): for i in range(len(L)): for j in range(len(L)-i-1): if L[j]>L[j+1]: L[j], L[j+1] = L[j+1], L[j] print(L) print(L) print(L) L = [50,52,53,51,55,54] BubbleSort(L)
6c0d4f8fcd8eda199121580303e38a797c91761a
ouss17/titanic-python
/base.py
1,683
3.75
4
import csv def read_titanic(): data = {} with open("titanic.csv") as titanic_data: reader = csv.DictReader(titanic_data, delimiter=',', quotechar="\"") for line in reader: for k, v in line.items(): if k not in data: data[k] = [] d...
0a643008d2cf9df141bf36ffdbb3a4efb6a43a02
Lsaiyang/ziliao
/老师发的作业/作业.py
1,916
3.9375
4
# 1、书写一个程序,用户输入一个数字(圆的半径)要求输出该圆的半径、周长和面积,输出格式如下: # 该圆半径为:xx # 该圆周长为:xx # 该圆面积为:xx #import math #radius = input('请输入圆的半径:') #radius = int(radius) #pi = math.pi #print('该圆的半径为{0:d}'.format(radius)) #print('该圆的周长为{0:f}'.format(radius * 2* pi)) #print('该圆的面积为{0:10.2f}'.format(radius**2*pi)) # 2、解释以下程序的打印结果 #print(1 ...
b9db6f1f5afca603c5b4c297b8643e22ed48c3f8
Priya1705/sentiment-analysis-using-twitter
/simple_basic.py
299
3.59375
4
import numpy as np import pandas as pd from textblob import TextBlob a="apples are fruits" obj = TextBlob(a) sentiment = obj.sentiment.polarity print(sentiment) if sentiment == 0: print("the text is neutral") elif sentiment > 0: print("the text is positive") else: print("the text is negative")
7581055a9b15bdc593bfdf8ddb100e09c19f39e1
lph4stalin/liao
/2.函数/2.1调用函数.py
970
3.796875
4
""" 我理解的函数:函数是一系列的动作,我们输入初始参数,它执行定义好的动作,并将输出返回给我们。所以使用函数,可以通过很短的代码实现复杂的功能,一旦完成,可以很方便的重复调用。 一般定义函数有两种,一种是名词类的,需要返回加工好的数据;一种是动词性的,不需要返回 Python内置了很多有用的函数,我们可以直接调用。 要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数abs,只有一个参数。可以直接从Python的官方网站查看文档,也可以通过help(abs)查看abs函数的帮助信息。 """ # 调用abs函数: # abs(100) # abs(-20) # abs(12.34) # 调用函数的时候,如果传入的...
9510d34a6a01e3c65001c35e594bd8fc6c98d0b2
lph4stalin/liao
/4.函数式编程/4.3匿名函数.py
533
3.59375
4
# 当我们传入函数时,有些时候,可以不需要显式的定义函数,直接传入匿名函数更方便。 # 例如,lambda x: x * x # 关键字lambda表示匿名函数,冒号前面的x表示参数。匿名函数有个限制,就是只能写一个表达式,不用写return,返回值就是该表达式的结果。 # 匿名函数的其他性质和函数一样。 # 备注:在实际操作中,不建议使用匿名函数!(因为函数名往往可以展示函数的功能,匿名函数的可读性较差)
fc04c4dbeb2e32f5a58e0893f07585c688325d14
lph4stalin/liao
/9.IO编程/9.2StringIO和BytesIO.py
1,466
3.75
4
""" StringIO 很多时候,数据读写不一定是文件,也可以在内存中读写。 StringIO 顾名思义就是在内存中读写 str. 要把 str 写入 StringIO,我们需要先创建一个 StringIO,然后,像文件一样写入即可: from io import StringIO f = StringIO() f.write('hello') >>> 5 f.write(' ') >>> 1 f.write('world!') >>> 6 print(f.getvalue()) >>> hello world! getvalue() 方法用于获得写入后的 str。 要读取 StringIO,可以用一个 str 初始化 Str...
d852cd34f8249ee22cd47ae3fb18bd531c4fc7fe
lph4stalin/liao
/9.IO编程/9.3操作文件和目录.py
3,258
3.953125
4
""" 如果我们要操作文件、目录,可以在命令行下面输入操作系统提供的各种命令来完成。比如 dir、cp 等命令。 如果要在 Python 程序中执行这些目录和文件的操作怎么办?其实操作系统提供的命令只是简单地调用了操作系统提供的接口函数,Python 内置的 os 模块也可以直接调用操作系统提供的接口函数。 打开 Python 交互式命令行,我们来看看如何使用 os 模块的基本功能: import os os.name # 操作系统类型 >>> 'nt' 如果是 posix,说明系统是 Linux、Unix 或 Mac OS X,如果是 nt,就是 Windows 系统。 要获取详细的系统信息,可以调用 uname() 函数:...
9d846d2f692993c989a29de7048a8644e24fe3ee
lph4stalin/liao
/4.函数式编程/4.4装饰器.py
3,922
3.6875
4
# 由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数 import functools # def now(a): # print(a, '2019-2-22') # # # f = now # f('a') # # # # 函数对象有一个__name__属性,可以拿到函数的名字: # print('now', now.__name__) --> 'now' # print('f', f.__name__) --> 'now' # 现在,假设我们要增强now()函数的功能,比如,在函数调用前后自动打印日志,但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式...
10dc31189235e6f6ee5635202ec3299e16de86dd
huangmao12345/Chess
/BoardAndPieces.py
3,725
3.515625
4
class Piece: identity = "" # location = Coordinates(0, 0) x = 0 y = 0 side = True move_set = [] captured = False has_moved = False def __init__(self, color, piece_type, location_x, location_y): self.identity = piece_type self.x = location_x self.y = location_...
dd66e4c4715e4d864aa8f01fe2ddec8252acfc21
Juxhinb7/azubi_exercises
/ex_5.1.py
293
3.71875
4
count = 0 summe = 0.0 while True: sval = input("Geben Sie eine Zahl ein: ") if sval == "done": break try: fval = float(sval) except ValueError: print("Invalid input") continue count += 1 summe += fval print(summe, count, summe / count)
dcab5a7fdbda4d76a8c0f2a7944aaa6496255784
hyeyoungryu2202/Raspberry-Pi-Tutorial
/cameraexample.py
534
3.5
4
#Import necessary modules for Pi Camera module import picamera import time camera = picamera.Picamera() #Define the camera object as camera camera.capture('example.jpg') #.capture() snaps a quick photo camera.vflip = True #Flips the camera vertifcally #.hlip flips the camera horizontally camera.capture('example 2.jp...
0fafc7ac1a530d05c2a9e8d3dbb2d871c31f6dbd
nitya244/python-code
/4(greater than 100 or not).py
281
4.03125
4
a=int(input("enter first number:")) b=int(input("enter second number:")) c=int(input("enter third number:")) sum=a+b print("sum=",sum) Number=sum*c print("Number=",Number) if Number>100: print("Number is greater than 100") else: print("Number is less than 100")
0095d32450eb799fcc01bcf537160898a46cecef
KenytSD/Midterm
/midterm_kenyt.py
610
3.921875
4
#midTerm #name:Kenyt #date:6_1_21 def play(): number1 = eval(input("What's your first number: ")) number2 = eval(input("What's your second number: ")) total = (number1+number2) print ("What is the result of:",number1, "+",number2) number_student = 0 while number_student != total: ...
2ef175367a5ab9c446d40c2b4979c87ac5d4e0c9
Div25singh/Python_basics
/greatest among 3.py
208
4.03125
4
a=int(input("enter a")); b=int(input("enter b")); c=int(input("enter c")); if a>b and a>c: print("a is the largest"); elif b>a and b>c: print("b is the largest"); else: print("c is the largest");
6191e450436393fc4ac30c36d1e16665b9cebdb2
wahahab/mit-6.0001
/ps1/ps1c.py
1,204
4.21875
4
# -*- coding: utf-8 -*- import math from util import number_of_month SCALE = 10000 if __name__ == '__main__': months = 0 current_savings = 0 portion_down_payment = .25 r = .04 min_portion_saved = 0 max_portion_saved = 10000 best_portion_saved = 0 semi_annual_raise = .07 total_cos...
e07b46b7e2a71105eaaf2536ec7ba77068c7c956
MrAliTheGreat/AI_Projects
/Game AI/Hands-on2.py
16,135
3.984375
4
import random import copy import time class Player: def __init__(self, name, num_of_cards): """ The base player class of the game Inputs ----------- name = (str) player's name num_of_cards = (int) number of cards in the deck """ self.name = name ...
cea1ddff070df08dd16f7cbd564e2a127335fa4c
Barrentd/ExerciceEntretienTech
/Python/computeJoinPoints.py
841
3.96875
4
"""[summary]""" def compute_join_point(s_1, s_2): """[summary] Returns: [type]: [description] """ print("s_1", s_1, "s_2", s_2) if s_1 < s_2: if s_1 > 2000: return('point de jointure trop haut') ajout = map(int, str(s_1)) s_1 = s_1 + sum(ajout) ...
ddcfcffc26cfb0ed113894481467e335a7ac5022
rdobr/Home-work
/HW1/HW_1.py
362
3.703125
4
#task1 a=int(input('Enter a= ')) b=int(input('Enter b= ')) print((a+b), (a-b), (a*b), (a/b)) #task2 name=input('What is your name? ') age=input('How old are you? ') address=input('Where do you live? ') print('Hello ', name) print('Your age is ', age) print('You live in ', address) #task3 from PIL import Image image =...
dc1f45b36980817771eca5d2837213b3de9489e2
blaza168/akr_project
/binary/utils.py
576
3.625
4
def set_last_2_bits(byte, bits): # wipe 2 last bits filter = 255 - 3 byte = byte & filter return byte | bits def get_last_2_bits(byte): str = f'{byte:b}' result = 0 if str[-1] == "1": result += 1 if str[-2] == "1": result += 2 return result def read_by_2_bits(byte...
6d40b1d4062790a1a746a96e5ea061fbb52b49ed
blaza168/akr_project
/extract.py
296
3.5
4
from os.path import exists from image.factory import get_reader filename = input("Enter filename of image: ") if exists(filename): reader = get_reader(filename) text = reader.read() print("Text extracted from image: " + text.decode("ASCII")) else: print("File doesn't exist")
a3670a985b01c721622c54261ed08722599b14a9
umakantv/courser_ml_using_python
/machine-learning-ex1/machine-learning-ex1/ex1/Linear-univariate-regression.py
4,510
3.640625
4
# To add a new cell, type '#%%' # To add a new markdown cell, type '#%% [markdown]' #%% #%% [markdown] # # Linear Regression # ## Hypothesis # $$ h_{\theta}(x) = \theta_0 + \theta_1 x $$ # ## Cost Function # $$ J(\theta) = \frac{1}{2 m} \sum_{i=1}^{m} ( h^i_{\theta}(x) - y_i)^2 $$ #%% import pandas as pd import numpy...
a39d1bae6906b8f19a577050d13fb168a0a027a4
kgjoni/DNA_sequences
/CS111_Project2.py
3,175
3.96875
4
# PROJECT ASSIGNMENT 2 # CS-111 GREEN # UIC, NOVEMBER 2016 import random # QUESTION 1: def makeFounders(red, purple, blue): """This function creates a random list that corresponds to a population with the given number of organisms of each type.""" myList_r = [] myList_p = [] myList_b = [] for x i...
6acbefd0ecfda9ff0266338680fe3224c7852990
kotegit2020/Python-Practice
/import.py
79
3.671875
4
import camelcase c=camelcase.CamelCase() txt="hELLO wORLD" print(c.hump(txt))
f453bec5c21a1660b53aae4ee0c13c72eab8c226
Tyrant1337/CNIDERP_Driver_Program
/Group 3 Driver Old Code/python.py
1,372
3.640625
4
import numpy as np ROW_COUNT =6 COLUMN_COUNT= 7 def create_board(): board = np.zeros((6,7)) return board def drop_piece(board,row,col,piece): board[row][column]= piece def is_valid_loc(board,column): return board[5][column] ==0 def get_nex_open_row(board,column): for r in range(ROW_CO...
9c377e6fac62397edf8a45ef18a904b4a1fff9ba
wdtxzy/python
/learn/02-get-params.py
674
3.625
4
import urllib.request import urllib.parse import string def get_method_params(): url = "http://www.baidu.com/s?wd=" #拼接字符串(汉字) name = "美女" #python 的解释器不支持汉字,需要转译 final_url = url + name print(final_url) encode_new_url = urllib.parse.quote(final_url,safe=string.printable) print(encode_ne...
e7252198d51cd2823c7b598accb10bed49c10531
PvtMuchacho/Pong
/middle.py
820
3.828125
4
from turtle import Turtle from random import randint class Middle_Line(Turtle): def __init__(self): super().__init__() self.shape("square") self.shapesize(1, 0.2) self.penup() self.hideturtle() self.pensize(10) self.color("white") self.speed("faste...
694c075a2c6495bb53a6a6e31b359bcf56fb7ea3
novuszed/CompetitiveProgram
/Assignement5.py
1,113
3.5
4
__author__ = 'zihaozhu' import sys import queue import heapq class Graph(object): def __init__(self,start,weight): self.start=start self.weight=weight def __cmp__(self,other): return (self.weight>other.weight)-(self.weight<other.weight) def make_graph(filename): fh = open(filenam...
13f44c6c33a899f425c0c7a91a6c03f2ccfc1857
mouna-byte/python
/exo_liste
830
3.765625
4
liste_animaux= ["lapin", "chat", "chien", "chiot", "dragon", "ornithorynque"] liste_animaux.sort() print(liste_animaux) liste_animaux.reverse() print(liste_animaux) liste_animaux.append("troll") print(liste_animaux) animaux_dom=["lapin", "chat", "chien", "chiot"] for i in animaux_dom: liste_animaux.remove(i...
7b434529b0c9acae0c50277ab942719f77490088
dmanral/Python-Automation
/Python-Automation-Udemy/word_read_write.py
1,549
3.625
4
# Read and write word document import docx # New document object. d = docx.Document('docx_files/demo.docx') # List of paragraph objects. print(d.paragraphs) # One paragraph object. print(d.paragraphs[0]) # Text of the one paragraph object. print(d.paragraphs[0].text) print(d.paragraphs[1].text) # Save the second ...
b5072d88b430d17355d94a7fdc7ba9ae2cf6dfaa
dmanral/Python-Automation
/Python-Automation-Udemy/phonenumber.py
1,151
3.984375
4
# Regex finds text patters. def isPhoneNumber(text): if len(text) != 12: return False # not a phone number for i in range(0,3): if not text[i].isdecimal(): return False # no area code if text[3] != '-': return False # missing dash for i in range(4, 7): ...
bc9a56767843484f90d5fe466adee8c1289a9052
JohanRivera/Python
/GUI/Textbox.py
1,360
4.125
4
from tkinter import * raiz = Tk() myFrame = Frame(raiz, width=800, height=400) myFrame.pack() textBox = Entry(myFrame) textBox.grid(row=0,column=1) #grid is for controlate all using rows and columns #Further, in .grid(row=0, column=1, sticky='e', padx=50) the comand padx o pady move the object, in this case #50 pixel...
916feb528012392d891033cc5655459650efdecd
Allu96/School-projects
/SchoolStuff/dict.py
294
3.609375
4
def dictionary(n): if n < 0: print("negatiivinen syöte") exit() else: dict = {} for i in range(1,n+1): dict[i] = i*i return dict def main(): print("Syota kokonaisluku:") n = int(input()) print(dictionary(n)) main()
744690224f98f2aace82c4d81dba3135a865e532
baejinsoo/TIL
/4th/파이썬/python_programming_stu/mycode/6_data_structure/tuple_test.py
424
4.09375
4
# 값의 변경이 불가능한 리스트 - tuple # 프로그램을 작동하는 동안 변경되지 않는 데이터의 저장 my_tuple = (10, 20, 30, 40, 20) print(my_tuple) # 값의 중복이 불가능한 리스트 - set a = {10, 20, 30, 40, 20} print(a) s = set([1, 2, 3, 5, 1]) print(s) s.add(4) print(s) s.add(3) print(s) s.remove(3) print(s) s.update([4, 8, 9, 10]) print(s) s.discard(5) print(s) s.clear(...
21d92cf2e0027b977d30c7f7af3383d0331e1ed0
baejinsoo/TIL
/4th/파이썬/python_programming_stu/Practice/prac_2.py
577
4.125
4
# # 일반적인 함수 정의 # def add(x, y): # return x + y # # # print(add(10, 20)) # # # 람다식 사용 # my_add = lambda x, y: x + y # print(my_add(10, 34)) # # square = lambda x: x ** 2 # print(square(4)) # # multi = lambda x, y: x * y # print(multi(40, 3)) # # division = lambda x, y: x / y # print(division(50, 5)) my_arr = [1, 2...
d4469fc053480149f231934dd9522262a641ddf0
baejinsoo/TIL
/4th/파이썬/python_programming_stu/mycode/lab/find_age.py
228
3.8125
4
print('태어난 년도를 입력하세요 :') year = input() age = 2020 - int(year) + 1 if 17 <= age < 20: print('고등학생 입니다') elif 20 <= age < 27: print('대학생 입니다') else: print('학생이 아닙니다')
fc983a401515748e95511a9ba0c07bbd7c228eea
ennguyennguyen/Mini-Game
/03_Flashcard.py
500
4.03125
4
class my_dictionary(dict): def __init__(self): self = dict() def add(self, key, value): self[key] = value import random my_list = my_dictionary() while True: my_list.key = input("Word: ") my_list.value = input("Definition: ") my_list.add(my_list.key, my_list.value) cont = ...
2f3f34d1af7a18819b4d53f7631adfc64cfd8fae
AbhaiPlayz31/P-105
/project.py
540
3.6875
4
import csv import math with open('project.csv', newline='')as f: reader = csv.reader(f) fileData = list(reader) data = fileData[0] def mean(data): n = len(data) total = 0 for d in data: total += int(d) mean = total/n return mean squaredlist = [] for number in data: a ...
182357e4e38a589180397e5f7cfa1a2e865b64d0
hbhattaram/HBLearning
/Py_Charm_coding_files/numbers.py
234
3.875
4
number_1 = 10 number_2 = 20 print(number_1+number_2) print(number_1*number_2) print(number_2-number_1) print(number_2/number_1) number_3 = 4.3 result = (number_1*number_2)/number_3 print(result) number_4 = result**2 print(number_4)
73b6f451680c4bdfcf59054f1a2eab9aa300e1a2
niemitee/mooc-ohjelmointi-21
/osa11-12_yleisimmat_sanat/src/yleisimmat_sanat.py
522
3.515625
4
# TEE RATKAISUSI TÄHÄN: from string import punctuation def yleisimmat_sanat(tiedoston_nimi: str, raja: int): with open(tiedoston_nimi) as tiedosto: sisalto = tiedosto.read() sisalto = sisalto.replace('\n', '') for merkki in punctuation: sisalto = sisalto.replace(merkki, '') ...
bd41fb98b858e08b8eb71475420179587c5ead75
niemitee/mooc-ohjelmointi-21
/osa07-06_salasanan_arpoja_2/src/salasanan_arpoja2.py
716
3.5625
4
# tee ratkaisu tänne from string import ascii_lowercase, digits from random import choice, shuffle def luo_hyva_salasana(pituus: int, numerot_mukaan: bool, merkit_mukaan: bool): salasana = [] erikoismerkit = '!?=+-()#' arvontajoukko = ascii_lowercase if numerot_mukaan: salasana.append(choice(...
64b6ebf15af87eec9d39f03761bff19ee5ce7355
niemitee/mooc-ohjelmointi-21
/osa04-18_uniikit/src/uniikit.py
265
3.75
4
# tee ratkaisu tänne def uniikit(lista): uusi = [] for luku in lista: if luku not in uusi: uusi.append(luku) return sorted(uusi) if __name__ == "__main__": lista = [3, 2, 2, 1, 3, 3, 1] print(uniikit(lista)) # [1, 2, 3]
06f74cac79b66c444543f34fd862e167c865e0a5
niemitee/mooc-ohjelmointi-21
/osa04-06_merkit_samat/src/merkit_samat.py
234
3.71875
4
# tee ratkaisu tänne def samat(mjono, i1, i2): if i1 not in range(len(mjono)) or i2 not in range(len(mjono)): return False return mjono[i1] == mjono[i2] if __name__ == "__main__": print(samat("koodari", 1, 2))
523d295629368c82f27dbd33b1529c705297d288
niemitee/mooc-ohjelmointi-21
/osa04-07c_lisays_ja_poisto/src/lisays_ja_poisto.py
362
3.609375
4
# Kirjoita ratkaisu tähän lista = [] while True: print(f'Lista on nyt {lista}') valinta = input('(l)isää, (p)oista vai e(x)it: ') if valinta == 'x': break if valinta == 'l': lista.append(len(lista) + 1) if valinta == 'p': if len(lista) == 0: continue lis...
7a7415220912c0e7e154e846165c7fcbfe9709c1
niemitee/mooc-ohjelmointi-21
/osa12-04_kiipeilyreitti/src/koodi.py
1,016
3.5625
4
class Kiipeilyreitti: def __init__(self, nimi: str, pituus: int, grade: str): self.nimi = nimi self.pituus = pituus self.grade = grade def __str__(self): return f"{self.nimi}, pituus {self.pituus} metriä, grade {self.grade}" def pituuden_mukaan(reitit: list): def pituus(re...
70f6364fc5676356c31378ac5d0ba1c1ee8d4a8d
niemitee/mooc-ohjelmointi-21
/osa10-04_sanapeli/src/sanapeli.py
2,961
3.765625
4
# TEE RATKAISUSI TÄHÄN: import random class Sanapeli(): def __init__(self, kierrokset: int): self.voitot1 = 0 self.voitot2 = 0 self.kierrokset = kierrokset def kierroksen_voittaja(self, pelaaja1_sana: str, pelaaja2_sana: str): # arvotaan voittaja return random.randint(...
6a3d2d47afc626198b7db0b56c1abbc5ea551222
serenafr/My2048
/src/board.py
7,568
3.84375
4
import random class Move(object): LEFT = 'left' UP = 'up' RIGHT = 'right' DOWN = 'down' class Board(object): def __init__(self, n_init_tiles): self.BOARD_SIZE = 4 self.board_data = self.initialize_board(n_init_tiles) self.__score = 0 def generate_board(self): '''Generate a None board''...
a87ca894e5399a37980c85f7dfeaaed11a045b05
ElshadaiK/Competitive-Programming
/add_end.py
588
3.578125
4
def addend(num): n = 0 while(int(num) > 1): possibles = [] possibles.append(len(num)*"1") if(len(num) > 1): possibles.append((len(num)-1)*"1") possibles.append((len(num)+1)*"1") minimum = int(num) for possible in possibles: x = int(num) - i...
2f901ba4252e6ab908775c76878a5cbd34363856
ElshadaiK/Competitive-Programming
/merge_two_sorted_linked_lists.py
956
3.9375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: res = ListNode() ptr = res x =...
4915cf71d8aa82f09cadc1bba2cde6f76ab12c18
ElshadaiK/Competitive-Programming
/coins.py
1,437
3.84375
4
from typing import DefaultDict def sortCoins(listr): map_to_greater = {} for string in listr: # A>B, A<B oper = string[1] if oper == "<": if string[0] not in map_to_greater: map_to_greater[string[0]] = set() map_to_greater[string[0]].add(string...
6d83989381228581e229b60ff29018e07b84b8d8
ElshadaiK/Competitive-Programming
/pigLatin.py
595
3.578125
4
def pigger(inp): result = "" vowels = ['a', 'e', 'i', 'o', 'u'] lines = inp.split(' \n ') for line in lines: words = line.split(' ') print(words) for word in words: hold = word for i in word: if i in vowels: toBe = hold ...
7d39b12fb86bfcf572329dca9ae91c83da28c75e
ElshadaiK/Competitive-Programming
/red_and_blue.py
687
3.65625
4
def maximizer(reds, blues): red_sum = 0 blue_sum = 0 max_red = 0 max_blue = 0 for red in reds: red_sum += int(red) max_red = max(max_red, red_sum) for blue in blues: blue_sum += int(blue) max_blue = max(max_blue, blue_sum) return max_blue+max_red if __nam...
22d40e2ed57691368bf4e08351191d7c4d2aac48
renzildourado/Algorithms_Independent_Study_Class
/password.py
1,535
3.921875
4
import sys def passwordCracker(passwords, attempt): # Complete this function attempt = "A" + attempt dynamic_prog_array = [False] * len(attempt) dynamic_prog_array[0] = True results = [] results.append("end") for i in range(1, len(attempt)): for word_in_dict in passw...
ff9e810acf5e6cfa4f31dcc44b2c49004f27d69b
rajitbanerjee/kattis
/Free Food/food.py
239
3.515625
4
"""https://open.kattis.com/problems/freefood""" N = int(input()) days = [] for _ in range(N): s, t = map(int, input().split()) for each in range(s, t+1): if each not in days: days.append(each) print(len(days))
2bee73009b46916b811a11c5b254a2e6b2e66149
rajitbanerjee/kattis
/No Duplicates/nodup.py
327
3.734375
4
"""https://open.kattis.com/problems/nodup""" line = input().split() freq = {} def isRep(line, freq): for each in line: if each not in freq: freq[each] = 0 freq[each] += 1 if freq[each] > 1: return "no" return "yes" print(isRep(line, freq)) ...
1df59596831d5603694a2d94ead67ace83f60428
rajitbanerjee/kattis
/Stacking Cups/cups.py
277
3.84375
4
"""https://open.kattis.com/problems/cups""" N = int(input()) cups, radii = {}, [] for _ in range(N): C, R = input().split() if C.isdigit(): C, R = R, int(C) // 2 cups[int(R)] = C radii.append(int(R)) for each in sorted(radii): print(cups[each])
8a9f0f93c3f4850a08992315458a78099f7ffc91
rajitbanerjee/kattis
/Weak Vertices/vert.py
1,203
3.703125
4
"""https://open.kattis.com/problems/weakvertices""" def weak(mat: list) -> str: ans = [] n = len(mat) for i in range(n): # there are less than 2 connected vertices or, # the connected vertices do not form a triangle if mat[i].count(1) < 2 or noTriangle(mat[i], mat): ans...
e705b762778b77f713312903839f5dda3a93e808
rajitbanerjee/kattis
/Eeny Meeny/eeny.py
554
3.765625
4
"""https://open.kattis.com/problems/eenymeeny""" rhyme = len(input().split()) n = int(input()) kids = [] for _ in range(n): kids.append(input()) teams = [[], []] choose, prev = 0, 0 while len(kids) > 0: # choose the kid at the end of the rhyme, starting from prev idx = (prev + rhyme - 1) % len(kids) ...
5f68e2f6053ad82307bbc1393442b96dab4c49cc
rajitbanerjee/kattis
/Avion/avion.py
253
3.53125
4
"""https://open.kattis.com/problems/avion""" codes = [] for _ in range(5): codes.append(input()) found = False for i in range(5): if "FBI" in codes[i]: print(i + 1, end=' ') found = True if not found: print("HE GOT AWAY!")
10c0ca50718bf1d90101fd89239d09a4b829a437
rajitbanerjee/kattis
/The Easiest Problem Is This One/easiest.py
372
3.53125
4
"""https://open.kattis.com/problems/easiest""" def sumDig(n): s = 0 for dig in str(n): s += int(dig) return s ans = [] while(True): N = int(input()) if N == 0: break p = 11 while(True): if sumDig(N * p) == sumDig(N): ans.append(p) break ...
883fce992b1bb646c91f6f855510062204065623
rajitbanerjee/kattis
/Railroad/railroad.py
155
3.5
4
"""https://open.kattis.com/problems/railroad2""" _, Y = map(int, input().split()) # same as Y % 2 == 1 print("impossible") if Y & 1 else print("possible")
f31c4b59bcecce48ee1232749dc635f85a4a2957
rajitbanerjee/kattis
/Left Beehind/beehind.py
389
3.765625
4
"""https://open.kattis.com/problems/leftbeehind""" ans = [] while True: x, y = map(int, input().split()) if (x, y) == (0, 0): break if x + y == 13: ans.append("Never speak again.") elif x > y: ans.append("To the convention.") elif x < y: ans.append("Left beehind.") ...
4dbeffc38a717bb1026e464c97c9f00f9f612a3b
rajitbanerjee/kattis
/Herman/herman.py
259
4
4
"""https://open.kattis.com/problems/herman""" from math import pi R = int(input()) # circle becomes a square with edge = sqrt(2 * r) def taxicab(R): return 2 * R * R def euclidian(R): return pi * R * R print(f"{euclidian(R)}\n{taxicab(R)}")
9dc49530fa2871579b459ec30285191da489f765
rajitbanerjee/kattis
/Provinces and Gold/prov.py
620
3.65625
4
"""https://open.kattis.com/problems/provincesandgold""" from collections import OrderedDict vic, tres = OrderedDict(), OrderedDict() vic = {"Province": 8, "Duchy": 5, "Estate": 2} tres = {"Gold": 6, "Silver": 3, "Copper": 0} inp = list(map(int, input().split())) money = inp[0] * 3 + inp[1] * 2 + inp[2] options = [] ...
706df22f30cb101a165e4cfe5b1873c562eafcbb
rajitbanerjee/kattis
/Line Them Up/line.py
271
3.609375
4
"""https://open.kattis.com/problems/lineup""" N = int(input()) players = [] for _ in range(N): players.append(input()) if players == sorted(players): print("INCREASING") elif players == sorted(players)[::-1]: print("DECREASING") else: print("NEITHER")
936b1b65b9e4a452ea5d98b3ac36df6d18d645cd
signofthefour/PPL
/FP/Question4.py
728
3.546875
4
def double(x): return x * 2 def increase(x): return x + 1 def square(x): return x * x # def compose(x, *args): # return compose(compose(x, *args[1:]), args[0]) if len(args) > 1 else args[0](x) def compose2(x, *args): from functools import reduce def compose(f, g): return lambda x : f...
afbc298dc7ee2758b20b39d91ae06ed889720b33
Haegin/hacksoc-emulator-notes
/lecture1/mem1.py
658
3.890625
4
class Memory: """A class to represent the memory store of our processor. """ def __init__(self, size): """Set up the memory, and reset it to all blanks. """ self.data = [] self.size = size self.reset() def reset(self): """Clear the contents of the memo...
45dc8830f242f81f074e88081d7155a368afa14f
hbaderman/algorithms
/swap.py
330
3.6875
4
# implement swap arr = [4,9,7,10,4,3,5,129,23] def findSmallest(arr): smallest = arr[0] for i in range(0,len(arr)): if ( arr[i] < smallest): smallest = arr[i] return smallest def selectionSort(arr): smallest = findSmallest(arr) secondSmallest = secondSmallest(arr,smallest) _sorted = selectionSort(arr) prin...
7e67906a790f004df57e8eed1a38fd0de53a1a25
Shaileshsachan/Algoexpert_problem_solution
/sorting/selection_sort.py
552
4.21875
4
def SelectonSort(list1): print(f'Unsorted Array: {list1}') for i in range(len(list1) - 1): min_index = i for j in range(i+1, len(list1)): if list1[j] < list1[min_index]: min_index = j if list1[i] != list1[min_index]: list1[i], list1[min_index] = li...
c96d75d18757185c2e9ea339c56d09950021f2ff
Shaileshsachan/Algoexpert_problem_solution
/MaxSubset.py
758
3.59375
4
# O(n) time | O(n) space def maxSubsetSumNoAdjacent(array): if not len(array): return elif len(array) == 1: return array[0] maxSums = array[:] maxSums[1] = max(array[0], array[1]) for i in range(2,len(array)): maxSums[i] = max(maxSums[i - 1], maxSums[i - 2] + array[i]) ...
525a6c976fc9c161c012dc5f0e715d8c502fcdcc
ashlie-li/GeorgiaTech
/cs7646/ML4T_2018Spring/strategy_learner/ManualStrategy.py
10,285
3.65625
4
""" Vincent La Georgia Tech ID: vla6 Strategy Learner -- Manual Strategy Code implementing a ManualStrategy object (your manual strategy). It should implement testPolicy() which returns a trades data frame (see below). The main part of this code should call marketsimcode as necessary to generate the plots used in the...
ef84d8959bba53504e35b7b2e34750d6012ef041
ashlie-li/GeorgiaTech
/cs6476/lectures/2a_l1_images_as_functions/testing.py
945
3.546875
4
from PIL import Image import numpy as np import os # Read image im = Image.open('ps0-1-a-1.png') im2 = Image.open('ps0-1-a-2.png') # Display image im.show() # Image size # (width, height) tuple size = im.size print(size) # Getting RGB Values pixels = list(im.getdata()) # Accessing a specific pixel print(im.getpixe...
8d040269d3ecf36538dd6a2c1de99d1ba79a20cc
ashlie-li/GeorgiaTech
/cs6476/problem_sets/ps0_python/ps0.py
4,522
3.78125
4
from PIL import Image import os import numpy as np def color_planes(im1, im2): """(a) Swap the red and blue pixels of image 1 Output: Store as ps0-2-a-1.png in the output folder (b) Create a monochrome image (img1_green) by selecting the green channel of image 1 Output: ps0-2-b-1.png ...
aec10ef730faa7874abc88c3649be827441b4b2a
dwkang92/learning-algorithm
/BOJ/basic_step/2753.py
469
3.734375
4
# 윤년은 연도가 4의 배수이면서, 100의 배수가 아닐 때 또는 400의 배수일 때이다. year = int(input()) if year % 4 != 0: print('0') elif year % 100 != 0: print('1') elif year % 400 != 0: print('0') else: print('1') # 아니면 이런 방법도 있다. 문제에서 제시해주는 내용 그대로 코드를 짜버리는 방법. if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: print...
6d7387733324e4f298709300822ae89316668c03
4leon/Self_Paced-Online
/students/christopher_gantt/lesson02/fizz_buzz.py
183
3.90625
4
for number in range(1,101): if number%5 == 0 and number%3 == 0: print('FizzBuzz') elif number%5 == 0: print('Buzz') elif number%3 == 0: print('Fizz') else: print(number)
d30f4551044ee335b04dc178f6432e380097598e
PhurbaGyalzen/Gyalzen
/exercise 1/9.py
121
3.96875
4
n=int(input("Input enter a positive integer:2")) sum=(n*(n+1))/2 print("The sum of the first n positive integer is:",sum)
dd43d49ed3f8b9b0c7851db1b5bd62ccd19cb24c
PhurbaGyalzen/Gyalzen
/exercise3/3.py
180
3.96875
4
def conversion(limit): a=0 while a < (limit): if a%2==0: print(str(a),"even") else: print(str(a),"odd") a=a+1 conversion(3)
0b4d0a0812579e02606085ed5eb59145f57eaa03
PhurbaGyalzen/Gyalzen
/exercise2/4.py
361
4.28125
4
number_1=int(input('number_1:')) number_2=int(input('number_2:')) number_3=int(input('number_3:')) if number_3 > number_2 and number_3 > number_1: print(f"{number_3} is greatest.") elif number_2 > number_3 and number_2 > number_1: print(f"{number_2} is greatest.") elif number_1 > number_2 and number_1 > number_...
42bb143238a706d20b33822544bacab53aab5d98
egene-huang/python-learn
/test-all/pyclass/access.py
2,128
4.4375
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- ## 访问控制 class Person(object): def __init__(self,name,age): self.name = name self.age = age def toString(self): print('我是%s,我%s岁了.' %(self.name,self.age)) p = Person('palm',25) p.toString() ## 我是palm,我25岁了. ## 可以随意修改 这个对象的属性值 p.name ...
820a54904cce0d1da89522eebfd0247017a801bc
egene-huang/python-learn
/test-all/pyclass/cls.py
2,797
4.21875
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- ## 在学习面向对象的时候, 我自做聪明误认为 __init__就是python class的构造方法, 其实不是 ## 查阅资料得知, 在执行 p = Person('测试',23)这行代码的时候, 首先调用的是 __new__这个类方法 ## __init__这个是实例方法,是在实例构造完成后 使用来处理实例属性值等类似工作的 地一个参数self 就是__new__构造出来的实例 # __ new__(cls, *args, **kwargs) 创建对象时调用,返回当前对象的一个实例;注意:这里的第一个参数是cls即class本身...
2b8d6ff84da2b400dd5e54461bc30ca5fe412f95
ascherer831/python_fundamentals
/python_fundamentals/for_loops_basic2/for_loops_basic2.py
5,062
4.5
4
# Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". # Example: biggie_size([-1, 3, 5, -5]) returns that same list, but whose values are now [-1, "big", "big", -5] # def biggie_size(list): # for i in range(len(list)): # if list[i] > 0: # list[i] ...
da07d8a83f32bb04d995d97bfc383736767bcbc0
zhimingshenjun/qtstyles
/qtstyles/picker.py
1,727
3.625
4
''' Defines StylePicker: a class that allows us to pick style sheets and collect their style sheet contents with get_sheet() ''' from qtstyles import errors from qtstyles.sheet import get_style_sheets class StylePicker(object): ''' The StylePicker class has the following properties: style: th...
5f004bd21d1553a87a446be505865cba2acd19a7
JustinCThomas/Codecademy
/Python/Calendar.py
2,021
4.125
4
"""This is a basic CRUD calendar application made in Python""" from time import sleep, strftime NAME = "George" calendar = {} def welcome(): print("Welcome", NAME) print("Opening calendar...") sleep(1) print(strftime("%A %B %d, %Y")) print(strftime("%H:%M:%S")) sleep(1) print("What would you like to do...
f71519df56b58cf832c396c0a91f9ad4e67ae267
mqy9811/abcd
/multproessing/10.py
847
3.609375
4
import threading import time def fun1(delay): print("现在运行的是线程--{}".format(threading.current_thread().getName())) time.sleep(delay) print("线程:{} 运行结束".format(threading.current_thread().getName())) def fun2(delay): print("现在运行的是线程--{}".format(threading.current_thread().getName())) time.sleep(delay)...
63af27a2f278e83659b46ee38f9d3e3437060220
LiamLowndes/CodeSignal-Solutions
/sudoku2/Answer.py
1,260
3.8125
4
def sudoku2(grid): #check row for i in range(9): if not check_line(grid[i]): return(False) #check col for i in range(9): col = [] for j in range(9): col.append(grid[j][i]) if not check_line(col): return(False) #check squar...
ade9c56c334381fec834d9449d57ed15584bd4b2
jjhua/tusharetest
/buildModel/testMaxDict.py
179
3.859375
4
#coding=utf-8 # dict = {'Alice': 2341, 'Beth': 9102, 'Cecil': 3258} # dict = sorted(dict.items(),key=lambda item:item[1],reverse=1) # for i in range(0,2): # print(dict[i])
9bb1dbcbc48fb65bfed606042aae9ff59fda5655
jiankang/pylab
/cfb.py
377
3.953125
4
#!/usr/local/bin/python3 import argparse parser = argparse.ArgumentParser(description="打印乘法表") parser.add_argument("-n", metavar='N', default=10, type=int, help="打印NxN乘法表") args = parser.parse_args() n = args.n for i in range(1,n): for j in range(1,i+1): print("{0:12}".format("{0}x{1}={2}"...
2a35c4bcc58d4e2399fe796c47995344b509d0f9
devskyfly/programming
/Python/old/simple_tps.py
664
3.578125
4
#Boolean tr = True fl = False print(tr and fl) print(tr or fl) print(tr + 0) print(fl + 1) #Numbers intg = 1 print(type(intg)) flt = 0.5 print(type(flt)) val = 2 * 0.5 print(val) val = 4/2 print(val) val = 5/2 print(val) val = 5/2.0 print(val) #Strings str1 = "string" print(id(str1)) str2 = "string" print(id(s...
9850d298081a9607991d75aa78fb7fda9bfd6593
xblh2018/LintCodePython
/LongestWord/Solution.py
501
3.609375
4
class Solution: # @param dictionary: a list of strings # @return: a list of strings def longestWords(self, dictionary): # write your code here res = [] if dictionary is None or len(dictionary) == 0: return res max = 0 for s in dictionary: if...
476747eca31ed3b1112c7bca54544cccfe5bb81a
xblh2018/LintCodePython
/StringPermutation/Solution.py
694
3.5625
4
class Solution: # @param {string} A a string # @param {string} B a string # @return {boolean} a boolean def stringPermutation(self, A, B): # Write your code here if A is None and B is None: return True if A is None or B is None: return False if l...
7996934a7bae3c59cdbb9b33bc81bc7668c20490
xblh2018/LintCodePython
/ConvertBSTToGreaterTree/Solution.py
716
3.75
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: # @param {TreeNode} root the root of binary tree # @return {TreeNode} the new root def convertBST(self, root): # Write your code here ...
32918dbb78fe40e035bf91d235e287399f668a24
xblh2018/LintCodePython
/RemoveDuplicatesfromSortedList/Solution.py
560
3.9375
4
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: A ListNode @return: A ListNode """ def deleteDuplicates(self, head): # write your code here if head is No...
1784bc843757392a1f1fa96c1d0780604fd3e635
xblh2018/LintCodePython
/PartitionList/Solution.py
874
3.984375
4
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ from ListNode import ListNode class Solution: """ @param head: The first node of linked list. @param x: an integer @return: a ListNode """ def partit...
da64405ede59d187cd874180c2f86fbe69239ebf
xblh2018/LintCodePython
/MajorityNumber/Solution.py
555
3.703125
4
class Solution: """ @param nums: A list of integers @return: The majority number """ def majorityNumber(self, nums): # write your code here if nums is None or len(nums) == 0: return 0 if len(nums) == 1: return nums[0] res = nums[0] c...
35bf42a64e0fef3601665c1876fdb56da57d0ad6
xblh2018/LintCodePython
/APlusBProblem/Solution.py
472
3.546875
4
class Solution: """ @param a: The first integer @param b: The second integer @return: The sum of a and b """ def aplusb(self, a, b): # write your code here, try to do it without arithmetic operators. res = 0 c = 0 for i in range(0, 32): res = res | ...
072097c463dda770214a4e914d76809e72603d0d
xblh2018/LintCodePython
/MergeIntervals/Solution.py
947
4.03125
4
""" Definition of Interval. class Interval(object): def __init__(self, start, end): self.start = start self.end = end """ class Solution: # @param intervals, a list of Interval # @return a list of Interval def merge(self, intervals): # write your code here if intervals ...
24dbab784da36ecf5f7301d0f909e86fe01b2f8c
xblh2018/LintCodePython
/SortIntegersII/MergeSort.py
1,272
3.53125
4
class Solution: # @param {int[]} A an integer array # @return nothing def sortIntegers2(self, A): # Write your code here if A is None or len(A) <= 1: return self.mergesort(A, 0, len(A) - 1) return def mergesort(self, nums, start, end): if start >= en...
7a40ac25c5140b55cccb90cb6de16b574d1564a9
zxcvbn848/TraningPlan2021
/WK2_Python&JavaScript/WK2-Python_Basic.py
2,991
3.984375
4
# 要求一:函式與流程控制 # 完成以下函式,在函式中 使用迴圈 計算最小值到最大值之間,所有整數的總和。 def calculate(min, max): sum = 0 for x in range(min, max + 1): sum += x print(sum) calculate(1, 3) # 要能夠計算 p1 + 2 + 3,最後印出 6 calculate(4, 8) # 要能夠計算 4 + 5 + 6 + 7 + 8,最後印出 30 # =============================== # 要求二:Python 字典與列表、JavaSc...