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
2885fbdd6ac9863f68ba0f1d2720be7e3ae4acbb
mashpolo/leetcode_ans
/700/leetcode748/ans.py
1,138
3.640625
4
#!/usr/bin/env python # coding=utf-8 """ @desc: @author: Luo.lu @date: 2019-01-21 """ from collections import Counter import re class Solution: def shortestCompletingWord(self, licensePlate, words): """ :type licensePlate: str :type words: List[str] :rtype: str """ ...
3adeab71bf5c1d0a779db718d7bd6c2ead64cd3a
mashpolo/leetcode_ans
/100/add_binary/ans.py
1,534
3.546875
4
#!/usr/bin/env python # coding=utf-8 """ @desc: 二进制求和 @author: luluo @date: 2018-8-13 """ class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ max_num = max(len(a), len(b)) min_num = min(len(a), len(b)) if no...
98c54c5ca4c2b62d71b03f3d3a7b593bb9e0bfeb
mashpolo/leetcode_ans
/100/leetcode148/ans.py
727
3.828125
4
#!/usr/bin/env python # coding=utf-8 """ @desc: @author: Luo.lu @date: 2019-07-16 """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def sortList(self, head): """ :type head: ...
e578a65e2835c29136ad2abcd7983cbee731b218
mashpolo/leetcode_ans
/100/leetcode43/ans.py
953
3.875
4
#!/usr/bin/env python # coding=utf-8 """ @desc: @author: Luo.lu @date: 2019-05-05 """ class Solution: def multiply(self, num1: str, num2: str) -> str: # 数字倒过来,因为计算的时候从最低位迭代 num1=num1[::-1] num2=num2[::-1] # 创建空列表99*99不超过10000,也就是n位数*m位数不会超过,n+m+1 LIST = [0] * (len(num1) ...
fa7633a7d485df4023ff0e7430c02b558bba6c9e
ramshidasiraj/pythonprograms
/CO2/co2 pgm6.py
123
3.765625
4
st = input("enter the string : ") c = 0 for i in range(0,len(st)): if st[i]! = " ": c=c+1 print("count = ",c)
1c3f12ee5b8e9cc6b336d7a1eee8d4bc70d23d05
ramshidasiraj/pythonprograms
/CO1/co1 pgm3.py
200
3.859375
4
n=int(input("enter the limit : ")) list = [] for i in range(n): num=int(input("enter the numbers : ")) if num<100: list.append(num) else: list.append(over) print(list)
a5bd4c1585d35a82db1e3cb3c636d1d210aeea06
ramshidasiraj/pythonprograms
/CO1/co1 pgm2.py
214
4.09375
4
list=[1,-3,0,5,7,-5] print(list) n = int(input("enetr the limit")) list = [] for x in range(n): d=int(input("enter numbers")) list.append(x) print(list) square = (3.14*r*r for x in list) print(square)
832fcf62795f3a32ab6587b50d00d25a37c3505d
mayzyang/GirlsWhoCode2018
/Blackjack/api_consumer.py
1,091
3.734375
4
import requests API_BASE_URL = "http://deckofcardsapi.com/api" # This function should shuffle a deck and return a deck_id from the Deck of Cards API def shuffle(): # TODO: Make HTTP request here to shuffle a new deck request = requests.get("https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1") ...
cdb1d2a648978b745483ecc33fcd93a78ebd66d2
swa-ds/aoc-2020
/day25/python/dfriedenberger/src/util.py
710
3.78125
4
import re import copy def insert(cups,selected,dest): l = len(cups) for i in range(l): if cups[i] == dest: for x in range(3): cups.insert(i+x+1,selected[x]) break def play(cups): current = cups.pop(0) #select selected = [] for i in range(3): ...
f574516754efe48961d8a5529aab837207af7093
Kazzuki/AlgorithmDataStructure
/chap04/fixed_queue_test.py
1,409
3.65625
4
from enum import Enum from fixed_queue import FixedQueue Menu = Enum('Memu', ['enque', 'deque', 'peek', 'search', 'dump', 'END']) def select_nemu() -> Menu: s = [f'({m.value}){m.name}' for m in Menu] while True: print(*s, sep=' ', end='') n = int(input(' : ')) if 1 <= n <= len(Menu): ...
985a082cc9a823ddb65299967e36bb74930ce764
Kazzuki/AlgorithmDataStructure
/chap03/chained_hash_test.py
1,044
3.65625
4
from enum import Enum from chained_hash import CahinedHash Menu = Enum('Memu', ['add', 'remove', 'search', 'dump', 'END']) def select_nemu() -> Menu: s = [f'({m.value}){m.name}' for m in Menu] while True: print(*s, sep=' ', end='') n = int(input(' : ')) if 1 <= n <= len(Menu): ...
acded7d30573d612761737d0ba506681c3c775b5
GSinghBinning/home_credit_default_risk_challenge
/src/data/load.py
1,302
3.53125
4
import dload import os import pandas as pd import constants as c def download_dataset(directory_path, train_set='application_train.csv', test_set='application_test.csv'): """ This function downloads the kaggle dataset, in case if it doesn't exist. In case the dataset is not available, it downloads the dataset...
3d7d0b7ed098294e80e2ae761ac499bfab56874e
amaresh02/Python-programs
/area.py
128
4.28125
4
radius = int(input("Enter the radius of circle: ")) area = 3.14 * radius**2 print("The area of the circle is: {}".format(area))
6390dc93dd5e2f225ed46e625442f4c702f1d7c2
RagnarLothbrok7/Mision-02
/Porcentajes.py
354
3.734375
4
# Autor:Oscar Macias Rodríguez, A01376398 # Calcula el porcentaje de hombres y mujeres inscritos en una clase m = int(input("Mujeres inscritas:")) h = int(input("Hombres inscritos:")) total = m+h p1 = m*100/total p2 = h*100/total print("Total de inscritos:", total) print("Porcentaje de mujeres:", "%.1f" %...
d0a1aff67806f19422988d7fedea676b84130567
SixSidedStudios/text-adventure
/story.py
982
3.75
4
#Text-adventure prototype 1.0 print 'Your eyes slowly open... an old man stands over you.' print '"Why hello my friend, what might your name be?"' name = raw_input('Enter your name:') print '"Ah,',name print 'a good name... there was a hero named ',name,' a long time ago."' print 'The old man sits you up.' print 'You ...
3bd2b00837fa5037a76a4fd3268468d629de232d
iQaiserAbbas/artificial-intelligence
/Assignment-01/Assignment_01.py
1,853
3.546875
4
# Owned __author__ = "Qaiser Abbas" __copyright__ = "Copyright 2020, Artificial Intelligence Assignment-01" __email__ = "qaiserabbas889@yahoo.com" #=============================================================== # {code} response = ["Hi, This is Food ChatBot by Qaiser!", "Yes Sir, I am here to assist you fo...
36a29f204892487912c3e60c6766a68a3a23a7b5
iQaiserAbbas/artificial-intelligence
/Lab-01/Lab-01.py
921
4.125
4
__author__ = "Qaiser Abbas" __copyright__ = "Copyright 2020, Artificial Intelligence lab-01" __email__ = "qaiserabbas889@yahoo.com" # Python Program - Calculate Grade of Student print("Please enter 'x' for exit."); print("Enter marks obtained in 5 subjects: "); subject1 = input(); if subject1 == 'x': exit(); else...
5117141ad689a4f93f842a6665fc3ee246788d04
joonjCode/python
/python-basics/basics/error_handling2.py
121
3.53125
4
def sum(num1, num2): try: return num1 / num2 except (TypeError, ZeroDivisionError) as e: print(e) print(sum(2,0))
b5409a541f0a96fab9c32e26dfcdf24ceb02c2d6
joonjCode/python
/python-basics/unittest/random_game_test.py
706
3.734375
4
import unittest import random_game class TestGame(unittest.TestCase): def test_input(self): # please note in the video, I had the parameters flipped it should be the "guess" parameter 1st and "answer" parameter 2nd result = random_game.run_guess(5, 5) self.assertTrue(result) def test_i...
3bd9e27cb808648c955957a93bfae2cfe585817c
joonjCode/python
/python-basics/interview-q/easy_interview.py
508
3.546875
4
def majority_element_indexes(lst): ''' >>> majority_element_indexes([1,1,2]) = [0,1] >>> majority_element_indexes([1,2]) = [] >>> majority_element_indexes([]) = [] ''' from collections import Counter if lst == []: return [] c = Counter(lst) # top_elems = sorted( # c.keys() # ) top_count = c.most_commo...
0fedf7dee1b47ddca489558ac266dd17e7f78215
jacob-thrasher/Hangman-Game
/words.py
239
3.5
4
#Function to fetch words import random; WORDLIST = "wordlist.txt" def getRandomWord(): with open("wordlist.txt") as file: words = file.read().split(); #splits words by whitespace return random.choice(words);
e47d3b8269e8df611d2b1a2c1e34bf659e08cfa7
AnthonyWlodarski/PythonInEasySteps
/Chapter2/bitwise.py
202
3.671875
4
a = 10 b = 5 print('a =', a, '\tb = ', b) #1010 ^ 0101 = 1111(decimal 15) a = a ^ b #1111 ^ 0101 = 0101 (decimal 10) b = a ^ b #1111 ^ 1010 = 0101 (decimal 5) a = a ^ b print('a =', a, '\tb = ', b)
10d9042a4a599cb046d48489e289a57e98ecb294
mattott/Cracking-The-Coding-Interview
/3_5.py
1,055
3.890625
4
class MyQueue: def __init__(self): self.stacks = {1: None, 2: None} def enqueue(self, data): self.push(data, 2) self.moveStack(1,2) self.moveStack(2,1) def dequeue(self): self.moveStack(1,2) val = self.pop(2) self.moveStack(2,1) return val ...
d48fee0011a48fa0b5386a7306aafbcf58b7da4e
deviyantiam/pymongo
/kasusmong.py
2,547
3.625
4
##Belajar input terus insert ##Hapus dokumen ##Cari yang dibawah sejuta ##Update nama produk ##Tambah satu field yaitu kota ##Edit kota pada barang yang harganya di range tertentu ##pip install pymongo ##Belajar input terus insert bar=str(input('Masukkan nama barang: ')) har=int(input('Masukkan harga: ')) import pymo...
abcd27856e5333ca2d8bbea491d5bda47ceaa9fe
kyle-gross/AirBnB_clone
/models/city.py
860
3.546875
4
#!/usr/bin/python3 """Module for class City. Inherits from BaseModel.""" from models.base_model import BaseModel from datetime import datetime class City(BaseModel): """City data - state_id and name of city""" state_id = "" name = "" count = 0 def __init__(self, *args, **kwargs): """ ...
e86b5ef1c5698654d766893ad76c986dd752c253
thwa7116/CSCI3308_Project1
/code_Leo/buildStudentList.py
1,074
3.921875
4
from student import Student from getStudentInfo import getStudentInfo def buildStudentList(): #return an array of Student objects studentList = [] askInsert = input("Add a new student? (1)Yes (2)No ") while (askInsert!=1 and askInsert!=2): askInsert = input("\nInvalid Selection. Add a new student? (1)Yes (2)No ")...
fdde4a4cdb3e37da6e6643a736a8b328d2549ef2
LiuKang1080/Machine_Learning
/1_Numpy_Stack/Numpy/LoopsVSdotProd.py
443
3.890625
4
import numpy as np a = np.array([1, 2]) b = np.array([2, 1]) dot = 0 for i, j in zip(a, b): dot += i*j print(dot) # ========================== # Now we will do this with the numpy array print(np.sum(a*b)) print((a*b).sum()) # The best way: print(np.dot(a, b)) # Find angle in between a and b cos_angle = a.dot(...
8c04e6024f34e24bfd032e4d9ee90a642cc872cf
LiuKang1080/Machine_Learning
/2_Linear_Regression/dummy_variable_gradient_descent.py
1,024
3.640625
4
# Dummy variable trap, and how to avoid this by using Gradient Descent import numpy as np import matplotlib.pyplot as plt N = 10 D = 3 X = np.zeros((N, D)) X[:, 0] = 1 X[:5, 1] = 1 X[5:, 2] = 1 # Y is our targets Y = np.array([0] * 5 + [1] * 5) # try to solve for w: try: weights = np.linalg.solve(X.T.dot(X), X...
dbfcb391c06e19b9c30cc0ff00e7de1ed11265f5
LiuKang1080/Machine_Learning
/1_Numpy_Stack/matplotlib/line_charts.py
266
3.9375
4
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = np.sin(x) # now we plot the sin wave plt.plot(x, y) # We can add things to the plot before showing. plt.xlabel("Time") plt.ylabel("Magnitude") plt.title("Data Set 1") plt.show()
729efbb04da9219e613557944e1dce7b3f567844
deepaksbss/deepa
/zip.py
660
3.640625
4
#Zip num = [1,2,3,4] num1 = [4,5,6,7] z = (zip(num,num1)) print(z) numb = [(0,1), (1,2), (2,3), (3,4), (4,5)] print(list(zip(*numb))) midterm = [80,91,78] finals = [98,89,53] students = ['dep', 'sbss', 'sai'] final_grades = [max(pair) for pair in zip(midterm, finals)] print(final_grades) fin...
6abdafcfca19987754151818fd4e8a2ef09fed6d
cp-27/lab09
/lab9_ClarkPrice_MattJeffries#.py
4,932
3.984375
4
import random import re def convert_file_to_list(file): """converts open file into list with tuples""" questions = [] for i, line in enumerate(file): if i%3 == 0 or i%3 == 2: line = line.split(' \n ') line[-1] = line[-1].replace('\n','') questions.extend(line)...
b67cfb8eb3dd73badb1505030024d8be606f3b2b
AliE99/Kruskal-algorithm
/UI/draw.py
1,076
3.578125
4
from tkinter import * class Graphic: def draw(self, result): canvas_width = 1280 canvas_height = 760 python_green = "#476042" master = Tk() w = Canvas(master, width=canvas_width, height=canvas_height) w.pack() points =...
8c9c3710c098a61b65675511afc73775019b02a9
bdnormann/ThreeBodyProblem
/ThreeBodyProblem.py
7,978
3.921875
4
""" This script is adapted from 1) The code at http://matplotlib.sourceforge.net/examples/animation/double_pendulum_animated.py Double pendulum formula, which was translated from the C code at http://www.physics.usyd.edu.au/~wheat/dpend_html/solve_dpend.c and 2) modified by Jake Vanderplas, email: vanderplas@astro.was...
cebbd60ba68145a139bc6382ea570f2b79d1a27d
aaabhilash97/thinkpython
/has_dups_dic.py
135
3.609375
4
def hasdups(x): dic={} for x1 in x: dic[x1]=dic.get(x1,0)+1 if dic[x1]>1: return True return False print hasdups([92,3,1,8])
d699274a88636a0b75419afc72836c2dbf1195fb
aaabhilash97/thinkpython
/moverectangle.py
191
3.734375
4
class point(object): x=1 y=1 class box(object): w=2 h=3 corner=point() def moverec(box,dx,dy): box.corner.x+=dx box.corner.y+=dy p=box() moverec(p,2,3) print box.corner.x,box.corner.y
99767785148bd057ad6275b59c397912f6c927d0
aaabhilash97/thinkpython
/Untitle/print_n.py
73
3.703125
4
def print_n(s,n): while n>0: print s n=n-1 print_n("abhilash",3)
37ea373d0b491b4fcf9e4ba6476c9a8f76601932
aaabhilash97/thinkpython
/point_init.py
215
4.0625
4
class point(object): def __init__(self,x=0,y=0): self.x=x self.y=y def __add__(self,n): p2=point() p2.x=self.x+n.x p2.y=self.y+n.y return p2 p=point(2,3) p1=point(4,5) p2=p.__add__(p1) print p2.x,p2.y
c1618435fa7f869ef442c821a408b17cdcf10d7b
aaabhilash97/thinkpython
/Untitle/Untitled/fermat.py
172
3.96875
4
def fermat(a,b,c,n): if n>2: print "Holy Smokes ,Fermat was Wrong" elif a**n+b**n==c**n: print "yes its fermat" else: print "No that doesn't work" fermat(1,1,2,4)
7e4e913a8f27e6a7c484bbb3eec8661d18a85b38
anishaswain/DSA
/Sort/Python/InsertionSort.py
338
4.03125
4
def insertion(arr): # worst-case O(n2) and average complexity of О(n) and space complexity 1 for i in range(1,len(arr)): j = i-1 anchor = arr[i] while j >=0 and anchor < arr[j]: arr[j+1] = arr[j] j = j-1 arr[j+1] = anchor return arr arr = [3,7,5,9,0,2,4...
f08ddbee60c66ad3563c9f457d673adb9b705e94
gamer496/toTeach
/main2.py
8,110
4.4375
4
import turtle import math # class circle class Circle: def __init__(self,snow,radius,x,y): snow.snowmani.up() #set the initial absolute direction of turtle snow.snowmani.sety(y) #set the x and y coordinates of the turtle.These will act as initial points.Could have used goto too here. snow.snowmani.setx(x) arc...
4603d37822ed1dc27093fe3e8760f17b9855d530
PAND-or/Python_lessons_basic
/lesson03/home_work/hw03_normal.py
3,637
3.9375
4
__author__ = "Андрей Петров" # Задание-1: # Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента. # Первыми элементами ряда считать цифры 1 1 def fibonacci(n, m): feb = 0 i = 1 list_feb = [1,1] #чтобы не перезаписывать сумму, а сделать обращение по индексам n = n-1 if n > 1 else 0 #...
e2bfdcd2f7a33954f3cecc2cc03bd5838b96f8e9
Programacion-Algoritmos-18-2/tutoria-clase-5-daburneo1
/paquete_academico/modelo.py
2,989
3.828125
4
class Ciudad(object): def __init__(self): self.nombre_ciudad = "" #ATRIBUTOS DE CIUDAD self.poblacion = 0 def agregar_nombre_ciudad(self, nciudad): self.nombre_ciudad = nciudad def obtener_nombre(self): return self.nombre_ciudad def agregar_poblacion(self, p): ...
51b44ccc439acacd8712e7458739afeb9b5a08d3
ericlongz/learn_python
/what_is_the_number.py
1,154
3.890625
4
#!usr/bin/python3 #import modules import random import sys from os import system, name print(name) if name == "nt": clear = system("cls") else: clear = system("clear") #create a random number between 1 - 10 created_number = random.randint(1,10) chances_counter = 0 #start the loop while True: #user make a guess ...
e3e5c4e05d891f70aefef3d0e45b32f62ce4009a
Seanc0315/AE401-Python
/hw6.py
472
3.65625
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 19 09:53:13 2020 @author: James """ import random r = random.randint(0,6) r2 = random.randint(0,6) r3 = random.randint(0,6) sentenceList = [] for i in range(7): name = input("請輸入名字:") noun = input("請輸入名詞:") verb = input("請輸入動詞:") sentenc...
b906287e4e05d30f76f660a11f9268d62ecfd25d
purdoo/Trading-Project
/pymath.py
911
3.59375
4
## Methods to be imported by main program import numpy as np def getSMA(closing, n, period): movingAverages = [] if(n > period): print("n cannot be greater than the number of days") return movingAverages count = (period - n) + 1 for i in range(count): sample = closing[i:(i+n)] #sample = self.testclosing[i:...
e9694f3b7c212d58f4ffbf830f418c61b2bbe6cd
HxnDev/AI-Based-Chess-Game-Using-Minimax-and-Alpha-Beta-Prunning
/piece.py
5,207
3.640625
4
from copy import deepcopy import extras class Piece: moves = [] def __init__(self, name, symbol, team, row, col, points): self.name = name self.symbol = symbol self.team = team self.row = row self.col = col self.points = points self.has_...
a9c810429e7becf38b9a58d5d385b17690e978c5
evelinacs/semantic_parsing_with_IRTGs
/code/generate_input_from_trees/sort_subtrees_width.py
325
3.53125
4
#!/usr/bin/env python3 import sys from nltk.tree import Tree def sort_subtrees_width(): with open(sys.argv[1]) as subtree_doc: for line in subtree_doc: t = Tree.fromstring(line) width = len(t) print(width, line, end = "") if __name__ == "__main__": sort_subtrees_wi...
6226b1311691d82932f26496bbac9d60f0ddf575
JordanLevin/Programming-Problems
/LeetCode/20-Valid-Parentheses.py
442
3.546875
4
class Solution(object): def isValid(self, s): parens = {')': '(', '}':'{', ']':'['} stack = [] for i in s: if i in '({[': stack.append(i) else: if len(stack) > 0 and stack[len(stack)-1] == parens[i]: stack.pop() ...
77ea657fda6ad810bac9f21b658a68a2a818b7e3
JordanLevin/Programming-Problems
/CTCI/ch1/one_away.py
502
3.5
4
#given 2 strings, determine if first can be made into second with one add/del/replace def one_away(a, b): if len(a) != len(b): return False; for i in range(len(a)): # print(a[:i]+a[i+1:]) # print(b[:i]+b[i+1:]) if a[:i]+a[i+1:] == b: return True if b[:i]+b[i+1...
7141406c0032f2a1ccc46ee8e94d426dc4787571
vanceleon/Sprint-Challenge--Graphs
/graph_dfs_debug/graph.py
2,947
3.53125
4
""" Simple graph implementation compatible with BokehGraph class. """ class Vertex: def __init__(self, label_id): self.label = str(label_id) self.edges = set() self.component = 0 def __repr__(self): # return 'Vertex: ' + self.label return f"Component: {self.c...
f24dd248b6f6fca462125e88fc92ad7e4569193f
wsrtka/Hyperreal
/hyperreal/textutils/stats.py
1,100
4
4
from math import log def get_word_freq(filename, split_char): """ Get the frequencies of words in filename. :param filename: string containing the file name :param split_char: string containing column separation symbol :return: dictionary of type (word: frequency) """ word_freq = {} w...
4c973dacd4d3aa0476a2cbe5c37eea1e6f796e7a
helgi98/num_mod
/main.py
589
3.703125
4
import matplotlib.pyplot as plt from calculator import HUCalculator mu = lambda x: 1 beta = lambda x: 50 * pow(x, 2) sigma = lambda x: 40 * pow(x, 2) f = lambda x: 40 * pow(x - 0.3, 5) N = 5 a = -1 b = 1 calc = HUCalculator(N, a, b, mu, beta, sigma, f) calc = calc.calc_until(5, 50) print("N\t| Норма оцінювача\t\t|...
43a0093f6554e4c2ae388be557c723df4a50e0fa
wulalakuaipao/api_auto
/week_2/class_0111/class_位置参数_函数.py
755
3.953125
4
# -*- coding: utf-8 -*- # @Time : 2019/1/11 21:13 # @Author : lemon_huahua # @Email : 204893985@qq.com # @File : class_位置参数_函数.py def add(a, b): # 形式参数/位置参数 这个表示 当你在调用函数的时候 要输入2个参数 '这个是一个加法函数 完成两个数相加的功能' # a=1 # b=2 c = a + b # 函数代码块 a+b的值存到c变量里面 # return c#return不是必须的 但是每个函数 你不写的时候 也会默...
b1f311ba9fb2e970eb4c94a585e476bee91a5ef7
wulalakuaipao/api_auto
/week_6/class_0220/http_request.py
1,186
3.515625
4
# -*- coding: utf-8 -*- # @Time : 2019/2/20 21:16 # @Author : lemon_huahua # @Email : 204893985@qq.com # @File : http_request.py # 2:编写一个类:你们自行去设计,要求写一个类, 初始化函数 对象函数 # 包含 根据你不同的选择完成get请求 OR post请求 , # 其中url 需要做参数化,并且最后要拿到响应结果 import requests class HttpRequest: def __init__(self,url,method='get'): ...
e461d4a4ea2ee9063578b58cba4a7e5dc0ee56ba
wulalakuaipao/api_auto
/week_3/class_0116/class_内置函数.py
1,621
3.65625
4
# -*- coding: utf-8 -*- # @Time : 2019/1/16 20:38 # @Author : lemon_huahua # @Email : 204893985@qq.com # @File : class_内置函数.py #元组 有序的不可变的数据类型 # t=('hello',2,3,4,1,2,1,1,1) # print(t.count(1)) # print(t.index('h'))#返回你遇到的第一个元素的索引位置 # 列表 有序可变的数据类型 # L=['hello',2,3,4,1,2,1,1,6666] #增:增加 insert # L.append('路人'...
7caf1de69c4c2acd7325c6adb68e0b89db1056c3
lindsayc20/Lindsay_Carlin_Programming_II_2019
/lists_and_comprehensions.py
3,265
4.15625
4
import random #LISTS (29PTS TOTAL) #In these exercises you should should use functions as needed. All functions should have comments to describe their purpose. # PROBLEM 1 (Using List Comprehensions - 6pts) # Use the list comprehension method to do the following: # a) Make a list of numbers from 1 to 100 # b) Make a ...
a84c410460ab4a6d1f4dac1a71f3dfacb4c460a6
lindsayc20/Lindsay_Carlin_Programming_II_2019
/scraping_problems.py
905
3.78125
4
# SCRAPING PROBLEM (12pts) # Go to your favorite follow on Twitter. (not someone who posts explicit materials please) # Inspect the twitter feed in Chrome. # You'll notice that the tweets are stored in a ordered list <ol></ol>, and individual tweets are contained as list items <li></li>. # Use BeautifulSoup and reques...
f2c41e4f2cbef4b9d331b423a27dd93e259b0329
cardigansquare/codecademy
/learning_python/reverse.py
221
4.1875
4
#codeacademy create function the returns reversed string without using reversed or [::-1] def reverse(text): new_text = "" for c in text: new_text = c + new_text return new_text print reverse("abcd!")
556e83e3f35ac103b07d064083e1288293ebc1f9
roseORG/GirlsWhoCode2017
/GWC 2017/story.py
1,154
4.25
4
start = ''' Rihanna is in town for her concert. Help her get to her concert... ''' print(start) done = False left= False right= False while not done: print("She's walking out of the building. Should she take a left or right?") print("Type 'left' to go left or 'right' to go right.") use...
f9291987ec98543712ec5d5c88ebe052c808db5b
sbraun27/AdventofCode
/Python/20201222.py
3,998
3.53125
4
import time class Deck(): def __init__(self, starting_cards, name): self.deck = starting_cards self.no_cards = len(starting_cards) self.card_history = [] self.name = name def play_card(self): self.no_cards -= 1 return self.deck.pop(0) def add_to_deck(self,...
5e98f486ac31eb355c35771cba640f8c72314022
alok15ee/Algorithm-Python
/stack-queue/Stack.py
542
3.921875
4
from LinkedList import LinkedList, LinkedListNode class Stack(object): def __init__(self): self.linked_list = LinkedList() def push(self, item): self.linked_list.add(item) def pop(self): self.linked_list.remove_from_top() def display_stack(self): self.linked_list.s...
17dccb7a8621b306bbae0dd58f64c23e17c746c8
shamramchandani/Code
/Python/chapter 3.py
410
4.15625
4
def collatz(num): if num%2 == 0: print(num / 2) return (num / 2) else: print((num *3) +1) return (num *3) +1 try: number = int(input("Please enter a number")) print(number) if number <= 1: print('Please input a number greater than 1') else: while number > 1: number...
5225ef80b35cdad2d5a8c9442e1f54170bc38973
Chandras999/python
/newwhile.py
306
4.0625
4
#!/usr/bin/python x = 0 while x < 15: print ('x is currently: ', x) print ('x is still less than 10: , adding 1 to x') x = x + 1 if x == 9: print ('x is equal to 9') print("condition satisfied so exiting") break else: print ('continuing') continue
a4630580b5fa0a5bc3f480cd7d4ff6ef63ee9640
GajananThenge/Assignment1
/Assignment1.8.py
759
4.375
4
''' Write a Python Program to print the given string in the format specified in the sample output. WE, THE PEOPLE OF INDIA, having solemnly resolved to constitute India into a SOVEREIGN, SOCIALIST, SECULAR, DEMOCRATIC REPUBLIC and to secure to all its citizens Sample Output: WE, THE PEOPLE OF INDIA, having ...
6d26ba4e5ce76beac39867108d738e49a490bfa9
joshtch/side-projects
/project-euler/47.py
1,178
3.53125
4
""" Distinct primes factors Problem 47 http://projecteuler.net/problem=47 The first two consecutive numbers to have two distinct prime factors are: 14 = 2 * 7 15 = 3 * 5 The first three consecutive numbers to have three distinct prime factors are: 644 = 2^2 * 7 * 23 645 = 3 * 5 * 43 646 = 2 * 17 * 19. Find the fir...
eabcd25afa0611eeea7b1e13d4605a4677955374
kasai-spring/KyoPro
/Other/Fibonacci.py
485
4.09375
4
# フィボナッチ数列を作るプログラム # 再帰関数とメモ化(?)を使用 def fib(n, plist): if n <= 2: result = 1 else: result = plist[n - 3] + plist[n - 2] return result def create_fib_list(x): fib_list = [0] * x for i in range(x): fib_list[i] = fib(i + 1, fib_list) return fib_list print("回数(整数):", ...
fcd905819f83613567245aa50cc7b0caad321697
kasai-spring/KyoPro
/AIZU/PCKWU1044.py
1,309
3.953125
4
while True: name, _type = input().split() if _type == "X": break name_list = list(name) if _type == "U": name_list[0] = name_list[0].upper() if "_" in name_list: for i in range(len(name_list)): try: if name_list[i] == "_": ...
d4f908e29a013a6bc9f0479ab6e5d5580005b0d4
emoron/PythonProgramming
/stdin.py
493
3.671875
4
# Numero de casos a leer de STDIN como un entero numofCases = input() i = 0 while i < numofCases: # numofNumbers = input() # raw_input() acepta una entrada como: 1 2 22 232 12 as a string # input() puede aceptar solo una entrada # raw_input().strip().split(" ") genera una lista con numeros como cadenas...
64ad8b00313fb0866093a403b3c1e6bef3d488bd
hynkis/Learning-Algorithm-with-Silicon-Valley-Questions
/Prac_1.5_maxSubArray.py
3,017
3.625
4
""" Prob 1-2 maxSubArray Find maximun Sub sum from and Array """ def maxSubArray_memoryLess(nums): maxSum = 0 tempSum = 0 """ maxSum would save maximum summation value until index i. """ for i in range(len(nums)): if (tempSum + nums[i] > 0): tempSum = tempSum + nums[i]...
03cc3ecbb3f50972f95ca8531db75865e6ff016d
hynkis/Learning-Algorithm-with-Silicon-Valley-Questions
/Prac_4.1_factorial.py
221
3.9375
4
def factorial(num): # base condition if num == 0: return 1 else: return num * factorial(num - 1) def main(): print(factorial(5)) # should return 120 if __name__ == "__main__": main()
3139b3ac9e8c731eb0032ceb3bde1c0184ca693d
vik-y/Code-Snippets
/LZW-Compression/encodelzw.py
1,750
4.03125
4
from utilityFunctions import * dictionaryLimit = 2**16 #Dictionary can't exceed the above size def buildCharacterSet(): ''' This function builds the initial character set required for the dictionary and returns the dictionary as well as the number of elements in the dictionary This build a character set of 12...
dca219a08ed2f7f2df67d01b3183926d4bae08dc
Selenamm/elecciones
/Progra/PrograElections.py
11,209
3.5625
4
usersList = [{"name":"Dayana","age":17,"id": 123,"email":"fsdfsd","typeUser":"Administrator", "password":"123"}] #Listado de usuarios registrados en el sistema userLogged = {} #Mantiene los datos del usuario autenticado politicalList = []# lista de partidos politicos distribution = [] territorialList = [{}] #Despliegu...
725dae518de7e42c11d4cd13c2c7378ad17b4220
otrabalhador/expenses-diary-api
/tests/utils/test_encrypt_password.py
1,068
3.859375
4
import unittest from authentication.password import PasswordHelper, encrypt class TestEncryptPassword(unittest.TestCase): def test_encrypt_password(self): """ Asserts if encrypted password doesn't contain actual given password """ password = "123456" actual...
7332e18abb422c41e5eaf7dd3047817a0875bb2c
PrayStarJirachi/Algorithm-Homework
/Week 1/source/xzj/ex5.py
290
3.5625
4
def binom(n, m, p = 0): if(m > n or m < 0): return 0; if(n < 2): return 1; if(p == 0): p = 1; while(p * 2 < n): p = p * 2; else: while(p >= n): p = p / 2; return binom(n - p, m - p, p) ^ binom(n - p, m, p);
771aafb570437f9bdbd5bc60ea6b4106b22c2541
hperry711/dev-challenge
/chapter2_exercises.py
1,534
4.21875
4
# Exercises for chapter 2: # Name: Hunter Perry # Exercise 2.1. # zipcode = 02492 generates a SyntaxError message because "9" is not within the octal number system. When an integer is lead with a zero in Python it generates the Octal representation for that number. >>> zipcode = 02132 only contains numbers between 0...
7d86e33c7065875cbe7845487fbe27c0e90f9041
paganism/palindrome
/unit_tests.py
714
3.8125
4
import unittest from palindrome import is_palindrome from palindrome_list import palindromes, not_palindromes class TestPalindromeStringMethod(unittest.TestCase): def test_is_palindrome(self): for pal in palindromes: print(pal) self.assertEqual(is_palindrome(pal), True) def t...
b35297d82e48eb414c164d72417652c3275ec415
LianaKhazaliya/BSU
/Algo/Sorts/hybrid_sort.py
1,504
3.5625
4
#! usr/bin/env python2.7 # coding: utf-8 from insertion_sort import insertion_sort from quick_sort import quick_sort from expected_bound import time_of_the_process from merge_sort import merge_sort from random import sample, randint def hybrid_sort(lst, start=0, end=None): start = start or 0 end = end or l...
025a5ed46d0c18568ca9f46cef9d3a03a69be28d
Memelank/LeetCode_Experience
/Stack/20.Valid parentheses.py
2,709
4
4
''' 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 ''' #MA class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ flag = True stack = [] for char in s: if ch...
1435bd56f23473cad0d00c81ce9434afd56f945a
mylin95/learnpython
/demo/basic/DictAndSet.py
1,494
4.28125
4
# dict # dict全称dictionary,在其他语言中也称为map. # 使用键-值(key-value)存储,具有极快的查找速度。 # dict的键值对存放是 无序的 # dict初始化,取值 dict1 = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print(dict1['Michael']) print(dict1) # 增、替换 dict1['Amy'] = 100 print(dict1['Amy']) # 删 delEle = dict1.pop('Amy') print(delEle) print(dict1) # 取值1:不存在key,报错 # print(dic...
d18655221e7642cc632f6875310fd3bbd85ae270
Vivek24-learner/Vivekfolder
/Factorial no.py
217
4.125
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 23 07:51:08 2021 @author: HP """ def factorilal(n): return 1 if(n==1 or n==0) else n*factorilal(n-1) n=5 print("The factorial of ",n,"is",factorilal(n))
28adaf2ab2e14ab8849226cf1826d9b2820e0752
TechTheGuy/autoconverter
/operazioni.py
482
3.75
4
#Matteo Crisafulli [TechTheGuy] #Programma per la conversione di un numero da decimale a binario con #l'algoritmo della divisione operando1 = int(input("first operand: ")) segno = str(input("sign: + - : ")) operando2 = int(input("second operand: ")) if segno == "+" : risoper = int(str(operando1), 2) + int(str(opera...
85844712361e4bf99644fedf4e555b847aa9e15b
SricardoSdSouza/Jogos_python
/Jogo_da_velha/jogodavelha.py
3,178
3.78125
4
import random print("Bem vindo ao Jogo da Velha") print("Tente vencer o computador se for capaz!!!") print("Você ganha se conseguir uma linha ou uma coluna ou uma diagonal no grid com o mesmo símbolo") print("Você precisa escolher uma posição no grid para marcar sua jogada, de acordo com a numeração\n") print("_ _ _"...
b98fb37acb9ed1b4cbf2d57f516cf650bc515332
Airbomb707/StructuredProgramming2A
/UNIT1/Evaluacion/eval02.py
304
4.15625
4
#Evaluation - Question 7 #Empty array #A length variable could be added for flexible user inputs lst=[] #Storing Values for n in range(3): print("Enter value number ", n+1) num=int(input("> ")) lst.append(num) #Built-in Max() Function in Python print("The largest number was: ", max(lst))
d9fad0b9f0dda940f073f6f461fd01c145eb5ba1
ZammadGill/python-practice-tasks
/task8.py
319
4.21875
4
""" Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers """ def squareOddNumber(numbers_list): odd_numbers_square = [n * n for n in numbers_list if n % 2 != 0] print(odd_numbers_square) numbers = [1,2,3,4,5,6,7,8,9] squareOddNumber(numbers)
d973ed2fe6a793239621b7839a7c5137a6296a6d
MokoSan/KNN_Python
/distance.py
820
3.84375
4
import math class IDistance( object ): ''' Interface for all Distance functions. ''' def compute( distance_context ): raise NotImplementedError class EuclideanDistanceContext( object ): ''' Context of the Euclidean Distance Class. ''' def __init__( self, item_a, item_b ): ...
9f95c561ddd8908e08ad9bd6d154f7e170f425d1
Adelaide95/laba8
/zd2.py
353
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- if __name__ == '__main__': bts = { 1: 'taehyung', 2: 'jungkook', 3: 'jimin', 4: 'namjoon', 5: 'hoseok', 6: 'jin', 7: 'yoongi' } print(bts) dict_items = bts.items() new_bts = dict(zip(bts.values(),...
744e57ef3e72541f7188f9154673ccd53bb22c10
jkrold/python_intermediate_traning
/sda_exercises_oop_2/Person.py
1,933
3.78125
4
from datetime import date class Person: def __init__(self, first_name: str, last_name: str, day_of_birth: date): self._first_name = first_name self._last_name = last_name self._day_of_birth = day_of_birth @property def first_name(self): return self._first_name @proper...
40f11ede895f7211965ebfa55551df2bc4a2eb72
jkrold/python_intermediate_traning
/sda_exercises_oop_1/Animal.py
217
3.65625
4
from abc import ABC, abstractmethod class Animal(ABC): def __init__(self, name: str, sound: str): self._name = name self._sound = sound @abstractmethod def make_sound(self): pass
e6b5440139f790fececb0ebb3f11a3ad77cf591a
pmduc2012/pythonbasic
/Lesson 2/BT5 - While loop.py
330
3.828125
4
n1 = int(input('Press number 1: ')) n2 = int(input('Press number 2: ')) Gcd = 1 k = 2 if n1 ==0 or n2 == 0: print('Gcd of',n1,'and',n2,'is:',max(abs(n1),abs(n2))) else: while k <=abs(n1) and k <=abs(n2): if n1 % k == 0 and n2 % k == 0: Gcd = k k+=1 print('Gcd of', n1, 'and',n2,'i...
88ed0250788155dfc4ac399b569d24beae0f2dca
pmduc2012/pythonbasic
/Lesson 7 - Class/Polymorphism.py
745
3.859375
4
__author__ = 'MinhDuc' class Animals(): def __init__(self, name): self.name = name def animalSay(self): pass class Tiger(Animals): def animalSay(self): return 'grwww' class Elephant(Animals): def animalSay(self): return 'trumpet' class Cat(Animals): def animalSay(...
cb611e5efb7fe55ca6e79a43a2eccfffd86b4834
Hrishikeshbele/Competitive-Programming_Python
/minimum swaps 2.py
1,891
4.34375
4
''' You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order. Sample Input 0 4 4 3 1 2 Sample Output 0 3 Explanation 0 Given arra...
15574dbe5d23e99b0f5b4c4047a4eff696c7601a
Hrishikeshbele/Competitive-Programming_Python
/nearest greater to left.py
557
3.65625
4
''' find next greater elm to left for all elms in list ex.[1,3,2,4] o/t: [-1, -1, 3, -1] ''' def ngl(a): stack=[] ans=[] for i in range(0,len(a)): if not stack: ans.append(-1) elif stack and stack[-1]>a[i]: ans.append(stack[-1]) elif stack and stack[-1]<a[i...
3df37853cc5ebc4f30777538846005393489316c
Hrishikeshbele/Competitive-Programming_Python
/Remove Duplicates from Sorted Array.py
1,661
3.90625
4
''' Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example 1: Given nums = [1,1,2], Your function should return ...
db867a4bc6a3a9ca50dcf57b4d12839f529ac8c5
Hrishikeshbele/Competitive-Programming_Python
/next smallest elm to left.py
548
3.8125
4
''' given the list find next smallest elm to left for all elm in list. ex.a=[1,3,2,4] o/t:[-1, 1, 1, 2] ''' def nsl(a): ans=[] stack=[] for i in range(len(a)): if not stack: ans.append(-1) elif stack[-1]<a[i]: ans.append(stack[-1]) elif stack[-1]>a[i]: ...
6924f572154443cb05c2c82a6a44568d2381710b
Hrishikeshbele/Competitive-Programming_Python
/Integer to Roman.py
1,398
4.03125
4
''' Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. Example 1: Input: 3 Output: "III" idea here is first create 2 list 1st contains roman letters and second containing corrsp values.then we loop through val's list and compare each elm in it with given num i...
2e3998204f8cf62aeb969ff28cd45b217b480bf0
Hrishikeshbele/Competitive-Programming_Python
/merge2binarytree.py
1,623
4.125
4
''' Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise...
e4f9ac7f865a6709f934e322ba2aee31fa6a1a41
Hrishikeshbele/Competitive-Programming_Python
/amazingsubarrays.py
982
3.84375
4
''' You are given a string S, and you have to find all the amazing substrings of S. Amazing Substring is one that starts with a vowel (a, e, i, o, u, A, E, I, O, U). Input ABEC Output 6 Explanation Amazing substrings of given string are : 1. A 2. AB 3. ABE 4. ABEC 5. E 6. EC ''' #idea is simple ju...
9e6d8ecd68c4c37de5fe56cfb017753816466b7a
Hrishikeshbele/Competitive-Programming_Python
/Excel Column Number.py
499
3.53125
4
''' Given a column title as appears in an Excel sheet, return its corresponding column number. Example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 ''' class Solution: # @param A : string # @return an integer def titleToNumber(self, A): ans=0 ...
989e49412084679ae529d72726e3f235fef36ba0
Hrishikeshbele/Competitive-Programming_Python
/max sum subarrray of window size k.py
562
3.84375
4
''' given a array and window size calculate the max sum of subarray having size k. ex. [1,5,3,4,2] output: 8 (sum of 5 and 3) we use the concept of sliding window to solve the problem .first we traverse one pointer to k position and other at 0 postion then we move the window to right by substracting first elm and a...
a95493a7365cb3835d6cecb703f07f06d23f127c
Hrishikeshbele/Competitive-Programming_Python
/Remove Duplicates from Sorted List II.py
1,769
4.0625
4
''' Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. Example 1: Input: 1->2->3->3->4->4->5 Output: 1->2->5 idea here is to use pre linked list to store values of linked list without duplicates and h...