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 |
|---|---|---|---|---|---|---|
08a014d8305e150afd319a86d6e369e1e1101419 | M-R-Epstein/poetics | /poetics/data/cmudict/syllabify/syllabifier.py | 5,754 | 4.15625 | 4 | """P2TK syllabifier for python 3.x.
Modified from python 2.x P2TK syllabifier by Joshua Tauberer, based on code originally written by Charles Yang.
The syllabifier requires a language configuration which specifies the set of phonemes which are consonants and vowels
(syllable nuclei), as well as the set of permissible ... |
e0ddce80e4f1b6646105b501cde60a351a65ecf0 | baggy2797/Leetcode | /remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.py | 779 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if not head:return head
# Create a dummy node
dummy = ListNod... |
57a48e7837ca3890143de593104dffe1f0c40986 | baggy2797/Leetcode | /sum-root-to-leaf-numbers/sum-root-to-leaf-numbers.py | 712 | 3.59375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
summ = 0
stack = [(root,0)]
wh... |
5ae932198791ccfffd9e0727388375b4084aa32b | baggy2797/Leetcode | /flatten-a-multilevel-doubly-linked-list/flatten-a-multilevel-doubly-linked-list.py | 873 | 3.90625 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
if head is None:
return
ptr = head
... |
74ee1f783055a6407417c87124a2876fe702c3aa | baggy2797/Leetcode | /construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.py | 1,156 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if len(inorder) =... |
b89772189acf885deae1abdf7353b71fed0197ac | baggy2797/Leetcode | /path-sum/path-sum.py | 608 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
# currSum = 0
def dfs... |
b531187045c7ce3964b4a959aece51ffebd3d1ee | baggy2797/Leetcode | /binary-tree-right-side-view/binary-tree-right-side-view.py | 817 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if root is None:
return r... |
36184c42b545bcc9a824761ef8a0d319c2bf099c | LK/advent-of-code | /2016/06-2.py | 211 | 3.5 | 4 | data = [{}, {}, {}, {}, {}, {}, {}, {}]
line = raw_input()
while line != '':
for i in range(8):
if line[i] in data[i]:
data[i][line[i]] += 1
else:
data[i][line[i]] = 1
line = raw_input()
print data |
3f4721a1820ccef30c8e6c5805d0e102c297ed04 | git-shamim/PP7_HangmanGame | /main.py | 949 | 4.03125 | 4 |
import random
from art import Logo, Stages
from words import WordList
print(Logo)
chosen_word = random.choice(WordList)
display = []
for letter in chosen_word:
display += "_"
print(display)
lives = 0
end_of_game = False
while not end_of_game:
guess = input("Guess a letter: ").lower()
if guess in dis... |
1325a23ac8808d7e1af99dd84633623b1fd02c7d | Sinak1228/python | /day2/python2_6.py | 520 | 3.6875 | 4 | import turtle
turtle.shape("turtle")
turtle.speed(4)
turtle.forward(10)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
for i in range(4):
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
def drawRec(size):
for i in range(4):
... |
ee01ecda0f25af5ea3109b8a996950ee46a4d4fe | Grabizza/tema_1 | /tema_1.3.py | 909 | 4.03125 | 4 | # Creati un program in care utilizatorul sa introduca un an. Calculati daca anul este
# bisect sau nu si afisati un raspuns in acest sens. OBS. Un an bisect se imparte exact
# la 4 (fara rest).
a = input("Introduceti un an între 1582 și 4818: ")
if int(a) % 100 == 0 and int(a) % 4 == 0 and int(a) % 400 == 0:
pri... |
8358b7abc87c5062eeb4b676eb1091b5d6d897ba | abhijit-nimbalkar/Python-Assignment-2 | /ftoc.py | 530 | 4.125 | 4 | #Author-Abhijit Nimbalkar & Sriman Kolachalam
import Functions #importing Functions.py file having multiple functions
temp_in_F=Functions.check_temp_input_for_F("Enter the Temperature in Fahrenheit: ") #Calling function check_temp_input_for_F() for accepting the valid input from User
... |
685d18829d1197fa5471cfed83446b14af65789e | hsuvas/FDP_py_assignments | /Day2/Q6_FibonacciRecursion.py | 263 | 4.25 | 4 | #6. fibonacci series till the Nth term by using a recursive function.
def fibo(n):
if n<=1:
return n
else:
return (fibo(n-1)+fibo(n-2))
n=int(input("How many numbers: "))
print("Fibonacci series: ")
for i in range(n):
print(fibo(i))
|
99bb6059454cf462afbe9bfc528b8ea6d9d84ecb | hsuvas/FDP_py_assignments | /Day2/Q3_areaCircumference.py | 279 | 4.5 | 4 | #3.compute and return the area and circumference of a circle.
def area(r):
area=3.14*r*r
return area
def circumference(r):
c=2*3.14*r
return c
r=float(input("enter the radius"))
a=area(r)
print("area is: ",a)
cf=circumference(r)
print("Circumference is: ",cf)
|
74fc29314eb63c66e57218e66e7696506a4217a6 | vxda7/HomeAlgorithm | /mystring.py | 377 | 3.796875 | 4 | def solution(strings, n):
answer = {}
for string in strings:
if string[n] not in answer:
answer[string[n]] = [string]
else:
answer[string[n]].append(string)
order = sorted(list(answer))
result = []
for i in order:
result.extend(sorted(answer[i]))
r... |
0a0ffbdb8ae89807c3e403f8dd39aac927f5d116 | ladyy27/comparacion-planes-NLP | /NLPcode_Lady/proyNLP/english-text.py | 691 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pattern.en import parse, split, pprint
from textblob import TextBlob, Word
cadena_spanish = u'La casa mas llenando' #problemas con tildes con textos en espaniol
cadena_english = u'University Technical Particular of Loja and University of Cuenca located in south of Ecu... |
2518fde059b39c5854137c045eccd2b3a49fb333 | sdbzmyh/Sort_Algorithms | /Sort_Algorithms(python)/Bucket_Sort.py | 714 | 3.515625 | 4 | import random
# 计时器:
import time
def cal_time(func):
def wapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print("%s running time is %s s:" % (func.__name__, end_time - start_time))
return result
return wapper
@ca... |
e95f31650450c53b51827fffc39b08ab8b2dd672 | fsabre/DocNetDB | /docnetdb/edge.py | 8,438 | 3.515625 | 4 | """This module defines a class for edge return."""
from typing import Optional, Tuple
from docnetdb.exceptions import VertexInsertionException
from docnetdb.vertex import Vertex
class Edge:
"""An Edge is an object that links two vertices in a DocNetDB."""
def __init__(
self,
start: Vertex,
... |
2e90bfd10bcee14a7ab0a6b82a2c1fce3f9daf72 | mochfatchur/Tucil2_13519009 | /src/main_13519009.py | 857 | 3.578125 | 4 | # NIM/Nama : 13519009/Mochammad Fatchur Rochman
# Program : Program Aplikasi Topology Sorting dengan Decrease and Conquer
# import file
import fungsi_13519009 as f
# ================== Main Program ==================
listAdja = f.makeListAdja()
listVertex = f.makeListVertex()
AdjaMatrix = f.makeAd... |
29e762e758d257839ef7584f1a2c11f821c85216 | python-basic/sem3-t4-nanashinogonbee | /vartask4.2/custom_factorial.py | 587 | 3.953125 | 4 | import re
def factorial(n):
if '.' in str(n):
raise ValueError("Факториала от дробного числа не существует!")
elif not re.sub('\.|\-', '', str(n)).isdigit():
raise TypeError("Аргумент не является числом!")
elif float(n) < 0:
raise ValueError("Факториала от отрицательного числа не с... |
d64ed4407b29e408d885fe128aa8d4f13bf73413 | BigQNo2/coding_interview | /coding_interview_book/python_solution/solution.py | 20,668 | 3.796875 | 4 | """A module contains the methods (interfaces) to solve the coding puzzles in
the book of coding interview"""
import random
from linkedlist import LinkedListNode
###chapter 1 Arrays and Strings###
#1.1
def is_unique_chars(string):
target = string[0]
for index in range(1, len(string)):
if string[index... |
be56efbdb9b4a112b83244cd2195409a642c8706 | GuilhermeFer/hello-word | /Jogo.py | 5,820 | 3.875 | 4 | def cabecalho(string):
print('=' * len(string))
print( string)
print('=' * len(string))
def geraDicionario():
"""
Gera um dicionario com todas as palavras do arquivo txt
:return: a lista
"""
dicionario = []
arq = open('PALAVRAS.txt', 'r')
for palavra in arq:
... |
deeab9d72859a0a14a9af7e47ac24db2c1228a8b | Hoiy/tf_playground | /Utils/visual.py | 542 | 3.546875 | 4 | import matplotlib.pyplot as plt
def hist(data, bin_width=1, title='Data Histogram'):
plt.hist(data, range(min(data), max(data) + bin_width, bin_width))
plt.title(title)
plt.show()
def plot(data, title="Data Plot"):
plt.plot(data)
plt.show()
def tally(iteratable):
from collections import defau... |
db52166c1da16e74c737522bf01ccbc2e3a5331b | jared0169/Project_Euler_Code | /PE_Problem4.py | 563 | 4.1875 | 4 | # File: PE_Problem4.py
#
# Finds the largest palindrome that results from the multiplication
# of two three digit numbers.
import string
def main():
i = 100
j = 101
largest_palindrome = 0
for i in range(100,999):
for j in range(100,999):
## print "Forwards: " + str(i*j)
## ... |
5ad69cd02b90d74e66bd7a3da0c418c8743371e6 | Dentistguba/Py-text-adventure | /Player.py | 2,935 | 3.828125 | 4 | class Player: # creates player class
def __init__(self):
self.items = ["cards", "biscuits"]
self.room = 'room1'
self.help = ["general", "commands"]
print "player created"
print ""
def printAttributes(self):
print "you have:"
... |
56123d2678142af4b8eb0693f190d05e2e910d03 | sarastavnitser/Tic-Tac-Toe | /TicTacToe.py | 21,806 | 3.609375 | 4 | class Player:
name, gamesPlayed, win, draw, loss, percentWin = '', 0, 0, 0, 0, 0.0
leaderBoard = []
def __init__(self, owner, games, wins, draws, losses):
self.name = owner
self.gamesPlayed = games
self.win = wins
self.draw = draws
self.loss = losses
if self.... |
ba02dd388bc913cdaa3b943b35b0003084e60a7e | amitamola/Python_codes | /Week5assign.py | 556 | 4.03125 | 4 | m=0
largest=None
smallest=None
while(m==0):
value=raw_input("Enter the number or type done to finish:")
try:
val=int(value)
if largest==None:
largest= val
if largest<val:
largest=val
if smallest==None:
smallest= val
if smallest>val:
sma... |
edb63793a549bf6bf0e4de33f86a7cefb1718b57 | onionmccabbage/python_april2021 | /using_logic.py | 355 | 4.28125 | 4 | # determine if a number is larger or smaller than another number
a = int(float(input('first number? ')))
b = int(float(input('secomd number? ')))
# using 'if' logic
if a<b: # the colon begins a code block
print('first is less than second')
elif a>b:
print('second is less than first')
else:
pr... |
ee715cb90cf4724f65c0f8d256be926b66dc1ddb | onionmccabbage/python_april2021 | /fifo.py | 1,739 | 4.1875 | 4 | # reading adnd writing files file-input-file-output
# a simple idea is to direct printout to a file
# fout is a common name for file output object
# 'w' will (over)write the file 'a' will append to the file. 't' is for text (the default)
fout = open('log.txt', 'at')
print('warning - lots of interesting loggy st... |
ef261feedf098b391d8c192486b1c83fadc10ec0 | dh-python/01-scraping | /scraping.py | 733 | 3.5 | 4 | #
# Pythonでスクレイピングするサンプルアプリです。
# はてなブックマークの人気一覧を取得します。
#
# 取得元:
# http://b.hatena.ne.jp/hotentry/all
#
# 01. 必要なモジュールを読み込む.
from urllib.request import urlopen
from bs4 import BeautifulSoup
# 02. HTMLを取得.
with urlopen("http://b.hatena.ne.jp/hotentry/all") as response:
html = response.read().decode("utf-8")
# 03... |
e8c48a47f332915ec4d155a4e87ffdee7ec4585d | B2YoonGwan/TIL | /day01/while_for.py | 129 | 3.625 | 4 | dust = [15, 20, 30, 40]
i = 0
while i < 3:
print(dust[i])
i += 1
dust2 = [10, 20, 30, 40]
for j in dust2:
print(j) |
341e1c8897b0554ef1610cf719ebf345425b33f9 | phillyc/kata | /data_munge/slcsp.py | 7,525 | 3.625 | 4 | import csv
import unittest
from shutil import copyfile
print("_____ SLCSP Data Munge! _____")
'''
functional flow:
load_slcsp_file opens a new working file and manages the other functions
get_rate_area returns a tuple of rate area for a given zipcode
lookup_silver_rate_planes returns all silver rate plans for the gi... |
e652cdfba0c6f216e0eebe4e8eb6f54116f40a5d | Avedavalli/others | /flames.py | 1,339 | 3.6875 | 4 | # MY OWN CODE FOR FLAMES GAME
# Visit https://flames.games for playing game
s1=input("enter name1")
s2=input("enter name2")
for i in s1:
for j in s2:
if i==j:
s1=s1.replace(i,'',1)
print(s1)
s2=s2.replace(j,'',1) # only once cancel
print(s2)
... |
0f80255b081389b448733bde339fbbae7461b01d | spops/python-examples | /grouping_adjacent_list_items_using_zip.py | 400 | 3.859375 | 4 | __author__ = 'Taio'
a = [1, 2, 3, 4, 5, 6]
# Using iterators
group_adjacent = lambda a, k: zip(*([iter(a)] * k))
print group_adjacent(a, 3)
print group_adjacent(a, 2)
print group_adjacent(a, 1)
# Using slices
from itertools import islice
group_adjacent = lambda a, k: zip(*(islice(a, i, None, k) for i in range(k)))
... |
6785115c8b39edc8406f7e195bb231fd641ce5b1 | Zemliakov-Sasha/python-online-marathon | /sprint_1/task_8.py | 332 | 3.546875 | 4 | def studying_hours(a):
mlist = list(a)
maxCom = []
mc = 1
for i in range(0, len(mlist)-1):
if mlist[i] <= mlist[i+1]:
mc += 1
elif mlist[i] > mlist[i+1]:
maxCom.append(mc)
mc = 1
if mc == len(mlist):
maxCom.append(mc)
return ma... |
a7bf0783b9b730eaf157dfdd65ed924de0f6935d | Zemliakov-Sasha/python-online-marathon | /sprint_8/Sprint_8_task_1.py | 1,218 | 3.84375 | 4 | import unittest
class Product:
def __init__(self, name, price, count):
self.name = name
self.price = price
self.count = count
class Cart:
def __init__(self, pr_list):
self.pr_list = pr_list
self.total_price = 0
self.discount1 = [1, 5, 7, 10, 20]
... |
a6387615e581fe67bf7b83706369ea63a79d0040 | Zemliakov-Sasha/python-online-marathon | /sprint_8/Sprint_8_task_3.py | 681 | 3.546875 | 4 | import unittest
import math
def quadratic_equation(a, b, c):
D = b ** 2 - 4 * a * c
if D < 0:
return None
try:
x1 = (-b - math.sqrt(D)) / (2 * a)
x2 = (-b + math.sqrt(D)) / (2 * a)
except:
raise ValueError
if D == 0:
return x1
return x1, x... |
61d3efbfc5bbcde0a82620665d70b392510f10fb | Zemliakov-Sasha/python-online-marathon | /sprint_7/Sprint_7_task_1.py | 1,659 | 3.953125 | 4 | from abc import ABC, abstractmethod
class Product(ABC):
@abstractmethod
def cook(self):
pass
class FettuccineAlfredo(Product, ABC):
def __init__(self):
self.name_of_the_dish = "Fettuccine Alfredo"
def cook(self):
print(f"Italian main course prepared: {self.name... |
c6ed8221c4ba443d70110116f2cb26b50fe6d222 | VadymGor/michael_dawson | /chapter10/labeler.py | 377 | 3.953125 | 4 | # Labeler
# Demonstrates a label
from tkinter import *
# create the root window
root = Tk()
root.title("Labeler")
root.geometry("200x50")
# create a frame in the window to hold other widgets
app = Frame(root)
app.grid()
# create a label in the frame
lbl = Label(app, text = "I'm a label!")
lbl.grid()... |
4417ee4d4251854d55dd22522dfef83a0f55d396 | VadymGor/michael_dawson | /chapter04/hero's_inventory.py | 592 | 4.40625 | 4 | # Hero's Inventory
# Demonstrates tuple creation
# create an empty tuple
inventory = ()
# treat the tuple as a condition
if not inventory:
print("You are empty-handed.")
input("\nPress the enter key to continue.")
# create a tuple with some items
inventory = ("sword",
"armor",
... |
abca200c4dd4b0f66efe91d0150f53d3191a3f5a | vladimir-popov-dev/Lesson_5 | /Lesson_5.py | 1,780 | 3.609375 | 4 | from divisor_master import *
# 1) проверка числа на простоту (простые числа - это те числа у которых делители единица и они сами);
for x in range(1, 30):
if isprime(x):
print(f'{x} - Простое число')
print()
number = 590
# 2) выводит список всех делителей числа;
print(f'Все делители числа {number}: ', al... |
6eee30d3f04256afe17c29c0b2fa22ff29c6bb42 | Marcocuma/ejercicioclasespython | /programa 1/programa1.py | 3,151 | 3.875 | 4 | import math
class Punto:
def __init__(self,x,y):
self.x = x
self.y = y
class Forma:
def __init__(self,color,coord,nombre):
self.color = color
self.coordCenFor = coord
self.nombre = nombre
def imprimir(self):
print(self.nombre)
print(self.color)
... |
1d5911d071561fa9f0e24036a56e6a8893ebbe77 | dmatt/learning | /linked_list_temp.py | 4,406 | 4.1875 | 4 | """Linked list with printing to show how it works"""
class LinkedList:
"""Linked list data type"""
empty = ()
def __init__(self):
self.head = self.empty
def append(self, data):
"""Appends node to LinkedList"""
# create a new Node instance with data
new_node = Node(data... |
0c9912a9f65d30a96f29ee5f011e05984d407add | DanLEE278/Python_practice | /19. 사용자 정의 예외처리.py | 945 | 4.03125 | 4 | '''
프로그램에서 의도적으로 에러를 발생시키는 경우
'''
class BigNumberError(Exception):
def __init__(self, message):
self.msg = message
def __str__(self):
return self.msg
try:
print("한 자리 숫자 전용 계산기 입니다")
num = []
num.append(int(input("첫 번째 숫자를 입력하세요:\n ")))
num.append(int(input(... |
680b0c77882242aed07f0769b2e4148e675b9854 | DanLEE278/Python_practice | /16. 스타크래프트.py | 5,362 | 3.625 | 4 | from random import *
class unit:
def __init__(self, name, hp, speed): # 여기서 __init__은 생성자이다
self.name = name
self.hp = hp
self.speed = speed
print("\n---{0} 유닛이 생성되엇습니다.---".format(self.name)) # 매개변수 self.name 혹시 파라미터 name 둘 다 상관없다
if self.speed > 0:
... |
bff74b2cb4ebf8c546634ae96ca20d21d3db8a11 | estods3/PathPlanning-withGeneticAI | /src/Sample.py | 5,843 | 3.5 | 4 | import pygame
import random
import math
import numpy as np
##---------------------------------------------------------------------------------------------------------
## Sample: A Sample of a Population. A Sample only knows where it starts and where the end is
## the Sample has Genetics (random decision-making) and Po... |
2c4cd4e5380046dbe6ad18b104900df6360e360f | prithvijitguha/CS-50x | /pset6/dna/dna.py | 1,956 | 3.96875 | 4 | from sys import argv, exit
from csv import DictReader
import sys
#minimum 3 elements for command line argument
if len(argv) != 3:
print("python dna.py data.csv sequence.txt")
exit(1)
#open dna_file
dna_file = open(argv[1], 'r')
#making strands[AGAT, ATTA] list and persons dictionary eg. Alice [1,2,3]
strands... |
88e73cf98c8d8afb7e218dd93de37e125f452005 | shetu000/9th_july_python_tutorial | /math_func_texting.py | 182 | 3.78125 | 4 | def fib(n):
a,b=0,1
for _ in range(n):
a,b=b,a+b
return a
def next_collatz_element(n):
if n%2==0:
return n/2
else:
return 3*n+1 |
a71684931574dd0626e416ccf42322b88eeac7a3 | tbae2/automatetheboringstuff | /chapter4/myPets.py | 253 | 4.0625 | 4 | myFurballs = ['Evey','Quorra','Riddick','Tetris','Guinevere']
print('Enter a name of one of my pets if you know it ')
petname = input()
if petname not in myFurballs:
print("I don't have a pet named" + petname)
else:
print(petname + " is my pet") |
dbb776b0d6442bb9aff550552e63cbc2202bcf31 | Wojtek001/gittting-dojo | /gittie.py | 336 | 3.515625 | 4 | def introduce():
x = "hello"
y = "gitttt"
print(x + y)
print("Hello,I'm Gittie!")
print("Hello Gittie, you are so fuc***g stupid!")
def add(a, b):
a = 5
b = 3
print( a+b)
def joke():
print("lalala")
def shout():
print("AAAAAAAA")
print("I really have to go home and tak... |
6d19be295873c9c65fcbb19b9adbca57d700cb64 | vedk21/data_structure_playground | /Arrays/Rearrangement/Pattern/alternate_positive_negative_numbers_solution.py | 1,882 | 4.125 | 4 | # Rearrange array such that positive and negative elements are alternate to each other,
# if positive or negative numbers are more then arrange them all at end
# Time Complexity: O(n)
# Auxiliary Space Complexity: O(1)
# helper functions
def swap(arr, a, b):
arr[a], arr[b] = arr[b], arr[a]
return arr
def righ... |
0459e918343c558a684be264163e07caca7e9633 | vedk21/data_structure_playground | /Arrays/Rearrangement/Pattern/reorder_array_according_to_index_array_solution.py | 2,327 | 3.859375 | 4 | # standard library packages and modules
import array as ar
# Reorder the array according to index array
# Time Complexity: O(n2)
# Auxiliary Space Complexity: O(1)
def reorderUsingArray(arr, size, indexes):
for i in range(size):
# unless we find correct number at ith location
while(indexes[i] != i... |
00d5800650241af3ce88a32f20a8af810b7c8de2 | vedk21/data_structure_playground | /Arrays/Rearrangement/main.py | 4,823 | 4.1875 | 4 | # lib imports
import numpy as np
# Pattern arr[i] = i imports
from Pattern.index_at_element_pattern_solution import arrangeUsingIteration, arrangeUsingSwap
# Pattern arr[i] >= arr[j] even positions, j < i
from Pattern.element_even_position_odd_position_solution import arrange as arrangeEvenOdd
# Pattern alternate po... |
90e9e4177bb6a0dbdb5e1d8dba480b3b5235aac9 | vedk21/data_structure_playground | /Arrays/Rearrangement/Pattern/index_at_element_pattern_solution.py | 2,086 | 4 | 4 | # Rearrange array such that arr[i] = i and if element is not present in array show -1
# Time Complexity: O(n)
# Auxiliary Space Complexity: O(1)
# helper functions
def swap(arr, a, b):
temp = arr[b]
arr[b] = arr[a]
arr[a] = temp
return arr
def arrangeUsingIteration(arr, size):
for i in range(size)... |
2287d11bd36b54502a71e290be074cab867ac5e3 | birdral/CodeProblems-Collect | /array_search.py | 763 | 3.71875 | 4 | class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
len_row = len(array)
len_column = len(array[0])
row = len(array)-1
column = 0
while (row >= 0 and column < len_column):
if (target == array[row][column]):
ret... |
506f29d4fdab36317e72b0e283b9ce16601536d5 | papyjimmie/workshop2 | /for/7.py | 1,024 | 3.6875 | 4 | # EX1
string_list = ["jim", "por", "tide", "bb", "lohma"]
string_upper_list = [string.upper() for string in string_list]
print("string_upper_list", string_upper_list)
string_upper_list = []
string_list = ["jim", "por", "tide", "bb", "lohma"]
for string in string_list:
string_upper_list.append(string.upper())
prin... |
e6500af80071e8f1fbbf21fa99a8ad6f4284e5ec | Kn0Juan/learnin | /containers.py | 488 | 3.84375 | 4 | a = [234, 543, 394]
print(a)
for thing in a:
print(thing)
c = []
for i in range(3):
b = a[i]
print('before' , i, b, c)
print (b % 2)
if b % 2 == 0:
c.append(b)
print('after' , i, b, c)
print('- ' *20)
# for i in range(12):
# if i % 3 == 0:
# print(i, 'i is div... |
87106ed1e493f1f028759151657a81df0b4a777c | tzuhsuancheng/Programming-for-Business-Computing | /hw7/HW7-Q3/sol_q3.py | 986 | 3.8125 | 4 | """
註解掉的是助教我自己的寫法
"""
# import re
file_path = input()
# processing query, split()也會對 tab 做處理
query = ' '.join(input().lower().split())
# query = re.sub('\s+', ' ', input().lower()).strip()
count = 0
# txt 第一與最後一個element都是空字串
txt = [""]
with open(file_path, encoding='utf-8') as file:
for line in file:
t... |
b73d252f2c07566863ff67a65ce531f2e52f7a33 | NewWisdom/Nomard-Corder-Python-Challenge | /Day-Eleven/scrapper.py | 1,806 | 3.640625 | 4 | import requests
from bs4 import BeautifulSoup
"""
When you try to scrape reddit make sure to send the 'headers' on your request.
Reddit blocks scrappers so we have to include these headers to make reddit think
that we are a normal computer and not a python script.
How to use: requests.get(url, headers=headers)
"""
he... |
793b2aaa505dfdd8be6a939dac241529b3503bf1 | acyclics/RL-Navigation | /environment/worldgen/transforms.py | 3,001 | 3.578125 | 4 | import numpy as np
from collections import OrderedDict
'''
Transforms are functions which modify the world in-place.
They can be used to add, remove or change specific attributes, tags, etc.
'''
def closure_transform(closure):
'''
Call closure on every OrderedDict.
This transfor... |
57f67489c5b0eb8294fa560d7e036a2ebd3ae518 | theArjun/bikeinfos | /bajaj/bajaj.py | 603 | 3.609375 | 4 | import pandas as pd
import re
import requests
from bs4 import BeautifulSoup
#site = input("Enter the url of the site that you want to scrape: ")
page = requests.get('https://nepal.globalbajaj.com/en/brands/dominar/dominar-d400')
name = input("Enter the bike: ")
soup = BeautifulSoup(page.content, 'html.parser')
sp... |
6486ac7ed372046816644a1ba40be85acb305e48 | Silvarion/python | /learning/code_samples/os_and_env.py | 132 | 3.796875 | 4 | #!/usr/bin/env python3
from math import pi
import os
decimals = int(os.getenv('DIGITS').strip() or 10)
print(round(pi,decimals))
|
e36582cbe73bd77e0fa66bb27cab1cbed541d02b | fakehacker0504/ip_address_teller | /Ip_teller.py | 400 | 3.8125 | 4 | import socket
user_input = input("Enter Your Name:")
hostname = socket.gethostname()
ip_address =socket.gethostbyname(hostname)
print ('Your ip address is',ip_address )
print('_'* 40)
print ("\nHello\t" + user_input)
print("have a great day?.\nIf you like my code then upvote👍👍 it otherwise you can comment👎🙄�... |
d68281a7c09e8591dada7d06881b244bf3ac65e4 | WilliamHYZhang/BullsAndCows | /main.py | 3,103 | 4.3125 | 4 | '''
Bulls and Cows
Searches through all https://scrabble.merriam.com/3-letter-words and makes the best possible guess every turn.
Usage:
add => adds a guess from another player's turn
play => output best guess at current turn
print => output current search space
'''
from collections import Counter
word_list = set(
... |
7d450ea502d0af7b2c6382a4a962a6ab2a14bea6 | theodcr/music-reviews | /musicreviews/formatter/markdown.py | 1,916 | 3.671875 | 4 | """
Functions for writing indexed reviews lists in markdown format.
Formatters take an integer index and a dictionary as inputs.
"""
from . import utils
parse_list = utils.parse_list
def parse_categorised_lists(
data,
header_formatter,
formatter,
descriptions=None,
description_formatter=None,
... |
7ca12f21d01ea969904bfa37bf6b9e74362d2be8 | kevinyou/emparser | /parser.py | 14,646 | 3.5 | 4 | #!/usr/bin/env python3
"""Self-contained python script that retrieves games, parses them, and then prints the output as text. """
import json
import re
import sys
import argparse
from pprint import pprint
from urllib.request import urlopen
from urllib.error import URLError
def run_arg(settings):
"""Runs with comm... |
5da3dfab50685e04ba5e435a7bf09a42765a9265 | kurijlj/IPython-Environment | /environment.py | 4,056 | 3.609375 | 4 | from os import listdir
from os.path import isdir, exists
class OsDirectory(object):
"""Wrapper for common os module directory functions.
Attributes:
_path (str): string representing path to directory. If not provided on
instantiation '.' is used as default value.
""... |
e149ad4cc8b69c2addbcc4c5070c00885d26726d | KyrillMetalnikov/HelloWorld | /Temperature.py | 329 | 4.21875 | 4 | celsius = 10
fahrenheit = celsius * 9/5 + 32
print("{} degrees celsius is equal to {} degrees fahrenheit!".format(celsius, fahrenheit))
print("Roses are red")
print("Violets are blue")
print("Sugar is sweet")
print("But I have commitment issues")
print("So I'd rather just be friends")
print("At this point in our relati... |
343e2adf234e4c96b4c52bc6d26ab88d035f426c | vsedll/pyGames | /gibbet.py | 1,799 | 3.84375 | 4 | import numpy as np
def Gibbet_game():
print("В этой игре от вас требуется угадать загаданное слово.")
print("Вы угадываете по буквам, если в загаданном слове таких букв нет вы потеряете 1 жизнь!")
print("У вас есть пять попыток...")
lifes = 5
word_state = list("-")
set_Of_Words = ["Слово... |
ef8b66b3c517a394d5e2cecb1238525f9ee3be3e | Akki1994-DS/Data-Science-2020 | /Spam NB.py | 2,683 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 8 02:24:45 2020
@author: axays
"""
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer,TfidfTransformer
import re
Mail=pd.read_csv('C:\\Users\\axays\\Downloads\\ham_spam.csv',encoding='latin1')
def clean... |
174ecfe445b7c69377624363e4a564ff14a60cdf | sadiqkanner/Pythoner | /Shop_Entry.py | 4,003 | 3.59375 | 4 |
def Display(records,today,no):
header="""
PEN AND PAPER SHOP
Cell# 0218838388
DHA COMMERCIAL AREA PHASE-6
Date : """+str(today.date())+"""
"""'PRICE'.ljust(1)+""" """+'QTY'.center(15)+""" """+'AMOUNT'.ljust(10)+"""
----------------------------"""
pri... |
04d886e75962ad8248b043976222f035750bf8e2 | kngovand/CodeWars | /phone_number.py | 310 | 3.8125 | 4 | def create_phone_number(n):
one = ""
two = ""
three = ""
phone = ""
for i in range(3):
one += str(n[i])
for i in range(3, 6):
two += str(n[i])
for i in range(6, 10):
three += str(n[i])
phone = "({0}) {1}-{2}".format(one, two, three)
return phone |
dffcd35fe03cff351c43dbee9dbca2ebed3bc0cc | kngovand/CodeWars | /CTCI/unique_char.py | 190 | 3.84375 | 4 | def unique_char(s):
result = []
for char in s:
if char not in result:
result.append(char)
elif char in result:
return False
return True
|
d89ea16537bd5770997d8bf803c0b0a282ba823d | varconstantine/reference-data-science-projects | /reproducible-data-analysis/helpers/data.py | 1,136 | 3.53125 | 4 | import os
import pandas as pd
from urllib.request import urlretrieve
# Define helper functions
# Fremont data url
FREMONT_URL = 'https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD'
# Download the Fremont data if it doesn't exist already
def get_fremont_data(file_name='Fremont.csv', url=FREMONT... |
6eb51864d00ad541707ffe5fcbd457461f648023 | peezy23/Practice-Project | /Macro_Calculator02.py | 1,193 | 3.671875 | 4 | ''' PROJECT 1 REMAKE (CLASS VERSION): MACRO CALCULATOR '''
# SECOND DRAFT:
# TURN The first version of Macro Calculator into a class
class Macro:
''' Represent a calulator to calculate a person macro '''
def __init__(self, gender, age, height, weight, active):
''' Initializing attributes... |
0d90ed22da2daf2a4c2eea428e11f430bb745786 | yedehrab/ProgrammingHandBook | /H-KesirSadeleştirme/KesirSadelestirme.py | 552 | 3.8125 | 4 | # Değişkenlerin tanımlanması
i = 2
print("Payi gir:")
# Pay ve paydanın girilmesi
pay = int(input())
print("Paydayi gir:")
payda = int(input())
# Pay ve paydanın küçüğünün tespit edilmesi
if (pay > payda):
kucuk = abs(payda);
else:
kucuk = abs(pay);
while i <= kucuk:
if pay % i == 0 and payda % i == 0:
... |
0be9a993b1fd3fd9757ee11b0f8edc61d6f34234 | yedehrab/ProgrammingHandBook | /8-RakamSayısınıBulmak/RakamSayisi.py | 334 | 3.921875 | 4 | # “x” ve “i”nin tanımlanması
x = 0
i = 0
print("3 haneli sayi giriniz: ")
# “x”in girilmesi
x = int(input())
# 3 kere dönen döngünün oluşturulması
for i in range(0,3):
# Kalanın yazdırılması
print(x % 10)
# “x”in onlar basamağının birler basamağına dönüştürülmesi
x = x / 10
|
0068408c4f9765c350df0f1e63048a4e9839662e | sailymarudwar/Leetcode | /91_Decode_ways.py | 1,548 | 3.90625 | 4 | '''A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example 1:
Input: s = "12"
Output... |
3d3f804f6ffb0d1027770dc1573efb717b874ac4 | sailymarudwar/Leetcode | /26_remove_deplicates_from_sortedarray.py | 1,229 | 3.96875 | 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 l... |
2fde83b14f6c363772e6eb7acb07068c13890678 | haoxiaoning1125/python_cookbook | /3_数字日期和时间/3_8.py | 333 | 3.71875 | 4 | # coding:utf-8
"""
分数运算
"""
from fractions import Fraction
if __name__ == '__main__':
a = Fraction(5, 4)
b = Fraction(7, 16)
print a + b
print a * b
print '-' * 20
c = a * b
print (c.numerator, c.denominator)
print '-' * 20
print float(c)
print Fraction(*3.75.as_integer_rat... |
d189989699fe8a945aad5495e4c4a9741ffa6f32 | haoxiaoning1125/python_cookbook | /1_数据结构和算法/1_2.py | 209 | 3.75 | 4 | def drop_first_last(grades):
# _, *middles, _ = grades # python versions < 3.0
return grades[1:len(grades) - 1]
if __name__ == '__main__':
list_ = [1, 2, 3, 4]
print drop_first_last(list_)
|
d27a03f5e6e3ad8dc854f8d2c49358530e861711 | haoxiaoning1125/python_cookbook | /8_类与对象/8_17.py | 469 | 3.671875 | 4 | # coding:utf-8
"""
创建不调用 __init__() 方法的实例
"""
class Date(object):
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __repr__(self):
return '{}-{}-{}'.format(self.year, self.month, self.day)
if __name__ == '__main__':
d = Date._... |
8a7c1b8944e170e94d17c024ffacf13f71ab64c9 | haoxiaoning1125/python_cookbook | /4_迭代器与生成器/4_10.py | 226 | 3.90625 | 4 | # coding:utf-8
"""
序列上索引值迭代
"""
if __name__ == '__main__':
my_list = ['a', 'b', 'c']
print [(idx, val) for idx, val in enumerate(my_list)]
print [(idx, val) for idx, val in enumerate(my_list, 1)]
|
5f014a15021c97477572b533ab5d9b3bb6a7b4d5 | haoxiaoning1125/python_cookbook | /8_类与对象/8_7.py | 429 | 3.75 | 4 | # coding:utf-8
"""
在子类中调用父类的某个已经被覆盖的方法
"""
class A(object):
def __init__(self):
self.x = 0
def spam(self):
print 'A.spam'
class B(A):
def __init__(self):
super(B, self).__init__()
self.y = 1
def spam(self):
print 'B.spam'
super(B, self).spam()
if ... |
d40f2cf3405f1825a8a06b4f2f0822e5b30b7eea | haoxiaoning1125/python_cookbook | /8_类与对象/8_14.py | 544 | 3.90625 | 4 | # coding:utf-8
"""
自定义数据容器
"""
import collections
class SortedItems(collections.Sequence):
def __init__(self, initial=None):
self._items = sorted(initial) if initial is not None else []
def __getitem__(self, index):
return self._items[index]
def add(self, item):
self._items.ap... |
0be7e1c8ffe32c1b7b8e7b1cd844f85a4ebfd373 | haoxiaoning1125/python_cookbook | /4_迭代器与生成器/4_7.py | 240 | 3.59375 | 4 | # coding:utf-8
"""
迭代器切片
"""
import itertools
def count(n):
while True:
yield n
n += 1
if __name__ == '__main__':
c = count(0)
# print c[10:20]
print [x for x in itertools.islice(c, 10, 20)]
|
9a3f9acaf6830aed46e2e5291c3ecba50be8767d | haoxiaoning1125/python_cookbook | /3_数字日期和时间/3_2.py | 518 | 3.640625 | 4 | # coding:utf-8
"""
执行精确的浮点数运算
"""
from decimal import Decimal, localcontext
if __name__ == '__main__':
print '4.2 + 2.1 == 6.3? : {}'.format(4.2 + 2.1 == 6.3)
print '-' * 20
# Decimal
a = Decimal('4.2')
b = Decimal('2.1')
print a + b
print a + b == Decimal(6.3)
print '-' * 20
#... |
c018cea22879247b24084c56731289a2a0f789f5 | abhay-jindal/Coding-Problems | /Minimum Path Sum in Matrix.py | 1,409 | 4.25 | 4 | """
MINIMUM PATH SUM IN MATRIX
https://leetcode.com/problems/minimum-path-sum/
https://www.geeksforgeeks.org/min-cost-path-dp-6/
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right,
which minimizes the sum of all numbers along its path.
Note: You can only move either do... |
a711681f3168d9f733694126d0487f60f39cdf56 | abhay-jindal/Coding-Problems | /Linked List Merge Sort.py | 1,275 | 4.21875 | 4 | """
LINKEDLIST MERGE SORT
"""
# Class to create an Linked list with an Null head pointer
class LinkedList:
def __init__(self):
self.head = None
# sorting of linked list using merge sort in O(nlogn) time complexity
def mergeSort(self, head):
if head is None or head.next is None:
... |
a70906f0124a0ecf81db226e6a5548054d0709aa | abhay-jindal/Coding-Problems | /Array/Fibonacci Number.py | 800 | 3.953125 | 4 | """
FIBONACCI SERIES USING DYNAMIC PROGRAMMING
https://leetcode.com/problems/fibonacci-number/
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence,
such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1
F(n) = F(... |
c2c19d072b086c899b227646826b7ef168e24a78 | abhay-jindal/Coding-Problems | /Array/Zeroes to Left & Right.py | 1,239 | 4.125 | 4 | """
MOVE ZEROES TO LEFT AND RIGHT IN ARRAY
https://leetcode.com/problems/move-zeroes/
Given an integer array nums, move all 0's to the end of it while maintaining the relative order
of the non-zero elements. Note that you must do this in-place without making a copy of the array.
Time complexity: O(n)
"""
def zeros... |
952943db49fe23060e99c65a295d35c1aff7c7d5 | abhay-jindal/Coding-Problems | /LinkedList/check_palindrome.py | 2,523 | 4.21875 | 4 | """
Palindrome Linked List
https://leetcode.com/problems/palindrome-linked-list/
https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false.
"""
from... |
0773d698157ef95a74e715512c70fdc1160092f1 | abhay-jindal/Coding-Problems | /LinkedList/plus_one_linked_list.py | 775 | 4 | 4 | """
Add 1 to a number represented as linked list
https://www.geeksforgeeks.org/add-1-number-represented-linked-list/
Number is represented in linked list such that each digit corresponds to
a node in linked list. Add 1 to it. For example 1999 is represented as
(1-> 9-> 9 -> 9) and adding 1 to it... |
9be41506dd4300748e2b37c19e73cd4e62d107f7 | abhay-jindal/Coding-Problems | /LinkedList/last_nth_node.py | 1,537 | 4.28125 | 4 | """
Clockwise rotation of Linked List
https://leetcode.com/problems/rotate-list/
https://www.geeksforgeeks.org/clockwise-rotation-of-linked-list/
Given a singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.
"""
from main import LinkedList
#... |
c48dd1efa3d7063cccf41adeceddb008fc7d8de0 | abhay-jindal/Coding-Problems | /Array/Searching Algorithms/Search Minimum in Rotated Array.py | 1,457 | 4.03125 | 4 | """
BINARY SEARCH ALGORITHM
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
Suppose an array of length n sorted in ascending order is rotated between 1 and n times.
For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if i... |
f5a7b3a2687114f76cb77f579f2c11046236e1ae | xiewenwenxie/168206 | /168206243/binary_search.py | 730 | 3.671875 | 4 |
#二分查找法
L = [2,12,22,32,42,52,62,72]
def binary_search(L,number):
low = 0
high = len(L) - 1
while low <= high:
mid = (low+high)//2
guess = L[mid]
if guess > number:
high = mid - 1
elif guess < number:
low = mid + 1
else:
... |
11c8488b119408af3a43fedc225b32309c335599 | xiewenwenxie/168206 | /168206209/03.py | 497 | 4.03125 | 4 | #!/usr/bin/python3
# -- coding: utf-8 --
'''快速排序'''
def quicksort(array):
if len(array)<2:
return array
else:
pivot=array[0]
less=[i for i in array[1:] if i <= pivot]
great=[j for j in array[1:] if j >pivot]
return quicksort(less)+[pivot]+quicksort(great)
if __name__... |
78433e5a63911e328884f5b5507d9106be43b647 | xiewenwenxie/168206 | /168206120/快速排序.py | 508 | 3.53125 | 4 | def quick_sort(alist, l, r):
if l < r:
q = partition(alist, l, r)
return quick_sort(alist, l, q - 1)
return quick_sort(alist, q + 1, r)
return alist
def partition(alist, l, r):
x = alist[r]
i = l - 1
for j in range(l, r):
if alist[j] <= x:
i += 1
a... |
23bb02b5a9eaba9704ab7768912e5cbbbeac1fae | xiewenwenxie/168206 | /168206243/selection_sort.py | 633 | 3.953125 | 4 |
#选择排序法
def selection_sort(array):
for i in range(0,len(array)):
for j in range(i+1,len(array)):
if array[i] > array[j]:
flag = array[i]
array[i] = array[j]
array[j] = flag
#选择排序法
if __name__ =='__main__':
... |
6e7e04e286ba06f3f6f481a5a847b900fc37e067 | xiewenwenxie/168206 | /168206134/quicksort.py | 261 | 3.6875 | 4 | def qs(arr):
if len(arr)<2:
return arr
else:
pivot=arr[0]
less=[i for i in arr[1:] if i<=pivot]
greater=[i for i in arr[1:] if i>=pivot]
return qs(less)+[pivot]+qs(greater)
print qs([1,5,3,8,9,7,6,2,4])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.