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 |
|---|---|---|---|---|---|---|
8132dc8fd2f2ed88fab536995f8acc2968700ed2 | jaypsingh/PyRecipes | /DS_and_Alg/DS_and_Alg_12.py | 1,562 | 4.3125 | 4 | '''
This program demos the use of Counter class from collections module.
Counter objects are very helpful in any case where you need to tabulate or count the data.
'''
from collections import Counter
mySong = ['I', 'wanna', 'be', 'your', 't-shirt', 'when', 'it', 'is', 'wet', 'I', 'wanna', 'be', 'the', 'shower', 'when'... |
05a2236c845b1f9093b405767e60d6380e480164 | jaypsingh/PyRecipes | /Num_Date_Time/Num_Date_Time_06.py | 397 | 3.984375 | 4 | '''
Working with Complex Number
'''
# represent complex Number
cNum1 = complex(2,3)
cNum2 = 4+5j
print(cNum1)
print(cNum2)
print(cNum1.real)
print(cNum1.imag)
print(cNum1.conjugate())
#Regular Math Operation
print(cNum1 + cNum2)
print(cNum2 - cNum1)
# Complex sin cos operation can be done using cmath module
import c... |
f8d563e8c1ce87996fe1f0df6ebe05e65ff8a543 | jaypsingh/PyRecipes | /String_n_Text/Str_n_Txt_05.py | 445 | 4.1875 | 4 | '''
This function demonstrates how can we search and replace strings
'''
import re
myStr = "Today is 03/09/2016. Game of Thrones starts 21/07/2017"
# Simple replace using str.replace()
print (myStr.replace('Today', 'Tomorrow'))
# Replace using re.sub() - Approach 1
print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3\-2\-1', my... |
a0be193b90cc0a8b7585e4ae190f4e91c834367a | yxudong/LeetCode | /155.最小栈.py | 2,945 | 3.75 | 4 | #
# @lc app=leetcode.cn id=155 lang=python3
#
# [155] 最小栈
#
# @lc code=start
# Tips: stack
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min_data = None
def push(self, x: int) -> None:
if not self.stack:
... |
20dc4d2242bcb8002c3871d4eff17010ffe418c0 | yxudong/LeetCode | /142.环形链表-ii.py | 1,417 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=142 lang=python3
#
# [142] 环形链表 II
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Tips: linked-list, two-pointers
class Solution:
def detectCycle(self, head: ListNode) -> ListNod... |
8d041c63bef2d4789d15055dcb235502014022d8 | yxudong/LeetCode | /337.打家劫舍-iii.py | 911 | 3.53125 | 4 | #
# @lc app=leetcode.cn id=337 lang=python3
#
# [337] 打家劫舍 III
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Tips: tree, depth-first-search, dynamic-programming
class Solution:
... |
31b62eedf47a19979d5a143b38c7cbdd0d334ee1 | manojsatya/ProjectEuler | /Hello.py | 156 | 3.734375 | 4 | def printing():
print("Hellooooooo")
print("Grrrrrrrr")
m = 10+5
print("I am " + str(m)+ " years old")
return m
n = printing()
|
8e7e6ee5f319ba994b906aed78385e51acb63a16 | VIJAYAYERUVA/100DaysOfCode | /Python/files.py | 328 | 3.71875 | 4 | openfile = open('data/input/read.txt')
a = openfile.read()
print(a)
openfile.seek(0)
b = openfile.read()
print(b)
openfile.seek(0)
for line in open('data/input/read.txt'):
print(line)
writefile = open('data/output/write.txt', 'r+')
writefile.write('New line in the file')
writefile.seek(0)
c = writefile.read()
p... |
c7dc85e349ccee1c1f9fa7edb94963325cd2f9b5 | o-leolleo/ArtificialIntelligenceExperiments | /tic_tac_toe/ttt.py | 5,876 | 4.40625 | 4 | """
An implementation of tic tac toe using MINIMAX algorithm
the program implements the tic tac toe game, where the
player play with the machine. The machine uses the MINIMAX
algorithm to make decisions.
@author leolleo
"""
import copy
# initial state of empty cells
state = [[' ' for j in range(3... |
72b205cff44cd1ad0ba0eda13807aac97e581add | metheoryt/itstep-python | /1_intro/c_logical_ops.py | 1,339 | 4.09375 | 4 | """
Логические операции
Операции, возвращащие в качестве результата булево значение - True/False
"""
# Приведение к bool
assert bool(0) is False
assert bool('') is False
assert bool([]) is False
assert bool(None) is False
assert bool(-1) is True
assert bool('a') is True
assert bool([1]) is True
# Сравнение
assert ... |
7d18a0cbc54c0ee2c4ced7e785433a986f7b8c40 | metheoryt/itstep-python | /1_intro/d_control_flow.py | 1,799 | 4.09375 | 4 | """
Управление потоком выполнения
Условия и циклы
"""
# самый простой вариант
if True:
print('этот блок выполнится т.к. условие удовлетворено')
# ветвление if-else
if len('spam') == 3:
print('длина spam равна трём (?!)')
else:
print('длина spam не равна трём')
color = 'красный'
# if-elif-else
if color... |
b6cf8c96c8700f9ee78828eae9ebbfb990cc82c7 | manzur1990/Intro-Python-I | /src/03_modules.py | 1,264 | 4 | 4 | """
In this exercise, you'll be playing around with the sys module,
which allows you to access many system specific variables and
methods, and the os module, which gives you access to lower-
level operating system functionality.
"""
# IMPORTS:
import getpass
import os
import sys
import platform
# See docs for the sys ... |
c8913860b13c4619cd5119cacdce93fce0e6bcb7 | DHSZ/programming-challenge-2 | /seven-seg-words.py | 300 | 4.40625 | 4 | def longest_word():
longest_word = ""
## Write your Python3 code inside this function.
## Remember to find words that only use the following letters:
## A, B, C, E, F, H, I, J, L, N, O, P, S, U, Y
## Good luck!!
return longest_word
print(longest_word())
|
70b23ae913caad5a139ae63a78c18df444647581 | shusingh/Python-Essential-Training | /Chap03/types.py | 542 | 4.03125 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
from decimal import *
x = 7
print('x is {}'.format(x))
print(type(x))
print("x is {1:<09} {0:>09}".format(8, 9))
a = 3
b = 4
print(f"hello values: {a:<9} {b:>9}")
# python doesn't work well with decimals as it sacrifices accuracy for precision
# so don'... |
c0527a9f6251fd917e5efed27bc5c2aea8124093 | leninexe/aoc2020 | /18/b.py | 2,798 | 3.734375 | 4 | class Node:
def __init__(self, value, operation):
self.value = value
self.operation = operation
self.childs = []
def buildTree(expression):
i = 0
previousNode = None
while i < len(expression):
c = expression[i]
if c == "(":
start = i + 1
length = findClosingParantheses(expression[start:])
# p... |
f62b7c7e29738623a7ff56231d539ef1d59beac1 | callmexss/leetcode | /solution-python3/5.longest-palindromic-substring.py | 657 | 3.5 | 4 | #
# @lc app=leetcode id=5 lang=python3
#
# [5] Longest Palindromic Substring
#
class Solution:
max_len = 0
loc = 0
def longestPalindrome(self, s: str) -> str:
length = len(s)
if length < 2:
return s
for i in range(length):
self.extend_palindrome(s, i, i)
... |
23613fcf401b5e9b9ffff46c2428a43659d7b0bb | callmexss/leetcode | /solution-python3/524.longest-word-in-dictionary-through-deleting.py | 2,614 | 3.5 | 4 | import heapq
class Solution(object):
def findLongestWord(self, s, d):
"""
:type s: str
:type d: List[str]
:rtype: str
"""
ret = []
for word in d:
it = iter(s)
if all(x in it for x in word):
ret.append(word)
if... |
1fabb4663b58bd89eb041ca547b346e962a8114d | microsoft/electionguard-python | /src/electionguard/hmac.py | 1,114 | 3.921875 | 4 | """Implementation of Hashing for Message Authentication Codes (HMAC)"""
from hmac import digest
from typing import Optional
_BYTE_LENGTH = 4
_BYTE_ORDER = "little"
def get_hmac(
key: bytes, message: bytes, length: Optional[int] = None, start: int = 0
) -> bytes:
"""
Get a hash-based message authenticati... |
f6566752f9da2b437d486db29dc86a293e3ec7f6 | suyushan/remotedesk | /加密方式.py | 976 | 3.703125 | 4 | # -*- coding: cp936 -*-
#A Test to Return a AES-File of a Common File
from Crypto.Cipher import AES
from Crypto import Random
import binascii
"""original password:"""
passwd=b'123456'
print 'The original password is',passwd
"""create way of encryption randomly
and ciphertext of original password:"""
key... |
5c7a83bd06654ebfd6d9669888f9643adb1d77c8 | anaiortega/parametricDesign | /python_modules/geometry_utils/bridges.py | 886 | 3.640625 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
class SlopedWall(object):
'''
:ivar alpha: embankment slope (radians)
:ivar Lambda: angle between the wall and the road axis (radians)
'''
def __init__(self,alpha,Lambda):
self.alpha=alpha
self.Lambda=Lambda
... |
a8cbd3837fa1e3996fe908a29244950cad3d7d38 | HarrisonPierce/Python-Class | /pierce-finalq4.py | 1,153 | 3.765625 | 4 | #Harrison Pierce
##Final q4
from tkinter import *
class Info(Frame):
#Initializer
def __init__(self):
self.window = Tk() #Create frame
self.new_frame = Frame(self.window, width=500, height=50,padx = 50, pady=30)
self.new_frame.grid(row = 5, sticky="nsew")
... |
5f4313bc5806a145daf721c578f7120dd2755c01 | HarrisonPierce/Python-Class | /pierce-assignment2.py | 1,258 | 4.28125 | 4 | ##Harrison Pierce
##This program calculates the factorial of a user defined number
##Set factorial variable to 1
factorial = 1
k = int(input('Enter a postitive integer: '))
##Ask user for an integer and set equal to the variable k
for k in range(1,k + 1):
##start for loop for k. while between 1 and the n... |
c29a04f4230b4ad1a5e1d73227ca164923ab42d2 | CodeDem/ML | /KNN.py | 503 | 3.671875 | 4 | # Fit a classification model using K Nearest Neighbour(KNN) Algorithm on a given data set. [One may use data sets like Caravan, Smarket, Weekly, Auto and Boston]
# Code: -
from sklearn import neighbors, datasets
import pandas as pd
breast_cancer = datasets.load_breast_cancer()
X = pd.DataFrame(breast_cancer.data, co... |
fb2e61b9507892b931bd4e65344f98c7a46e2b14 | ptcodingyahak/urlstoreMysql | /fetching01.py | 271 | 3.515625 | 4 | #-*- coding: utf-8 -*-
# Fetching URLs
import urllib.request
def fetching01():
utf= ('컴퓨터과학')
kurl = utf.encode('UTF-8').decode('UTF-8')
response = urllib.request.urlopen('https://ko.wikipedia.org/wiki/')
html = response.read()
return html
|
7c9cd88fc5062e2d77b565b11551f0ad88917ee6 | RoscoeOBrian/Python_Training | /game_review.py | 1,298 | 3.8125 | 4 | import random
def get_guess():
return list(input("What is your guess"))
def generate_code():
digits=[str(num) for num in range(10)] #create list of strings with numbers 0 to 9
random.shuffle(digits)
return digits[:3]
#Generat clues
def generate_clues(code,user_guess):
if user_gues... |
6a0bd296ddaf1da97a6ed99d9b8c9ba0fc357b2d | bdarapu/NLP524 | /questionInput.py | 1,658 | 3.5 | 4 | '''
clean the questions data provided in qno_list and adds the question to a single file "cleaned_data_questions.csv"
'''
import csv
#convert txt to csv
def txt_csv(txt_file, csv_file):
in_txt = csv.reader(open(txt_file, "r"), delimiter = '\t')
out_csv = csv.writer(open(csv_file, 'w'))
out_csv.writerows(in_txt)
... |
0d6eaaec0b06a34ddec74387dead0933d539f49d | GeorgiusKurli/Analysis_of_Algorithm | /ShannonFano_Compression.py | 2,993 | 3.828125 | 4 | # nodes are [letter, number, code]
from PriorityQueue import *
# function to split a priority queue into two lists of equal (more or less) value and add code
def split_equal_list(priorityq, letter_dict):
# check if more than 1 node in priority queue
if len(priorityq.return_all()) > 1:
priorityq1 = Pr... |
ed002064d2e995e65a6a12191e206056e03c1d31 | EbonyRiddick/Soda-Machine-Testing-Prodject | /test_soda_machine.py | 6,822 | 3.765625 | 4 | import unittest
from soda_machine import SodaMachine
from coins import Quarter, Dime, Nickel, Penny
from cans import Cola, OrangeSoda, RootBeer
class TestFillRegister(unittest.TestCase):
""""Test method for filling register list"""
def setUp(self):
self.soda_machine= SodaMachine()
def test_fill... |
88fd11c60d63541882a29e61b01f5409e532e156 | NityaK123/PythonProgram | /Palindrome.py | 285 | 4.09375 | 4 | x=int(input("Enter number to check Palindrome or not:"))
k=0
j=x
while x>0:
r=x%10
k=k*10+r
x=x//10
print(k)
if k==j:
print("Number is Palindrome")
else:
print("Number is Not Palindrome")
|
081148817550a17eb5ca47db205d9379bbc59c8d | oulenz/fuzzy-rough-learn | /frlearn/uncategorised/transformations.py | 1,689 | 3.5 | 4 | """Functions for transforming ranges of values."""
import numpy as np
__all__ = [
'contract', 'shifted_reciprocal', 'truncated_complement',
]
def contract(x, c: float = 1):
"""
Strictly order-preserving function from `[-∞, ∞]` to `[0, 1]`
that sends `-∞, -c, 0, c, ∞` to `0, 0.25, 0.5, 0.75, 1`, resp... |
2ac360e3c1a07e7657a216f587f807b055f1111c | oulenz/fuzzy-rough-learn | /examples/data_descriptors/one_class_classification.py | 3,139 | 3.796875 | 4 | """
========================
One class classification
========================
Data descriptors generalise knowledge about a target class of data to the whole attribute space.
This can be used to predict whether new data instances belong to the target class or not,
or to identify which new instances should be subjecte... |
a9f0b22836ca6ae81e7d60383386fffdc7ef8011 | Rayansh14/Term-1-Project | /rock paper scissors.py | 2,289 | 4.25 | 4 | import random
score = 0
def generate_random():
return random.choice(["rock", "paper", "scissors"])
def is_valid(user_move):
if user_move in ["rock", "paper", "scissors", "r", "p", "s"]:
return True
return False
def result(comp_move, user_move):
if comp_move == user_move:
return "ti... |
4cac682b2744d3ce1fed901bdc4c85d92606f6ae | shaodan/coder | /leetcode/structures.py | 7,524 | 3.53125 | 4 | """
Basic Data Structures for Leetcode
Author: ShaoDan(shaodan.cn@gmail.com)
"""
class Structure(object):
pass
# def __str__():
# pass
# def __iter__(self):
# pass
class Node(object):
def __init__(self, v):
self.val = v
def __str__(self):
return str(self.val)
... |
728fec813dbad76695eabdd881804cdc93ac9949 | shaodan/coder | /leetcode/023.merge-k-sorted-lists.py | 1,570 | 3.734375 | 4 | #
# [23] Merge k Sorted Lists
#
# https://leetcode.com/graphql
#
# algorithms
# Hard (27.82%)
# Total Accepted: 189.8K
# Total Submissions: 682K
# Testcase Example: '[]'
#
#
# Merge k sorted linked lists and return it as one sorted list. Analyze and
# describe its complexity.
#
#
# Definition for singly-linked li... |
b02b3f4f7df53f05ff807221a75d08d2b9272162 | shaodan/coder | /leetcode/035.search_insert_positon.py | 1,439 | 3.625 | 4 | class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# another binary search
l = len(nums)
if l == 0:
return 0
start = 0
end = l-1
while end>start:... |
1952a1245c37c92ce94e9a157ec0345d7ab9cad9 | shaodan/coder | /leetcode/005.longest-palindromic-substring.py | 1,460 | 3.78125 | 4 | #
# [5] Longest Palindromic Substring
#
# https://leetcode.com/problems/longest-palindromic-substring
#
# Medium (25.14%)
# Total Accepted:
# Total Submissions:
# Testcase Example: '"babad"'
#
# Given a string s, find the longest palindromic substring in s. You may assume
# that the maximum length of s is 1000.
#... |
8bf06720307a1cc2b2dc42de6e64905d0022372d | shaodan/coder | /leetcode/279.perfect_squares.py | 1,306 | 3.640625 | 4 | import math
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
root = int(math.sqrt(n))
self.root = [x*x for x in range(1, root+1)]
self.num = [0] * (n+1)
# dynamic programming
for i in xrange(1, n+1):
... |
85bf1a3903f440d8064c7c9737d401acc386de82 | shaodan/coder | /leetcode/024.swap_nodes_in_pairs.py | 1,246 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
... |
b3e22b635a04c95e29734074c2296ffb64226552 | Julian-J0/MadlibProject | /main.py | 1,692 | 4.15625 | 4 | from random import randint
uinput = input("Choose from 1-2 or type random: " )
def story_1():
Title_1 = input("Input a title: ")
Name_1 = input("Input a name: ")
Adjective_1 = input("Input an adjective: ")
Group_1 = input("Input a group, ex. soldiers: ")
Verbed_1 = input("Input a verb ending in -ed: ")
Feel... |
f2fecdbb89348ffe78c176612a476de9cc05a939 | Dashulkacss/pythonGB | /Lesson3/lesson3_Functions.py | 834 | 3.78125 | 4 | # def simple(s1, s2):
# sub = s1-s2
# sum_ = s1 + s2
# return [sub,sum_]
# print(simple(5,2))
# def registration(*args):
# print(*args)
# def simple(**kwargs):
# return kwargs
# print(simple(s1 = 45, s2 = 23, s3 = 45, s4 = 64))
# my_func = lambda p1, p2: p1+p2
# print(my_func(1,2))
# print((lambda ... |
b9a95cf07a9a61e43704b97ff907e00b95135ebd | Dashulkacss/pythonGB | /Lesson6/L6_Task5.py | 918 | 3.71875 | 4 | class Stationery:
def __init__(self, tittle):
self.tittle = tittle
def draw(self):
print("Запуск отрисовки")
class Pen(Stationery):
def draw(self):
return print("Начинаем создавать шедевры с помощью ручки")
class Pencil(Stationery):
def draw(self):
return print("Я ... |
37422289d5e6607af6cf5d36ed66577d50b448e9 | xrendan/marsweeper | /marsweeper/main.py | 21,281 | 3.625 | 4 | import pygame
from pygame.locals import *
from math import floor
import board
import Ai
import os
class Tiles:
'''
This class provides squares to blit onto the main pygame surface;
there is an initial.
type is an int from 0-11 where type:
0-8 correspond to tiles with numbers 0-8 on them
9 is ... |
88d178029d341771fc474d715722fb530eaa5528 | orhanvegs/2019_spring_week1 | /while_loop.py | 907 | 4.0625 | 4 | # counter = 0
# while counter < 10:
# print(counter)
# counter = counter + 1
# infinte loop = if you wanna exit to push; ctrl+C
# var = 1
# while var == 1: # This constructs an infinite loop
# number = input("Bir numara girin: ")
# print("Sizin girdiginiz numara: ", number)
# sayac = 10
# while sayac... |
8ee3cc72e07a43244e75ee51be02d5187d442a10 | orhanvegs/2019_spring_week1 | /integers.py | 3,682 | 4.0625 | 4 | # no1 = 25
# no2 = 30
# no3 = 27
# no4 = 7
# sum = no1 + no2
# multiplication = no1 * no2
# division = no1 / no2
# modulo= no2 % no1 # ilk sayinin ikinci sayiya bolumunden KALAN sayiyi verir
# remainder = no2 // no1 # ilk sayinin ikinci sayiya bolumunden SONUC olan sayiyi verir
# remainder2 = no3 // no4
# print(sum)
#... |
2b8e83517b987cdc08ae3db8a5eb3542d839d90f | joaomendesln/topicosECT2703 | /Aula 09/pc02.py | 377 | 3.71875 | 4 | from typing import Iterable, Iterator, TypeVar, List
T1 = TypeVar('T1')
def elementos_da_lista(c:Iterable[Iterable[T1]]) -> Iterator[T1]:
i = iter(c)
while True:
try:
g = next(i)
for x in g:
yield x
except StopIteration:
return
l : List[List[int]] = [[1,2,3],[4,5],[],[6,7]]
print(list(elementos_... |
ec5d16c52b7f05a5e0670fb5909bbee2468f2520 | joaomendesln/topicosECT2703 | /Aula 04/02-init.py | 222 | 3.6875 | 4 | from typing import List, TypeVar
T1 = TypeVar('T1')
def init(l1:List[T1]) -> List[T1]:
'''Retorna uma lista com exceção do seu último elemento'''
return l1[:-1]
print(init([1,2,3]))
print(init(['a','e','b','-'])) |
45b3536b992d9e1a7b9d5b61d1287bc29d16c2ef | joaomendesln/topicosECT2703 | /Aula 02/05.py | 356 | 4 | 4 | def eh_triangulo_retangulo(x:int, y:int, z:int) -> bool:
'''Função que verifica se três números correspondem aos lados de um triângulo retângulo'''
if y > x:
x, y = y, x
if z > x:
x, z = z, x
if x ** 2 == y ** 2 + z ** 2:
return True
return False
x, y, z = int(input()), int(input()), int(input())
print(eh... |
e35cd411a4a8bda410742e58574277e43696c916 | njweaver/python-challenge | /PyBank/main.py | 1,579 | 3.703125 | 4 | import os
import csv
csvpath = os.path.join('budget_data.csv')
#Make lists
floatnet = []
monthlist = []
#Open file
with open(csvpath, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
next(csvreader)
# Read row
for row in csvreader:
floatnet.append(float(row[1]))
... |
e36f329bab4dc4e46d3eb1e8fb1f844a7966ca94 | vmarois/ECE6254_Stat_ML | /HW1/problem1.3.py | 2,967 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets
from sklearn.model_selection import GridSearchCV
np.random.seed(2017) # Set random seed so results are repeatable
n = [100, 500, 1000, 5000] # number of training points
plt.figure(... |
19efffb8e53b3ae564a06e73b4cb84c742d7ab55 | pxue/empireofcode | /verify_anagram.py | 930 | 3.921875 | 4 | # https://github.com/Checkio-Game-Missions/checkio-empire-verify-anagrams.git
def verify_anagrams(first_word, second_word):
if len(''.join(first_word.split())) != len(''.join(second_word.split())):
return False
s = 0
for c in first_word:
if c != " ":
s ^= ord(c.lower())
fo... |
503a840dd26af25c2ca6bd143ca70471f93f4285 | pxue/empireofcode | /crystal_row.py | 601 | 3.609375 | 4 | def check_line(line):
p = line[0]
for x in line[1:]:
if x == p:
return False
p = x
return True
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert check_line(["X", "Z", "X"]) == True
assert... |
1a71f16c6162645d9f6ec89e35a42f9ec36394cc | sergiolucero/nltk_tutorial | /vid2.py | 427 | 3.6875 | 4 | # sentdex tutorial videos, part 2
# https://www.youtube.com/watch?v=w36-U-ccajM
from nltk.corpus import stopwords
from nltk.tokenize import sent_tokenize, word_tokenize
example_sentence = "This is an example showing off stop word filtration."
stop_words = set(stopwords.words("english"))
words = word_tokenize(example... |
81801652a849bf3fa24c405f91a7e9a28821cc09 | start530/python | /io/osRename.py | 667 | 3.734375 | 4 | #-*- coding: utf-8 -*-
'os rename'
__author__ = 'star'
import os
fileName = raw_input("please input file name...")
print("old file name:%s"% fileName)
#check file is in dir
def checkFile(filename):
list = os.listdir('.')
print list
for f in list:
if f == filename:
print("file in dir")
return
return 0... |
adf3afd09b8f22f2e06876ce9cde8580ef6717d8 | benjamin-chavez/AlgoExpertWork | /LinkedLists/removeDuplicatesFromLinkedList.py | 860 | 3.984375 | 4 | # This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
# O(n) time | O(1) space - where n is the number of nodes in the Linked List
def removeDuplicatesFromLinkedList(linkedList):
# Create two pointers: curNode, nextNode
curNode = l... |
f39ef919370a913b1cbba6b24ad6418b909ba9a8 | benjamin-chavez/AlgoExpertWork | /Strings/TandemBicycle.py | 670 | 3.609375 | 4 | # Solution 1: My Solution
# O(nlogn) Time | O(1) Space
def tandemBicycle(redShirtSpeeds, blueShirtSpeeds, fastest):
sumTotal = 0
redShirtSpeeds.sort()
blueShirtSpeeds.sort(reverse = True) if fastest else blueShirtSpeeds.sort()
for i in range(len(redShirtSpeeds)):
sumTotal += max(redShirtSpeeds[i], blueShirtSpeed... |
d5f5f6c4921961869a820c594d28000bc29f28f3 | benjamin-chavez/AlgoExpertWork | /Arrays/ThreeNumberSum.py | 374 | 3.65625 | 4 | # SOLUTION 2:
# SOLUTION 1:
def threeNumberSum(array, targetSum):
sol = []
array.sort()
for i in range(len(array)):
for j in range(i + 1, len(array)):
targetToSolve = targetSum - (array[i] + array[j])
for q in range(j + 1, len(array)):
if array[q] == targetToSolve:
sol.append([array[i], arra... |
09f9e82a5aa30b9906beb4a686fbbab9ab55b4d0 | arogovoy/algorithms- | /w3/fractional_knapsack.py | 2,412 | 3.984375 | 4 | # Uses python3
import sys
# Task. The goal of this code problem is to implement an algorithm for the fractional knapsack problem.
# Input Format. The first line of the input contains the number 𝑛 of items and the capacity 𝑊 of a knapsack.
# The next 𝑛 lines define the values and weights of the items.
# The 𝑖-... |
94ccd6920bd36170b6f5fa3c4356a8678fce4bf9 | arogovoy/algorithms- | /w3/largest_number.py | 882 | 3.53125 | 4 | # Uses python3
import sys
from math import log, pow
from functools import reduce
# Maximum Salary
def compare(a, b):
order_a = int(log(a, 10))
order_b = int(log(b, 10))
num1 = a * pow(10, order_b + 1) + b
num2 = b * pow(10, order_a + 1) + a
return num2 < num1
def largest_number(arr):
i =... |
0381d8d1cf2200ef3a21c5edfa8dcea8cef37dbc | 2PacIsAlive/programming.fyi | /python_KB/sorting_algorithms/insertion_sort.py | 1,132 | 3.90625 | 4 | #!/usr/bin/python
import random
import ipdb
breakP = ipdb.set_trace
def makeRandomString(string):
sortedList = list(enumerate(string))
randomList = []
while sortedList != []:
randomIndex = random.randrange(0,len(sortedList))
randomList.append(sortedList.pop(randomIndex))
return randomList
def insertionSort(u... |
0dd3401181b259ac0ac5b71dfc34c0a7e5cde7de | 2PacIsAlive/programming.fyi | /python_KB/random_challenges/palindrome_checker.py | 669 | 3.90625 | 4 | #!usr/bin/env python
import itertools
def checkPalindrome(word):
if len(word) < 2:
return
if word[0] != word[-1]:
return False
return checkPalindrome(word[1:-1])
def loadWords(file_):
words = []
file_ = open(file_)
for word in file_:
words.append(word[:-2])
file_.close()
return words
def main():
dat... |
56c15bb76dea70b94a5a13ca5514ea1f7074d436 | vlasove/sum_pu_1 | /Lecture2/func_second.py | 197 | 3.5 | 4 | def Summer(a,b):
return a+b
#parametric type
print(Summer(2,3),Summer("lol","kek"))
def Mult(a,b=1,c=2,d=3,e=3,f=6,g=8,h=9,lol=20):
return a*b*c*d*e*f*lol
print(Mult(5,7, f = 10))
|
3067092a2bfaad998771bb21eeb71b8247944c06 | ash0411/cgm-lab | /lab1,2/triangle.py | 343 | 3.765625 | 4 | from graphics import *
from random import randint
def triangle():
win = GraphWin("triangle")
vertices = []
for i in range(3):
x = randint(0,200)
y= randint(0,200)
vertices.append(Point(x,y))
triangle = Polygon(vertices)
triangle.setFill("ORANGE")
triangle.draw(win)
wi... |
ac3a8044d085ce31beab084c129d4b422761685a | yws179/algorithm-set | /sort/bubble_sort.py | 461 | 4.03125 | 4 | #!/usr/bin/env/python
# coding=utf-8
from utils.timer import timer
@timer
def bubble_sort(arr):
"""
冒泡排序
"""
count = len(arr)
for i in range(count):
for j in range(i+1, count):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr
if __name__ == ... |
653be7576bca6574e38f581a43d0275caea23cc9 | spectralDNS/shenfun | /demo/poisson1D.py | 2,768 | 3.765625 | 4 | r"""
Solve the Poisson equation in 1D
.. math::
-\nabla^2 u(x) = f(x), \quad x \in [a, b]
where :math:`a < b`. The equation to solve is
.. math::
-(\nabla^2 u, v) = (f, v)
and we need two boundary conditions. These boundary conditions
can be any combination of Dirichlet or Neumann, specified on
either sid... |
15342af769f2affec5c89c5fc328768b0100d75e | RohiBaner/HashTree | /HashTree-Python3.py | 5,748 | 3.921875 | 4 | """Created on Sat Sep 22 15:37:52 2018
@author: BANERJEE, Rohini (Student ID: 20543577)
MSBD5002: Data Mining and Knowledge Discovery (Assignment 1)
Title: Implementation of Hash Tree using Python 3"""
"""Class representing the structure of the Hash Tree Node
Each node has 3 leaf lists and 3 initially empty no... |
1bd93d500350c63fca4ba7e6a8ed3e1fb80bd1fe | UnKn0wn27/PyhonLearning-2.7.13 | /ex11.py | 505 | 4.21875 | 4 | #raw_input() presents a prompt to the user(the optional arg of raw_intput([arg])
#gets input from the user and returns the data input by the user in a string.
#Exemple:
# name = raw_input("What is your name?")
# print "Hello, %s." % name
#raw_input was renamed input() in Python 3
print "How old are you?",
age = raw_in... |
09da1758cb052f055d1b9fe2a0b9b8b6a6255328 | UnKn0wn27/PyhonLearning-2.7.13 | /ex37.py | 2,010 | 3.515625 | 4 | import sys
print "\nand keyword"
if True and True:
print "True"
print "\nas keyword"
with open("test.txt") as f:
print f.read()
print "\nassert keyword"
assert 2 + 2 == 4, "Houston we've got a problem"
print "\nbreak keyword"
for letter in 'Python':
if letter == 'h':
break
print 'Current let... |
c6264951dea9bcc3d673356bedbbe7a7dbab9e05 | kriistell/Python_week8_A | /Untitled8.py | 1,542 | 3.859375 | 4 |
# coding: utf-8
# In[2]:
import sqlite3
conn = sqlite3.connect(r"D:\July.db")
# In[3]:
# Get a cursor object
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT,
phone TEXT, email TEXT unique, password TEXT)
''')
conn.commit()
# In[4]:
curs... |
51c6e20d154cdcaa93cc8077e84981fa7ed83eff | ols3er/about-python | /types/list/list_comprehension.py | 294 | 3.828125 | 4 | # -*- coding: utf-8 -*-
squares = [i**2 for i in range(11)] # compare with « map(lambda i: i**2, range(11)) »
print squares
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares_of_even_numbers = [i**2 for i in range(11) if i % 2 ==0]
print squares_of_even_numbers
# [0, 4, 16, 36, 64, 100]
|
ca8d83d16965ff820005cee3af858c6c81fce834 | Gonnny/lesson2 | /exception1.py | 1,179 | 3.9375 | 4 | """
Домашнее задание №1
Исключения: KeyboardInterrupt
* Перепишите функцию ask_user() из задания while2, чтобы она
перехватывала KeyboardInterrupt, писала пользователю "Пока!"
и завершала работу при помощи оператора break
"""
def ask_user():
while True:
try:
questions = {"Как дел... |
b4c9a3551c665d07d112d1618173ad1cd82ef042 | DenisFuryaev/PythonProjects | /tasks from uneex.org 2018/AndOr.py | 119 | 3.75 | 4 | a = eval(input())
b = eval(input())
if ((a and b) == a) and ((b and a) == b):
print('NO')
else: print(a or b)
|
92b51cf14c1a40e94d140e09276628cc9e661087 | DenisFuryaev/PythonProjects | /PycharmProjects/Progect #1/PublicFriend.py | 260 | 3.515625 | 4 | a = eval(input())
d = dict()
while a != (0,0):
if a[0] not in d:
d[a[0]] = str(a[1])
else: d[a[0]] = d[a[0]] + str(a[1])
if a[1] not in d:
d[a[1]] = str(a[0])
else: d[a[1]] = d[a[1]] + str(a[0])
a = eval(input())
print(d) |
b94998ee637d6e34dbadec2e7e2a15605c3decd1 | kaneez9/Assignment-2-letsupgrade | /assignment day 2.py | 675 | 3.53125 | 4 | #Assignment day 2
# Question 1
list=[]
for i in range (10):
if i%2==0:
list.append(i)
print(list)
#Question 3 solution
n=int(input())
d=dict()
for i in range(1,n+1):
d[i]=i*i
print(d)
#question 4
pos = {"x":0,"y":0}
num = int(input())
for _ in range (num):
command = input().spl... |
534aa4240a3d5aa0b9eb738f52c5ed12dc636df2 | Anthony-Margotta/section_grader | /generate_grader_data.py | 7,422 | 3.921875 | 4 | import random
import datetime
import csv
class Student:
"""A class to represent students in the course
Attributes
----------
name : name of the student
section : the discussion section the student is in
motivation : motivation score of the student, affects simulation
successes : list trac... |
4d7eb9d814d4cd5db77400c7a96e1c18900eb00f | cantayma/web-caesar | /caesar.py | 1,197 | 4.21875 | 4 | import string
def alphabet_position(letter):
"""
receives a letter, returns 0-based numerical position in the alphabet;
case-sensitive; assumes letters only input
"""
if letter in string.ascii_uppercase:
position = string.ascii_uppercase.find(letter)
elif letter in string.ascii_lowerc... |
edade43e581b50d60bf0e15528f4216bc1fdeaa9 | Sebby37/Python-Pocket | /Master Convertor.py | 7,313 | 3.96875 | 4 | import sys
from time import sleep
__Author__ = "Toenail"
__Lisence__ = "Unliscenced", False
__Property__ = "For"
#exit protocol
def userExit():
while True:
user_exit = input("Input Q to quit or M to return to the main menu: ")
if user_exit == "Q":
print("Guten tag")
... |
449b0a1c5cc14f9c0b481f80daf1fb40bec446b9 | Farubegum/intnumber | /leaapppp.py | 163 | 3.796875 | 4 | while True:
try:
sam=int(input())
break
except:
print("invalid input")
break
if sam%400==0 or sam%4==0 and sam%100 !=0:
print("yes")
else:
print("no")
|
b86b9f3ab0806524f27b75ec514a84e00a185348 | clwilson625/Python-Projects | /drill50_phonebook_main.py | 2,096 | 3.640625 | 4 | # Python Ver: 3.9
#
# Author: Carol Wilson
#
# Purpose: Phonebook Demo. Demonstrating OOP, Tkinter GUI module,
# using Tkinter Parent and Child relationships.
#
# Tested OS: This code was written and tested to work with Windows 10.
from... |
a71016a4013bfe9ddec1c5899d37127c98ab88b6 | qsoo/algo | /SWEA/d3_4406/cant_see_vowel.py | 348 | 3.671875 | 4 | for tc in range(1, int(input()) + 1):
# 모음 사전 리스트 생성
vowel = ['a', 'e', 'i', 'o', 'u']
sentence = input()
result = ''
for word in sentence:
if word in vowel:
continue
else:
result += word
print('#{} {}'.format(tc, result))
'''
3
congratulation
synthetic... |
0f1dca397b91efd982515d57be2f31946bd95f0f | qsoo/algo | /BOJ/BOJ_9095/123_plus.py | 1,015 | 3.546875 | 4 | # 1. queue를 만들어서 리스트(1, 2, 3), 이전까지의 합 정보를 가져간다
# 2. N과 리스트의 합이 같아질 때 break
def one_two_three_plus(perm:list, total:int):
global cnt
# perm: 현재까지 저장된 배열, total: 현재까지 가지고 있는 합
queue = []
queue.append((perm, total))
# iterations = 1
while queue:
# iterations += 1
new_perm, new_tot... |
51ce7e9672fed70d7f26df07d3a079fa0bb9e9d7 | xiaobaiskill/python | /day05/proctice/练习 列表元素 小写转大写.py | 143 | 3.953125 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
# Author Jmz
names = ['jmz','qqq','egon']
names = [name.upper() for name in names]
print(names) |
b5b89eda173c093c8f3a5bcc5f7cc5831370247d | xiaobaiskill/python | /day06/re/findall.py | 147 | 3.796875 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
# Author Jmz
import re
content = 'asd3fdsjk43dsndf'
print(re.findall('\d',content))
# ['3', '4', '3'] |
bb3538359076a437ae79315149834cfaf53218ab | xiaobaiskill/python | /day1/zuoye1.py | 410 | 3.65625 | 4 | #!/usr/bin/env python
# Auther Jmz
'''请使用python passwd.py 执行'''
import getpass
username = 'jmz'
password = '123123'
count = 0
while count < 3:
user = input('username:')
pwd =getpass.getpass('password:')
if username == user and pwd == password :
print('login success')
break
else :
... |
9beec2d49a8d54110e68786dcd1f0632ebfe1dc3 | xiaobaiskill/python | /day2/day2_proctice/pramid.py | 893 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author Jmz
#一个空格一个星星
'''
# 面向过程编程
max_level = 4
count =0
tag = True
while tag:
num = 2 * max_level - 1
star=(2*count+1)*'*'
print(star.center(num,' '))
count +=1
if count >= max_level:
tag=False
'''
# 函数式编程
def order_star(max_level:int,o... |
7a160a798d9d51ae955eb10c914687dc6c9db60a | xiaobaiskill/python | /day1/for1.py | 332 | 3.8125 | 4 | #!/usr/bin/env python
# Auther Jmz
old_age = 23
for i in range(3) :
input_age = int(input('oldname age:'))
if input_age > old_age:
print('think smaller...')
elif input_age < old_age:
print('think bingger...')
else:
print('yes ,this right')
break
else :
print('正常走完执行') |
fb359dab168c6021eb0e9757889ca4a4a0a2c522 | xiaobaiskill/python | /day08/proctice/类的定义调用.py | 736 | 3.515625 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
# Author Jmz
# 1.1定义类
# 1.1.1 无参定义
class test(object):
def __init__(self):
pass
def func(self): # 类方法
pass
# 1.1.2 有参定义
class foo(object):
def __init__(self,name,age):
self.name = name # 类属性
self.age = age
# 1.2 调用类(与函数的方式很... |
7906a30029f6df7fed37b88accfa53d87c33e232 | xiaobaiskill/python | /day07/datetime/index.py | 888 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author Jmz
import datetime,time
print(datetime.datetime.now())
# 2018-05-21 22:52:39.542560
print(datetime.date.fromtimestamp((time.time())))
# 2018-05-21 时间转日期
print(datetime.datetime.now() + datetime.timedelta(-3))
print(datetime.datetime.now() - datetime.timedelta(3... |
7e90c4e5291716692c731b42e429ba10a3453d5a | tlananthu/python-learning | /98_tools/training_ram/day2/ex7.py | 384 | 3.765625 | 4 | #label encoder
#input list
#['Yes','NO','yes','YES','no']
#output
#[1,0,1,1,0]
#1 for yes, 0 for no
# l=eval(input("Enter list: "))
# nl=[]
# for i in l:
# if i.upper()=="YES":
# nl.append(1)
# elif i.upper()=="NO":
# nl.append(0)
#updated with ternary
l=eval(input("Enter list: "))
nl=[]
for... |
00585bc27141ada23149b8f272f33ab23710a2ee | tlananthu/python-learning | /98_tools/training_ram/day1/ex4.py | 529 | 4.25 | 4 | #fizzbuzz problem
# take number as input (1-100)
# if divisible by 3 print Fizz
# if divisible number is divisible by 5 print buzz
# if both print fizzbuzz
# none: print number
num=int(input('Number between 1 to 100: '))
# if num%3 == 0 and num%5 == 0:
# print('FizzBuzz')
# elif num%5 == 0:
# print('Buzz')
#... |
36d1432db82c986858bf650aa2c8281d494e01ac | tlananthu/python-learning | /00_simple_examples/06_maths.py | 336 | 4.1875 | 4 | number1=int(input('Please input a number'))
number2=int(input('Please input another number'))
operation=input('Please input an operation. +-/*')
if operation=='+':
print(number1+number2)
elif operation=='-':
print(number2-number2)
elif operation=='/':
print(number2/number2)
elif operation=='*':
print(... |
ff953a07ea5e838077adf9d5bf516b6ab28080b7 | RinaGrim/Python_exercises | /Tick-tack-toe/tick_tack_toe.py | 3,969 | 3.984375 | 4 | import random
import time
game_field = ["_1_|", "_2_|", "_3_|", "_4_|", "_5_|", "_6_|", "_7_|", "_8_|", "_9_|"]
field_index = [1, 2, 3, 4, 5, 6, 7, 8, 9]
win_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
player_comb = []
comp_comb = []
cross = "_X_|"
zero = "_O_|"
d... |
e9e57002488337b221da85cf41a79403e1e3e916 | ArunkumarGoge/MachineLearning | /SimpleLinearRegression.py | 1,256 | 4 | 4 | # Importing the libraries
import pandas as pd
import matplotlib.pyplot as plt
# Importing the dataset in current directory
dataset = pd.read_csv('SimpleLinearRegression.csv')
#import the independent variable contains all rows and all columns
#import the dependent variable: The last column
X = dataset.iloc[:, :-1].va... |
ff7a0a6744063885c863d85fbf8e8bd28d33a6b8 | Shwebs/Python-practice | /BasicConcepts/3.strings/string-methods/Program-2-srting-format.py | 137 | 4.375 | 4 | #Formatting a String
name=input("Enter you Name:")
salary=input("What is your salary:")
print("{}\'s Salary is {} ".format(name,salary)) |
90094aafd436e093d00d2300a8278938caa788c1 | Shwebs/Python-practice | /BasicConcepts/3.strings/string-multiplication.py | 567 | 4.15625 | 4 | #Strings can also be multiplied by integers. This produces a repeated version of the original string.
# The order of the string and the integer doesn't matter, but the string usually comes first.
print("spam" * 3) #O/p:spamspamspam
print (4 * '2') #O/p: 2222
#Strings can't be multiplied by other strings.
#Strings ... |
44303dbd36226bc72b953271490a2ffb0f0224e1 | Shwebs/Python-practice | /BasicConcepts/3.strings/string-methods/string-replace.py | 247 | 4.03125 | 4 | #replace(old, new [, max])
##Replaces all occurrences of old in string with new or at most max occurrences if max given.
str="Want to be a Developer"
test=str.replace('Developer','DevOps')
print(test)
#OR
print (str.replace('Developer','DevOps')) |
fd7d34be554f52a0f81a67937c4b59bea578df8a | Shwebs/Python-practice | /python-fundamental-thenewboston/7.function-return-2.py | 305 | 3.96875 | 4 | #################### Function Return ###########################
def allowed_dating_age(boy_age):
girls_age = boy_age/2 + 7
return girls_age
# Lets assign the return value to a variable
limit = allowed_dating_age(32)
print("The Boy of age " ,boy_age, "should date a girl of age " ,limit, "or older")
|
28b923b625a0d8e716f3a85b98cfea1ac81d285b | Shwebs/Python-practice | /ControlStructure/List/List-method-count.py | 305 | 4.125 | 4 | #list.count(obj): Returns a count of how many times an item occurs in a list
letters = ['p', 'q', 'r', 's', 'p', 'u']
print(letters.count('r')) #O/P:-1
print(letters.count('p')) #O/P:-2 # index method finds the "first occurrence" of a list item and returns its index
print(letters.count('z')) #O/P:-0 |
2fd82e086ef9fd6b383c2055f70ced123c94963d | Shwebs/Python-practice | /BasicConcepts/3.strings/string-methods/split.py | 489 | 4.21875 | 4 | #Splits string according to delimiter string, returns list of substrings.
#Default delimiter is ' ' .
str='Test My Skill'
output=str.split()
print(output) #o/p:- ['Test', 'My', 'Skill']
for x in output:
print(x) #o/p:-Test
# My
# Skill
#Delimiter can be change... |
e21cba589f4928a7ad09bd7ad84d786b5a4fb73c | Shwebs/Python-practice | /ControlStructure/range/basic-range.py | 727 | 4.75 | 5 | #The range function creates a sequential list of numbers.
#The call to list is necessary because range by itself creates a range object,
# and this must be converted to a list if you want to use it as one.
#If range is called with one argument, it produces an object with values from 0 to that argument.
numbers = li... |
909325fdb03654071ecb54104d622e35e96a3497 | Shwebs/Python-practice | /python-fundamentals-by-pluralsight/Object_Reference.py | 1,065 | 4.25 | 4 | #Pass by Object Reference
#The value of the reference is copied , not the value of the object
# Helpful Link https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/
m = [9, 15, 24]
def modify(k):
"""Appending a value to function.
Args:
A any literal can be added.
R... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.