blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d21be501a5a0a095337946117e3b072da69c43e7
duck-bongos/python_development
/python_dev/py_analyticats/py_EN_tutorials/if_then.py
526
4.09375
4
# This is a proram designed to teach Emmalese about Conditional statements # import random library to access random methods import random num = 0 random_num = random.randint(0, 100) print(random_num) # set a variable equal to a value, if it is higher than x, make it print y. if random_num > 90: print("Deez Nuts") ...
34201aaf2623ca635080f4e347e48681fdf8f9c4
keerow/python-Q2
/MainFolder/August EXAM/Cp2.5EXAMLP2.py
420
3.75
4
import random nb_à_trouver = random.randint (1,10) print ("Trouver un nombre entre 1 et 10. Vous avez 3 chances") i=0 nombre_lu = int(input("Entrez un nombre : ")) while (i<2): if nombre_lu == nb_à_trouver: print ("Trouvé !") i = 2 else: print ("Raté...") nombre_lu = int(input("E...
cf7d9d0aa779bfdf6b9ae93858ec95c98ee8502a
shivngishrma23/FSDP19
/day1/replace.py
347
4.0625
4
input_string = input("enter a string : ") replaced_char = input("enter the chracter which you want to replace : ") replacement_char = input("enter char you want to replace : ") first_occurence = input_string.find(replaced_char) print(input_string[:first_occurence+1] + input_string[first_occurence+1:].replace(replaced...
1799f0cc61fac19cc22c38d4a74c2622984c83f7
Murugar/ML_BestFit
/BestFit.py
1,533
3.703125
4
from sklearn.pipeline import make_pipeline from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.model_selection import cross_val_score import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import learning_curve, ShuffleSpli...
0b72bb74364b22ee95853b8d8700ad660bba9c9d
huncros/texas_holdem
/src/texas_holdem/card.py
2,211
3.78125
4
from typing import NamedTuple from enum import Enum, IntEnum class Suit(Enum): CLUBS = 'Clubs' HEARTS = 'Hearts' DIAMONDS = 'Diamonds' SPADES = 'Spades' class Rank(IntEnum): ACE_LOW = 1 # Ace that is counted as 1 for the purpose of creating 5 cards of sequential rank TWO = 2 THREE = 3 FOUR = 4 FI...
536715379470505423f225e02b2d61097dc4ca92
CS-for-non-CS/Data-Structure
/4.스택1/Stack_practice2.py
310
4
4
stack = [] def push_stack(item): stack.append(item) def pop_stack(): if len(stack) == 0: result = "Stack is empty" return result else: return stack.pop() push_stack(1) push_stack(2) push_stack(3) print(pop_stack()) print(pop_stack()) print(pop_stack()) print(pop_stack())
f8c6bb40d51dcac80f7438bf49c2050c64f7a39e
FITM-KMUTNB/TMRS
/Cluster.py
6,737
3.5
4
import networkx as nx import math # Area = Average Distance[cluster] + (3 * Standard Deviation[cluster]) # Standard Deviation[cluster] = Math.sqrt( (x-average)**2 / n-1 ) # First Centroid, Average distance = 1, Standard Deviation = 1/2 cluster = dict() #{ cid : {n1 : dis_ct, n2 : dis_ct, n3 : dis_ct}, } cluster_ct ...
ade43b3c41ce5c6a0140a40dab057835b7cdfb2c
iddlee/Python-learning
/python语言基础/面向对象之前的小练习/List_practice.py
574
3.765625
4
'''编写程序,用户输入一个列表和2个整数作为下标, 然后使用切片获取并输出列表中介于2个下标之间的元素组成的子列表。 例如用户输入[1, 2, 3, 4, 5, 6]和2,5,程序输出[3, 4, 5, 6] ''' entry = input("请输入列表:") list1 = entry.split(",") entry2 = input("请输入两个整数:") list_xb = entry2.split(",") subscript = list1[int(list_xb[0]):int(list_xb[1])] # 取下标,从list_xb中,取第1个和第二个数字的范围 bianli = [] for i in su...
3d717cee3289a98ff649ab6608b9ddffccb7fefc
TokyGhoul/Coursera
/Week2/HW3.py
537
4.40625
4
''' Даны три целых числа. Найдите наибольшее из них (программа должна вывести ровно одно целое число). Какое наименьшее число операторов сравнения (>, <, >=, <=) необходимо для решения этой задачи? ''' num1 = int(input()) num2 = int(input()) num3 = int(input()) if num1 >= num2 and num1 >= num3: print(num1) elif n...
da145253880768f0afca64fab7e62722787c79e6
Changron/dbfinal
/ExecuteSQLfiles.py
938
3.78125
4
import psycopg2 def show_table(cursor, table_name): SQL = """SELECT * from """ + table_name cur.execute(SQL) # fetch [variable?] rows = cur.fetchall() print ("\nShow me the databases:") for row in rows: print (" ", row) # https://wiki.postgresql.org/wiki/Psycopg2_Tutorial if...
74730727094eb37dc616de9b7bad0e2e672b8f26
jorgeMorfinezM/binary_search_algorithms
/binary_for_search.py
1,637
4.15625
4
# -*- coding: utf-8 -*- """ Algoritmo de busqueda binaria usando el ciclo while escrito en Python. Este metodo funciona con cadenas y numeros por igual, ya que el lenguaje trata a las cadenas lexicograficamente; comparando sus valores en el codigo ASCII """ def binary_search(list_data, search_data): left_index,...
9fa9bda98f401bc3c84e9d716ba20baa8b701eb7
a198/prueba_python
/python/el que madruga.py
249
3.984375
4
print("Al que madruga Dios lo ayuda\n") nombre="Andrea" print("Tu nombre es:",nombre) edad=int(input("Dame tu edad:")) print("tu edad es:",edad,"años") print("tu proxima edad es:",edad+1) input("Presiona cualquier tecla para continuar....")
332c51032f7ca65e948fd249477719dfa01734a4
Colton9810/Portfolio
/KeystrokeWriter.py
896
3.78125
4
# This will allow you to "type" on someones computer with the characters you tell it to type from pynput.keyboard import Key, Controller from time import sleep import termios keyboard = Controller() password = input() timings = input() password = password.split(", ") password = password[:len(password) // 2 ...
cfb7c826fe6a5e46014cd6be5407d77923f5ac01
srawla3010/py-training
/_practice/MS_corey/oop-class5.py
1,347
3.65625
4
''' special method -> dunder operator overloading __<method>__ i.e. __repr__ , __str__, __add__, __len__ refer datetime module ---->> return NotImplemented don't want to throw an error , other object may know how to handle the operation ''' class Employee: raise_amt = 1.04 def __init__(self, first, last...
7802d18cf55121aa7722c2709378345ddde63538
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/360f5cb10c9447fd8d101df97a224473.py
723
3.875
4
import string import collections class Phrase(object): """Provides word count stats for a phrase""" def __init__(self, phrase): """Sets the phrase""" self.phrase = phrase def word_count(self): """Generates word counts for words (lower case, no punctuation)""" words = self...
ad082f8f0829be0b7928b24f682e9bce3a481c3e
danielgil1/question-answering-mx
/index.py
4,613
3.6875
4
### Index creation ### Hector Salvador Lopez ''' These functions generate word indices, later used to find quickly word appearance on documents. Indices are stored as json files in a folder called indices/. ''' from nltk.stem.snowball import SpanishStemmer import json import os import pandas as pd import regex as re...
4ecf5512a21e8b981cefba079e1b2462238628f2
arundhaj/python_sandbox
/userinput/squarearea.py
127
4
4
# simple program to test user input a = int(input('Enter the square side: ')) print('Area of square is : {0}'.format(a * a))
19123759893b8321e5f131219c23e98cfc7abf8d
ignat980/CS-Theory
/tests/test_hash_table.py
1,835
3.5625
4
import unittest from data_structures.hash_table import HashTable class TestHashTable(unittest.TestCase): def setUp(self): self.hash_table = HashTable(13) def test_init(self): bucket_size = len(self.hash_table.buckets) self.assertEqual(13, bucket_size) self.assertEqual(bucket_s...
8bfdabecaf3d2bc4c83e338714b5ca8c55138f56
qmnguyenw/python_py4e
/geeksforgeeks/python/easy/3_12.py
3,837
3.984375
4
How to control PC from anywhere using Python? **Prerequisite –** **Socket programming in Python** In this solution, we use the concept of Socket Programming for establishing communication between two computers. ### **Socket Programming in Python** Socket Programming is a way of connecting two systems ...
4c49a9cd33e16722876b9296bcd417636b38723e
AbdulSami-07/datastructure
/python/quickSort.py
509
3.765625
4
import random def QuickSort(A,l,r): if l >= r: return m = partition(A,l,r) QuickSort(A,l,m-1) QuickSort(A,m+1,r) def partition(A,l,r): i,j = 1,1 pivot = 0 #pivot element is 1st element. for k in range(1,r): if A[k] <= A[pivot] and i < j : A[j] , A[k] = A[k] , A[j] elif A[k] <= A[pivot]: i = k eli...
c168a90d6b09919f74b947853d25232cb76f0d6d
abphilip-codes/Hackerrank_Interview
/2_Arrays/3.py
739
3.5
4
# https://www.hackerrank.com/challenges/new-year-chaos/problem #!/bin/python3 import math import os import random import re import sys # # Complete the 'minimumBribes' function below. # # The function accepts INTEGER_ARRAY q as parameter. # def minimumBribes(q): # Write your code here p,q,ans=list(range(len...
954f7eddd7c0146cec7eea6641638604fc21d147
tang2021/leetcode_test
/522. 最长特殊序列 II.py
1,108
3.5
4
# 522. 最长特殊序列 II # 给定字符串列表,你需要从它们中找出最长的特殊序列。最长特殊序列定义如下:该序列为某字符串独有的最长子序列(即不能是其他字符串的子序列)。 # 子序列可以通过删去字符串中的某些字符实现,但不能改变剩余字符的相对顺序。空序列为所有字符串的子序列,任何字符串为其自身的子序列。 # 输入将是一个字符串列表,输出是最长特殊序列的长度。如果最长特殊序列不存在,返回 -1 。 # 示例: # 输入: "aba", "cdc", "eae" # 输出: 3 # 提示: # 所有给定的字符串长度不会超过 10 。 # 给定字符串列表的长度将在 [2, 50 ] 之间。 def findLUSlength(self...
d32b3e1a5cd099b0b99ab832ec19850cb862b5c4
bekhy/Class1_write
/7(2).py
680
3.71875
4
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. dict_a = {} list_az = [1, 4, "3", "8", {"121":121}, {"12":12}, [1, 3, 6, 9, 12], [2, 8, 16, 32, 48]] for i in list_az: if isinstance in (i, int): if "int" not in dict_a.keys(): int_list = [] ...
e6ea66169542fe536995b890f695b51f02609fbd
Alissonfelipe1234/URI_Estudos
/1165.py
1,036
4.09375
4
''' Na matemática, um Número Primo é aquele que pode ser dividido somente por 1 (um) e por ele mesmo. Por exemplo, o número 7 é primo, pois pode ser dividido apenas pelo número 1 e pelo número 7. Entrada A entrada contém vários casos de teste. A primeira linha da entrada contém um inteiro N (1 ≤ N ≤ 100), ...
2818ae28dbb4e4cd3fa04d4c32531849f7558413
ewald30/Connect4-Python
/domain1.py
2,948
3.609375
4
class colors: blue = '\033[94m' green = '\033[92m' white = '\033[39m' red = '\033[91m' class symbols: ''' Class for symbols used in the board * white empty square - empty * blue filled square - player1's dot * green filled square - player2's dot ''' def __init...
3d88a25bf33087dd38ccdd2bab5f1397d74a5f0a
yuriyshapovalov/Prototypes
/Rosalind/lexf.py
640
3.921875
4
# Enumerating k-mers Lexicographically # http://rosalind.info/problems/lexf/ import sys from itertools import * class lexf: def main(self, dna_file): symbols = dna_file.readline() symbols = list(symbols[:-1]) symbols = filter(lambda x: str(x) != ' ' , symbols) n = int(dna_file.readline()) result = list(pro...
27ef69e90a4be7fe4dd368a028ec3a40a9e1000c
jdavancens/RhyPy
/rhypy/distance.py
2,893
3.78125
4
# -*- coding: utf-8 -*- from rhypy import Rhythm import math ''' Drawn from Toussaint, "A Comparison of Rhythmic Dissimilarity Measures" Forma, 21, 129-149, 2006. ''' def chronotonic(A, B): ''' Chronitonic distance: the difference of the sum of squares of inter-onset interval vectors A and Bs .. containe...
6d502c5884a1b59a47f5b07c184b27990ab83d74
javiteri95/hackerRank
/DrawingBook/drawingBook.py
460
3.75
4
# Complete the 'pageCount' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER n # 2. INTEGER p # def pageCount(n, p): # Write your code here beggining_pages = p // 2 final_pages = (n + 1 - p) // 2 if n % 2 == 0 else (n - p) // 2 ...
c22f3dce3a360b5ed29f2b00445996c59e402c05
NamkyuHan/bit_seoul
/keras/keras40_fashion_1_imshow.py
924
3.703125
4
#이미지 종류가 10개 ''' 데이터 (Data) Fashion-MNIST 데이터셋에는 10개의 카테고리가 있습니다. 레이블 설명 0 티셔츠/탑 1 바지 2 풀오버(스웨터의 일종) 3 드레스 4 코트 5 샌들 6 셔츠 7 스니커즈 8 가방 9 앵클 부츠 ''' #1. 데이터 from tensorflow.keras.datasets import cifar10, fashion_mnist from tensorflow.keras.utils import to_categorical from tensorflow.keras.models import Sequential, Mode...
f14b1abcaf3c50b4368070d237d3ab324530753c
AlastairMacWillson/dowhatisay
/venv/metodi.py
224
3.5625
4
class Car: # создание методов класса def __str__(self): return "Car class object" def start(self): print("Двигатель заведён") car_a = Car() print(car_a)
58a626dd7b3d45976020d4bee8c2331ba738a845
MarkPowellDev/py_workspace
/E-Class_Def/KeyValue.py
132
3.671875
4
x = { 'one': 1, 'two': 2, 'three': 3} n=1 for k, v in x.items(): print('number =', n, ' Key = ', k, ' Value =', v) n += 1
1fdf7d1e9a436ac4e1ebd4bbd9ec68a16098592a
nitya123-github/-PYTHON-GAMES
/hangman.py
4,914
3.515625
4
#Hangman Game from random import * import sys player_score = 0 computer_score = 0 def hangedman(hangman): graphic = [ """ +---------------+ | | | | | | | | ...
83c759b2d06fc5451f895951aa4f7ff64e5eb4b5
cs-fullstack-2019-fall/python-arraycollections-b-cw-LilPrice-Code
/index.py
2,186
4.0625
4
def main(): pro1() pro2() pro3() pro4() pro5() # Problem 1: # Create a function with the variable below. After you create the variable do the instructions below that. # arrayForProblem2 = ["Kenn", "Kevin", "Erin", "Meka"] # a) Print the 3rd element of the numberList. # b) Print the size of the array...
2f3be78f5cf407d79a2230962710621958ebdfff
dmavridis/katas
/duplicate_word.py
284
3.609375
4
def duplicate_encode(word): word_count = {} for c in word.lower(): if c not in word_count: word_count[c] = 1 else: word_count[c] += 1 return ''.join([''.join('(') if word_count[c]== 1 else ''.join(')') for c in word.lower()])
ab215f5f990bf962247817400057d033b1519c00
KadenBiel/Python-Zork
/PyZork.py
27,762
3.6875
4
import player, room, time, random try: startScreen = input("PyZork v1.2\nHit enter to start\n") except: print("Your version of python is not compatible with this program, please use Python 3 or up") end = raw_input("Hit enter to quit") quit() class Game: def __init__(self): """ ...
22a84db03486221f3202441f92368940e7d4687a
LiquidDuck/Time-Attack
/time_attack.py
23,195
4.03125
4
import tkinter as tk import math import random import time answer = "" points = 0 #number of incorrect attempts allowed. If you reach 0 incorrect attempts, the game ends. attempts = 3 #45 second timer for added difficulty. seconds = 45.0 global time_attack_seconds time_attack_seconds = 35.0 ...
423702ff976f1b8a21ffd3c3280463c0fcab0253
JasonOnes/PythonWork
/crimey.py
4,383
3.578125
4
import csv with open('/home/jasonones/Git/PythonFullStack/1_Python/labs/projects/pdx_crime_data/data/crime_incident_data_2011.csv', 'r') as taco: data = csv.reader(taco) crime_stats = dict() for row in data: crime, date = row[3], row[1] if crime in crime_stats: crime_stats[...
5cd1e232e883c2d5d8e033f0441aa9a44bc8c99f
ojhaanshu87/LeetCode
/15_threeSum.py
2,610
3.609375
4
``` Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Notice that the solution set must not contain duplicate triplets. Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Example 2: ...
a7c87143e92a88cbfe591b028b37475c98206600
fabianjmnz/List-Exercises
/Exercise_#4.py
84
3.78125
4
for number in range(10): if number%2 == 0 and number != 0: print(number)
6323f78c85107276858e2fcd316c42f9f4aa3a3b
kungergely92/SegwayLearning
/population.py
2,075
3.734375
4
from unit import unit from physics import physicsHandler import random class populationHandler: def __init__(self): """ This class handles the populations, generates the generations.""" self.generations = [] self.pHandler = physicsHandler(1,1) def initFirstGen(self, size): """ ...
d50ad4a3d21df04228f323ac6e0670576beb70b6
lailacampos/Natural-Language-Processing-Course
/chinking.py
1,296
3.984375
4
# Chinking # https://realpython.com/nltk-nlp-python/#chinking # While chunking is used to include a pattern, chinking is used to exclude a pattern. import nltk from nltk.tokenize import word_tokenize lotr_quote = "It's a dangerous business, Frodo, going out your door." words = word_tokenize(lotr_quote) print(words)...
52fd8bd53ee59d7aeef4fad22921d4be796eec63
oqolarte/python-noob-filez
/largest_palindrome_product.py
674
4.1875
4
#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. #Find the largest palindrome made from the product of two 3-digit numbers. # function which return reverse of a string def reverse(s): return s[::-1] def isPalindrome(s): ...
ba7dc711ea8d2b6b1be63aa8b06db5e14e05ec9f
likelion-kookmin/python-study-8th
/장세연/Assignment2-2.py
112
3.65625
4
n= int(input("원하는 층 수를 입력하세요:")) for i in range(n) : print(" "*(n+i)+"*"*(2*(n-i)-1))
fa4ad6724918871b747e0aa7e66fe5a290b4b660
Louis-Gabriel-TM/computer_science
/4_classic_puzzles/4_1_with_arrays/same_frequencies.py
1,607
4.125
4
""" Puzzle Wording ============== Write a function called 'same' which accept two arrays. The function should return True if every value in the first array has it's corresponding value squared in the second array, at the same frequency. Example: ------- same([1, 2, 3], [4, 1, 9]) --> True same([1, 2, 3], [1, 9]) --> F...
77ed3e28c05347a63bd09dfea9f3c1d732846072
morlandi/sitecopy
/sitecopy.py
4,520
3.609375
4
#!/usr/bin/env python # Script to sync db and/or data from remote host # # Brainstorm S.n.c - http://brainstorm.it # author: Mario Orlandi, 2019 from __future__ import absolute_import REMOTE_HOST = 'www1.somewhere.com' PROJECT = 'someproject' __version__ = '1.0.1' import os import sys import argparse import traceba...
0d77b6bc7424658a7bf36744b3d0723b0b34ff85
jhsparks/Introduction_to_programming_using_python
/1.10.py
161
3.703125
4
#exercise 1.10 #distance in miles distance = 14 / 1.6 #time in hours time = 45.5 / 60 rate = distance / time print(str(rate)) print((14 / 45.5) * 60 / 1.6)
ffde308c942fba28f116fabe2caa419719a618ae
vishwesh5/HackerRank_Python
/Introduction/function.py
310
4.0625
4
# function.py # Link: https://www.hackerrank.com/challenges/write-a-function/problem def is_leap(year): leap = False # Write your logic here if (year%100==0) and (year%400==0): leap=True elif (year%4==0) and (year%100!=0): leap=True return leap # HR's code below
fc1055ce507d79704af1d2fcfa366c5fb87047f7
imsilence/actual_05_homework_mage
/02/huangyisan/insertion_sort.py
3,202
3.6875
4
#!/usr/bin/env python3 # encoding: utf-8 """ @version: 1.0 @author: huangyisan @license: Apache Licence @file: insert_task.py @time: 2017/3/26 15:40 """ ''' 一、首先判断原本序列是升序还是降序排列 1、降序情况: 若输入的数字大于第一个索引对应的值,则在0号索引位置进行插入。 情况1 若输入的数字小于最后一个索引对应的值,则在最后一个索引位置插入。 情况2 若输入的数字已经存在原本序列中,则插入到原本序列中该数字所存在的索引位置。 情况3 若输入的数字,从索引0...
7891ca9a688ded2b597b67d2c9f5ade1a416299c
SeungsuHa95/Python
/Python for Beginner/1007 실습2.py
1,005
3.578125
4
import turtle import random #전역변수 선언 swidth, sheight, pSize, exitCount = 300,300,3,0 r,g,b,angle,dist,curX,curY=[0] * 7 #메인 turtle.title('거북이 맘대로 다니기') turtle.shape('arrow') # turtle, circle, square turtle.pensize(pSize) turtle.setup(width = swidth +30, height = sheight +30) turtle.screensize(swidth,sheight) while T...
ef7d91689f72150a78d7ef43203edb1013f6cead
JanBartoszek/ERP
/sales/sales.py
6,959
3.765625
4
# data structure: # id: string # Unique and random generated (at least 2 special char()expect: ';'), 2 number, 2 lower and 2 upper case letter) # title: string # price: number (the actual sale price in $) # month: number # day: number # year: number # month,year and day combined gives the date the sale was made # ...
c09da4f5698d9f6a3131fb2a321ca0d4ec1a853a
Hshah1989/Strong-Password-Generator
/main2.py
1,358
3.984375
4
# Name: Hiren Shah # Date: 1/3/21 # Purpose: To create random password based on the # of letters, symbols and nums import random letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', ...
dff1fc514324868df71e1a0ce3763724af4c33cf
FengFengHan/LeetCode
/Insertion Sort List_L.py
999
3.859375
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a ListNode # @return a ListNode def insertionSortList(self, head): if head == None or head.next == None: return head ...
6645ca2ce7df36973958665ffbeafb9a1723b29c
brigidrose/mixed-feelings
/text_sentiment.py
1,446
4
4
#NOTE: THIS CODE WAS FOUND HERE: #https://finnaarupnielsen.wordpress.com/2011/06/20/simplest-sentiment-analysis-in-python-with-af/ import math import re import sys reload(sys) sys.setdefaultencoding('utf-8') # AFINN-111 is as of June 2011 the most recent version of AFINN filenameAFINN = 'AFINN-111.txt' afinn = dict(...
a00e0c8539acf889a7268ce71a2bf54266d33d2e
arcnb/python-ICE
/ICE2/source/character frequency.py
187
4.25
4
charstr = input("Enter the string: ") dict = {} for char in charstr: value = charstr.count(char) dict[char] = value print("frequency of the string:\n{} - {}".format(charstr,dict))
42b9d96c778a8ea577317a5ae7465fc96ae2c4dc
hu357/python
/20201005 tk2 label排列.py
503
3.75
4
from tkinter import * root = Tk() Label(root,text="red",bg="red",fg="white").pack(fill=X)#横向填充 #bg="red"背景颜色,fg="white"字体颜色 Label(root,text="green",bg="green",fg="black").pack(fill=X)#横向填充 Label(root,text="blue",bg="blue",fg="white").pack(fill=X)#横向填充 Label(root,text="red",bg="red",fg="white").pack(side=LEFT)#横向排列 L...
4de424e1481fa394789558cea2147ee1c55e9225
gaford/project-euler
/python/19.py
556
3.921875
4
# -*- coding: utf-8 -*- # Project Euler 19 # 1 Jan 1901 was a Tuesday Year = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] LeapYear = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] TimePeriod = (Year * 3 + LeapYear) * 24 + Year * 4 dayTicker = 0 # adding one for each day; first day is a Tues, so need to add S...
c9a5b87753f39fcba2507dccad905d0e9dc8b279
avi527/Encapsulation
/encap_intro2.py
166
3.6875
4
class Person: def __init__(self,name,salary): self.__name=name self.__salary=salary p=Person('avinash',5000) p.salary=6000 print(p.salary)
f5b708b8e28da9465e970231e3299f9f30a524b5
vivekaxl/LexisNexis
/ExtractFeatures/Data/shenwei356/module_concurrent.py
222
3.515625
4
#!/usr/bin/env python3 import multiprocessing from multiprocessing import Pool def f(x): print(x) return pow(x, 6) with Pool(processes=multiprocessing.cpu_count()) as pool: print(pool.map(f, range(1, 100)))
438711f7f221609928bc7aeec13518a21a1d9049
t-tran2/ebay-webscraper
/market-price-calc.py
688
3.59375
4
from urllib.request import urlopen from bs4 import BeautifulSoup as soup """ Create ebay url to search for items based on name, condition, purchase method, and sold & completed items. """ """ https://www.ebay.com/sch/i.html?_from=R40&_nkw=macbook+pro&_sacat=0&LH_Auction=1& LH_ItemCondition=3000&rt=nc&LH_Sold=1&LH_Com...
240a9b6d4986f35ff6933090f8bc4a6f104b7847
amadev/dojo
/flip.py
1,187
3.5625
4
# coding: utf-8 # проблема: найти подмассив, сделав xor на который мы получим максимальное число 1 # вход: строка из 0 и 1, например '010' # выход: два индекса старт и финиш (счет начинается с 1) # идея: каждый 0 добавляет 1, а один - вычитает, идя по массиву ищем макс. сумму, # если сумма уходит в минус, игнорируем та...
53e8f4b40983e6a0b28849302769c035eb995ae7
WeiBai/Language
/solution/Solution1.py
603
3.796875
4
import requests import json '''This program detect the language of console input from users using MeaningCloud''' # Input from console input_str = raw_input("Enter your input: ") print "Received input: ", input_str url = "http://api.meaningcloud.com/lang-2.0" payload = "key=1b2ea248af8252d4d3ef84d0ef6798ce&txt="...
0e4b2d700d71753f5e95a5c4f985e8205674ee8d
SylviaDu99/pythonPractice
/L12.py
510
3.703125
4
def addall (x) : total = 0 for q in x : total += q #total += q equal to total = total + q return total #x = [15, 74, 3, 28] #x.sort () #print (x) #[3, 15, 28, 74] def only_upper (t) : res = [] for s in t : if s.isupper() : res.append (s) return res numlist = list () while True : ...
b6d2b78c09dedf65056dbaec1f29a3f04ba288c0
dwdii/py-sandbox
/src/graph-search/graph-dijkstra.py
6,233
4.03125
4
# # Author: Daniel Dittenhafer # # Created: April 29, 2019 # # Description: Coursera Algorithms Graph Search and Data Structures # __author__ = 'Daniel Dittenhafer' import collections import graph import myheap import itertools import os import sys from timeit import default_timer as timer """ Your task is to run D...
ab33ca4e42db13d367adb352cac4d2f606229f1f
Sukhrobjon/exercism
/python/pangram/pangram.py
621
4.3125
4
import re, string def is_pangram(sentence): """Determine if a sentence is a pangram. A pangram (every letter) is a sentence using every letter of the alphabet at least once. Runtime: O(n) where n number of chars """ # remove all chars/space except letters and lowercase them norm_sent = ''....
d73069ee8b8338636181a0db4ac32054275e3072
FabianUlrich96/Bachelor-Thesis
/StatisticalAnalysis/Ktlint/ktlint_analysis.py
928
3.515625
4
import pandas as pd import seaborn as sns from matplotlib import pyplot as plt def select_answers(): answer_df = pd.read_csv("ktlint_answer_score_error.csv", encoding='utf8') return answer_df def select_questions(): question_df = pd.read_csv("ktlint_question_score_error.csv", encoding='utf8') retu...
96f826104b2bb80d439b60a88f0e47c909c38935
dev-viniciusjorge/pythonEx
/ex057.py
220
3.875
4
sexo = str(input('Digite seu sexo [M/F]: ')) while sexo != 'M' and sexo != 'F': print('Por favor digite M ou F') sexo = str(input('Digite seu sexo [M/F]: ')) print('Sexo {} registrado com sucesso.'.format(sexo))
2bcddffa6f55325a2c33e70d6c9c4ecd5c5a4eeb
Onil-90/3_colors_game
/gui_tkinter.py
3,544
3.8125
4
from tkinter import * import numpy as np from functions import * def app(): # Function for change color of buttons def color_change(btn,r,c): ind = array_col[r,c] btn.config(bg=colors[ind], activebackground = colors[ind]) # change color array_col[r,c] = (array_col[r,c] + 1)%4 ...
62fb250c971f75f0f7f781aa6709a25f7b6b03aa
sairamprogramming/beginner-project-solutions
/bottle99.py
1,156
4.34375
4
# Program to give lyrics to the song 99 bottles. def main(): # Initalizing the number of bottles bottles = 99 # Looping through and printing the appropriate lyrics while bottles > 0: if bottles > 1: print(bottles, "bottles of beer on the wall,", bottles, "bottles of beer.") ...
c9c04b489d6949f2db2674e146a044d09d36008f
dinodre1342/CP1404_Practicals
/Prac1/shipping.py
286
4.09375
4
quantity = int(input("Please enter quantity of the item")) shipping_cost = 0 while quantity > 0: shipping_cost += float(input("Enter shipping cost:")) quantity -= 1 if shipping_cost > 100: print (shipping_cost - (shipping_cost * 0.1)) else: print (shipping_cost)
cfc7335ce6f068325e552f03b3cd0ac22a553e4e
Levva/GeekPythonAlg
/lesson9/task_2.py
1,699
3.828125
4
import heapq from collections import Counter from collections import namedtuple # Класс для узла class Node(namedtuple('Node', ['left', 'right'])): def walk(self, code, path): self.left.walk(code, path + '0') self.right.walk(code, path + '1') # Класс для листьев class Leaf(namedtuple('Leaf', ['c...
e4cb2dbb2b1c04009dddc669af1c32c4a3232d79
sunshot/LeetCode
/11. Container With Most Water/solution.py
625
3.671875
4
from typing import List class Solution: def maxArea(self, height: List[int]) -> int: if not height or len(height) < 2: return 0 left = 0 right = len(height) - 1 area = 0 while left < right: area = max(area, min(height[left], height[right]) * (right - ...
6525b4e8320c350828dd7f739c1a7bcb1af3cb4a
lariodiniz/Udemy-Python-Kivy
/app-comerciais-kivy/aulas/exercicio_pratico1.py
4,243
4.46875
4
''' #1 - Faça um algoritmo que apenas imprima o seu nome na tela e # em seguida finalize a aplicação. print("Lário dos Santos Diniz") #2 - Faça um algoritmo que solicite ao usuário digitar o seu # nome e em seguida envie a seguinte frase para a saída padrão: # "O seu nome é: [nome do usuário]". nome = input("Digi...
e1afc6c7c050f41a4e4b8306839111ba568da898
RainersJusts/RTR105
/cietaisrieksts.py
465
3.5625
4
# -*- coding: utf-8 -*- from math import * def manssin(x): k = 0 a = (-1)**0*x**1/(1) S = a while True: k = k + 1 R = (-1)*x*x/((2*k)*(2*k+1)) a = a * R S = S + a if abs(sin(x)-S) < 0.01: k = k - 1 return k x = pi y = manssin(x) p = u"\u...
5a8274994dea6f720f5470f5f067865716a1ceae
nalwayv/bitesofpy
/bite_135/bite_135.py
2,922
4.125
4
""" Bite 135. Sort a list of book object """ from collections import namedtuple from datetime import datetime from operator import attrgetter from typing import List Book = namedtuple('Book', 'title authors pages published') books = [ Book(title="Python Interviews", authors="Michael Driscoll", ...
b18e13468121b7b671a338fbdf653233daeaed1e
JoshuaSamuelTheCoder/Quarantine
/Count_Islands/old.py
1,719
3.609375
4
""" Given a 2D matrix, where 1 represents land and 0 represents water, count how many islands are present Input: [ [0, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 0, 1, 1], [0, 0, 0, 1, 0] ] Island 1 = [(1, 0), (1, 1), (2, 0), (2, 2)] Island 2 = [(2, 3), (2, 4), (3, 3)] """ from collections import deque cla...
e53b6ef51c84bd7a45418e67e061ec498706d253
AlexKlein/machine_learning
/project/fourth_week/stock_index_compilation.py
2,172
3.859375
4
"""The task of machine learning - dimension reduction ================================================ Contents -------- Script uses principal component analysis with stock indexes. Task ---- 0. Download a data set from the close_prices.csv. 1. On the downloaded data set, train the PCA conversion with the number of c...
c3219132171996642ea8d5e21bebdcf12ab716ce
Randle9000/pythonCheatSheet
/pythonCourseEu/1Basics/21Generators/Ex8.py
1,492
4.53125
5
#yield from" is available since Python 3.3! #The yield from <expr> statement can be used # inside the body of a generator. <expr> has # to be an expression evaluating to an iterable, # from which an iterator will be extracted. #The iterator is run to exhaustion, i.e. until # it encounters a StopIteration exceptio...
5076b903befa61a8127fa7aaec95bfd321ae3dd4
jmsimang/PythonToolkit
/useful_functions/merge_sort.py
1,278
4.03125
4
def combine(l, s, m, e): # Using the a and b previously defined in the merge function as it was # causing recursion depth errors. a = l[s: m] b = l[m: e] start_index = s item_a = 0 item_b = 0 # New while loop to test if I'm iterating over both a and b simultaneously. # It stops when ...
8dc7c442de042a0cd9a012aacfbf839626408c4e
sudheemujum/Python-3
/recursion.py
525
4.21875
4
#Without recursion def fact(n): result=1 while n>=1: result=result*n n-=1 return result print(fact(3)) op=fact(5) print('Factorial value is:',op) #With recursion def fact2(n): print('Executing Factorial Function with n value:',n) if n==0: result=1 else: result...
1281e060aa58f3a48c8c1667131fde67f5cbdf80
Tclack88/Lambda
/CS/CS-5-Graphs/projects/graph/warmup/islands.py
849
3.859375
4
islands = [[0, 1, 0, 1, 0], [1, 1, 0, 1, 1], [0, 0, 1, 0, 0], [1, 0, 1, 0, 0], [1, 1, 0, 0, 0]] visited = {} island_count = 0 width = len(islands[0]) height = len(islands) def find_neighbors(islands, visited, i, j): if (j,i) not in visited: visited.add((j,i)) ...
5652b9f99b8cfa595be7ac2aff75e6e34acf92ee
bansalishika/movie_trailer_udaicty
/media.py
858
3.78125
4
import webbrowser class Movie(): """ class movie helps to make instances of different movies without repeating the code. This class helps to write information for different movies and show trailer for the same. """ VALID_RATINGS = ["G", "PG", "PG-13", "R"] # the above variable includes the valid ratings for any...
30630370812604f8028d6762692f25172a7cc8c6
Mostofa-Najmus-Sakib/Applied-Algorithm
/Leetcode/Python Solutions/Recursion & Backtracking/SubsetsII.py
1,364
3.578125
4
""" LeetCode Problem: 90. Subsets II Link: https://leetcode.com/problems/subsets-ii/ Language: Python Written by: Mostofa Adib Shakib Time Complexity: O(n*2^n) Space Complexity: O(n*2^n) """ class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: def recursiveHelper(index, c...
fa7b685af69a1884918a4a07a574b3c8f4263eca
zzeleznick/pymaze
/wrapper.py
3,973
3.546875
4
#!/usr/bin/env python # coding=UTF-8 import sys from blessings import Terminal import time import numpy as np import argparse from random import gauss def process_input(): out = None args = sys.argv[1:] if args: out = args[0] return out class EggTimer(object): """ Dings when the timer ...
f19508748d2dd39b0f5efb635362e510f97cd372
mttymtt/DrawBot-Sketchbook
/Classes/Andy-Clymer/2019-07-30/01_animation.py
428
3.53125
4
import math print(e) total_frames = 20 speed = 1/15 # represented as a fraction of a second for frame in range(total_frames): percent = frame / (total_frames - 1) print(percent) newPage("A5") frameDuration(speed) # represented as a fraction of a second fill(1) rect(0, 0, width(), height(...
71bc939935c064114f66270940a00d3d94ba92bd
litianhe/webApp3
/www/test_yield.py
760
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def accumulate(): # 子生成器,将传进的非None值累加,传进的值若为None,则返回累加结果 tally = 0 while 1: next = yield if next is None: return tally tally += next def gather_tallies(tallies): # 外部生成器,将累加操作任务委托给子生成器 while 1: tally = yield f...
d3a1cd6382b7506b626e709b00ec17028e22c46b
cbranch/libsudoku
/generate_sudoku.py
1,890
3.875
4
import random # rules for standard sudoku puzzles MAX_VALUE = 9 BLOCK_SIZE = 3 LINE_SIZE = 9 def main(): print grid_to_string(generate_grid()) def grid_to_string(grid): row_strings = [''.join(map(str, row)) for row in grid] return "\n".join(row_strings) # list of rows, 9 values per r...
35baeeb5e2df542146406a034ee354fd7ec27171
timmahrt/praatIO
/examples/anonymize_recording.py
1,314
3.578125
4
""" Replaces someone saying a name with a tone over the name to 'hide' the name. The times that the names are spoken are taken from a transcript of the recording. """ import os from os.path import join from praatio import textgrid from praatio import audio path = join(".", "files") outputPath = join(path, "anonymiz...
c285a55185e62c040771c6549aa3ef2646314edd
rahimo01uni/programming-styles-ss-2020-exercises
/session-06/task-01/word_index.py
944
3.953125
4
#!/usr/bin/env python import sys, re, operator, string # Program Description: # # Word Index is a program that takes a plain text file as input and # outputs all the words contained in it # sorted alphabetically along with the page numbers on which they occur. # The program assumes that a page is a # sequence of 45 li...
d555cb351d488fc570af6d348f9391bd41076db0
summer0350386/C-to-F
/range.py
320
3.765625
4
# range import random range(5) #[0,1,2,3,4] 自動0開始,不包含5 for i in range(3): r = random.randint(1, 10) print(i) print('hi') print('這是第', i + 1, '次產生隨機數', r) range(2, 5) #[2, 3, 4] range(2, 10, 3) #[2, 5, 8] range(10, 3, -2) #[10, 8, 6, 4] range(100) for i in range(100): print('hi')
b80bcbf8408a46a892ee5dca2e2b8b8ad9c9a4c2
vardaofthevalier/Miscellaneous
/project_euler/python/PalindromeProduct.py
611
4.09375
4
from math import * def main(): largestPalindrome = None; for m in range(100, 1000): for n in range(100, 1000): if isPalindrome(m*n) and m*n > largestPalindrome: largestPalindrome = m*n print "The largest palindrome product of 3-digit numbers is: " + str(largestPalindrome) def isPalindrome(n): headPosi...
31f19f6e1781aea0f515435cdfd3cd5547fc72a2
danaklowe/TSP-Deliveries
/Package.py
1,347
3.734375
4
from HashTable import ChainingHashTable import csv # creates 40-key package hashtable and reads in data from package csv file # space-time complexity: O(N) def create_package_table(): package_table = ChainingHashTable(40) with open('Package File.csv', newline='') as csvfile: reader = csv.read...
70e145e6d982e08a9a41382c60eb58201feef30f
j0s/aoc2019
/16/solution_2.py
2,084
3.546875
4
#!/usr/bin/env python import sys import math import doctest class Logger: """ Logger class """ logfile = None @classmethod def init(cls, filename): """ Initialize logger to write to given file """ cls.logfile = open(filename, 'w') @classmethod def initialized(cls): r...
542be8afc4192a3b2955f5c26cd94118ae976a91
Tzahy/WorldOfGames2
/MemoryGame.py
1,835
4.3125
4
# Include necessary modules and functions import random, time from Utils import screen_cleaner from Score import add_score # Generate n random numbers between 1 to 101 by the player level entry. # The numbers will be shown for 0.7 seconds and then disappear (clean screen). def generate_sequence(difficulty): rando...
5782abeace73a9cdef40f7a553e5bd29185552c9
Jdb156158/python3.6.2_handouts
/for循环语句.py
227
3.875
4
sites = ["Jason", "Jason1","Jason2","Jason3"] for site in sites: if site == "Jason2": print("hi,Jason2") break print("循环数据 " + site) else: print("没有循环数据!") print("完成循环!")
151d9888fa2ef2b0536c1b54766c654499b4e278
windniw/just-for-fun
/leetcode/298.py
783
3.546875
4
""" link: https://leetcode-cn.com/problems/binary-tree-longest-consecutive-sequence problem: 求二叉树自上而下的最长连续递增长度 solution: 记录当前父节点的长度向下 dfs """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Soluti...
fe0a9a3fcb4e91114619ca75af3c2b6b04796efd
urbanisaziya/Python
/week7/193.py
274
3.59375
4
N = int(input()) Dict1 = dict() Dict2 = dict() for i in range(N): line = list(map(str, input().split())) Word = line[1] Key = line[0] Dict1[Key] = Word Dict2[Word] = Key M = input() if M in Dict1: print(Dict1[M]) elif M in Dict2: print(Dict2[M])
1987b9df220aab585be192415601cfa758eb6872
Ivanqza/Python
/Python Basics/pythonProject11/02. Password.py
153
3.53125
4
username = input() password = input() new_password = input() while new_password != password: new_password = input() print(f"Welcome {username}!")
69de055bdc8d65176fe32e0ada46dda38b4234d5
nato4ka1987/lesson4
/part2.py
586
3.9375
4
''' Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента. Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор. ''' a = [1, 5, 1, 5, 1] answer = [] for i in range(len(a)-1): i...
86c29bfb2fdfdd54da06ee0c624a0946fcdd567e
abharga997/networks_p1
/classes.py
2,181
3.546875
4
import time # All accounts users = { "root": { "password": "password", "group": "admin" # "SmartObj": [Lights, Alarm, Lock, Thermostat, SecCam, AutoBlind] } } class User: def __init__(self, username, password): self._username = username self._password = ...
67507668922727b63e940f5f10a497e5f5baa555
conrowland32/CI_Evolutionary_Blackjack
/Player.py
7,605
3.578125
4
import random as rand import CardHelpers as ch CARDS = {"Two": 2, "Three": 3, "Four": 4, "Five": 5, "Six": 6, "Seven": 7, "Eight": 8, "Nine": 9, "Ten": 10, "Jack": 10, "Queen": 10, "King": 10, "Ace": 11} BET_VALUE = 2 # Decisions """ Normal decisions (soft or hard hands): S -> Stand H -> Hit DH -> Double ...