blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e0db1997ee45a69578007d4cb2b64ea2f085c718 | arpitansu/code-chef | /easy/uncleJhony.py | 475 | 3.78125 | 4 | for _ in xrange(input()): #testacases
numOfSongs = input() #this line here is just to make online judge a fool
songsUnsorted = map(int, raw_input().split())# takes input of songs
uncleJhonyPosInSongsUnsorted = input()# position of UJ song in the playlist
uJinUnsorted = songsUnsorted[uncleJhonyPosInSongsUnsorted-1]#... |
3d895cf544ed03ce889fcc0081498b646274c670 | rjames86/advent_of_code | /day_14.py | 2,912 | 3.609375 | 4 | class Reindeer(object):
def __init__(self, name, speed, duration, rest):
self.name = name
self.speed = speed
self.duration = duration
self.rest = rest
self._current_seconds = 0
self.points = 0
@property
def distance_travelled(self):
total_seconds = se... |
3e2dccf572c23c309942232e738861a9a7885d65 | LitianZhou/Intro_Python | /project3_blackjack_game/project3.py | 6,236 | 3.625 | 4 | # Project 3: Blackjack game
import random
class Deck:
def __init__(self):
self.suits = ["club", "diamond", "heart", "spade"]
self.jqk = ["J", "Q", "K"]
self.cards = dict()
for suit in self.suits:
self.cards[suit + "-Ace"] = 1
for i in range(2, 11):
... |
b1d9d314d354268e5128cdd68dc07136e1d493aa | airportyh/begin-to-code | /lessons/python/lesson-4/students.py | 225 | 3.859375 | 4 | student_list = []
grade_list = []
while True:
print('1. Add a student')
print('2. Remove a student')
print('3. Display students')
print('4. Assign a grade')
answer = input('What do you want to do? ')
|
534bdd466b60f5ee487196225505738c5f4a12f6 | PrajwalAI/Rock-Paper-Scissors | /rock paper scissors.py | 1,857 | 4.1875 | 4 | # importing tkinter for GUI
import tkinter as tk
from tkinter import messagebox
# importing random module for our game
import random
# initialization
root = tk.Tk()
# Set the geometry of the screen(GUI)
root.geometry("355x70")
# Title
root.title("Rock Paper Scissors")
# computer's choice
a = rando... |
cb8cf170747dcd87b560fe0087b57a72edec796a | lakinsm/wgs-meg | /truncate_headers.py | 1,334 | 3.734375 | 4 | #!/usr/bin/env python3
import sys
def fasta_parse(infile):
""" Parses a fasta file in chunks of 2 lines.
:param infile: path to the input fasta file
:return: generator of (header, sequence) fasta tuples
"""
with open(infile, 'r') as fasta_file:
# Skip whitespace
while True:
... |
5a21f2ce529488f8e9a35e68e2ff4d5b8c235cfe | Michael-Pan95/Algorithm_Python | /SymmetricTree.py | 3,020 | 3.828125 | 4 | from .TreeBuilder import TreeNode
class SymmetricTree:
@staticmethod
def treeBuilder(val_list):
head = TreeNode(val_list[0])
level = 1
current_root_list = [head]
val_list = val_list[1:]
# This method has some flaw, it needs a list with lots of redundancy
# while... |
645a3c548aafb12c99518463d44d7d6caadc0cdf | mme/vergeml | /vergeml/views.py | 7,503 | 3.53125 | 4 | """
This module implements the data structures returned by Data.load() to
support the unique data loading requirements of different deep learning
libraries.
"""
import random
import itertools
from typing import Callable, Any
import numpy as np
def _rand_batch_ixs(num_samples: int, batch_size: int, fetch_size: int, r... |
940553b161f86b9b37161fa6fd24efe0a24bb472 | simtb/coding-puzzles | /leetcode-june-challenge/unique_bst.py | 347 | 3.640625 | 4 | """
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
"""
class Solution:
def numTrees(self, n: int) -> int:
if n <= 1:
return 1
ans: int = 0
for i in range(n):
ans += (self.numTrees(i) * self.numTrees(n - i - 1))
... |
7f8a5183dc839da5ad436024f9f17f8d4f5b01f5 | denze11/BasicsPython_video | /theme_15/4.py | 552 | 3.765625 | 4 | import math
numbers = int(input('Введите число от 1 до 100: '))
def error_detect(item):
if 0 < item < 100:
try:
if item == 13:
raise ValueError('Введено не коректное число 13')
except ValueError as e:
return ('Программа завершила работу с ошибкой', e)
else:
return (f'Ваше число возведенное в коре... |
6986aadc8f3bba960efb5c374b7268200f3a6a34 | aalparslan/METU-CENG | /Ceng489-Introduction to Security in Computing/THE2/part1/e2171395.py | 3,782 | 3.609375 | 4 | import os
import random
import string
def generate_key(length_of_file):
# This generates a key in the length of the file to be encrypted which contains random numerical and char values
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length_of_file))
def encrypt():
... |
29f4d233148ffd7c02816d27dad0d1477502926b | annekadeleon/Codeacademy-Learn-Python-2 | /Loops/foryourA.py | 277 | 4.15625 | 4 | phrase = "A bird in the hand..."
#prints "X b i r d i n t h e h X n d . . ."
for char in phrase:
#filters out letter A from string
if char.lower() == "a":
#comma after print statement means next print is on the same line
print "X",
else:
print char,
|
f9f52a7d1f9774c2d5f7498156c7e9c15b9812e0 | Jonathan-aguilar/DAS_Sistemas | /Ago-Dic-2017/Luis Zúñiga/Primer Parcial/Parte 1/Electrodomestico.py | 1,597 | 3.53125 | 4 | class Electrodomestico(object):
"""description of class"""
__color = ''
__precio = ''
__sku = ''
__fecha_creacion = ''
__pais_de_origen = ''
__marca = ''
def __init__(self,color,precio,sku,fecha_creacion,pais_de_origen,marca):
self.__color = color
self.__precio = pr... |
fcfc0794aa1c6a16024b164a75c98de0f942bb59 | coders-as/as_coders | /20210601_COS_Pro_1급_기출_1차/1차 문제/YOON/4_solution_YOON.py | 625 | 3.78125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[41]:
#You may use import as below.
#import math
def solution(num):
# Write code here.
num=num+1
print(str(num))
for i in range(len(str(num))):
if str(num)[i]=='0' :
# print(i)
# print(10**(len(str(num))-i-1))
... |
a0a4a12beb533e5dffdde752da44e871c3649cd1 | octomberr/RestockBot | /product_dict.py | 2,337 | 3.8125 | 4 |
class Product:
# Constructor
def __init__(self):
self.products = dict()
# Initializing a new product
def new_product(self, product_name):
self.product_name = product_name
self.products[product_name] = {
'Product URL': None,
'Product ID': None,
... |
5c383cb2eca63066ad72bf886d46bc2cb38597e9 | Abdeljalil97/automation-with-python | /strings/command_line2.py | 590 | 3.859375 | 4 | import argparse
def main(charctere,number):
print(charctere*number)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='printing a number of charactere')
parser.add_argument('number',type=int , help='a number')
parser.add_argument('-c',type=str , help='a charactere to print', defaul... |
e4e06dc42078a30b8bef29b4948ea6b79cb06aa5 | jefriadisetiawan/uji_coba | /list.py | 293 | 3.8125 | 4 | barang=['kunci','jam tangan','sepeda','mobil']
print(barang)
#method yang bisa digunakan untuk manipulasi list
barang.append('becak')
print(barang)
for i in 'rumah':
barang.append(i)
print(barang)
barang.insert(0,'kapal laut')
print(barang)
|
b69c78fe8e0d0cbbd482b98b4c6304202c9d2d29 | parthdt/hackerearth-algo-practice | /searching/binarySearch/bugs.py | 921 | 3.828125 | 4 | def binSearch(low,high,key,arr):
while low<=high:
mid = (low+high)//2
if arr[mid]<key:
low=mid+1
elif arr[mid]>key:
high=mid-1
else:
return mid
return -1
n = int(input())
arr = []
count = 0
for _ in range(n):
a = list(map(int,input().split... |
5f09a889d13eef917603d8b2ffc8496c8a16a8eb | BaiYiTseng/Network-Tools | /TCP Connection Test across An IP Range/tcp_connection_test_with_concise_output.py | 1,670 | 3.8125 | 4 | # Testing connections across a IP range on a specified port by attempting TCP three-way handshake
# Output: printing on the screen, consecutive successful connections will be shown with only one line and only the latest successful connection will be shown
# Program requirement: Python 3.5
python import argparse, socke... |
b1c5942d78ccd9f457b83b0aab5fe7c8f81498f4 | eopr12/pythonclass | /python20200322-master/class_Python기초/py10함수/py10_33_클로저.py | 346 | 3.53125 | 4 | # 변수의 유효 범위(Scope)
def outer_func(tag): # 1
text = "Some text" # 5
tag = tag # 6
def inner_func(): # 7
str = "<%s> %s </%s>" % (tag, text, tag) # 9
return str
return inner_func # 8
h1_func = outer_func("h1") # 2
p_func = outer_func("p") # 3
print(h1_func()) # 4
print(p_fu... |
8bb40ec35b3017c7cce6709fb17e8508b9b75133 | hg-pyun/algorithm | /leetcode/minimum-time-to-type-word-using-special-typewriter.py | 367 | 3.515625 | 4 | class Solution:
def minTimeToType(self, word: str) -> int:
count = 0
prev = 'a'
for char in word:
clockwise = abs(ord(char) - ord(prev));
counterclockwise = abs(clockwise - 26)
count += min(clockwise, counterclockwise)
prev = ... |
b321a28d3af3d07be88da7b2d6681ff74c239735 | ane4katv/STUDY | /Basic Algorithms/Recursion/Basic.py | 1,541 | 3.796875 | 4 | # def sum_elem(array):
# if len(array) == 0:
# return 0
# return array[0] + sum_elem(array[1:])
# def fact(array):
# if len(array) == 0:
# return 0
# if len(array) == 1:
# return array[0]
# # print(array[1:]) * fact(array[1:])
# return array[0] * fact(array[1:])
# def c... |
a7c9c7b46033e87fdb198cdad3504d3e614545af | yonicarver/ece203 | /Lab/Lab 5/build_sentence.py | 422 | 4.25 | 4 | def build_sentence( sentence ):
"input: string containing entire sentence, output: scrambled words in a sentence"
from scramble import scramble
split = sentence.split()
empty = ''
for word in split:
str(scramble(word))
#empty = empty + ' ' + word
#print(' ... |
8e492125c1997b30121c9440424121f2ab2ba0d8 | DebRC/My-Competitve-Programming-Solutions | /Codechef/BSTOPS.py | 1,515 | 3.6875 | 4 | # cook your dish here
class Node:
def __init__(self,data,pos):
self.key=data
self.pos=pos
self.left=None
self.right=None
def minval(root):
temp=root
while (temp.left is not None):
temp=temp.left
return temp
def insertnode(root,key,pos):
if root is... |
c37d3ac8b15cb08c6322efb6c597b2e80474cabe | arthurosipyan/Python-Programming-Bootcamp | /archieve/WhatGradeAreYou.py | 386 | 4.25 | 4 | # If age 5 "Go to Kindergarten"
# Ages 6 through 17 goes to grades 1 through 12... "Go to Grade 6"
# If age is greater then 17 then say "Go to College"
age = int(input("Enter age: "))
if age == 5:
print("Go to Kindergarten")
elif 6 <= age <= 17:
print("Go to Grade {}".format(str(age - 5)))
elif age > 17:
... |
04770a13dcfdbf4fd9f6e1519d8efb5e9acc9851 | tospe/adamastor | /python/kadane.py | 211 | 3.6875 | 4 | #kadanes ALGORITHM
def findMaxSubarray(arr):
mx_c = mx = arr[0]
for i in range(1,len(arr)):
mx_c = max(mx_c + arr[i],arr[i])
if mx_c > mx:
mx = mx_c
return mx
print(findMaxSubarray([1,-3,1,2,-1]))
|
074598fab77fe471181ca73c9d613af371a14a6a | gustavgransbo/Recommender-Systems-Course | /matrix_factorization/iterative_factorization_with_biases_and_reg.py | 6,062 | 3.546875 | 4 | """
This file implements matrix factorization for recommending movies to users.
It is a modified version of iterative_factorization_with_biases.py, now
including regularization.
The implementation approximates a user-item rating matrix R as
R_hat = WU' + user_bias + movie_bias + average_rating,
where R has dimensions ... |
fe942e684503097780ee52b5f84458617547c8d5 | iamneo007/Raven | /distance.py | 122 | 3.5 | 4 | x1 = 2
x2 = 4
y1 = 9
y2 = 11
d = ((x2-x1)**2+(y2-y1)**2)**0.5
print("distance between two points (x1,x2) & (y1,ey2)=",d) |
f058207b44dceda236b1fa39ce0eccb312dcd226 | jaiz25/IS211_Assignment6 | /conversions.py | 611 | 3.609375 | 4 | #!usr/bin/env/python
# -*- coding: utf-8 -*-
"""IS211 Assignment Week 6: Conversions"""
def convertCelsiustoKelvin(degrees):
return round(degrees + 273.15, 2)
def convertCelsiustoFahrenheit(degrees):
return round(degrees * (9.0/5.0) + 32, 2)
def convertFahrenheittoCelsius(degrees):
return round((degre... |
ff5c43ed63cbe5fd65ccd46b0cb57dff1c75f80f | pyjune/python3_doc | /4_3.py | 303 | 3.8125 | 4 | # 기본 형식
for i in range(1, 10): # 줄 번호 1~9
for j in range(1, i+1): # 별의 개수 1~9
print('*', end='')
print() # 한 줄이 끝나면 새줄로 바꿈
# 파이썬의 형식 사용
for j in range(1, 10):
print('*' * j) # '*'를 j번 출력
|
c1f4f7c7d39ba69b26994e430c6d4b7ca8f9e9bb | sinabolouki/margin_watermark | /water_mark.py | 2,258 | 3.5 | 4 | # import the necessary packages
import argparse
import os
import cv2
import numpy as np
from imutils import paths
from functions import watermarker
# construct the argument parse and parse the arguments
def watermark_maker(watermark_path, input_path, output_path, alpha, posH=0, posW=0):
watermark = cv2.imread(... |
49a1add157b4e87a9ec8f9547631a2f4f34d2f67 | hello-wangjj/Introduction-to-Programming-Using-Python | /chapter13/TestException.py | 442 | 3.75 | 4 | def main():
try:
number1,number2=eval(input('please input two numbers,separated by a comma: '))
result=number1/number2
print('Result is',result)
except ZeroDivisionError:
print('Division by zero')
except SyntaxError:
print('a comma may be missing in the input')
except :
print('Somthing wrong in the inpu... |
b570664bfef54e351cdd64ec5e77a8325863f199 | kkorolyov/algorithms | /Stacks.py | 1,304 | 3.640625 | 4 | # Prints the minimum cost for rearranging n items with an altitude and weight into k stacks.
def main():
poles = []
n, k = input().strip().split(' ')
n, k = int(n), int(k)
for i in range(n):
xi, wi = input().strip().split(' ')
poles.append(pole(int(xi), int(wi)))
print(str(memoCost(poles, k)))
class pole:... |
b4e06a06d10ae0e8c7152dafdc9eabbe99e786e4 | Radu1990/Python-Exercises | /think python/src_samples_2/Tuples_theory.py | 846 | 4.5 | 4 | t = ('a', 'b', 'c', 'd', 'e') # with or without paranthesis gets to work
print(t)
t1 = 'a', # this is how a single element tuple looks like, you habe to put the final comma
print(t1)
t2 = 'a' # written like that it is a string
print('this a has type', type(t2))
t3 = ('abc', '123')
print(t3)
t4 = tuple() # this... |
b245fc306c2de2c9deb7fb65f8c0654277911a81 | hpellis/module3_test_driven_development | /ch4_intro_to_unit_testing/test_ch4_harriet.py | 2,782 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 09:58:46 2019
@author: 612383249
"""
import unittest
from ch4_harriet import is_prime
from ch4_harriet import word_count
import sys
#TestCase is the individual unit of testing
#it checks for a specific respones to a particular set of inputs
#unittest pr... |
a16ed03ff655986131b67e6069e397c5758214a3 | vipinpillai/ricochet-robots | /Robot.py | 7,066 | 3.828125 | 4 | import operator
class Robot:
"""This class will be used to perform operations as part of the Ricochet Robot game traversal."""
def __init__(self, row_count, column_count, start_coordinates, goal_coordinates, block_locations):
self.row_count = row_count
self.column_count = column_count
... |
308e2e3af1fe6edf928c76252e10b90f83806ecd | AlexMunoz905/PythonTest | /ImportFunc.py | 641 | 3.921875 | 4 | def move(direction, int):
if direction == "foward":
print("Character moved foward ", int)
elif direction == "back":
print("Character moved back ", int)
elif direction == "right":
print("Character moved right ", int)
elif direction == "left":
print("Character moved left ",... |
50d39e215b79af792115500b6375143b1c633b4b | DinakarBijili/Data-structures-and-Algorithms | /ARRAY/20.Rearrange_arr_in_alternating_positive_negative.py | 2,348 | 4.03125 | 4 | """
Rearrange array in alternating positive & negative items with O(1) extra space | Set 1
Given an array of positive and negative numbers,
arrange them in an alternate fashion such that every positive number is followed by negative and vice-versa maintaining the order of appearance.
Number of positive and negative n... |
04384ece0abb1885b510c1c89cf9966613d1b5ba | xiang-daode/Python3_codes | /生成器_generators_v0.py | 365 | 3.671875 | 4 | # 在这里写上你的代码 :-)
#生成器,generators:
#生成器也是一种函数,每一次调用,只会交出一个值:
def fun01(iterable):
for i in iterable:
yield i*i #每一次只提供一个值
#在大量元素的搜索中,节约了空间与时间:
for j in fun01(range(1,0xFFFFFFFFF)):
print(j,end=';')
if j>=100:
break
|
10a9b71c9007a3f2f4d297e3262d56e2945243df | Jayshri-Rathod/function | /debugs.py | 983 | 3.921875 | 4 | # def sum():
# print(12+13)
# sum()
# def welcome():
# print("Welcome to function")
# welcome()
# def isEven():
# if(12%2==0):
# print("Even Number")
# else:
# print("Old Number")
# isEven()
# numbers_list = [1, 2, 3, 4, 5, 6, 7, 10, -2]
# print (max(numbers_list))
# def add_... |
a5517d87af067494e07cc8da52283cd99bd1e03d | aaaaasize/algorithm | /func/7_natural.py | 449 | 3.828125 | 4 | # 7. Напишите программу, доказывающую или проверяющую,
# что для множества натуральных чисел выполняется равенство: 1+2+...+n = n(n+1)/2, где n — любое натуральное число.
def _current(n):
return n * (n + 1) / 2
def _next(n):
return (n + 1) * (n + 2) / 2
for i in range(1000):
print(_current(i + 1) == _... |
995c38832f6e1a4634e61ef47c3b8da3ba352b62 | kpm1117/kmcdermott_ej | /cusip_lookup/utils.py | 214 | 3.703125 | 4 | def deduplicate_list(_list):
"""
Deduplicate input but preserve order.
"""
seen = set()
seen_add = seen.add
return [
x for x in _list
if not (x in seen or seen_add(x))
]
|
5a9d009f0af663c859ec699c3a47326ba2e449da | muzigit/PythonNotes | /section7_面向对象高级编程/action1_使用__slots__.py | 1,441 | 3.859375 | 4 | # 使用__slots__
# __slots__:限制class实例能添加的属性
# 动态语言的灵活性:创建一个class后,可以给该实例绑定任何实例和方法
# 注:
# 1.__slots__定义的属性仅对当前类属性起作用 对继承的子类不起作用
# 2.如子类也定义__slots__ 子类实例允许定义的属性就是自身的__slots__加上父类的__slots__
class Student(object):
pass
s = Student()
# 给该实例绑定属性name
s.name = 'Tom'
print(s.name) # 输出:Tom
# 给该实例绑定方法
def set_age(self,... |
ff144453b66168ca4ad9f0d12bf018f895e18079 | iFission/Project-Euler | /17.py | 658 | 3.8125 | 4 | # If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
# If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
# NOTE: Do not count spaces or hyphens. For example, 342 (... |
4e83012500816d4b125d3ca41fc5a78d4585a96c | llafcode/Udacity-DataStructure-Algorithms | /Unscramble Computer Science Problems/Task1.py | 776 | 4.21875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone nu... |
96ae0209f1ea0347f91fbb5f957e86635cc27c54 | farinfallah/Python-for-Beginners | /Week2/sumRasht.py | 139 | 3.625 | 4 | #Farinaz Fallahpour
win = 0
sum = 0
for i in range(1, 31):
x = int(input())
sum = sum + x
if x == 3:
win = win + 1
print(sum, win)
|
3a606ec5e9c07c624911996c748ba11b4e630ac3 | cocoaButterCoder/TheCodeBook | /railFenceVideo.py | 1,278 | 4.1875 | 4 | #! /usr/bin/env python3
import math
def decrypt(ciphertext):
middle = math.ceil(len(ciphertext) / 2)
topRail = ciphertext[:middle]
bottomRail = ciphertext[middle:]
plaintext = ''
for index in range(len(ciphertext)):
if index % 2 == 0:
plaintext += (topRail[index // 2])
... |
258c878aa5113f3bc7d8d5315ef8f3aa77ce45b2 | Jackline-cheptanui/python1 | /student.py | 204 | 3.609375 | 4 | class Student:
school="Akirachix"
def __init__(self,name,age):
self.name=name
self.age=age
def speak(self):
return f"Hello class my name is {self.name}"
|
ceddffa64fe6f0cbd78e4c0eddf985d75d835be8 | belnast5/sudoku-solver-frontend | /app/grid.py | 9,133 | 3.703125 | 4 | class Grid(list):
"""
A Wrapper for a list of list of values (1,..,9 or None), representing Sudoku grid.
Provides methods for compact URL-safe encoding of valid and invalid grids.
Tip 1: Use encode_1() / decode_1() methods for valid grids.
Tip 2: Use encode() / decode() as universal... |
e3b0af01b1409bfd29f7a585741fca593e2f5b8b | miguelvelezmj25/sros | /sei/crypto/cypt.py | 2,279 | 4.09375 | 4 | from cryptography.fernet import Fernet
import os
def write_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("key.key", "wb") as key_file:
key_file.write(key)
def load_public_key():
"""
Loads the key from the current directory named `pub... |
9f66acf56bc61378698dab30849b92fd6816ed9d | Knimisha/Python_Basics | /NMK_Common strings function2.py | 285 | 4.1875 | 4 | # lstrip is to remove the leading spaces
# rstrip is to remove the trailing spaces
# strip is to remove the leading and trailing spaces
String1 = " I love my country "
print(len(String1))
print(len(String1.lstrip()))
print(len(String1.rstrip()))
print(len(String1.strip())) |
8b11a23261a6749b1a23ffb47e6845eac94b6cd3 | goodwin64/pyLabs-2013-14 | /1 семестр/lab 5/5lab_09var_Donchenko.py | 397 | 3.53125 | 4 | # 9) Знайти максимальне значення функції
# y=sin(x*х)*x+cos(x), на відрізку [c,d] з кроком 0.001
from math import sin, cos
shag=0.001
c=float(input('c: '))
c1=float(c)
d=float(input('d: '))
max=sin(c**2)*c+cos(c)
while c<=d:
if max<sin(c**2)*c+cos(c):
max=sin(c**2)*c+cos(c)
c+=shag
print ('max(y) fro... |
f1fd7edd1940c200365df6920d7c7edd799974ed | rlads2019/project-sea120424 | /src/vsm_v2.py | 6,865 | 3.5 | 4 | import os
import math
essay_num = 312
beginner_num = 100
native_num = 60
medium_num = 43
professional_num = 109
beginner_len = 6529
medium_len = 11764
professional_len = 39555
native_len = 69943
total_len = beginner_len + medium_len + professional_len + native_len
beginner_dict = {}
native_dict = {}
professional_dic... |
bd9f08746cb4588a99902794b2010e4f95b78855 | sbtries/Class_Polar_Bear | /Code/Reece/python/lab9.py | 2,424 | 3.875 | 4 | # DICTIONARIES #
cards = {
'A': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10,
'J': 10,
'Q': 10,
'K': 10
}
'''while True:
card1 = input('Enter your 1st card: ')
card2 = input('Enter your 2nd card: ')
card3 = input('Enter you... |
790345a576fab24eec46aa511c55afd9a0ab6a9e | jkaria/coding-practice | /python3/Chap-17_GreedyAlgosAndInvariants/17.6-gasup_problem.py | 549 | 4 | 4 | #!/usr/local/bin/python3
def find_ample_city(gallons, distances):
""" gallons: """
MPG = 20
CityAndRemainingGas = collections.namedtuple('CityAndRemainingGas', ('city', 'gas_left'))
tracker = CityAndRemainingGas(0, 0)
gas_left = 0
for i in range(1, len(gallons)):
gas_left += gallons[i ... |
1e8bc356c964566b39fee90303b2802f35ee9261 | roukaour/sudoku | /sudoku.py | 1,755 | 3.765625 | 4 | #!/usr/bin/python
from __future__ import print_function
from board import Sudoku
from strategies import *
from argparse import ArgumentParser
import sys
def solve_board(board, guess, verbose):
"""Solve a single board."""
board = Sudoku(board)
exclude = None if guess else [999]
board.solve(exclude=exclude, verbo... |
0101b92b380ddffa087c861efafa8e4b09d422f3 | gilmana/Gilman_earning | /mortgage_calculator/mortgage_app.py | 1,710 | 3.859375 | 4 | import numpy as np
import pandas as pd
loan_params = []
def create_loan():
"""
Everytime the function is run, the user will be asked to enter paramers
of the loan. The parameters of each loan are appended as a dictionary to
a list containing all the laons of interest.
"""
# enter terms of loan... |
4981aee884cbc2ffa682075accd271551328e57f | deepanjanroy/206reviewsession | /python/todo/sliceme.py | 156 | 3.859375 | 4 | l = [1,2,3,4,5]
def f(x):
# Implement me!
# return 3 elements, starting from the second element (element at index 1)
return x[1:4]
print f(l)
|
f4b6fe0476f53dec1144ccc600408ff7caab46ab | deepika087/CompetitiveProgramming | /LeetCodePractice/32. Longest Valid Parentheses.py | 2,236 | 3.578125 | 4 | class Solution(object):
#such that ()()() will return 6 and ()(()) will return 6
def longestValidParentheses(self, arr):
#tutorial : https://leetcode.com/problems/longest-valid-parentheses/solution/
stack = []
max_len = 0
for i in range(len(arr)):
if arr[i] == '(':
... |
3108e4211a75e8cdd5c33bdfda07c15b08e15a30 | Djenzenpan/Datavisualisatie | /Homework/Week_1/moviescraper.py | 5,242 | 3.78125 | 4 | #!/usr/bin/env python
# Name: Jesse Pannekeet
# Student number: 10151494
"""
This script scrapes IMDB and outputs a CSV file with highest rated movies.
"""
import csv
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
TARGET_URL = "ht... |
dfc0a27b435d242d61789ca5693ccb1a7b3b28eb | dev2404/Python_Strings | /longest_palindrome.py | 262 | 3.90625 | 4 | def longest_palindrome(string):
m=""
for i in range(len(string)):
for j in range(len(string)-1,i, -1):
if len(m) >= j-i:
break
elif string[i:j] == string[i:j][::-1]:
m = string[i:j]
break
return m
print(longest_palindrome("cbbddd"))
|
f90c3417ee264062b3c5c64066d71ab66abc9cf8 | wenchi53/LeetCode | /Python/26_removeDuplicates.py | 356 | 3.609375 | 4 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
result = 0
for i in xrange(1,len(nums)):
if nums[result] != nums[i]:
result += 1
nums[result] = nums[i]
return result+1
mySolution = Solution()
print mySolu... |
c0cc0a984151b5ebfc9e9a9c53957ef0ebf61814 | grey-area/advent-of-code-2017 | /day19/parts1_and_2.py | 791 | 3.59375 | 4 | with open('input') as f:
data = f.read().splitlines()
# Initial position
x = data[0].index('|')
y = 0
# Initial velocity
dx = 0
dy = 1
letters_seen = ''
steps = 0
while data[y][x] != ' ':
# Step forwards
x += dx
y += dy
steps += 1
# If we see a letter, add it to the sequence seen
if dat... |
e85eb58c0ca0149e27a334e5fb0e3a745c316b0c | congthanh97/root | /Python/New folder (2)/bai3.py | 572 | 3.75 | 4 | array = [1,4,2,5,7,9,2,3]
array.sort()
num1 = int(input("input num1: "))
print("day so nho hon ",num1)
for i in range(0,len(array)):
if array[i] < num1:
print("number %d "%array[i])
else:
break
a = list()
for i in range(0,len(array)):
if array[i] < num1:
a.append(array[i])
else:... |
ff9bc4c029ec053412e6ec1bc24ed5d8ed5b2494 | Einstellung/AlgorithmByPython | /BinarySearch.py | 478 | 3.96875 | 4 | # 实现一个二分查找
# 输入:一个顺序list
# 输出: 待查找的元素的位置
def binarySearch(alist, item):
first = 0
last = len(alist) - 1
while first <= last:
mid = (first + last)//2
print(mid)
if alist[mid] > item:
last = mid - 1
elif alist[mid] < item:
first = mid + 1
else:
... |
40413d7298bc481abada5db93117edcef23aaa78 | humbertoperdomo/practices | /python/PythonCrashCourse/PartI/Chapter04/cubes_comprehension.py | 102 | 3.578125 | 4 | #!/usr/bin/python3
cubes = [value**3 for value in range(1, 11)]
for value in cubes:
print(value)
|
d67c6a3284ebe5728f05d2c677fe11b5f3b341b1 | kris71990/China_info | /china.py | 13,795 | 3.5625 | 4 | # This program stores information related to regions and cities in China in dicts and lists
# Through user interaction, it then presents the desired information
import webbrowser, requests, bs4
from num2words import num2words
import chinadicts
def start():
print(u'\n\u4f60\u597d, let\'s learn about China!')
start_... |
d4afee956c3992976c71bbe839a9410c5145bdab | Brooks-Willis/softdes | /chap04/polygon.py | 1,483 | 4.3125 | 4 | """Created as a solution to an excersize in
thinkpython by Allen Downey
Written by Brooks Willis
Creates a polygon with any number of sides of any length
or an arc of set set radius and sweep angle
"""
from swampy.TurtleWorld import *
from math import pi
world = TurtleWorld()
bob = Turtle()
bob.delay = 0.01
def l... |
f1e71a78120bdddcd2d9510ea42b6b5c554484d7 | haodonghui/python | /learning/py3/基本数据类型/Number(数字)/isinstance 和 type 的区别.py | 781 | 4.21875 | 4 | """
查询变量所指的对象类型
内置的 type() 函数可以用来查询变量所指的对象类型。
此外还可以用 isinstance 来判断
isinstance 和 type 的区别在于:
type()不会认为子类是一种父类类型。
isinstance()会认为子类是一种父类类型。
"""
print('======type')
# type()
a, b, c, d = 20, 5.5, True, 4 + 3j
print(type(a), type(b), type(c), type(d)) # <class 'int'> <class 'float'> <class... |
0e7f4ab012d7043608dbe98b4ffcb0e2cd9a806d | nykh2010/python_note | /02pythonBase/day03/res/if3.py | 395 | 3.765625 | 4 | #1、输入一个整数,用程序判断数据是奇数还是偶数,并打印输出?
#2、输入一个整数,用程序判断数据是正数还是负数,并打印输出?
# a = input("输入整数")
# b = int(a)
b = int(input("输入整数"))
# if b%2 == 0:
# print("偶数")
# else:
# print("奇数")
if b%2 != 0:
print("奇数")
else:
print("偶数")
print("end")
|
e51236325c41793ca0eacf5a0dee0065da12d915 | yeboahd24/python202 | /python_etc_4/filtering.py | 732 | 4.125 | 4 | #!usr/bin/env/python3
# Sometimes, the filtering criteria cannot be easily expressed in a list comprehension or
# generator expression. For example, suppose that the filtering process involves exception
# handling or some other complicated detail. For this, put the filtering code into its own
# function and use... |
7e97fcd60de55b89a1725cfaa5b4cdf4b7d20c9c | maw3193/aoc-2016 | /12/12-1.py | 2,574 | 3.640625 | 4 | #!/usr/bin/python
import argparse, sys, re
parser = argparse.ArgumentParser(description="Program to solve Advent of Code for 2016-12-12")
parser.add_argument("--input", default="input.txt")
args = parser.parse_args()
# 4 registers, a, b, c, d
# instruction cpy x y (copies value of x into y)
# instruction inc x (incr... |
5312d89ce46b6bd7b7c0e481e3c2836638bb050e | MarlonMa/recreation | /drinker.py | 1,516 | 3.90625 | 4 | #!/usr/bin/env python
"""Program to calculate how many bottles of wine the drinkers with specified amount of money can drink.
==========
Conditions:
1 bottle of wine is worth 2 yuan
2 bottles can exchange for 1 bottle of wine
4 caps can exchange for 1 bottle of wine
==========
"""
class Drinker:
def __init__(sel... |
f2bb53923db08fb7ee8919ada7dde17d9ade7415 | ctlewitt/PracticeProblems | /guessing_game.py | 756 | 4.21875 | 4 | # have the computer think of an integer between 1 and 100
# have a human guess the number responding "higher" or "lower" for incorrect guesses
# bonus points: keep a high-score table with names that persists between runs
import random
MIN_NUM = 1
MAX_NUM = 100
def guessing_game():
number = random.randint(MIN_NUM... |
0d0c0f8ae10d85b9fb08eeddb9dda074c0c74a8b | Zahidsqldba07/coding-problems-2 | /dynamic-programming/Andrey-Grehov/0015_top_down_bottom_up.py | 2,140 | 3.953125 | 4 | import unittest
from collections import Counter
# recursive
def fib(n):
if n == 0: return 0
if n <= 2: return 1
return fib(n-1) + fib(n-2)
# top down -> recursion + memoization
def fib_top_down(n):
memo = Counter()
return fib_top_down_helper(n, memo)
def fib_top_down_helper(n, memo):
if n ==... |
e91e78cdabc9de8377bbb42bc830e0f299041659 | hofertg/web-caesar | /caesar.py | 619 | 3.71875 | 4 | # Copied functions from previous Caesar project
#from Caesar
def encrypt(text, rot):
encrypted = ""
for letter in text:
encrypted += rotate_character(letter, rot)
return encrypted
#from helpers
def alphabet_position(letter):
letter = letter.upper()
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ".inde... |
37216445dab351f20c4557a1c33a2fbad9d27806 | Allen-ITD-2313/hello-world | /math.py | 223 | 3.890625 | 4 | def main():
iteration = int(input("Please enter a value for iterations:"))
total=0
for i in range(1,iteration):
total += (-1)**(i+1)*((1.0/(i+i+1)))
pi = 4*(1-total)
print(pi)
main()
|
357a704ac00196e34622b5ec2496177a794f7d8c | jeagle1286/Hort503 | /Assignment04/ex18.py | 638 | 4.09375 | 4 | # this one is like your scripts with argv
def print_two(*args):
arg1, arg2, = args
print(f"arg1: {arg1}, arg2: {arg2}")
# DO not start a function name with a number
#ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
# Args is like... |
81c932fefd0c379496e677fe298118c30f54e159 | zx-joe/Computational-Motor-Control-for-Salamandar-Robot | /Lab0/Python/10_Classes.py | 3,250 | 4.78125 | 5 | #!/usr/bin/env python3
"""This script introduces you to the usage of classes in Python. """
import farms_pylog as pylog
#: Creating a new class
class Animal:
"""New class for animal class.
"""
def __init__(self, name):
"""Initialization function with one input to set the name of
the an... |
606de12ff3f057c9005bb4f90520bf43708d325c | dennisnderitu254/HackerRank-3 | /Python/numpy/dot-and-cross.py | 215 | 3.609375 | 4 | #!/usr/local/bin/python3
import numpy
n = int(input())
array1 = numpy.array([input().split() for _ in range(n)], int)
array2 = numpy.array([input().split() for _ in range(n)], int)
print(numpy.dot(array1, array2))
|
bd9906a85365d75bb5d58693320ee23978610ae4 | hehuanshu96/PythonWork | /dailycoding/TextStatistics/StatisticsTLBB.py | 2,433 | 3.71875 | 4 | # coding=utf-8
"""
统计天龙八部.txt里的一些文本信息
"""
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像的负号'-'显示为方块的问题
def read_characters(characters_path, txt_format='utf-8'):
"""
将角色.txt中的所有人物... |
4c36846aaeb90116acaf58d6be5b99f1c8b391dc | ncturoger/CodilityPractice | /Lesson3/task3_FrogJmp.py | 166 | 3.578125 | 4 | import math
def solution(X, Y, D):
step = 0
if X <= Y:
dist = Y - X
step = math.ceil(dist / D)
return int(step)
print(solution(1, 5, 2))
|
6b1d2e12c2968bea558cc354e14a4ed79917d664 | HanKKK1515/PycharmProjects | /while.py | 1,083 | 3.65625 | 4 | '''
count = 1
while count <=30:
print("你是大傻子吗")
print("嗯是啊撒")
count = count + 1
while True:
s = input("请开始喷:")
if s == 'q':
break
if "马化腾" in s:
print("输入非法")
continue
print("喷的内容是:" + s)
count = 1
sum = 0
while count <= 100:
print(count)
sum = sum + coun... |
e0c97cf96a0458dca21705648307a6a0f75a75ff | xzela/code-samples | /python/file_checks.py | 4,598 | 3.640625 | 4 | '''
Attempts to test a file for specific
attributes
'''
import os
import re
from PIL import Image
def detect_special_characters(file_name):
'''
Attempts to detect whether a filename contains
special characters. Special characters are bad
We only accept the following characters:
... |
568816f69911834abc77af5a84e9ac53a7ee4c25 | koking0/Algorithm | /LeetCode/Problems/990. Satisfiability of Equality Equations/990. Satisfiability of Equality Equations.py | 1,221 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-H -*-
# @Time : 2020/6/H 7:34
# @File : 990. Satisfiability of Equality Equations.py
# ----------------------------------------------
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
# >>> Author : Alex 007
# >>> QQ : 2426671397
# >>> Mail : alex18812649207@gmail.com
# >>> Github : htt... |
e03dcbc33be5ae6d3dfbc0eb482c7b83f3b0bafe | Raquelcuartero/phyton | /texto_aleatorio.py | 251 | 3.625 | 4 | def texto_aleatorio():
texto=raw_input("Dime cualquier cosa")
todo="a"or"e"or"i"or"o"or"u"
for cont in range(0,len(texto),1):
if texto[cont]==todo:
print texto
texto_aleatorio()
|
b3bd5dc39596b904cda049d055bd8b3770f01fcf | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/codeabbey/codeabbeyPrograms-master/division_of_two_numbers_with_round_off.py | 715 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 26 21:40:05 2016
@author: rajan
Problem 6
This problem rounds off the number when divided by another number.
"""
print('Enter the numbers you want to divide. Dividend and divisor separated by space.')
num = input()
num_array = num.split()
l = len(num_array)
final_array ... |
c9530acac16566b004f47a3317b385fcee257737 | antoniolj07/IPC2-Practica1 | /components/ReadCSVFiles.py | 3,062 | 3.671875 | 4 | class Read:
candidates = []
def __init__(self):
self.read_file()
def read_file(self):
path = input('Please enter the path of the CSV file \n')
rows = []
try:
with open(path, 'r') as f:
lines = f.readlines()
for line in lines:
... |
9ca627f50673cf748bfd3c897ca19fe6afd47baf | faithmyself92129/hellow100day | /D13/asyncio1.py | 564 | 3.75 | 4 | """异步I/O 操作-asyncio模块"""
import asyncio
import threading
async def hello():
print('%s:hello,world!' % threading.current_thread())
#休眠不会堵塞主线程因为使用异步I/o操作
#注意有yield from才会等待休眠操作执行完成
await asyncio.sleep(2)
print('%s: goodbye, world!' % threading.current_thread())
loop = asyncio.get_ev... |
f3a0a1c9d79b91ac4871a504e3a58549ffeda59a | L200170180/Prak_ASD_E | /Modul-8/4_queue.py | 611 | 3.8125 | 4 | class Queue(object):
def __init__(self):
self.qlist = []
def isEmpty(self):
return len(self)==0
def __len__(self):
return len(self.qlist)
def enqueue(self,data):
self.qlist.append(data)
def dequeue(self):
assert not self.isEmpty()
return sel... |
ac885fef4d28db790ab4ed5c6dec9f932b91db71 | renjieliu/leetcode | /1001_1499/1315.py | 1,239 | 3.671875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
def dfs(node, output):
curr = 0
if node.left != None:
... |
43eb7c6e5dc6cfda2631c7db80fd1eba6f39bfa7 | mariomanalu/shidoku_groebner | /test_shidoku.py | 2,994 | 3.71875 | 4 | import shidoku as S
# This program solves a 4x4 version of the famous Sudoku puzzle called Shidoku using the Gröbner bases
# How to use:
# 1. Store any "solvable" Shidoku board as a 1D array of length 16 with 0 representing the empty cells
# 2. Call solve_shidoku()
# 3. Print the answer in the form of 2D array
# We i... |
d93f75ca496622e5ce8d827faec674876770f448 | eliasingea/interview-prep | /buildTree.py | 930 | 3.71875 | 4 | from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(preorder, inorder):
preorder = deque(preorder)
inorder_map = {}
for i, order in enumerate(inorder):
in... |
2a5a39774a964880a2ecf5b145f6a84aee2d541c | kristinadziuba-zz/python | /lesson_1_task_1.py | 708 | 4.15625 | 4 |
time = int(input('Duration: '))
second = time % 60
print('duration in seconds = ', second, "sec")
time = int(input('Duration: '))
second = time % 60
minutes = (time % 3600) // 60
print("duration in minutes and seconds = ", minutes, "min", second, "sec")
time = int(input('Duration: '))
second = time % 60
hour = (time... |
320e9639a3cbe75cfc4836697f550f654e156fcd | Lansefanggezi/Reptile | /python/program1.py | 186 | 3.515625 | 4 |
# zongshushi"+count
count = 0
for a in range(1,5):
for b in range(1,5):
for c in range(1,5):
for d in range(1,5):
print d + c *10 +b *100 + a*1000
count +=1
print (count)
|
ee883ba6f2d13676566a78482dd844d81d706375 | dailycodemode/dailyprogrammer | /Python/066_comparingRomanNumerals.py | 1,797 | 4.09375 | 4 | # DAILY CODE MODE
# def is_X_bigger_than_Y(x,y):
# l = len(max([x,y], key=len))
# for ind in range(l):
# if ord(x[ind]) == ord(y[ind]):
# pass
# elif ord(x[ind]) >= ord(y[ind]):
# return True
# elif ord(x[ind]) <= ord(y[ind]):
# return False
#
#
#
# An... |
d373f925e23e7fa8493152ccd12fca876baaa6c6 | GreenVengeance/Matplotlib | /test_matplotlib_Ue6A3.py | 847 | 3.671875 | 4 | import unittest
import Matplotlib_Ue6A3 as mat
"""Created by Bilal"""
class TestMatplotlibUe6A3(unittest.TestCase):
def test_create_plotF(self):
""" F=x """
plt = mat.create_plot('x+2', min_range=0, max_range=4)
self.assertEqual(plt[0], 2) # x=0 --> y=2
self.assertEqual(plt[1], 3) # x=1 --> y=3
... |
08f062bd6d8484c42c402b9484bdfe90be5711bd | RyanHiltyAllegheny/blockchain-19 | /src/print_content.py | 2,540 | 3.5625 | 4 | """Prints tables and other program content."""
from prettytable import PrettyTable
class color:
"""Defines different colors and text formatting settings to be used for CML output printing."""
PURPLE = "\033[95m"
CYAN = "\033[96m"
DARKCYAN = "\033[36m"
BLUE = "\033[94m"
GREEN = "\033[92m"
... |
5cfd68769569e0cf54f5aebc03dee2d45629249d | younheeJang/pythonPractice | /algorithm/fromPythonTutorials/Linear_Search.py | 286 | 3.65625 | 4 | def linear_search(list, value):
index = 0
for index in range(len(list)):
if list[index] == value:
return index
else:
index += 1
return None
l = [64, 34, 25, 12, 22, 11, 90]
print(linear_search(l, 12))
print(linear_search(l, 90)) |
25d2f53f6c83ffe70f515338b78c12dd5d096f09 | gohar67/IntroToPython | /Practice/lecture4/practice7.py | 166 | 3.765625 | 4 | for num in range(1,21):
print(num)
if num % 5 == 0 and num % 3 ==0:
break
x = 0
while x <21:
x +=1
print(x)
if x % 15 ==0:
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.