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
7bfecdfe9b0c5e2849a3686060b14e970d9ce931
OleskaL/CURSOR_HW
/HW_5.py
6,582
4.3125
4
# 1. class Laptop: """ Make the class with composition. """ def __init__(self, laptop_manufacturer, hours_of_work): self.laptop_manufacturer = laptop_manufacturer self.battery = Battery(hours_of_work) def __str__(self): return f'{self.battery}' class Battery: """ Ma...
ecd6d5a4dd312d52e8342ca443c3b43e35769397
maryam800/simple_snake_game
/snake.py
3,156
3.640625
4
import turtle import time import random #Variable decleration delay=0.1 score=0 high_score=0 segments=[] #set up the screen wn=turtle.Screen() wn.title("Snake game by Maryam Ali") wn.setup(width=600, height=600) wn.bgcolor("#007f00") wn.tracer(0)#turnoff the animation # Snake head head=turtle.Turtle() head.speed(1)...
8a0dc7fd345a41b7654b7ebfa91d428fe4eae0a0
avalouev/basic_algorithms
/counting_sort/counting_sort.py
1,005
3.59375
4
def counting_sort(A, B, k): assert(len(A) == len(B)) # input and sorted output sizes match # init temp list for working storage C = [0] * k for j in range(len(A)): C[A[j]] = C[A[j]] + 1 # C now contains the number of elements equal to i+1 for i in range(k): C[i] = C[i] + C[i-1] # C now contains the number ...
9f46d64a71da6c0f76d1ee2cfea186c3acfb191c
tonquangtu/HackerRank
/largest_sub_array/largest_sub_arr.py
1,326
3.65625
4
# Way 1: Using divide and conquer. def find_largest_sub_arr(arr): return find_max_sub(arr, 0, len(arr) - 1) def find_max_sub(arr, start, end): if start >= end: return arr[start] medium = int((start + end) / 2) # Find largest sub array in left ml = find_max_sub(arr, start, medium) # F...
161e68967d27b530a2382f16b6c43fdd7ca01d7d
ramyasutraye/PythonProgramming-5
/Beginnerlevel/count.py
95
3.84375
4
count=0 a=int(input("Enter the integer:")) while(a!=0): a=a//10 count=count+1 print(count)
11fa97e6729ca71dbc9bc74872522f2a0d8e163c
ramyasutraye/PythonProgramming-5
/Beginnerlevel/multiple.py
68
3.625
4
a=int(input()) s=[] for i in range(1,6): s.append(a*i) print(s)
d493636932a8dcf35fcee05c40c6b45237294efc
jibinsamreji/Python
/Python_Basics/forLoop.py
743
3.734375
4
for item in 'Jibin Sam': print(item) for itemList in ['Jibin', 'Sam', 'Reji']: print(itemList) for rangeList in range(10): print(rangeList) for rangeListR in range(1, 10, 2): print(rangeListR) price = [10, 20, 30] for total in price: total += total print(f"Total at payout : {total}") # Nested L...
987adf3d6c77ee903e0cf74b398c8cfdcb2d54f3
jibinsamreji/Python
/MIni_Projects/carGameBody.py
964
4.15625
4
print("Welcome player! Type 'help' for more options..!") user_input = input(">") i = 0 start = False stop = False while user_input.upper() == "HELP": if i < 1: print(""" start - to start the car stop - to stop the car quit - to exit""") i += 1 game_option = input(">").upper()...
fed672f2fd343c1e0abec6bd799363dba8ee7b99
davidncuba/Enigma-Machine-Python
/cdc.py
1,683
3.734375
4
def SalvaMensagem(resultado): with open('senhascdc.txt', 'a+') as file: file.write(f'{resultado};') print('Salvo com sucesso') def MensagensCriptografadas(): with open('senhascdc.txt', 'r') as file: mensagens = file.read() mensagens = mensagens.split(';') for mensagem in men...
b08160ac9c880c3f08d4d117fe190b71514c49cd
VisionistInc/advent-of-code-2015
/rawjoe/01/sol.py
343
3.515625
4
with open('input', 'r') as file: input = file.read() up = input.count('(') down = input.count(')') print("Part 1: %d" % (up-down)) floor = 0 count = 0 for c in input: count += 1 if c is '(': floor += 1 else: floor -= 1 if floor == -1: break print(...
823a72c5049f1b0df23c64169a5ac9a127e1ec0a
KEVINWANGXIANG/Scrapy_and_Data_analyse
/day13/1-数据变换.py
1,062
3.9375
4
''' 常见的函数变换包括:开方,平方,对数 数据规范化: 1.离差标准化(最小最大标准化)--消除量纲(单位)影响以及编变异大小因素的影响 x1=(x-min)/(max-min) 2.标准差标准化(零-均值标准化)--消除单位影响以及变量自身变异影响 x1=(x-平均数)/标准差 3.小数定标规范化--消除单位影响 x1=x/10^k k=log10(x的绝对值的最大值) ''' import numpy import pymysql import pandas import matplotlib.pylab import math conn = pymysql.connect(host="127.0.0.1", ...
63393f1781d5bd1afeb5d195dc4c591e6a3ea97d
KEVINWANGXIANG/Scrapy_and_Data_analyse
/day11/数据挖掘/2-numpy模块.py
473
3.921875
4
import numpy # import numpy as nn 别名 #创建一维数组 x = numpy.array(["a", "9", "8", "2", "abcd"]) print(x) print(x[1]) print(type(x)) #创建二维数组 x2 = numpy.array([[5, 4, 6], [1, 2, 3], [9, 8, 7]]) print(x2) print(x2[1][2]) print(type(x2)) #排序 sort # x.sort() # print(x) # x2.sort() # print(x2) #取最大值和最小值 y1 = x2.max() print(y...
d7ac4f4df607624664e4dbd869c7c9e70516846d
KEVINWANGXIANG/Scrapy_and_Data_analyse
/day12/1-matplotlib基础.py
1,267
3.625
4
import matplotlib.pylab import numpy #折线图/散点图plot x = [1, 2, 3, 4, 8] y = [5, 7, 2, 1, 5] # matplotlib.pylab.plot(x, y)#plot(x轴数据,y轴数据,展现形式) # matplotlib.pylab.plot(x, y, 'o') #设置颜色 c-cyan青色, r-red, m-magente品红, g-green, b-blue, y-yellow, k-black, w-white # matplotlib.pylab.plot(x, y, 'or') # matplotlib.pylab.show()...
e6f6adf6e3a6685290c9995f7a2bec2948bdaf28
swlincode/standard-deviation
/my_sd_function.py
686
3.703125
4
import math, random class MyMath: def __init__(self, values): self.values = values def sd_func(self): sum_values = 0 for i in self.values: sum_values += i number_values = len(self.values) mean_values = sum_values / number_values sum_count_values =...
dd7235c285252a967ca25015f5f7a449b84c27d6
j4cobgarby/pluto-lang
/obj.py
5,440
3.640625
4
# Types which the user should never directly see ERROR = "<!error>" RETURN_VALUE = "<!return value>" FUNCTION = "<!function>" NEXT = "<next>" BREAK = "<break>" # Normal types NUMBER = "<number>" BOOLEAN = "<boolean>" STRING = "<string>" CHAR = "<char>" ARRAY = "<array>" NULL = "<nu...
1992f4e10928888ed89763d6ec7d1c9e111fa9e4
CaseysC/PGV
/pgv/get_top2.py
543
3.859375
4
from collections import Counter ## return [1st, 2nd] or [1st] def get_top2(neighbors): res = [] top3 = Counter(neighbors).most_common(3) ## only one node in neighbors if len(top3) == 1: res = [top3[0][0]] ## only two nodes in neighbors elif len(top3) == 2: res = [top3[0][0], top3[1][0]] ## >= 3 nodes else...
083157a52b1887f7042cf173d430353a9a030f8e
Djcarrillo6/TwilioQuest-Python
/functions.py
321
3.53125
4
import sys first_number = float(sys.argv[1]) second_number = float(sys.argv[2]) # hail_friend(captain) # For the glory Python and the Pythonic Temple!! def add_numbers(first_number, second_number): resulting_sum = first_number + second_number return resulting_sum add_numbers(first_number, second_number)...
a99bdf458c70f9dc3f2e469a82e229ea88b2ad3f
Sanskrati18/MindReaderGame
/main.py
1,110
3.78125
4
import random count_zero=0 count_one=0 player_score=0 computer_score=0 def prediction(): if count_zero>count_one : predict=0 elif count_one>count_zero : predict=1 else : predict=random.randint(0,1) return predict def update_counts(player_input): global count_zero, count_one if player_input==...
f22725c37bb2582a2809a17c8fae79e9af45ece1
riven314/SelfDrivingCar_Simulator
/log_file.py
6,328
3.890625
4
""" General functions applied on log file, such as: 1. distribution query on steering angle 2. create header for log file if headless 3. copy log file 4. deleted some rows with specified steering angle 5. append augmented data on log file 6. change path for log file remarks: 1. assume log file name is 'driving_log.csv...
c5141fca58644fc97a84f6cd3ced88d83dcdb736
SpeckledFern/362_Homework7
/programs.py
458
3.703125
4
def output_at(x): if(x%5 == 0): if(x%3 == 0): return "FizzBuzz" return "Buzz" elif(x%3 == 0): return "Fizz" else: return x def list_print(): for x in range(1,101): print(output_at(x)) return x def leap(y): if(y%4 == 0): if (y%100 == 0): if(y%400 ==...
0600c55c8b6d406d9d7a4a894a72dbb5f3f92c69
JudeLabs/freemindtocsv
/freemindconvert3.py
4,520
3.546875
4
from array import * last_position = 0 x = 0 y = 0 initlist = list() last_position = 0 first_run_flag = 0 position = -1 global num def init_array(): global req_array req_array = [[0 for x in range(20)] for x in range(400)] def get_title_and_note(num, pos, position): global last_position global first...
56bcc59e315653bc8e1bd81d9887fb18cd57c7d3
buddharajuramaraju/Acadglid_Session_1
/Assignment2.py
524
4.03125
4
# coding: utf-8 # ### Session1 # Assignment-2 # Problem Statement # # Write a program which will find all such numbers which are divisible by 7 but are not a # multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be # printed in a comma-separated sequence on a single line. # # In[7]: ...
408ffc3f89cd3fe9bc8896486cb00bdecadcaee0
FennaHD/cs465
/aes/key_expander.py
2,700
3.8125
4
from ff_math import FFMath as ffm from r_con import Rcon as rc from s_box import SBox class KeyExpander: """ Class in charge of performing all operations involving key expansion. Is also in charge of transforming input into the format we want to work with. So far we are inputting a string of space separated bytes...
53d4fe0c67ea59645c94e47f8a131aee9aec0dc1
armenjuhl/MoorishCodeEncrypter
/myVigenere.py
2,904
3.859375
4
def alphabet_position(letter): if letter.isupper(): upperc_position_letter = ord(letter) - 64 return upperc_position_letter if letter.islower(): lowerc_position_letter = ord(letter) - 96 return lowerc_position_letter def rotate_character(char, rot): #to p...
5e39ab9ee7977e7b3eb121cfc49450964ce28e74
jiamiaohao/python
/1月11日/hanshu求和.py
112
3.515625
4
def sum(a,b): sum = 0 for i in range(a,b+1): sum += i print(sum) sum(1,100)
42095b82443ea778923f49994c6b617338e40163
jiamiaohao/python
/练习/练习方法例题.py
973
3.671875
4
class Person(object): def play_computergames(self): print("玩游戏") def sleep(self): print("该睡觉了") class Father(Person): def __init__(self,name): self.name = name def play_computergames(self): print("%s在玩游戏"%self.name) class Mather(Person): def __init__(self,name): self.name = name def sleep(self): ...
d94035ea197609af0ae827aec443c72e7f272910
jiamiaohao/python
/1月8号/个人信息系统.py
774
3.78125
4
tip = "个人信息管理系统" print(tip.center(40,"*")) list = [] while True: mode = int(input("请选择功能 1、新增 2、查看 3、修改 4、删除 5、退出:")) if mode == 1: name = input("输入名字:") age = input("输入年龄:") sex = input("输入性别:") job = input("输入工作:") list.append(name) list.append(age) list.append(sex) list.append(job) prin...
413cecd1cec40a89d6a71a92e5315e20a1c4fe70
jiamiaohao/python
/练习/异常.py
236
3.625
4
def print_passwd(): #用户输入密码 pwd = input("请输入密码:") #对输入密码进行判断 if len(pwd) > 8: print("密码正确") else: print("密码错误") ex = Exception("密码长度少于8位") raise ex
c6f4b2abb328c5e45ee116e3dab4b0f0fdcb54bc
EmillyLopes/projetos-em-python
/ex3.py
854
4.03125
4
from time import sleep for a in range(0,2) : A = float(input("Digite um número: ")) B = float(input("Digite um número: ")) opcao = int(input(''' Selecione uma operação:\n1 | Média entre os números digitados\n2 | Diferença do maior pelo menor 3 | Produto entre os números digitados\n4 | Divisão do primeir...
04843452be850af019af43f042a02f29c9e6f1fa
EmillyLopes/projetos-em-python
/ex4.py
286
3.9375
4
salario= float(input("Digite o seu salário:")) if salario < 300: salario= salario + (salario * 0.45) elif 300 <= salario < 600: salario= salario + (salario * 0.25) elif salario > 600: salario= salario + (salario * 0.15) print("O Salário reajustado é:",salario, "reais")
f22de54567e896876b852be140a67d3058133085
EmillyLopes/projetos-em-python
/ex10.py
738
3.765625
4
c = 1 while c != 0 : print("----------------------------------------------") print("""1- Caderno - R$ 12.00 |2- Régua - R$ 2.50 | 3- Borracha - R$ 0.25 |4- Mochila - R$ 50.00 | """) print("----------------------------------------------") c = int(input("Digite o código do produto: ")) q= int(input...
d53e4469e2b5acf4bf4aa8de51fbcecc9be65692
EmillyLopes/projetos-em-python
/lista.py
290
3.921875
4
lista = ["detergente","desinfetante","agua sanitaria","sabão em pó","luva","papel toalha"] print(lista) lista[0]= "sabão em barra" print(len(lista)) print(lista[len(lista)- 1]) lista.remove("desinfetante") lista2= ["esponja","vassoura", "espanador"] lista3 = lista + lista2 print(lista3)
6b685c474fbcc1928ac6ae57356eebcfb4fd8d9b
gsraditya/chatbot
/SpeechTranslation/text_to_speech.py
1,222
3.5625
4
# Sai Raghavendra Aditya # Notes: # 1. Accept user specific language text and convert to english # 2. Remove Stop words # 3. english text -> voice import pyttsx3 import traceback from textblob import TextBlob from google_trans_new import google_translator,LANGUAGES from translate_eng import Translate cl...
d7d5c671c98cf5e2959a7da2c1a186cf83de7745
dfhampshire/RInChI
/rinchi_add.py
1,522
3.5
4
#!/usr/bin/env python3 """ RInChI Addition Script ---------------------- This script adds together flat files of RInChIs separated by newlines. Modifications: - C.H.G. Allen 2012 - D.F. Hampshire 2016 Rewritten to use argparse module and Python3 """ import argparse from rinchi_tools import tools, utils ...
3d8b2938eed4cd2d299218d4dd787d80518e8154
victorsibanda/python-basics
/102_python_data_types.py
1,696
4.59375
5
#Strings #Text and Characters #Syntax #"" and '' #Define a string #Anything that is text is a string my_string = 'Hey I am a cool string B)' print(my_string) type(my_string) #Concatenation joint_string = 'Hey I am another' + ' cool string, ' + my_string print (joint_string) #example two of concatenation name = 'M...
11db910c5a2842e1c8b03abf5b2b50a88f74d6b9
victorsibanda/python-basics
/exercises/exercise_112_3.py
636
4
4
user_input = ' ' while user_input != 'pineapple': user_input = input("Input?\n") if user_input.isdigit(): user_input = int(user_input) for number in range(1,user_input+1): if (number % 3 == 0) and (number % 5 == 0): print('Bizzuu',number) elif number %...
faa0ffceb30031674446ed24efdb4e6085fa9873
victorsibanda/python-basics
/101_python_variables_print_type.py
531
4.1875
4
# Variables # it is like a box, you give it a name, and put stuff inside book = 'Rich dad poor dad' ## Print function #Outputs content to the terminal (makes it visible) print(book) # Type function #Allows us to check data types data_type_of_book = type(book) print (data_type_of_book) #input() - prompt for user...
d6320818cdbf2b26bcffb410c1cad8e27ef9477f
devionb/MIM_Software_code_sample
/Part_A.py
642
4.375
4
# Devion Buchynsky # Part A - Reverse the string if its length is a multiple of 4. # multiples of 4: 4,8,12,16...... multiple_of_4_string_letter = 'abcd' multiple_of_5_string_letter = 'abcde' print('Before function is ran.') print(multiple_of_4_string_letter) print(multiple_of_5_string_letter) def reverse_string(s...
bbc16620f949ba8f7a270d5318ff40d19fcbbe61
jackdewinter/pymarkdown
/test/test_listfiles.py
13,334
3.5
4
""" Module to provide tests related to the "-l" option. """ import os from test.markdown_scanner import MarkdownScanner def test_markdown_with_dash_h(): """ Test to make sure we get help if '-h' is supplied """ # Arrange scanner = MarkdownScanner() supplied_arguments = ["scan", "-h"] exp...
ea382afa0a9c70c78d0b472c4d2210c1cc7272a4
patricegamakuoh/Python_Arduino_IDE1
/Examples/Basic_Controls/10-0-Servos.py
552
3.65625
4
'''servo control''' from Arduino import Arduino import time board = Arduino(port="COM14") #choose your COM port=" " while 1: anglerange=[0,50,100,180] #declare Angle range for angles in anglerange: #for loop board.Servos.attach(10) #attach the desired digit...
70652c1cac26b2cdf8ad9f48f5100f367674db76
patricegamakuoh/Python_Arduino_IDE1
/Examples/Basic_Controls/10-1-ServoDemo.py
1,596
3.640625
4
from Arduino import Arduino import time port="COM14" #Change the COMport '''Defined functions here''' def ServoSweep(ServoPin): """ 从 o 扫描伺服到 180 和回 Sweep Servo from o to 180 and back """ board = Arduino(port=port) while True: board.Servos.attach(ServoPin) #attach the servo pin ...
439598aac4f7f16ea0b2a6ec378dfb9be4f435a7
hauntgossamer/Sprint-Challenge--Data-Structures-Python
/reverse/reverse.py
1,887
4.09375
4
class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList:...
8aa68030c777bfabcaf4069dd9bc197b2516956c
PlumpMath/Lisp-C-Compyler
/labels.py
1,026
3.8125
4
# labels labels = [] def branchesAndInfos(labels): branches = [makeLabel(label) for label in labels] infos = [labelInfo(branch) for branch in branches] return (branches, infos) def labelInfo(label): print_info = 'print_info("%(label)s");' % locals() return (label + ':' + ' ' + print_info) # label numbering la...
2fe3874291e19f84c98d7f391ca174e285e010d1
synapse99/20190504
/파이썬/20190504/startend.py
269
3.625
4
def print19(st, ed): for i in range(st, ed+1): print(i, end=" ") print() s = int(input("시작 값 입력 : ")) e = int(input("끝 값 입력 : ")) if (s<e): print19(s,e) else: ("시작값이 끝값보다 작아야 합니다.")
ba22854cb5a39ea00c2d0984ad4e36734d627da0
ddevlin/advent-of-code-2020
/day_02.py
1,211
3.65625
4
from dataclasses import dataclass from re import compile from typing import Sequence, Tuple @dataclass class Password: arg1: int arg2: int char: str text: str def part_1(passwords: Sequence[Password]) -> int: return len([p for p in passwords if p.arg1 <= p.text.count(p.char) <= p.arg2]) def pa...
24b6529bbf9f87e097ce3c96723a02585c18e606
TheTechAccountant/python_practice
/Python Division.py
204
3.640625
4
if __name__ == '__main__': a = int(input()) b = int(input()) #This contains integer division a//b i.e. To a whole number print(a//b) #This contains float division i.e. decimal places print(a/b)
064a088d379dc1010eaa365e9857615bcd8f4d56
diallog/PY4E
/assignment5.2/assignment5.2_noIntTest.py
1,133
4.1875
4
# Assignment 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the ...
4b0ec224525c1b9e584710cbe2456aa7c2f9000d
diallog/PY4E
/assignment2.3/assignment2.3.py
606
4.21875
4
# This assignment will obtain two pieces of data from the user and perform a calculation. # This script begins with a hint from the course...but lets do a little over-achievement. print("Alright, let's do our first calculation in Python using information obtained from the user.\r") # This first line is provided for ...
1cf41e90b96bd90d88b8f7397fbc3dc0935ea4fb
priyanshu3666/my-lab-practice-codes
/if_elif_else_3.py
492
3.90625
4
#program started amount = int(input("Enter the amount of shopping by customer")) if amount > 25000: discount = amount*0.20 amount = amount - discount print("GOLD CUSTOMER \n the amount to be paid =",amount) elif amount>10000 and amount<=25000: discount = amount*0.10 amount = amount - discount print("SILVER CUSTOM...
5ca9a7f9fec6fbab5642a6d1fc52d4c17ec4c32b
priyanshu3666/my-lab-practice-codes
/program5.py
177
4.1875
4
#program started num1 = int(input("Enter 1st number")) num2 = int(input("Enter 2nd number")) product = num1*num2 print("The product of ",num1,num2," is ",product) #program Ends
7c023a7743c6f76a6f4c5b2bd46535ccae3d2efe
priyanshu3666/my-lab-practice-codes
/if_else_1.py
237
4.21875
4
#Program started num = int(input("Enter a number")) #input taking from user if (num%2) == 0 : #logic start print("The inputted muber",num," is Even") else : print("The inputted muber",num," is Odd") #logic ends #Program Ends
cc2debc19438dbc38391898f443d47c5867cb713
tongxinw/data1050
/cp03-hash-tables-sorting-tongxinw/epi_judge_python/cp3/heap_sort.py
1,065
3.65625
4
#!/usr/bin/env python # coding: utf-8 # %% from myBinHeap import myBinHeap # %% def heap_sort(L, key = None): bh = myBinHeap(key = key) bh.buildHeap(L) for i in range(len(L)): bh.delMin() return L # %% # def heap_Sort(arr): # n = len(arr) # # Build heap (rearrange array) # f...
1f3007154c8734dce197638aae123261f4fd3eca
iamdoublewei/Leetcode
/Python3/125. Valid Palindrome.py
983
4.28125
4
''' Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false ''' #Orig...
336f4764f1208ed1e8cea45946a6e097187ec098
iamdoublewei/Leetcode
/Python3/1507. Reformat Date.py
1,545
4.375
4
''' Given a date string in the form Day Month Year, where: Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}. Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}. Year is in the range [1900, 2100]. Convert the date string to the format YYYY-MM-DD, ...
5626569c71a78ab20b2923e9d7dc37c4584edbd4
iamdoublewei/Leetcode
/Python3/692. Top K Frequent Words.py
1,304
4.09375
4
''' Given an array of strings words and an integer k, return the k most frequent strings. Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order. Example 1: Input: words = ["i","love","leetcode","i","love","coding"], k = 2 Output: ["...
4c586049e03bdb010781f3dd5eb6f14e7869d759
iamdoublewei/Leetcode
/Python3/2235. Add Two Integers.py
821
4.03125
4
''' Given two integers num1 and num2, return the sum of the two integers. Example 1: Input: num1 = 12, num2 = 5 Output: 17 Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. Example 2: Input: num1 = -10, num2 = 4 Output: -6 Explanation: num1 + num2 = -6, so -6 is returned. ''' #A...
79fa43692527c73ad8d997130d2e458ecb53a8d4
iamdoublewei/Leetcode
/Python3/1752. Check if Array Is Sorted and Rotated.py
1,348
3.90625
4
''' Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false. There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[...
873c717632dc897658651a53f5728e97cb03f8ca
iamdoublewei/Leetcode
/Python3/1539. Kth Missing Positive Number.py
1,006
3.75
4
''' Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Return the kth positive integer that is missing from this array. Example 1: Input: arr = [2,3,4,7,11], k = 5 Output: 9 Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing posit...
4cff4656aff4218a5cd17c4ce4579dad2f18b325
iamdoublewei/Leetcode
/Python3/1046. Last Stone Weight.py
1,305
3.8125
4
''' You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is: If x == y, both s...
ce27ffc885a80945dc8e09c7b3b7e067260240f1
iamdoublewei/Leetcode
/Python3/1207. Unique Number of Occurrences.py
763
4.03125
4
''' Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise. Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. Example 2: I...
38e0976de0b8376345610a411550df8ca5639293
iamdoublewei/Leetcode
/Python3/680. Valid Palindrome II.py
1,005
4.15625
4
''' Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You could delete the character 'c'. Note: The string will only contain lowercase characters a-z. The maximum length o...
f945997346557c32cbca525c4ee4df21fe808c03
iamdoublewei/Leetcode
/Python3/653. Two Sum IV - Input is a BST.py
782
3.9375
4
''' Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. Example 1: Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 Output: True Example 2: Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 28 Output: ...
84a99ce38f0a9fa7e7456be2ec28f70c54b8d41d
iamdoublewei/Leetcode
/Python3/849. Maximize Distance to Closest Person.py
1,464
4.25
4
''' In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return that maximum distance to...
98ceacd32d0924643b4f6caa745e67c3f754951e
iamdoublewei/Leetcode
/Python3/417. Pacific Atlantic Water Flow.py
2,184
4.40625
4
''' There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an m x n integer matrix he...
06603409c216e418a50c655532a82a17429f040c
iamdoublewei/Leetcode
/Python3/2000. Reverse Prefix of Word.py
1,366
4.40625
4
''' Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that start...
b0dbac6457c43e8934e6cbd384a88a8f6bb90aeb
iamdoublewei/Leetcode
/Python3/869. Reordered Power of 2.py
622
3.953125
4
''' You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return true if and only if we can do this so that the resulting number is a power of two. Example 1: Input: n = 1 Output: true Example 2: Input: n = 10 Output: false Const...
da1ced72b390ad02518acf1327bb3c696655c9ac
iamdoublewei/Leetcode
/Python3/567. Permutation in String.py
786
3.953125
4
''' Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is the substring of s2. Example 1: Input: s1 = "ab", s2 = "eidbaooo" Output: true Explanation: s2 contains one permutation of s1 ("ba"). Example 2: Input: s...
bdd9b3128039c0072638b994a98f3bb0f835cec1
iamdoublewei/Leetcode
/Python3/2114. Maximum Number of Words Found in Sentences.py
1,476
4.0625
4
''' A sentence is a list of words that are separated by a single space with no leading or trailing spaces. You are given an array of strings sentences, where each sentences[i] represents a single sentence. Return the maximum number of words that appear in a single sentence. Example 1: Input: sentences = ["alice ...
dac0c2bd358e88a9ad7a067c8a8c08f194d8217e
iamdoublewei/Leetcode
/Python3/504. Base 7.py
575
4.0625
4
''' Given an integer, return its base 7 string representation. Example 1: Input: 100 Output: "202" Example 2: Input: -7 Output: "-10" Note: The input will be in range of [-1e7, 1e7]. ''' class Solution: def convertToBase7(self, num): """ :type num: int :rtype: str """ res =...
096013bb648559b092f07e04f09000e9e3574427
iamdoublewei/Leetcode
/Python3/367. Valid Perfect Square.py
699
4.03125
4
''' Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Output: true Example 2: Input: 14 Output: false ''' class Solution: def isPerfectSquare(self, num): """ ...
d6d6a095492d5503f35f35af515b905d4f685e10
yuhsuann/final-report
/final report.py
1,356
3.9375
4
n = 0 while n < 15: print("Oh ya!!!!") n = n+1 print("看到你太開心了啦") print("小哥哥小姊姊你好!我叫做模擬卡!我是你的聊天機器人") skill = ("我可以陪你聊天~什麼話題都可以哦~") print(skill) name = input("阿忘了問你名字!你叫什麼名字啊?:") print("我叫", name) print("哈囉",name, "很高興能成為你的朋友") # country = input("你喜歡去哪個國家玩啊?:") print("哦~原來你喜歡",country) print("好剛好哦~我也喜歡誒~") 文化 =...
adcfe22a5b713b76ac4eed926d1ee2e29e934619
hannykee/trial
/문자열 반복 누적.py
154
4.03125
4
#print라는 문자열을 한 단어씩 누적 반복하여 출력하기 txt = "print" i=0 for i in range(0,len(txt)+1): print(str(txt[0:i]))
c6e95d619b115dfd1fd128b21d786d08f9f3b2b9
hannykee/trial
/공백 문자열에서 단어만 리스트로 추출,숫자만 추출,값 이외에 위치까지 함께.py
437
3.828125
4
#findall은 list로 넘어온다. #공백이 있는 문자열에서 단어만 뽑기 import re p=re.compile('[a-z]+') result=p.findall("life is too short") print(result) #숫자만 추출하기 re.findall("\d+","서진수는 1975년 10월 23일 입니다 ^^") #값 이외에 위치까지 함께 r=re.compile("[a-zA-Z]+") result=r.finditer("My birthday is October 23th.") for i in result: print(i.group())...
bf177b7cb15c85d63d6dc27f1e68bf2abc682af2
ck032/quant-trading
/Bollinger Bands Pattern Recognition backtest.py
8,423
3.6875
4
# coding: utf-8 # In[1]: #bollinger bands is a simple indicator #just moving average plus moving standard deviation #but pattern recognition is a differenct case #visualization is easy for human to identify the pattern #but for the machines, we gotta find a different approach #when we talk about pattern recognition ...
f92df7e532c846388d6a48bcb74882b721533e99
jillasuresh/jillasuresh4
/armstronginterval.py
148
3.59375
4
for n in range(1,100): sum = 0 temp=n while temp>0: digit=temp%10 sum+= digit**3 temp//=10 if n==sum: print(n)
2a6cd05450cda6dfc30d694431bcb2cc1571775b
jillasuresh/jillasuresh4
/prime.py
136
4.03125
4
n= int(input("") for i in range(2,int(n/2)): if n%i== 0: print("not prime number") break else: print("prime number")
877a1be84c69694d607dc115d4cf420651b98caa
Williamdayu/PythonCodeLibrary
/sort/QuickSort.py
800
3.890625
4
def partition(nums, l, r, comp): if l > r: return i = l # i is the final position of nums[l] for j in range(l+1, r+1): if comp(nums[j], nums[l]): i += 1 nums[i], nums[j] = nums[j], nums[i] nums[l], nums[i] = nums[i], nums[l] partition(nums, l, i-1, comp) ...
cbdb75958777efde10a41073c82f4846ea8f2a32
OcampoPythonZen/pythonCourse
/POO_3.py
2,153
3.765625
4
''' Clase con Metodo privado, encapsulamos el procedimiento del chequeoInterno el cual solo se llama antes de arranacar el auto @author: Omar Ocampo ''' class Coche(): def __init__(self): self.LargoChasis=350 self.AnchoChasis=500 self.__ruedas=4 #Esta variable es privada y s...
665ed0a6fe4903fe534cbe0423b74daf68e304f7
solkan1201/Vivace
/code/libs/sensors/celula.py
744
3.796875
4
class Celula(object): """Classe responsavel pela criaçao e comunicaçao de objetos do tipo Celula. Esta classe ira receber e tratar os dados de força vindos de cada uma das células (através do Arduino).""" def __init__(self, nome, apelido, cal_factor, arduino, UM = "N"): self.nome = nome ...
4747c535780be6f1c2ed8ec1932802e5d920211e
Monster-Moon/hackerrank
/baekjoon/05/2562.py
184
3.625
4
max_inx = max_val = 0 for i in range(9): n = int(input()) if n > max_val: max_val = n max_inx = i + 1 else: continue print(max_val) print(max_inx)
ed6ee32ec20d5296dc0239cb26f866c1d00e7376
Monster-Moon/hackerrank
/hackerrank/midium/regex_substitution.py
137
3.53125
4
import re N = int(input()) for i in range(N): print(re.sub(r'(?<=\s)&&(?=\s)', 'and', re.sub(r'(?<=\s)\|\|(?=\s)', 'or', input())))
af5b65a100558fd7979afc494f3525012fa50964
Monster-Moon/hackerrank
/baekjoon/09/1978.py
348
3.703125
4
from math import sqrt def isprime(x): s = True if x == 1: s = False else: for i in range(2, int(sqrt(x)) + 1): if x % i == 0: s = False break return(s) input() num_vec = map(int, input().split(' ')) print(sum(list(map(isprime,...
e3b81970fb6473a49d9a480991999a110605927d
kirakrishnan/krishnan_aravind_coding_challenge
/TLS/turtle_simulator.py
2,218
4.125
4
import turtle import time def setup_simulator_window(): """ set up a window with default settings to draw Traffic Lights :param: :return t: turtle object """ t = turtle.Turtle() t.speed(0) t.hideturtle() screen = turtle.Screen() screen.screensize() screen.setup(width = 1.0,...
821841d56e1589047ba0d635d99b954d3328bc57
gentritbiba/euler
/new_euler/prob60.py
1,862
3.671875
4
def isPrime(n): if(n%2 == 0): return False for i in range(3, int(n**(1/2)) + 1, 2): if(n%i == 0): return False return True def SieveOfEratosthenes(n): prime = [True for i in range(n+1)] p=2 while p**2 <= n: if(prime[p]): for i in ran...
b710c7458aee51aa31582a3b502cb428a45345c5
gentritbiba/euler
/Python/p51.py
2,014
3.75
4
import math def isPrime(n): if n%2==0: return False for i in range(3,int(math.sqrt(n)),2): if n%i==0: # print(i) return False return True def generatePrimes(low,high): primeArr=[] for i in range(low,high): if isPrime(i): primeArr.append(i...
70852ff6040be2eeadea37f0e137a6af5e8c9fbb
cebltran/Programacion---IV-----UL
/Parcial1/menu.py
1,638
3.828125
4
import DB opcion = -1 def menu(): print("***********PARCIAL NRO 1***********") print("1- Crear BD (Reinicia datos)") print("2- Agregar articulo") print("3- Editar articulo") print("4- Borrar articulo") print("5- Buscar articulo") print("-----------------------------------") print("0- Sal...
813862e1f7e52f901ef3e15ac4aba9e063e69330
amscotti/adventofcode_2017
/day_4_high_entropy_passphrases.py
2,053
3.78125
4
#!/usr/bin/env python import unittest def passphrase_validation(input_passphrase): word_list = input_passphrase.split(' ') return not [i for i in word_list if word_list.count(i) > 1] def anagram(word_a, word_b): return word_a != word_b and sorted(word_a) == sorted(word_b) def anagrams_passphrase_vali...
f01e2fcef034c270b281fac88765cd371559e969
readleyj/LeetCode
/Python/1880_check-if-word-equals-summation-of-two-words.py
296
3.53125
4
class Solution: def calc_sum(self, word): return int(''.join(str(ord(char) - 97) for char in word)) def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool: return self.calc_sum(targetWord) == (self.calc_sum(firstWord) + self.calc_sum(secondWord))
e724f62a3c5e2f5dc737e21b2054d050c9692e3c
readleyj/LeetCode
/Python/0263_ugly-number.py
331
3.625
4
class Solution: def isUgly(self, n: int) -> bool: if n == 0: return False divisors = [2, 3, 5] while True: for divisor in divisors: if n % divisor == 0: n //= divisor break else: ret...
f33603c9af25a016b56d3864b3290967856f1198
readleyj/LeetCode
/Python/0100_same-tree.py
455
3.765625
4
class Solution: def traverse(self, node1, node2): if not node1 and not node2: return True elif (node1 and not node2) or (not node1 and node2): return False if node1.val != node2.val: return False return self.traverse(node1.left, node2.left) and s...
2c497019e2962c4c1b4cbb77741ab69cd1b08e8a
readleyj/LeetCode
/Python/0965_univalued-binary-tree.py
353
3.703125
4
class Solution: def traverse(self, node, prev_value): if not node: return True if node.val != prev_value: return False return self.traverse(node.left, node.val) and self.traverse(node.right, node.val) def isUnivalTree(self, root: TreeNode) -> bool: retu...
9026779b55788af258b5964a073ad6876076ebd0
readleyj/LeetCode
/Python/0202_happy-number.py
505
3.5
4
class Solution: def sum_digit_squares(self, n): digit_square_sum = 0 while n: digit_square_sum += (n % 10) ** 2 n //= 10 return digit_square_sum def isHappy(self, n: int) -> bool: seen = set() while n != 1: digit_square_sum = self.s...
c83364913d76d2f3691e2d1f88f648f15b5cc789
cfcooney/Spam-Classifier
/Split_Functions.py
499
3.78125
4
""" Name: Ciaran Cooney Date: April 2017 Functions for splitting text data """ from textblob import TextBlob def split_into_tokens(text): message = unicode(text, 'utf8', errors='ignore') # convert bytes into proper unicode return TextBlob(message).words def split_into_lemmas(text): message ...
78045293bc58913b2ea0c955d31dc5fd00dd8f13
Asson46/LabExercises
/Lab1/Ono5.py
190
4
4
name=input('Enter your name:') age=int(input('Enter your age:')) print('My name is ' + name + ' and I am ' + str(age) + 'years old') print('My name is',name,' and I am ',age, 'years old ')
6ea1f43372e42a8d5deae32fa8f1a981a8da3899
Saeedtayebati/python-Class
/S3_1_h_Masahat.py
290
3.609375
4
def mostatil(width,height,vahed='Metre'): if vahed=='Metre': masahat=(width*height) return masahat elif vahed=='centimetre': width1=width/100 height1=height/100 masahat=(width1*height1) return masahat m=mostatil(3,3,'Metre') print(m)
c60f4fee41ea4dec89f3e552e82c3505d2e41da1
Saeedtayebati/python-Class
/S4_0_h_class.py
153
3.625
4
P1={'Reza','Fatemeh','ali','narges'} R1={'ali','narges','mahdieyh','ziba'} A1=P1.intersection(R1) print(A1) B1=P1.union(R1) print(B1) C1=R1-P1 print(C1)
f8908c31f9db805893fd528c2f357e70f636817e
gaoshanmicai/COMLearn
/matlab/besel.py
759
3.609375
4
import numpy as np import matplotlib.pyplot as plt def bezier_curve(control_points, num_points=100): t = np.linspace(0, 1, num_points) curve = np.zeros((num_points, 2)) for i in range(num_points): curve[i] = (1-t[i])**3 * control_points[0] + \ 3*(1-t[i])**2 * t[i] * control_point...
f959b5d0964400ffd3f35234bb492ff868d4bb1f
Lmarier00/Mission-to-Mars
/scrape_mars.py
4,996
3.625
4
# Ran script to convert the jupyter notebook "mission_to_mars" into a Python script called scrape_mars_py # ipython nbconvert --to script notebook.ipynb # # Mission to Mars # Import dependencies from splinter import Browser from bs4 import BeautifulSoup as bs from selenium import webdriver import numpy as np import...
97e610f274673b9e4c182b0f6deb702e76d47eab
Grozly/python_basics
/lesson_4/task_2.py
999
3.546875
4
# Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента. # Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор. # Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]. # Р...
c90c3ea6133b0c451afa9be78653d795ff786db1
Grozly/python_basics
/lesson_4/task_6.py
1,078
3.796875
4
# Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение. # При вызове функции должен создаваться объект-генератор. # Функция должна вызываться следующим образом: for el in fact(n). # Функция отвечает за получение факториала числа, а в цикле необходимо выводить # только первые n ч...