blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e58bec92720dca8a3794f26da3dc6daa2528c70b | Yangqqiamg/Python-text | /robot_text.py | 1,449 | 3.625 | 4 | '''获取并分析robots.txt文件
使用RobotFileParser(), 格式如下:
urllib.robotparser.RobotFileParser(url='')
'''
from urllib.robotparser import RobotFileParser
urly = 'http://www.jianshu.com/search?q=python&page=1&type=collections'
rp = RobotFileParser() # 创建对象
rp.set_url('http://www.jianshu.com/robots.txt') # 添加链接
rp.read() ... |
df321f4e23c36b5e7f3b6275283c9276a7bf00f8 | Yangqqiamg/Python-text | /基础学习/python_work/Chapter 15/homework/15-1 and 15-2.py | 407 | 3.546875 | 4 | import matplotlib.pyplot as plt
x_values = list(range(1, 5001))
y_values = [x**3 for x in x_values]
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Reds,
edgecolor='none', s=20)
plt.title("Three ***", fontsize=24)
plt.xlabel("value", fontsize=14)
plt.ylabel("Number of Value", fontsize=14)
plt.tick_param... |
37e36ce621fceb652de854e3633abaaadea0ba4b | Yangqqiamg/Python-text | /基础学习/python_work/Chapter 11/employee_hw.py | 428 | 3.5 | 4 | class Employee():
def __init__(self,first,last,money):
self.first = first
self.last = last
self.money = money
def give_raise(self,add_money=5000):
full_name = self.first + ' ' + self.last
self.money += add_money
# print("name: " + full_name.title())
# pri... |
c878aa69ea2a998ee2e43416846549af039df2de | Yangqqiamg/Python-text | /基础学习/python_work/Chapter 4/piza_text.py | 199 | 3.578125 | 4 | #one
pizas=['panpan','shanhe','bishengke']
print('piza lists:')
for piza in pizas:
print('\t'+piza.title())
for f_piza in pizas:
print('I love '+f_piza.title())
print('\nI really love piza !')
|
8597d45bf757ddc2a02c9c1a745f1578f1a99153 | Yangqqiamg/Python-text | /基础学习/python_work/Chapter 4/people_text.py | 435 | 4.21875 | 4 | #one
people=['joke', 'xiaoming', 'joe', 'whinte', 'mary']
print(people[1:4]) # will show ['xiaoming', 'joe', 'whinte']
#two
print(people[:]) # will show the lists same as the people
#three
print(people[-2:]) #will show ['whinte', 'mary']
#four
print('here are the member lists :')
for num in people[:5]:
pri... |
73a0dfda68f9b8398763b4a6ac69c997b92aebca | Smily-Pirate/LeetCode | /twoSum_LeetCode.py | 1,621 | 3.78125 | 4 | # Given an array of integers nums and an integer target, return indices of the
# Two numbers such that they add up to target.
from typing import List
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:return: List[int]
"""
... |
4b37afdd26b7c442d049bb76a656387d7164e8ca | hindujabk/Deep-Learning-and-Machine-Learning-Real-World-Projects | /cifar10_cnn.py | 4,403 | 3.546875 | 4 | #Project 2 for CNN with 10 Different classes
"""
-AirPlanes
-Cars
-Birds
-Cats
-Deer
-Dogs
-Frogs
-Horses
-Ships
-Trucks
"""
#Import Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn
import tensorflow as tf
#Importing the Dataset
from keras.datasets ... |
16805df621a8bed2df90a4f07c7a2a8d8fc5f077 | Barmaley13/SwissArmyKnife | /py_knife/decorators.py | 3,174 | 3.921875 | 4 | """
Collection of decorators to make our life a little easier
Simple Decorator is based on a recipe from here:
https://wiki.python.org/moin/PythonDecoratorLibrary
"""
### INCLUDES ###
import time
### CONSTANTS ###
## Multiple Attempt Settings ##
ATTEMPT_NUMBER = 10
ATTEMPT_TIMEOUT = 10 # second... |
34b5063675adb260cd10860ebcf3d960c339eb8e | pandilwar605/Applied-Algorithms | /Insertion vs. Bubble Sort/sort.py | 6,611 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 24 17:39:38 2020
@author: Sanket Pandilwar
"""
import numpy as np
import time
import random
import matplotlib.pyplot as plt
import copy
# =============================================================================
# This funtion sorts the array using bubble sort with c... |
7fd23b7886393874e100400340f92b00556fe708 | Shayan-Asgari/InstagramBot | /Instamplfiy.py | 3,541 | 3.515625 | 4 | import tkinter as tk
from tkinter import *
from InstagramAccount import *
class Instamplify:
"""
Instagram Bot user interface that allows for easy access to typical daily user needs
"""
def __init__(self):
self.master = tk.Tk()
self.username = tk.Label(self.master, text="Username", bg=... |
46c18b71f9570ec8e028d6c9667805c41f688dd4 | m1roSlavit/UZNU1 | /labs/lab6/dest/3.py | 604 | 3.890625 | 4 | a_v = [float(x) for x in input("введіть через пробіл координати вектора a: ").split(" ")]
b_v = [float(x) for x in input("введіть через пробіл координати вектора b: ").split(" ")]
c_v = [float(x) for x in input("введіть через пробіл координати вектора c: ").split(" ")]
def calculate_scalar(a, b):
if len(a) == len... |
b649f0043b5a34c4e599c7c76d952ab8b240c0e2 | m1roSlavit/UZNU1 | /labs/lab10/dist/1.py | 1,210 | 3.578125 | 4 | class Straight_on_the_set:
def __init__(self, guide_vector, dot):
self.guide_vector = guide_vector
self.dot = dot
def input_data(self):
self.guide_vector = list(input("input guide vector").split(","))
self.dot = input("input dot").split(",")
def print_data(self):
pr... |
abdf2a03f599389d43aef4704a6a7044bf09fb59 | m1roSlavit/UZNU1 | /labs/lab11/dist/1.py | 963 | 3.6875 | 4 | class TArray:
def __init__(self, array):
self.array = array
self.array_elem_count = len(array)+1
def input_data(self):
self.array = list(input("input new array").split(","))
self.array_elem_count = len(self.array)+1
def print_data(self):
print("array: {0}; elem coun... |
21f48194d26c0cce7154954aa921ea0f8ed8084e | m1roSlavit/UZNU1 | /labs/lab12/dist/1.py | 1,610 | 3.609375 | 4 | import numbers
class TArray:
def __init__(self, array):
self.array = array
self.array_elem_count = len(array)+1
@property
def array(self):
return self.__array
@array.setter
def array(self, val):
if len([el for el in val if isinstance(el, numbers.Number)]) == len(va... |
3182651192fdf88d799b1c6c2aea5ea9c5d37278 | H-rafael/python-note | /code/python-06.py | 732 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
print(len("中国"));
print("==============");
print('''中国人名''');
print("hi, %s 是我的媳妇 "%('王菜菜'));
print('占地 %d%%'%(70))
print("=====");
r = (85-72)/72;
print("%.1f%%"%(r * 100))
print("=======");
classmates = ('Michael', 'Bob', 'Tracy')
print('classmates =', classmates... |
7505c56bc892317dc2672081fe7f373ab20bb83b | H-rafael/python-note | /code/python-14.py | 586 | 3.640625 | 4 | # -*- coding: UTF-8 -*-
class Student(object):
def __init__(self,score):
self.__score = score
def get_private_attr(self):
return self.__score
def set_private_attr(self,score):
self.__score = score
lisa = Student(95)
lisa.set_private_attr(23)
print(lisa.get_private_attr())
print(... |
b73b4b62fc6ec541191f94515474848f669c3d93 | agomusa/playground | /others/challenges-of-my-father/draw_in_terminal/draw_jalapeno.py | 495 | 3.859375 | 4 | def run():
draw_rhombus(8, "*")
def draw_rhombus(value, symbol):
lines = []
for i in range(value + 1):
line = ""
for _ in range(i):
line = line + symbol
lines.append(formater(line, value))
for line in lines:
print(line)
for line in lines[::-1]:
... |
1bb49cb7d7ba49df3d78b4c6e5c2e2e70d5dde83 | agomusa/playground | /others/challenges-of-my-father/draw_in_terminal/square.py | 383 | 3.921875 | 4 | def run():
num = int(input("Enter a number: "))
draw_square(num)
def draw_square(number: int) -> None:
for i in list(range(number)):
if i == 0 or i == number - 1:
print("* " * number)
else:
print("*", spaces(number), "*")
def spaces(number: int) -> str:
return... |
f9b54771df1a7e0540bcbb6b5395db2205716dd7 | zaihtml/intro-to-python | /lesson2.py | 1,469 | 4.34375 | 4 | """"# exercise 1
name = input("What is your name?")
print("Hello, {}".format(name))
colour = input("What is your favourite colour?")
room_colour = input("Would you paint your room this colour?")
print("You like {} and the answer to whether you\'d paint your room this colour is {}.".format(colour, room_colour))
# exe... |
f1d0591aff6e749447003ddc0c2b593dd34ce551 | DoctorEmmetBrown/ntssp | /Formation Editor/src/Data/Bezier.py | 4,826 | 3.796875 | 4 | # -*- coding: utf8 -*-
#Simple point class
import math;
def sqr(x):
return x*x;
class Point:
def __init__(self,x,y):
self.x = x;
self.y = y;
def __eq__(self,o):
return o.x == self.x and o.y == self.y;
class Line:
def __init__(self,p1,p2):
self.p... |
6f719efed77045baf19703450a6f05e90e08f105 | andriiglukhyi/leetcode | /replace_words/solution.py | 464 | 3.515625 | 4 | class Solution:
def replaceWords(self, dict, sentence):
"""
:type dict: List[str]
:type sentence: str
:rtype: str
"""
d = {}
for item in dict:
d[item] = 0
nw = sentence.split(" ")
for word in range(len(nw)):
for letter i... |
65499d361e5851bfe627eac7728a6827796ac867 | andriiglukhyi/leetcode | /intersection.py | 225 | 3.921875 | 4 | a = [2, 3, 3, 4, 6, 6, 8]
b = [3, 10, 6, 7, 9]
def intersection(a, b):
for item in range(len(b)):
if b[item] not in a:
b[item] = 0
while 0 in b:
b.remove(0)
print(b)
intersection(a,b) |
b29e1fcc5f48c62b1019a5296c8d731afc9092e4 | andriiglukhyi/leetcode | /triangle/solution.py | 752 | 3.515625 | 4 | class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
min_sum = None
sum = 0
def walk(i,j, sum):
print(sum)
nonlocal min_sum
if i == len(triangle) or j < 0 or j > len(t... |
ab0aa7639fce86d80f76b6c3cc24cef3a84475ea | andriiglukhyi/leetcode | /string_parser/solution.py | 1,997 | 3.90625 | 4 |
def parser(str):
# try:
# a = int(st)
# return a
# except ValueError:
# flag = None
# if st[0] == '-':
# st = st[1:]
# flag = True
# i = 0
# a = b = ''
# sign = ''
# while i < len(st):
# if st[i].isnumeric() and... |
a71ea0f068945f2dd6455d51863baceb419ed92a | andriiglukhyi/leetcode | /inversion.py | 339 | 3.59375 | 4 | def getInvCount(arr, n):
# import pdb; pdb.set_trace()
inv_count = 0
for i in range(n):
for j in range(i+1, n):
if (arr[i] > arr[j]):
inv_count += 1
return inv_count
# Driver Code
arr = [5, 4, 3, 2, 1]
n = len(arr)
print("Number of inversions are",
g... |
b6461984ee305f4f329fb45f235947b0b2dfcf9a | andriiglukhyi/leetcode | /third_maksimum_numer/solution.py | 310 | 3.796875 | 4 | class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# sort
temp = list(set(nums))
temp.sort(reverse = True)
if len(temp) >= 3:
return temp[2]
if len(temp) <= 2:
return max(nums) |
a9e0fcb469ca38311da9c12adcef773044101f7b | andriiglukhyi/leetcode | /positive_and_negative/solution.py | 487 | 3.6875 | 4 | def move(arr):
# Count negative numbers
n = len(arr)
count_negative = 0
for i in range(n):
if (arr[i] < 0):
count_negative += 1
i = 0
j = i + 1
while i != count_negative:
if arr[i] < 0:
i +=1
j = i + 1
elif arr[i] > 0 and j < n:
... |
1c90df6d8f451ff26b42ed64d23ef6cf636c4255 | andriiglukhyi/leetcode | /match_brackets.py | 490 | 3.5625 | 4 | def isValid(s):
"""
:type s: str
:rtype: bool
"""
opn = ['(', '{', '[']
closed = [')', '}', ']']
if s == "":
return True
if len(s) == 1:
return False
a = []
for item in s:
print(s, item)
if item in opn:
a.append(item)
if item i... |
b2455b49f35d2f39c27c2084f64350377bae61a6 | dammyai/my_py_journey | /rockscpap.py | 1,875 | 4.21875 | 4 | print("Welcome to Rock, Paper, Scissors Game")
print("Here are the Rules:")
print("Rock crushes Scissors")
print()
print("Paper covers Rock")
print()
print("Scissors cuts Paper")
print()
import random
list1 = ["Rock", "Paper", "Scissors"]
scores_computer = 0
scores_human = 0
num_of_rounds = 1
while num_of_round... |
dd1206084084ad647f465231f3e684355473d8c3 | ribolive/python_basico | /palavra_preEsufixo.py | 1,024 | 3.859375 | 4 | # Le uma palavra e informa N prefixo ou N sufixo (usuario escolhe)
def pre(p, qtd): # p = minha Palavra e qtd = quantas letras vamos retornar
i = 0
pre = ""
while qtd > 0: # IDEIA: vamos percorrer a palavra e pegar as letras desejadas (serão 'qtd' letras)
pre += p[i]
i += 1 # i começa na primeira let... |
be3b76f335d1a9c0df3d8e420b5d67589810448d | dtotheb/LedGame | /dot.py | 1,280 | 3.578125 | 4 | import pygame
class Dot():
def __init__(self, pos=(0, 0), radius=25, lit=False):
"""
Initializes the Dot
pos_x/pos_y hold the pygame co-ords to match the LED grid locations in pos
"""
self.pos = pos
self.lit = lit
self.radius = radius
self.screen = p... |
7a900eb84855b49e689d9ba9c41b80a41b5fd748 | RisabhKedai/Spectrum-intership-drive2020 | /task0.1.6.py | 1,578 | 4.4375 | 4 | #a function that generates n fibonacci terms list
def fibonacci(n):
# return a list of fibonacci numbers
a=0
b=1
c=0
l=[]
for _ in range(n):
l.append(c)
a=b
b=c
c=a+b
return l
print("Select between the following by entering apt number:")
print("1.print all th... |
43474c9415e5eb489d7873b64702bb759e52247a | naturalis/mebioda | /doc/week3/w3d5/lecture3/transform.py | 1,635 | 3.6875 | 4 | import unicodecsv as csv
society = {}
crops = {}
mapping = {}
# reads an individual mapping file, has 'ID' and 'Description' columns
# allows lookups of the crop name through the id
def read_mapping(variable_id):
path = variable_id + '.csv'
with open(path) as csvfile:
mapping[variable_id] = {}
... |
09b5675510952c62a8686b2e7aafdc958a8049e7 | rotyflo/pyalgos | /intermediate/intermediate_algorithms.py | 10,743 | 4.125 | 4 | import math
def sum_all(arr):
"""
Return the sum of two numbers and all the numbers between them.
The lowest number will not always come first.
"""
arr.sort()
return sum(range(arr[0], arr[1] + 1))
# print(sum_all([1, 4]))
def diff_array(arr1, arr2):
"""Return the difference between two ... |
b50c9780fc00d69558cd48891bbf7497543b1135 | alejack9/Transport-Mode-Detection | /examples_py_har/examples_py/test_scikit_preprocess.py | 1,119 | 3.625 | 4 | import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
from sklearn.impute import SimpleImputer
#Example of classification problem via Scikit-learn
#Load the dataset containing NULL values
myfile="iris2.csv"
#Load the dat... |
61e9407c0fc6b77859b824baf4125a5ba70a7558 | alejack9/Transport-Mode-Detection | /examples_py_har/examples_py/test_python_comprehension.py | 144 | 3.71875 | 4 |
def main():
print("Simple Python list example (version 3: list comprehension)")
mylist=[x**2 for x in range(0,11)]
print(mylist)
main()
|
e7f47e71b78d7fe0a73a7f3fa575fe0e0e8b295a | alejack9/Transport-Mode-Detection | /examples_py_har/examples_py/test_python_lambda.py | 197 | 4.0625 | 4 |
def main():
print("Simple Python list example (version 2: use lambda function)")
square=lambda x:x**2
mylist=[]
i=0
while (i<=10):
mylist.append(square(i))
i+=1
print(mylist)
main()
|
6c7b204de5b93dac274b877ff07086e376665cb4 | zhengshunjie/learn_tensorflow | /1-科学计算库numpy/numpy用法.py | 643 | 3.65625 | 4 | import numpy
world_alcohol = numpy.genfromtxt("world_alcohol.txt", delimiter="," ,dtype=str)
print(type(world_alcohol))
#The numpy.array() function can take a list or list of lists as input. When we input a list, we get a one-dimensional array as a result:
vector = numpy.array([5, 10, 15, 20])
#When we input a... |
46a52b63a5ff10f2f0a1b55796ffebcb40b7902c | jliou3212/Games | /Simulations/probability_test.py | 804 | 3.8125 | 4 | allies = 3
def find_poss(allies):
poss_list = [0] * allies
poss_count = 2 ** allies
total_list = []
for i in range(1, poss_count + 1):
total = 0
poss_list_fin = []
counter = 1
# swaps the count of one number in list
for j in range(1, allies+1):
if i ... |
1f5d0a99f3c926105a6e3f4d44d21ff8cb62ac88 | fractal1729/primes2017 | /nn/test-keras-th/keras_cnn_example.py | 1,511 | 4.1875 | 4 | # Following https://elitedatascience.com/keras-tutorial-deep-learning-in-python
# unfinished due to the tutorial not working for Keras 2
########## Step 3: IMPORT LIBRARIES AND MODULES ##########
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from k... |
77ce6bd9944d92dd6e605e6d3fcd70f69a14e2e3 | fractal1729/primes2017 | /nn/test-keras-th/deep-mlp-mnist.py | 2,688 | 4.15625 | 4 | from keras.datasets import mnist # subroutines for fetching the MNIST dataset
from keras.models import Model # basic class for specifying and training a neural network
from keras.layers import Input, Dense # the two types of neural network layer we will be using
from keras.utils import np_utils # utilities for one-hot ... |
67f3c2bc97a0576eac2aef49342186706774935a | fazeeldin/password-generator-with-sqlite3 | /generate_pwd.py | 2,463 | 3.59375 | 4 | from tkinter import *
import db
import string, random
def create_unique_password(pwd_len):
pwd = ""
list_chrs = []
x = random.randint(0,25)
list_chrs.append(string.ascii_uppercase[x])
x = random.randint(0,25)
list_chrs.append(string.ascii_lowercase[x])
x = random.randint(62,9... |
042daadb5e2e4a835177d39c86af40174907ec5c | DmytroZn/tasks_from_lesson | /lesson_2.py | 5,132 | 3.96875 | 4 | # Create a class car. Describe common attributes.
# Create passenger car and truck classes.
# Describe basic attributes for cars in the main class.
# It will be a plus if you override the methods of the base class in the heir classes.
class Car:
def move(self):
return 'Car drives'
def add_fuel(self,... |
bf3e45acc7c35391ab1e9ad4135455e2c28f8879 | paradisepilot/statistics | /exercises/programming/stephenson-python-workbook/06-dictionary/src/Ex128.py | 937 | 3.96875 | 4 |
'''
dummy comment
'''
def reverseLookup( dictionary, value ):
output = []
for k in dictionary.keys():
if value == dictionary[k]:
output.append(k)
return( output )
def ex128():
print("\n### ~~~~~ Exercise 128 ~~~~~~~~");
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
my_... |
c7d28935f224eeec85c04925084053dbb736e245 | PedroSantana2/exercicios-cursos-udemy | /exercicios-de-cursos-udemy/fundamentos-de-python/ex003.py | 534 | 4.1875 | 4 | '''
Escreva um programa que peça o nome e a idade do usuário. Caso a idade do usuário seja maior ou igual a 18 anos apresente a seguinte mensagem: "Seja bem-vindo ao nosso site [nome]!"; caso contrário, apresente a seguinte mensagem: "Você não pode acessar nosso site [nome]'''
nome = input('Digite seu nome: ').strip().... |
2fb25610d46d2b7e8bb0faef3a8af5e622e66347 | PedroSantana2/exercicios-cursos-udemy | /exercicios-de-cursos-udemy/fundamentos-de-python/ex005.py | 1,149 | 4.125 | 4 | '''
O Índice de Massa Corporal (IMC) é utilizado para mensurar o peso ideal de uma pessoa. Escreva um programa que peça o nome, a idade , o peso e a altura do usuário. Ao final calcule e mostre o resultado do seu IMC e classifique este resultado de acordo com a regra a seguir.
IMC<17 - Muito abaixo do peso ideal
17... |
53d639c6e5de3149e8437b66c79bf2949cf8737d | Euel-Yirga/ICS3U-Ass6-Python | /perimeter_of_rectangle.py | 526 | 4.28125 | 4 | #!/usr/bin/env python3
# Created by: Euel Yirga
# Created on: Oct 2019
# This program uses user defined functions
def calculate_perimeter(length, width):
perimeter = 2 * (length + width)
print("The perimeter is {0} cm".format(perimeter))
def main():
length_from_user = int(input("Enter the length of ... |
2b2cf425b19897f2c3ba7bf210a8a9ffda4235cc | sinegami301194/Python-HSE | /1 week/nextEven.py | 53 | 3.5625 | 4 | num = int(input())
x = num % 2
print(num + 2 - x)
|
7ae2f739efb9569fc541248ddbde400a3a3824ad | sinegami301194/Python-HSE | /5 week/morePrevious.py | 153 | 3.578125 | 4 | myList = list(map(int, input().split()))
for i in range(0, len(myList) - 1):
if myList[i + 1] > myList[i]:
print(myList[i + 1], end=' ')
|
dffac58d7fd1781da7dd7147d28cfd318684158d | sinegami301194/Python-HSE | /5 week/evenIndex.py | 133 | 3.6875 | 4 | myList = input() # Input the list
a = myList.split()
for i in range(0, len(a)):
if i % 2 == 0:
print(a[i], end=' ')
|
0abe640bcff2c05f25737bff7726c8c6733c4e98 | sinegami301194/Python-HSE | /7 week/sinonyms.py | 171 | 3.734375 | 4 | N = int(input())
myDict = {}
for i in range(N):
f_word, s_word = input().split()
myDict[f_word] = s_word
myDict[s_word] = f_word
print(myDict[input()])
|
7f17d2900bfcc1a5009c9b98eaf1a641c8c923de | checkDev/PythonProgramming | /week3/week3assignments/problem3_3.py | 465 | 4.09375 | 4 | def problem3_3(month, day, year):
""" Takes date of form mm/dd/yyyy and writes it in form June 17, 2016
Example3_3: problem3_3(6, 17, 2016) gives June 17, 2016 """
d = {1 : "January", 2 : "February" , 3 :"March" , 4 : "April", 5 : "May", 6 : "June" ,7 : "July"
, 8 : "August"
,9 : "Se... |
4951f4c937efbabfeeac0aff1ea8e5a13c3636ee | ms2020bgd/ErwanFloch | /exo_cc_lesson1_Erwan_Floch.py | 6,112 | 3.875 | 4 | import math
import unittest
# Given a string and a non-negative int n, return a larger string
# that is n copies of the original string.
# Example: string_times("hey", 3) should return "heyheyhey"
def string_times(string, n):
return string * n
# Write a function which returns True if a year is a leap year.
# A ... |
78afec367fc296b20ab8076ea87f3eb585fb4a87 | ucyang/AlgoEx | /baekjoon/10871/print_less_than_x.py | 167 | 3.515625 | 4 | _, x = map(int, input().split())
flag = False
for a in map(int, input().split()):
if a < x:
print(" " + str(a) if flag else a, end="")
flag = True
|
3fa867116f1aa674eea2cd459c651fbadc44c498 | politewasp/DadBot | /txt_to_json.py | 772 | 3.796875 | 4 | ### txt_to_json.py ###
## converts text file to array of each line in a json format.##
import json
# First, get all needed data in an array.
filein = open('txtin.txt', 'r')
data = filein.readlines()
filein.close()
reg = 0
for line in data:
data[reg] = json.dumps(line)
reg += 1
reg = 0
for line in data:
... |
3be507980a854a2ddfc4e141be41c677d00c496a | juntuu/advent_of_code_2018 | /day_18/solution.py | 2,492 | 3.765625 | 4 | import curses
import sys
import time
from collections import Counter
def step(yard: list[str]):
"""
. -> | if | >= 3
| -> # if # >= 3
# -> . if # == 0 or | == 0
"""
def adjacent(x0: int, y0: int, what: str, limit: int):
n = 0
xs = slice(max(0, x0 - 1), x0 + 2)
for r in yard[max(0, y0 - 1) : y0 + 2]:
f... |
ca047ced5cdca8d04e5382176d9fec1a5e20c6ad | juntuu/advent_of_code_2018 | /day_08/solution.py | 834 | 3.640625 | 4 | from collections import namedtuple, Counter
with open("input.txt") as f:
license = list(map(int, f.read().split()))
Node = namedtuple("Node", ["children", "metadata"])
def parse(license):
c, m, *license = license
children = []
for _ in range(c):
child, license = parse(license)
children.append(child)
metad... |
535410fc90f129f1e9054373a0fbbe2bc6c0e37e | diN0bot/miller | /GUI/gui.py | 13,794 | 3.84375 | 4 | """
Main user interaction module.
GUI is the main class. For example, it contains a ControlPanel, which in turn contains a tabbed pane,
which in turn contains tabs, which in turn contains buttons. Drawing and event handling
are piped down the chain.
Drawer is in a separate file and is instantiated externally t... |
73fa5059be3b94e98203b0dfa3408337e01c6553 | leafs1/Escape-The-Labrynth | /main.py | 36,193 | 3.84375 | 4 | import pygame
# Define colours
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
brown = (139,69,19)
blue = (0,191,255)
yellow = (255,255,0)
darkBrown = (101, 67, 33)
darkGrey = (128,128,128)
class Wall(pygame.sprite.Sprite):
"""This class is for all visible and hidden walls in the g... |
adc756eb94e8e6c9a86cc91abb239098fb09315d | advaithb97/Final | /backend/data/schema.py | 2,464 | 3.515625 | 4 | import sqlite3
def schema(dbpath="nbabase.db"):
with sqlite3.connect(dbpath) as conn:
cur = conn.cursor()
cur.execute("""
CREATE TABLE users (
pk INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(16) UNIQUE NOT NULL,
password_hash V... |
0ad46d3f7048e3e01afb4cd81223f03c42484c30 | Nyhilo/Adventure | /adven.py | 5,012 | 3.75 | 4 | # Choose your own adventure game
# Nyhilo, Nov 2017
###########
# Classes #
###########
class Node(object):
def __init__(self, script, choices):
"""
script is a string
choices is an array of arrays of the format [[key, text], [key, text]]
"""
self.script = script... |
9e3ecb3cad3fdcbbf948dc559b05290e441c2124 | fivemoons/LeetCode_Python | /Q145_BinaryTreePostorderTraversal.py | 728 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
... |
79b4d8725f437179f504daab26457f6f52cd298b | joewaldron/ALevel | /loopy.py | 266 | 4.34375 | 4 | myWord = "hello"
for eachLetter in myWord:
#remember to indent using a tab. Everything indented runs in the loop. Anything else runs after the loop.
print("Give me an",eachLetter)
print(eachLetter.upper()+ "!")
print("What have we got?")
print(myWord)
|
e2e2b4f3593d534c0077b5ec4df8f976e2e43d81 | nandorusrin/IF2123-Face-Recognition | /algorithm.py | 531 | 3.828125 | 4 | # Author: Nando Rusrin Pratama (13517148@std.stei.itb.ac.id)
#
# Algorithm for Euclidean Distance and Cosine Similarity
import math
class Matcher(object):
def euclidean_distance(x, y):
distance = math.sqrt(sum([(a - b) ** 2 for a, b in zip(x, y)]))
return distance
def cosine_similarity(x, y):
similarity = s... |
7bba0ad7c7cb9209b96f0b72e06ad2022f652f06 | aakbar5/handy-python | /general/py_thread.py | 825 | 4.0625 | 4 | """ A python threading """
import os
import threading
import time
class PyThread(threading.Thread):
def __init__(self, delay_seconds=0.500):
print("Thread init is called...")
self._delay = delay_seconds
self._stop_event = threading.Event()
threading.Thread.__init__(self)
def ... |
cea8b8c04aee2bad04275220ca093f653651ba15 | aakbar5/handy-python | /general/dict_to_tuple.py | 412 | 4.125 | 4 | """ Dictionary to tuple """
def convert_dict_into_tuple(py_dict):
"""
Convert dictionary object to tuple.
"""
if not isinstance(py_dict, dict):
return
py_tuple = tuple([x for x in py_dict.values()])
return py_tuple
# Simple tuple
ret = ("val1", "val2", "val3")
print(type(ret), ret)
# Conversion test
d = {... |
3c5f1dcb7bf773b01d9db16a92afcb8b9baac279 | voltrevo/project-euler | /python/p14.py | 371 | 3.90625 | 4 | #!/usr/bin/python
lrecord = [0,0]
for x in range(1,1000000):
n = x
length = 0
while n != 1:
if n%2 == 0:
n /= 2
else:
n = 3*n + 1
length += 1
if length > lrecord[1]:
lrecord[0] = x
lrecord[1] = length
print "The longest chain started at",... |
af827acbf7a050119cc76964d24c84a49c3d94bb | leahfrye/MITx-6.00.1x | /week2/creditPayments.py | 439 | 4.1875 | 4 | # Returns the remaining balance at the end of each month, if the minimum amount is payed.
balance = 42
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate/12
monthlyPaymentRate = 0.04
for month in range(0, 12):
payment = balance * monthlyPaymentRate
balanceRemaining = balance - payment
balan... |
829e2a65e10f1a7f7ee1e7350549638d2a44d6cd | leahfrye/MITx-6.00.1x | /week6/aDict.py | 584 | 3.796875 | 4 | class myDict(object):
""" Implements a dictionary without using a dictionary """
def __init__(self):
""" initialization of your representation """
self.dict = {}
def assign(self, k, v):
""" k (the key) and v (the value), immutable objects """
self.dict[k] = v
... |
85c18b4de48e43123b37f9585da573b60b8222af | nebulaliang/euler | /14/problem14.py | 915 | 3.921875 | 4 | '''
Problem 14
'''
# global variable, used to store the computed key value pairs
# represent start number and numbers of terms of the chain
cache={1:1}
# given start number, return the number of terms of the chain
# recursively build cache if given start number not exists in cache
def numOfChain(n):
if not cach... |
f19b3c5b8dd4a42d9da05d21855c1e394603430f | OtCrown/Compression | /Task2.py | 126 | 3.578125 | 4 | sentence = ["ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"]
sentence.split()
print(sentence)
|
610fde6696e4b873caec8401b4df2dbdbc0c9c58 | RockLloque/Exercism | /python/rotational-cipher/rotational_cipher.py | 376 | 3.953125 | 4 | import string
def rotate(text, key):
encryptet=''
for char in text:
if char not in string.ascii_letters:
encryptet += char
else:
index = (string.ascii_lowercase.find( char.lower() )+ key)%26
encryptet += string.ascii_lowercase[index] if char.islower() else st... |
86e3762a12105bb23ff5d94c17120f396f3eb8f0 | prateekchandrajha/usaco-grader | /prateek1.py | 4,187 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 20 19:03:45 2019
@author: Prateek Chandra Jha
Roll Number -> MDS-2019-22
"""
from sympy import *
import numpy as np
import matplotlib
#Question Number 1 - Graphing of a few functions - The plots are not attached, ONLY CODE BELOW
# Plotting Sine Functi... |
38c5867407dcc2d7060b43d7cf4d71615107230a | athul-santhosh/Hackerrank | /Word order.py | 338 | 3.796875 | 4 | # from collections import OrderedDict
# words = OrderedDict()
# for _ in range(int(input())):
# word = input()
# words.setdefault(word, 0)
# words[word] += 1
# print(words)
# print(len(words))
# print(words.values())
car = {
"brand": "Ford",
"model"
"year": 1964
}
x = car.setdefault("model", "Br... |
7431934e25c2ba199653c77feafafed7b3be4f4f | nikhilmborkar/fsdse-python-assignment-14 | /build.py | 244 | 3.671875 | 4 | def solution(list):
l = [3,4,3,5,4]
n= []
for i in l:
if i not in n:
n.append(i)
print (n)
unique = []
for x in list:
if x not in unique:
unique.append(x)
return (unique)
|
6279c3f6a4a29e1fc1bed28e69499d57e3f4a6c4 | junseokseo-KR/pythonAlgorithm | /venv/src/codeAlgorithm/leetCode/4_AlgorithmPractice/1_Level1/inverstmentGenius.py | 502 | 3.609375 | 4 | def sublist_max(profits):
profit_list = []
maxValue = 0
# 코드를 작성하세요.
for i in range(len(profits)):
sum = 0
for j in range(i,len(profits)):
sum += profits[j]
if sum > maxValue:
maxValue = sum
return maxValue
# 테스트
print(sublist_max([4, 3, 8, -2,... |
0ad23be330c6c86ff1c5fd7f68c925851b2f126a | BrichtaICS3U/assignment-1-functions-zane8182 | /main.py | 603 | 4.03125 | 4 | # Assignment 1
# ICS3U
# Nathan Ilunga elelellel
# March 28 2018
def CtoF(C):
""" Convert the temperature written in celsisus to fahrenheit"""
F = 1.8 * C + 32
return F
def FtoC(F):
""" Convert the temperature in fahrenheit to celsius"""
c = (0.55556) * (F-32)
return C
print('enter 1 to... |
7609361b20deeb4195de80eb66180df8053a740a | maybe-william/holbertonschool-web_back_end | /0x04-pagination/0-simple_helper_function.py | 242 | 3.640625 | 4 | #!/usr/bin/env python3
""" pagination """
from typing import Tuple
def index_range(page: int, page_size: int) -> Tuple[int, int]:
""" get the start and end range for two numbers """
return ((page-1) * page_size, page * page_size)
|
aa1858f98ccdf6f1ee64f04c27b06beba05cb46a | siumingdev/coding-exercises | /crokking the coding interview/9. Pattern Tree Depth First Search/All Paths for a Sum (medium)/solution.py | 855 | 3.640625 | 4 | class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left, self.right = left, right
def find_paths(root, S):
all_paths = []
def dfs(node, path, cur_sum):
path.append(node.val)
next_sum = cur_sum - node.val
if (node.left is None) and (node.right is None):
... |
cefdb4cfb9c5f408b2383609401ac30d2e2428e9 | siumingdev/coding-exercises | /crokking the coding interview/9. Pattern Tree Depth First Search/Sum of Path Numbers (medium)/solution.py | 826 | 3.734375 | 4 | class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left, self.right = left, right
def find_sum_of_path_numbers(root):
def dfs(node, path_number, path_numbers_sum):
if node is None:
return path_numbers_sum
cur_path_number = path_number * 10 + node.val
if (... |
41528495a8ad5ff0bd1e5964483c89129b3c9a91 | siumingdev/coding-exercises | /crokking the coding interview/2. Sliding Window/No-repeat Substring (hard)/solution.py | 495 | 3.703125 | 4 | # https://leetcode.com/problems/longest-substring-without-repeating-characters/
def solve(s: str) -> int:
start = 0
char_set = set()
max_len = 0
for end in range(len(s)):
rc = s[end]
while rc in char_set:
lc = s[start]
char_set.remove(lc)
start +... |
18a0bccfba4fc2d2687a352c20504d3e2e36ce34 | mariusbu/DavidPlayground | /two-little-games-1.py | 3,907 | 4.03125 | 4 |
#David Leisse
#07.08.2011
#Zwei kleine Spiele
import random
guessesTaken = 0
rightAnswers = 0
print ("Hey! What is your name?")
Name = input()
print ("And how old are you?")
Alter = input()
# up 17
if Alter > "17":
runGame = 't'
while runGame == 't':
number = random.randint(1, 100)
print("W... |
d58d0715c212b70a77c7dd8e74c0d0d46a5af8d2 | mariusbu/DavidPlayground | /segelquiz.py | 2,034 | 3.5625 | 4 | #autor: georg
#datum: 21.7.09
#arbeit: hobbyquiz
from turtle import *
#einleitung
print """Hallo, liebe Optikinder!
Wir beginnen heute mit einem kleinen Quiz,
dass überprüfen soll, was ihr alles schon wisst!
Ich bin übrigens die Möwe Jonathan."""
name = raw_input ("Und wie heißt Du? ")
print "Na dann Mast- und Scho... |
63f68dddc599fda8dd204180991d1bcbe4d0044a | kt170/Google-internship | /python/TRY2/video_player.py | 7,379 | 3.59375 | 4 | """A video player class."""
from TRY2.video_library import VideoLibrary
from TRY2.video_state import PlayState, VideoState
from TRY2.video_playlist import Playlist
from . import video_playlist_library
import random
"""PLAY funny_dogs_video_id"""
class VideoPlayer:
"""A class used to represent a Video Player.""... |
65d9c2aa469a659c78e468198a13903bd331d2cf | zzg-971030/Learn_ML_in_Python | /算法设计基础/LeetCodeBook/array/215.py | 1,735 | 3.75 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
def findKthLargest0(nums, k):
"""普通的排序方法"""
nums.sort()
return nums[-k]
def findKthLargest1(nums, k):
"""堆排序"""
class maxheap:
def __init__(self):
self._data = []
self._count = 0
def size(self):
return self._count
def add(self, x):
"""
往最大堆中... |
27ff53b6e54067f0ecdff8efaa364b037f4a2b32 | zzg-971030/Learn_ML_in_Python | /算法设计基础/剑指offer/python/EnterNodeOfLoop.py | 795 | 3.6875 | 4 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# time: 2020-05-20 11:47:21
# 描述: 链表中环的入口结点
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def EnterNodeOfLoop(self, pHead):
'''
双指针
Variables:
if pHead {[type]} -- [description]
p1 {[type]} ... |
431b7ce61e66271d36f6d4a663000d7eb175c072 | zzg-971030/Learn_ML_in_Python | /算法设计基础/LeetCodeBook/array/259-threeSumSmaller.py | 1,298 | 3.875 | 4 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# time: 2020-04-29 11:07:10
# 描述: 较小的三数之和
# 给定一个长度为 n 的整数数组和一个目标值 target,
# 寻找能够使条件 nums[i] + nums[j] + nums[k] < target 成立的三元组 i, j, k 个数
# (0 <= i < j < k < n)
class Solution(object):
def threeSumSmaller(self, nums, target):
n = len(nums)
# 数组排序
... |
febe605f8ed62d13e38aa6476afe1fd378228d7b | marloncard/byte-exercises | /02-currency/currency.py | 965 | 4.1875 | 4 | #!/usr/bin/env python3
"""
* Takes in a float as an argument
* Returns the number of American coins and bills needed to represent that float. (Round to the nearest penny)
"""
currency = {'hundred': 100,
'fifty': 50,
'ten': 10,
'five': 5,
'one': 1,
'quarter':... |
6647b710ff5ef5cfb4921001d1d6d3885841efb4 | Arunavaskar/CodingBatChallenge | /Challenge6.py | 87 | 3.515625 | 4 | def makes10(a, b):
return b == 10 or a == 10 or a+b == 10
print(makes10(9,9))
|
7eddc4e591e23e4a382f598c957c7dfb745dedd5 | CMNWestbrook/hw3 | /accounting.py | 1,235 | 3.75 | 4 |
def output_customer_payment_errors():
"""Get customer info for comparison of what was paid, what is owed, what
overpaid
"""
customer_file = open("customer-orders.txt")
for each_line in customer_file:
each_line = each_line.rstrip()
customer_info = each_line.split('|')
custo... |
83d08e7a6810748b9ad7b78787e1328807355bb8 | arjunbangari/Problem-Solving | /codeforces/1249/C1.py | 523 | 3.515625 | 4 | from math import log
def isa(n):
sm = log(n,3)
if (sm).is_integer():
ans = 3**int(sm)
else:
sm = int(sm)
sumt = 0
for i in range(sm):
sumt += 3**i
if (n-3**sm)>sumt:
ans = 3**(sm+1)
else:
ans = 3**sm
temp = n- 3... |
a3ae8272af7b61ba4609411962ca0d1348a0e3b8 | arjunbangari/Problem-Solving | /codeforces/1281/A.py | 212 | 3.984375 | 4 | for _ in range(int(input())):
s = input()
if s[-2:]=="po":
print("FILIPINO")
elif s[-4:]=="desu" or s[-4:]=="masu":
print("JAPANESE")
elif s[-5:]=="mnida":
print("KOREAN")
|
af3be760f9e50146c8fa6bb6927448135e32b0d7 | rohith2334/hackerrank | /algorithms/Migratory_Birds.py | 412 | 3.53125 | 4 |
import math
import os
import random
import re
import sys
# Complete the migratoryBirds function below.
def migratoryBirds(arr):
a=[]
for i in range(1,6):
a.append(arr.count(i))
return(a.index(max(a))+1)
if __name__ == '__main__':
arr_count = int(input().strip())
arr = list(map(int, in... |
15d1e30f448ec92ec5af2043b566ca8aeaa7038e | rohith2334/hackerrank | /python/Strings/Merge the Tools!.py | 402 | 3.65625 | 4 | def merge_the_tools(s, k):
# your code goes here
temp = []
count = 1
for i in range(len(s)):
if s[i] not in temp:
temp.append(s[i])
if count == k:
print(''.join(temp))
temp = []
count = 1
else:
count += 1
if __name__ =... |
4a1b424799ac4d845aaedcc50d09b61598f69b2b | rohith2334/hackerrank | /algorithms/Time_Conversion.py | 674 | 4.09375 | 4 | """Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock. """
import os
import sys
#
# Complete the timeConversion function below.
#
def timeConversion(str1):
#
# Write your code here.
#
if str1[-2:] == ... |
eb66b57458b53a4a84b8d12d8404dbef40f01096 | pwilczynski/PythonChallenge | /3/retry.py | 657 | 3.703125 | 4 | #!/usr/bin/env python
import string
def check_string( st ):
#this function checks if a string is what we want it to be, if not, it returns
#lUUUlUUUl
fail = 0
#print st
upper = [1,2,3,5,6,7]
lower = [0,4,8]
for i in upper:
if st[i].islower():
fail = 1
break
else:
continue
if fail ... |
e01eb89048f04ff63103729c34c9a2eb43ca032f | quatrix/rate_limit | /rate_limit/utils.py | 236 | 3.90625 | 4 | def join_non_empty(delimiter, *args):
"""
join the string representation of all non empty args with delimiter.
(empty means "" or None)
"""
return delimiter.join([str(x) for x in args if x is not None and x != ""])
|
1435749c702e40c2103cca61482315f895d75ffa | rafalmierzwiak/yearn | /code/longest_lines/longest_lines.py | 681 | 3.765625 | 4 | #!/usr/bin/env python3
from sys import argv
lines = {}
with open(argv[1]) as f:
n = int(f.readline())
for line in f:
lines[len(line)] = line
if len(lines) == n:
break
shortest = min(lines)
longest = max(lines)
for line in f:
length = len(line)
if le... |
616ac4b92f56a34ce7cabf98f6ae21f4ff8c771f | nziokaivy/password_locker | /password_test.py | 985 | 3.796875 | 4 | import unittest
from password import Account_user
class TestAccount_user(unittest.TestCase):
'''
Test class that defines test cases for the account user behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating tets cases
'''
def setUp(self):
'''
Metho... |
0a8b9769395d56594dd10acc873674e766be5cc0 | naymanpo/python-tutorial | /lines-identation.py | 174 | 3.78125 | 4 | #!/usr/bin/python3
if True:
print ("Hello1")
print ("Helllo2")
if (True):
print ("hello")
# print("Hello") not correct
#print("Hello") not correct
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.