blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
13e4ecc1ae667399a763f8e3a28014d38b1f0639 | daniel-reich/ubiquitous-fiesta | /Xkc2iAjwCap2z9N5D_12.py | 137 | 3.53125 | 4 |
from datetime import date
def has_friday_13(month, year):
if date(year, month, 13).isoweekday() == 5:
return True
return False
|
d7b5630b85f8236689606279ab151628bc8d9a17 | ClareVGitHub/LearningTools | /wortschatz_2.2.py | 4,272 | 3.65625 | 4 | # wortschatz is a learning aid for learning german as a foreign language. You can choose to add words and thier translation
# to a sqlite database using sqlalchemy or you can choose the play mode which will cyce through your words to help you
# memorize them.
# Open in the terminal with >>> python3 wortschatz_2.2.py... |
093b73ba2ff2b0242193509732eaee7179e9a318 | zavadsk20/GospAvtoBot | /KPZAV/test.py | 596 | 3.625 | 4 | import codecs
#дозволяє обробляти кириличні символи
def NewLetter(let):
lett = {
'Е' : 'E',
'І' : 'I',
'О' : 'O',
'Р' : 'P',
'А' : 'A',
'Н' : 'H',
'К' : 'K',
'Х' : 'X',
'С' : 'C',
'В'... |
135bf2213cec4d618b51185a7a3d0b5ef9a03133 | KhauTu/C4E15---Khau-Tu | /Fundamentals/session02/for_example.py | 143 | 4.21875 | 4 | # for _ in range(2, 8, 3):
# print("Hi")
# print("Bye")
# for i in range(2, 8, 3):
# print("Hi")
x = 7
for i in range(x):
print(i)
|
034444d34f62a966482898e0571899c5677ca1f6 | SticketInya/fcc_12_beginner_python_projects | /project_nbr_guesser/main.py | 889 | 4.125 | 4 | from random import randint
def Guesser(max_nbr):
nbr = randint(1, max_nbr)
guess = 0
while guess != nbr:
guess= int(input(f"Guess a number between 1 and {max_nbr} : "))
if guess<nbr:
print(f"{guess} is too low.")
elif guess>nbr:
print(f"{guess} is too high."... |
4e0ce6237e44a95639a509f338f026a6e8735e92 | stgleb/problems | /python/linked_list/k_element_from_tail.py | 552 | 3.796875 | 4 | """
Find element on k-th position from list tail
"""
from python.linked_list import Node
def kth_element(head, k):
first = head
second = head
cnt = 0
while first is not None and cnt < k:
first = first.next
cnt += 1
while first is not None:
first = first.next
secon... |
cbeb6412c56e10b5e60b2f8b0e23bf79e4599b01 | daher7/Python_Pildoras | /11_try_except_2.py | 361 | 4.0625 | 4 | def divide():
try:
op1 = (float(input("Introduce un numero: ")))
op2 = (float(input("Introduce otro numero: ")))
print("La division es {}".format(op1/op2))
except ZeroDivisionError:
print("Ha ocurrido un error. No se puede dividir entre 0")
finally:
... |
63365f512db4dd4f6f9ec941e37184891e437e96 | alvinyeats/DesignPatterns | /Iterator/main.py | 409 | 3.671875 | 4 |
from book_shelf import BookShelf
from book import Book
def main():
book_shelf = BookShelf()
book_shelf.append_book(Book('21天精通Java'))
book_shelf.append_book(Book('21天精通C++'))
book_shelf.append_book(Book('21天精通PHP'))
book_shelf.append_book(Book('21天精通Python'))
for book in book_shelf:
... |
69746b1102c7144ae9368add912d4ba80eb8c582 | asadiqbalkhan/shinanigan | /syntax practice/writingfiles.py | 974 | 4.46875 | 4 | # List of commands
# close -- Closes the file.
# read -- Reads the contents in your file
# readline -- Reads just one line of a text file
# trancate -- Empties the file. Watch out if you care about a file
# write('stuff') -- Writes "stuffs" to the file
# Lets use some of this to make a simple little text editor
fr... |
6d69b679b04a8cabe807510a03ccf7ca20875035 | yuhsh24/PythonMultiprocess | /lock.py | 928 | 3.984375 | 4 | # -*- coding:utf-8 -*-
# RLock and Lock
import threading
from time import sleep
class Counter:
def __init__(self):
self.__count = 0
self.__lock = threading.RLock()
#self.__lock = threads.Lock() # Lock()不能在一个线程中被多次acquire,否则会进入死锁
def Increase(self, threadNum):
self.__lock.acq... |
239bdbed20d44cf8abc0301178c9630b113f8d0c | alexreyes/LeetCode | /520.Detect Capital.py | 461 | 3.59375 | 4 | class Solution:
def detectCapitalUse(self, word):
splitWord = list(word)
upperCount = 0
lowerCount = 0
for x in splitWord:
if x.isupper():
upperCount +=1
else:
lowerCount += 1
if (upperCount == len(word)):
return True
elif lowerCount == len(word):
return True
elif splitWord[0]... |
5609504999847d39ffcb04dac76189950d0c2297 | kirigaikabuto/distancelesson2 | /lesson10/5.py | 177 | 3.75 | 4 | s="1 2 3 4 5 6 7 8 9"
words=s.split()
numbers=[]
for i in words:
num = int(i)
numbers.append(num)
print(numbers)
sumi=0
for i in numbers:
sumi = sumi + i
print(sumi) |
0239dcb9dacad51ffb7453395ad3c185d04cab8c | PriyankaKhire/ProgrammingPracticePython | /Verifying an Alien Dictionary.py | 1,145 | 3.84375 | 4 | # https://leetcode.com/problems/verifying-an-alien-dictionary/
class Solution(object):
def __init__(self):
self.orderHash = {}
def putOrderInHash(self, order):
for i in range(len(order)):
self.orderHash[order[i]] = i
def compareWords(self, w1, w2):
i = 0
... |
a0f388c0b5ef8de62166c3523d858abfb7a2898a | nicolasfcpazos/Python-Basic-Exercises | /Aula15_Ex066.py | 488 | 3.765625 | 4 | # Crie um programa que leia vários números inteiros pelo teclado.
# O programa só vai parar quando o usuário digitar o valor 999, que é
# a condição de parada. No final, mostre quantos números foram digitados
# e qual foi a soma entre eles. (desconsiderando o flag, 999).
n = s = 0
d = 0
while True:
n = int(input(... |
1fd32dc39ba5daa5552b610ec98e56b30b40936a | bhayer96/Configuration-Scrubber-An-Automation-Tool | /Hide.py | 4,373 | 3.59375 | 4 | # User interactive program that hides sensitive material in a configuration.
class Hide:
def __init__(self): # Constructor
valid = 0
while valid == 0: # Keep asking for a file name until an existing config is entered
try:
self.filename = self.fileName() # Gets the name for the config that needs to
... |
a2d0d6d80c05947bd69a5edd389a86a8ac16626f | n20084753/Guvi-Problems | /beginer/set-6/53-sum-digits.py | 81 | 3.625 | 4 | n = int(raw_input())
sum = 0
while n > 0:
sum += n % 10
n = n / 10
print(sum) |
1c0282cbe2d13b2f1c38755b7606f68871d943b5 | matrix-revolution/algorithms | /addDigits.py | 502 | 3.796875 | 4 | class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
sum_v = 0
sum_v += num % 10
num /= 10
while num > 0:
sum_v += num % 10
num /= 10
if num <= 0 and sum_v > 9:
num = s... |
0b7725048f485a4c3afa4565568633ad1e96ca65 | rafaelperazzo/programacao-web | /moodledata/vpl_data/139/usersdata/159/61423/submittedfiles/diagonaldominante.py | 439 | 3.703125 | 4 | # -*- coding: utf-8 -*-
import numpy as np
def soma(a):
b=[]
for i in range (0,a.shape[0],1):
soma=0
for j in range (0,a.shape[1],1):
if i!=j:
soma=soma+a[i,j]
b.append(soma)
return (b)
n=int(input('Tamanho da matriz:'))
a=np.zeros((n,n))
for i in ra... |
16b8b6fa104b1e0bb92580d504752ce07070295b | chanyoonzhu/leetcode-python | /1650-Lowest_Common_Ancestor_of_a_Binary_Tree_III.py | 1,017 | 3.84375 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
"""
"""
- hashset
- O(h), O(h), h = n in worst case
"""
class Solution:
def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
... |
7d173bda4453e1a124eca2beec5d05cf21380a2e | mkhoeini/random_problems | /python2.7/prob2.py | 601 | 3.546875 | 4 |
def palindrom(s):
a, b = 0, len(s)-1
while a < b:
if s[a] == s[b]:
a += 1
b -= 1
else:
return False
return True
def find(s, b, e):
result = s[b:e]
while e < len(s):
b += 1
e += 1
if palindrom(s[b:e]):
while ... |
afa8e6cbadefbf36eb15a9ea0f988ad211d2721d | xiluhua/python-demo | /demo/demo11_list_03切片.py | 865 | 4.125 | 4 | '''
@author: xilh
@since: 20200125
'''
list1 = ['physics', 'chemistry', 1997, 2000, 1, 2, 3, 4]
print("== 列表切片 ==")
print("list1 :", list1)
list2 = list1[0:3]
print("list2-1:", list2)
list2 = list1[0:2]
print("list2-2:", list2)
list2 = list1[1:3]
print("list2-3:", list2)
list2 = list1[:3] # 和... |
8c1cfa91f4f99b72f62f8b8c07a3ac2791574d54 | e1630m/green-hub | /green.py | 4,968 | 3.765625 | 4 | from alphanumeric import *
import random
import subprocess
def num_days(year, month=13):
'''
Returns number of days in given year (optionally, given year and month)
Args:
year (int): year in Gregorian calendar
month (int): (optional) month
'''
modifier = year % 4 ... |
3d0dd1c21f47c3aaecf00f38f422ed1e5726dd30 | GalickayaAleksandra/hillel_hometask5 | /task(5).py | 815 | 3.9375 | 4 | def my_file():
f_path = 'C:/Users/Александра/Desktop/homework6/file2'
out_path = 'C:/Users/Александра/Desktop/homework6/shifr_file'
open_file = open(f_path)
file_read = open_file.read()
my_date = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
key = int(input("Please, enter your key... |
427cbe1ca1cd0eba1e9e045ea03a761d1d4155c8 | rokib7/pythoncrashcourse | /chapter_08/great.py | 383 | 3.75 | 4 | def show_magicians(magicians):
for magician in magicians:
print(magician.title())
def make_great(magicians):
new_list = []
for magician in magicians:
new_list.append(magician.title() + " the Great")
return new_list
magicians = ['merlin','gandalf','voldemort']
new_list = make_great(mag... |
9e3bece0699928e54d8b97a092391d9bec2d2376 | wang264/JiuZhangLintcode | /Algorithm/L2/optional/71_binary-tree-zigzag-level-order-traversal.py | 1,604 | 4.0625 | 4 | # 71. Binary Tree Zigzag Level Order Traversal
# 中文English
# Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right,
# then right to left for the next level and alternate between).
#
# Example
# Example 1:
#
# Input:{1,2,3}
# Output:[[1],[3,2]]
# Explanation:
# 1
... |
a02a8a74d4a739a4f098cdb8e445843beb4bdea1 | BeniaminK/hackerrank_project_euler | /Max/21-30/_22_names_scores.py | 1,084 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
def get_name_score(name):
score = 0
for elem in name:
score += ord(elem) - 64
return score
def solve(name, name_list):
score = get_name_score(name)
# print "Score: %d" % (score)
import bisect
idx = bisect.bisect_left(name_... |
849a2a8005b34cc3ad63f079c9a30d7c7c6528ef | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/odtjoh001/question1.py | 1,068 | 3.84375 | 4 | """Python program to analyse student marks read in from a file and determine which students need to see a student advisor.
John Odetokun
11 May 2014"""
import math
filename= input("Enter the marks filename:\n")
f = open( filename, "r")
list = []
for line in f:
list.append(line)
f.close()
nlist = [... |
47f7a499c705405822c50fa86959851d63c5f42d | Gbolly007/AdvancedPython | /Assignment6/As6_Number5.py | 4,243 | 3.765625 | 4 | # Python version 3.8
import sympy as sym
from fractions import Fraction
# list for storing results of operations
lis = []
# variables to store symbolic computation
a = sym.Symbol('a')
b = sym.Symbol('b')
c = sym.Symbol('c')
d = sym.Symbol('d')
e = sym.Symbol('e')
f = sym.Symbol('f')
g = sym.Symbol('g')
h = sym.Symbol('... |
ebf677c433a29be7f7dc78605a2480618c75e246 | timmyshen/LearnPython | /euler-mike/1.py | 137 | 3.90625 | 4 | #!/usr/bin/env python3
# MZ
# 233168
sum = 0
for x in range(1, 1000):
if x % 3 == 0 or x % 5 == 0:
sum = sum + x
print(sum)
|
7d8bd5b8a3d7d4c02fc5e9216ba89ed3fd591b91 | VineetPrasadVerma/GeeksForGeeks | /SudoPlacementCourse/BinarySearch.py | 427 | 3.671875 | 4 | def bin_search(arr, left, high, key):
flag = 0
left = 0
high = len(arr)-1
while left <= high:
mid = int((left + high) / 2)
if arr[mid] == key:
flag = 1
return mid
break
elif arr[mid] > key:
high = mid - 1
else:
l... |
d7ebb612f997020cb2f5b39aabd94748c8c51649 | Luucx7/POO-P4 | /3209.py | 1,059 | 3.734375 | 4 | # -*- coding: utf-8 -*-
casos = int(input()) # Recebe a quantia de casos de teste
for i in range(casos): # Executa o programa na quantia de vezes especificada
entrada = list(map(int, input().split())) # Recebe uma linha de entrada, separa os valores, transforma em inteiro e transforma em lista
soma = 0 # V... |
26da94d4a58cc8c912faf1465767c66db07986ed | gauthamej/Gautham | /checkint.py | 193 | 3.6875 | 4 | user_input = input()
try:
if "." in user_input :
val = float(user_input)
print("yes")
else:
val = int(user_input)
print("yes")
except ValueError:
print("No")
|
b011f79b1dd8cd37658c34efd2bcce252b910374 | tophatraptor/avogadro-format | /avogadro.py | 1,817 | 3.5625 | 4 | import sys
import os
import argparse
#Ordinal code from user 'Winston Ewert' on stackexchange
SUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'}
def ordinal(num):
# I'm checking for 10-20 because those are the digits that
# don't follow the normal counting scheme.
if 10 <= num % 100 <= 20:
suffix = 'th'
els... |
e8ebe4106f25138b6a82edb6e2b689f6f814b810 | nguyenquangnhat1208/NguyenQuangNhat-fundamental-c4e27 | /Fundamentals/Session05/Homework/ex78.py | 395 | 4.25 | 4 | def remove_dollar_sign (s):
s_remove = s.replace("$","")
return s_remove
n = input("nhap vao ky tu : ")
print("chuoi sau khi bo ky tu :",remove_dollar_sign(n))
string_with_no_dollars = remove_dollar_sign("$80% percent of $life is to show $up")
if string_with_no_dollars == "80% percent of life is to show up":
... |
813805f6b8749b5b7f92f14c27275347e7e51a65 | Jyoshna9346/Become-Code-Python | /recursions basics.py | 1,051 | 3.640625 | 4 |
'''
def fun(n):
if n<=1:
return n
return fun(n-1)+fun(n-2)
n=int(input())
print(fun(n)) #fun(n)//5
'''
'''
def fun(n):
if n<=1:
return
print(n)
fun(n-1)
fun(n-2)
n=int(input())
fun(n)
input = 5
5
4
3
2
2
3
2
'''
'''
def fun(n):
if n<=1:
... |
ede3267830ccafcd3a73939155ecc0a8f774d27d | CircularWorld/Python_exercise | /month_01/teacher/day16/demo03.py | 971 | 3.84375 | 4 | """
迭代器
让自定义对象参与for循环
迭代自定义对象
练习:exercise02,03
"""
class SkillIterator:
def __init__(self, data):
self.data = data
self.index = -1
def __next__(self):
self.index += 1
if self.index < len(self.data):
return self.data[self.index]
else:
... |
1ebd447ee36364fd4aa4d8e52feac65d2bc9efc9 | radomirbrkovic/algorithms | /dynamic-programming/exercises/maximum-path-sum-triangle.py | 446 | 3.515625 | 4 | # Maximum path sum in a triangle. https://www.geeksforgeeks.org/maximum-path-sum-triangle/
N = 3
def maxPathSum(tri, m, n):
for i in range(m - 1, -1, -1):
for j in range(i+1):
if tri[i +1] [j] > tri[i+1][j +1]:
tri[i][j] += tri[i+1][j]
else:
tri[i][j... |
94d85afd1650593013fed37ba59cedfc813a2c89 | faf4r/pynput | /连点器v1.py | 1,348 | 3.5625 | 4 | from pynput import mouse
from pynput.mouse import Button, Controller
import time
def listen():
def on_move(x, y):
print('Pointer moved to {0}'.format(
(x, y)))
def on_click(x, y, button, pressed):
print('{0} at {1}'.format(
'Pressed' if pressed else 'Releas... |
99a9b9c7187e1698d6ded73de850f8a22fb09206 | tofuadmiral/leetcodermans | /findduplicate.py | 633 | 3.6875 | 4 | class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
"""
look for duplicates,
at least one duplicate, find it
constant extra space
can't modify the array
runtime should be less than n squared... |
2080483b6560a32ff7e0c920026364483da32b20 | basiliomp/intro_to_python | /Intro_to_Python2019-10-07.py | 796 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Seventh session
Created on Mon Oct 7 19:33:20 2019
@author: Basilio
"""
###################
# Mathematical sets
###################
# A set is a collection of unique objects
s = set()
print(len(s))
# Adding the first element into the set 's'
s.add('b')
print(len(s))
print(s)
# Sets do n... |
b45f505c99ceb493467602b4b379dcd37f1acbf9 | OrianaLombardi/Python- | /fundamentos/ejercicio-if.py | 388 | 4.09375 | 4 | mes=int(input("Ingrese un numero de mes(1-12): "))
estacion: None
if mes==1 or mes==2 or mes==12:
estacion="Invierno"
elif mes==3 or mes==4 or mes==5:
estacion="Primavera"
elif mes==6 or mes==7 or mes==8:
estacion="Verano"
elif mes==9 or mes==10 or mes==11:
estacion="Otoño"
else:
estacion="Mes inc... |
6cdabf4b24903aee31e0a37f83d729945a68b803 | AkshayMirashe/Codinjas | /Conditionals & Loops/Assignment_SumOfEven&Odd.py | 494 | 4.125 | 4 | '''
Write a program to input an integer N and print the sum of all its even digits and sum of all its odd digits separately.
Digits mean numbers, not the places! That is, if the given integer is "13245", even digits are 2 & 4 and odd digits are 1, 3 & 5.
'''
n = int(input())
evenSum = 0
oddSum = 0
while n !=... |
6842ce63f7ca84e85cd5b7ac3e94212a7ea534af | maykim51/ctci-alg-ds | /mybst.py | 1,492 | 4.0625 | 4 | '''
CTCTI 4.2. Minimal Tree:
Given a sorted (increasing order) array with unique integer elements,
write an algorithm to create a binary search tree with minimal height.
'''
'''
Minimal heights = 꽉채워서?
BST Soltuion: 루트의 상황으로 생각!!! 무조건!! sub tree개념으로.
'''
class Node():
def __init__(self, data):
... |
e5d80ea2a252927d9753d86179fd105c6899236f | mengyx-work/CS_algorithm_scripts | /leetcode/LC_318_maximum_word_length_product.py | 1,709 | 3.78125 | 4 | '''
1. use bit to indicate whether a letter exists
2. sor the word list by word length, so the maximum computation O(n^2)
a.
ASCII value for character:
convert ASCII value into character
ord('a') ## 97
chr(97) ## 'a'
convert character into ASCII value
ord('z') ## 122.
b.
convert string to list
list('abc') ## ['a',... |
b5bcbbeb743fa2df495e303dc70e10e37647fc64 | MJC598/Personal-Projects | /MachineLearning/naive_bayes.py | 659 | 3.5 | 4 | #prepping for Machine Learning class by following along with code from Intro to Machine Learning on Udacity
#just creating so simple datasets since its Naive Bayes
import numpy as np
#import data from GSBC data collected
#currently throwing an error regarding invalid numbers in np.array, when I have internet check do... |
8cf70328c6a3483dc74c6a2cfc1fb3031de148f6 | AlBeck862/rummy_game | /rummy_fxns.py | 4,645 | 3.953125 | 4 | import random
import itertools
from card import Card
from deck import Deck
def start_new_hand():
"""Initialize a new hand of Rummy 500."""
deck = Deck() #get a new deck
hand_size = 10 #10 cards dealt to each player
player1_hand = [] #empty player 1 hand
player2_hand = [] #empty player 2 hand
discard_line = [] #e... |
933b29e07c4696bf067c15511f5c7055e44e3f72 | zombiewafle/Estructure-Class-Lab-No.9 | /Lab No.9.py | 1,293 | 3.78125 | 4 | # Author: Javier Salazar
# Optional program of the Floyd Algorithm
#The import of the math library
from math import inf
from itertools import product
def floyd_warshall(n, edge):
#Variables
rn = range(n)
distance = [[inf] * n for i in rn]
nxt = [[0] * n for i in rn]
#The a... |
1b63ff94eac013b1eb2ef69af104cbd6fbb24765 | meirf57/CS50x-MyProjects | /pset6/mario/mario_less.py | 429 | 4.40625 | 4 | # this is a function to prompt for a digit
def number():
global num
num = input("height: ")
if num.isdigit() == False:
num = 0
num = int(num)
# using function
number()
# checking that digit is 1-8
while num < 1 or num > 8:
number()
sign = num - 1
# printing # in steps shape
for i in range... |
2bc17120a3b02f6b96cb7d60db1fabcbe47efa3a | lechodiman/IIC2233-Learning-Stuff | /Functional/generators.py | 429 | 3.609375 | 4 | def square_numbers(nums):
for i in nums:
yield(i * i)
def double_inputs():
while True:
x = yield
yield x * 2
def generator_function():
while True:
val = yield
print(val)
if __name__ == '__main__':
g = generator_function()
next(g)
g.send('Holi')
g.... |
d4b339c4ab50eddfed622bfaff236f7730b30fda | Rodger-M/Machine-Learning-Python | /Regression/Multiple Linear Regression/multiple_linear_regression_m.py | 1,664 | 3.9375 | 4 | # Multiple Linear Regression
# Importing the libraries
# Importando as bibliotecas
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
# Importando os dados
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
# Encoding cat... |
111f578358b04a67edc011cab30168c2dc578e86 | MauricioBritoCon/EstudosdePython | /Mundo2/CondicoesAninhadas.py | 5,143 | 3.859375 | 4 | import datetime
import random
computador = random.randint(0, 2)
usuario = input("Escolha entre 'pedra' 'papel' 'tesoura': ")
usuario = usuario.lower()
if computador == 0:
escolha = 'pedra'
elif computador == 1:
escolha = 'papel'
else:
escolha = 'tesoura'
if computador == 0 and usuario == 'ped... |
d851e0130a4835c40033926e46aa805d999ea8ea | siyingl6/Algorithmic-Trading-Bot | /venv/lib/python3.6/site-packages/fmclient/data/message.py | 1,758 | 3.53125 | 4 | import datetime
from enum import Enum
class Message(object):
"""
Class for abstract the message entity.
The messages will be exchanged between a web browser and the algorithm.
"""
def __init__(self, source, content, type, date=datetime.datetime.utcnow(), name=None):
"""
The messag... |
2413a8b38b5da912a19ecd7ceeabd9c9a5aacf04 | sirejik/software-design-patterns | /creational_patterns/builder/builder.py | 1,112 | 4.3125 | 4 | """
Separates the construction of a complex object from its representation, so that different representations can result
from the same design process.
"""
from abc import ABCMeta, abstractmethod
class Product:
def __init__(self):
self.param = None
def set_param(self, param):
self.param = para... |
2d3b1373fd48e20acd707d3b248a6bfc40006abc | Jhesker/StatisticalComputing | /HeskerStatComp1/11.1codeImplimentation.py | 2,884 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 24 21:12:50 2019
@author: jhesk
"""
class Node(object):
def __init__(self, name):
self.name = name
def getName(self):
return self.name
def __str__(self):
return self.name
class Edge(object):
def __init__(self, src, dest):
s... |
627f0ec95dd584a25f43722f110f08103a641d2a | 0n1udra/Learning | /Python/Python_Problems/Rosalind-master/019_PERM.py | 839 | 3.78125 | 4 | #!/usr/bin/env python
'''
A solution to a ROSALIND bioinformatics problem.
Problem Title: Enumerating Gene Orders
Rosalind ID: PERM
Rosalind #: 019
URL: http://rosalind.info/problems/perm/
'''
from itertools import permutations
def factorial(n):
'''Returns the value of n!'''
if n < 2:
return 1
else:
return n*... |
80c3d50c8f0445a7cdc5fcc301f975c6297fe52a | sonthanhnguyen/projecteuler | /project_euler_21.py | 2,149 | 3.875 | 4 | """
Project Euler 21: Amicable numbers
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a <> b, then a and b are an amicable pair and each of a and b are called
amicable numbers.
For example, the proper divisor... |
2d3a49e3b209c563a6d500a93cb328922658d924 | AlexLinGit/SICP-and-Other-Code | /Python Crash Course Exercises/chapter 7 - while and input/rollercoaster.py | 249 | 4.25 | 4 | height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
print("You are eligible to ride!")
elif height <= 0:
print("Ain't no one that short. Enter a new value.")
else:
print("You are too short, midget!")
|
ccf9030ee228ffd57e6bdf782596d01652a41815 | JasonVann/CrackingCodingInterview | /LeetCode/Ex700/Ex720.py | 5,674 | 3.859375 | 4 | class TrieNode:
def __init__(self):
self.child = [None]*26
self.is_end_of_word = False
class Dis(object):
def longestWord3(self, words):
ans = ""
wordset = set(words)
for word in words:
if len(word) > len(ans) or len(word) == len(ans) and word < ans:
... |
c8820b2f437f1423e6b1fc658c9da58a1e183fae | matthappens/iterator_talk | /code/tree.py | 2,263 | 3.734375 | 4 | import random
class IterableTree(object):
def __init__(self):
self.root = None
def __iter__(self):
self.clear_visited()
return InorderTraversalIterator(self.root)
def insert(self, value):
z = TreeNode(value)
parent = None
traverse = self.root
whil... |
f73e64b0a3bc08400a0205d7aacda60ba3e32ba0 | helbertsandoval/verificadores-conversores-impresion-tipo-boleta | /conversores_booleano.py | 836 | 4.09375 | 4 | #1 Convertir el real 85.2 a booleano
x=85.2
a = bool(x)
print (a, type(a))
#2 Convertir el entero 105 a booleano
x =105
a = bool(x)
print (a, type(a))
#3 Convertir la cadena75 a booleano
x ="75"
a = bool(x)
print (a, type(a))
#4 Convertir la cadena 205 a booleano
x ="205"
a = bool(x)
print (a, type... |
251d15629f898fe7d65af27ff0e4735f95775429 | GuanYangCLU/AlgoTestForPython | /LeetCode/linkedList/0025_Reverse_Nodes_in_k-Group.py | 1,050 | 3.671875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
# as max length is 5000, should valid for recursion, link to a asuumed reversed ... |
ff0350292913f5b0b07e5685e597fbc5471c6a82 | Luca2460/Imeneo-Leetcodes-Solutions-in-Python | /13. Roman to Integer.py | 680 | 3.859375 | 4 | def romanToInt(s: str) -> int:
# note: len(s) <= 15
out = 0
symbols = {'M':1000, 'CM':900,
'D':500, 'CD':400,
'C':100, 'XC':90,
'L':50, 'XL':40,
'X':10, 'IX': 9,
'V':5, 'IV':4,
'I':1}
while len(s) != 0:
... |
8af83ac2c0fe7c48146b52e564db417e86f11a72 | yhuang13/projecteuler | /problem6.py | 356 | 3.65625 | 4 | #etween the sum of the squares of the first one hundred natural numbers and the square of the sum.
min_num = 1
max_num = 100
sum_square = 0
for x in range(min_num, max_num + 1):
sum_square += x**2
square_sum = 0
for x in range(min_num, max_num + 1):
square_sum += x
square_sum = square_sum *... |
d5d3862dc089e0ddee1a548ffdba9632f13515d3 | Aasthaengg/IBMdataset | /Python_codes/p03826/s651345424.py | 300 | 3.78125 | 4 | height_a, length_a, height_b, length_b = map(int, input().split())
rectangle_a = height_a * length_a
rectangle_b = height_b * length_b
if rectangle_a == rectangle_b:
print(rectangle_a)
elif rectangle_a > rectangle_b:
print(rectangle_a)
elif rectangle_b > rectangle_a:
print(rectangle_b) |
8b4ac3603cb25ed412c241e7add97952d29ab866 | millanmilu/Learn-Python-with-Milu- | /53_class_sup.py | 260 | 3.71875 | 4 | class Vehicle:
def start(self):
print("starting engine")
def stop(self):
print("stopping engine")
class TwoWheeler(Vehicle):
def say(self):
super().start()
print("i Have two wheels")
super().stop()
a = TwoWheeler()
a .say()
|
122810a056dc0623a00f4fb2174b2aa0151bdd06 | tammyvitorino/AD1-Cederj_ProgramacaoComInterfacesGraficas | /Projeto Vídeo Locadora/DVD.py | 1,548 | 3.546875 | 4 | #!/usr/bin/env python
# coding: UTF-8
#
## @package DVD
#
# @author Tamara Vitorino
# @since 23/08/2017
import AbstractItem, sys, datetime
class DVD(AbstractItem.AbstractItem):
##
# Constructs a new Item with the given title, genre, and barcode.
# This constructor may only be invoked by subclasses.
... |
a3f01e06cc170831e99324d76fb86266e417579f | triztian/UCLAIntroDataScience | /Module2/module2b.py | 5,821 | 4.3125 | 4 | # Module 2b
# Author: Tristian Azuara
# Email: tristian.azuara@gmail.com
# UCLA: Introduction to Data Science
#
print('# A) Variables, types and casting')
# Unlike other languages like javascript, python does not implicitly cast
# objects into strings when using the '+' operator with strings.
# One must cast any non-s... |
d1107f6cf16d534ba7794d9556e737cf3df4e6c7 | shaktisinghmandhan/data_structure | /linked_list/k_consecutive_nodes_string.py | 741 | 3.78125 | 4 | from linked_list import LinkedList
def k_consecutive_nodes_string(head, k):
result = ""
j = k
while head and j >= 0:
if j == 0:
j = k
result += " "
else:
j = j - 1
result += head.data
head = head.next
return result
if __nam... |
420b68a6cd270854a4199e21385e581df4647e3e | fly2rain/LeetCode | /move-zeroes/move-zeroes.py | 683 | 3.515625 | 4 |
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nonzero_idx = 0
for current_idx in range(len(nums)):
if nums[current_idx]:
nums[nonzero_i... |
5dc073a3f190362d3e1687a5106b275ef82d85ea | IvanWoo/coding-interview-questions | /puzzles/top_k_frequent_elements.py | 1,313 | 3.90625 | 4 | # https://leetcode.com/problems/top-k-frequent-elements/
"""
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
1 <= nums.l... |
44796c76337d1d79711ef03be3cb9f668625fbda | Amrisha0306/python-task3 | /c5.py | 324 | 3.953125 | 4 | W= input('Please enter a string: ')
def most_frequent(string, reverse= False):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return dict(sorted(d.items(), key = lambda x: x[1], reverse = reverse))
print (most_frequent(W, True... |
3e8b2f65228cb1c3fc8badc726fbfdf72c70f3ac | shenchuang006/python | /calc.py | 735 | 3.671875 | 4 | # coding=utf-8
import sys;
def add(a, b):
return a + b;
# 这时,要解析传递的参数,需要用到 sys 模块:
if __name__ == '__main__': #意思是说:模块既可以被导入(到 Python shell 或者其他模块中),也可以作为脚本来执行
args = sys.argv # 用于获取命令行参数
print(args)
print(add(int(args[1]), int(args[2])));
'''
没错,通过 sys.argv 可以获取命令行参数,它是一个 list 类型。
sys.arg... |
3a6f47d24e0cbecc5b399eec78e829c4568d6578 | Parolo41/advent-of-code-202 | /D3P1.py | 499 | 3.640625 | 4 | inputFile = open('D3P1.txt', 'r')
FileLines = inputFile.readlines();
xPosition = 0
xVelocity = 3
treeCount = 0
for line in FileLines:
xPosition %= (len(line) - 1)
pointer = ''
pointer += ' ' * xPosition
pointer += 'v'
print(pointer)
print(line[:-1])
if line[xPosition] == '#... |
0eee0cff7baa1859e16d2cc5eeb67421f5236034 | jrjed/advent_of_code_2016 | /day6/script6.py | 753 | 3.59375 | 4 | import collections
def readcol(datafile):
with open(datafile) as f:
rows = []
for line in f:
rows.extend(line.split())
columns = zip(*[list(row) for row in rows])
f.close()
return columns
def decode_col(columns, rank):
code = ''
for column in columns:
... |
0fe749861eb9ea3ef034d1013a5a8a898b322153 | arpan0317/AI440 | /Project_3/Code3_asg235_ftt7.py | 10,255 | 3.65625 | 4 | import random
import sys
import csv
class point:
def __init__(self, col: int, row: int):
self.col = col
self.row = row
#state 1 = flat, 2 = hilly, 3 = forested, 4 = maze of caves
class cell:
def __init__(self, pt: point, state, prob):
self.pt = pt
self.state = state
sel... |
6c132434f5b177a6ae62032a13145739f60a7670 | t0ny00/Inteligencia-2-Proeycto-1 | /RLM.py | 4,433 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def Normalize(array):
n = len(array)
media = np.mean(array,axis=0)
dev_standar = np.std(array,axis=0)
#Create normalized array
new_array = []
for elem in array:
temp = np.divide((elem - media) ,dev_standar)
new_array.append(tem... |
d6bdd3af96b503e38548a06717e136f15d957824 | kmouse/Game_1 | /Game/Data/Code/button.py | 6,064 | 3.671875 | 4 | import pygame
import os
from Data.Code.load import get_image, get_font
pygame.init()
def resize_image(width, height, location):
image = pygame.image.load(get_image(location)).convert_alpha()
if width == 0:
width = image.get_width()
if height == 0:
height = image.get_height()
image = py... |
56fe9f0c301b899c41af2e74f2fbdfa758a44974 | ErkkoI/Sahkista | /minority_game.py | 4,247 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 19 19:04:54 2020
@author: eelil
"""
import numpy as np
import matplotlib.pyplot as plt
def lastMBits(n, m):
return n & ((1 << m) - 1)
def insertRightBit(n, bit):
return (n << 1) | bit
# N is the number of players, m is the length of memory
def runMinorityGame(... |
8e052ec9d528c4a88e9e23d3ee04ddad24d14a35 | Rupsa25/DailyCodingProblem | /day2.py | 861 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 09:27:12 2020
@author: Rupsa
"""
"Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i."
"Time Complexity:O(n^2)"
def newArray(arr):
... |
b339f6ced09317166f5ce49eb6f4bab693da1020 | ProvisionLab/Iris_reco | /blob.py | 874 | 3.671875 | 4 | # Standard imports
import cv2
import numpy as np;
# Read image
gray = cv2.imread("02.bmp", cv2.IMREAD_GRAYSCALE)
output = gray.copy()
# detect circles in the image
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.9, 300)
# ensure at least some circles were found
if circles is not None:
# convert the (x, y)... |
c12ac60099dc44da4d268f5e8862e4af681d5e2f | kinsonpoon/CUHK | /csci3320/asg2/ex2.py | 4,230 | 3.71875 | 4 | import os.path
import numpy as np
import matplotlib.pyplot as plt
from scipy import misc
from sklearn.decomposition import PCA
def load_data(digits, num):
'''
Loads all of the images into a data-array.
The training data has 5000 images per digit,
but loading that many images from the disk may take a w... |
7585618cdc4739146bd08508afe1271da2697437 | AnmAgrawal/HackerrankSolutions | /betweenTwoSets.py | 854 | 4.03125 | 4 | # You will be given two arrays of integers and asked to determine all integers that satisfy the following two conditions:
# The elements of the first array are all factors of the integer being considered
# The integer being considered is a factor of all elements of the second array
# These numbers are referre... |
81c2978ad2e7d8049879d7cec0452d1c8d19d459 | keurfonluu/My-Daily-Dose-of-Python | /Solutions/31-spiral-traversal-of-grid.py | 2,303 | 3.921875 | 4 | #%% [markdown]
# You are given a 2D array of integers. Print out the clockwise spiral traversal of the matrix.
#
# Example
# ```
# grid = [
# [1, 2, 3, 4, 5],
# [6, 7, 8, 9, 10],
# [11, 12, 13, 14, 15],
# [16, 17, 18, 19, 20],
# ]
# ```
# The clockwise spiral traversal of this array is:
# 1, 2, ... |
f564b75a0550add414a2987b036263ed73008e3b | mychristopher/test | /pyfirstweek/tkinter学习/Label控件.py | 839 | 3.71875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import tkinter
#创建窗口
win = tkinter.Tk()
#设置标题
win.title("caicai")
#设置大小和位置
win.geometry("400x400+200+20")
#label:标签控件可以显示文本
#win 父窗体,text:文本内容 , bg 背景色 ,fg 字体颜色
# font 字体,wraplength 指定多宽之后换行,justify 指定怎样对齐
#anchor 位置n e s w 居中center ne se,
label = tkinter.Label(... |
0834893cf6dab92a818df60b683be9e3ed929134 | stOracle/Migrate | /Programming/CS313E/ExpressionTree.py | 6,241 | 3.578125 | 4 | # File: ExpresssionTree.py
# Description: An algorithm to do math using a tree
# Student's Name: Stephen Rauner
# Student's UT EID: STR428
# Course Name: CS 313E
# Unique Number: 50945
# Date Created: 4/24/16
# Date Last Modified: 4/25/16
# //////////////////////////////////////////////////////////////... |
290013d5c272fdce351d88002e6ac56cbaed6acd | MargulisMax/opsschool3-coding | /home-assignments/session1/exercise2.py | 1,942 | 3.796875 | 4 | """
Usage:
python3 exercise2.py
"""
import json
from urllib.request import urlopen, quote
API_KEY = 'APPID=9c8b160816fc48b0288a6136e0989b2a'
API_UNITS = '&units=metric&'
API_QUERY = 'http://api.openweathermap.org/data/2.5/weather?q='
def get_location_by_ip():
with urlopen('http://ip-api.com/json') as jsonrsp... |
3410168797f2572b3d5620ac99de91deb53a77eb | Asfhen/python-para-zumbis-resolvido | /Lista de exercicio 3/exercicio 2.py | 251 | 4.09375 | 4 | user = input('Digite seu nome de usuario: ')
while True:
psw = input('Digite sua senha: ')
if psw == user:
print('Sua senha não pode ser igual seu nome de usuario')
else:
print('Usuario e senha cadastrados!')
break |
3ca55a7c42b6ef0b7d7827d41b4dadc4550e1667 | YashasviBhatt/Python | /countdown.py | 208 | 3.90625 | 4 | import time
countdwn=int(input("Enter Countdown Limit : "))
while countdwn >= 0 :
print(countdwn)
countdwn=countdwn-1
time.sleep(1) # sleep(n) to give delay of n seconds |
1510caa6aae575e8cea528c18a60ba15c6ded254 | Maanume/Final-Project-SDL | /remove_stopwords.py | 901 | 4.125 | 4 | import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
stop_words = nltk.corpus.stopwords.words('english')
# if desired, add more words for the stopword list.
New_stopwords = ["hon.", "member", "mr."]
stop_words.extend(New_stopwords)
# below add the text file you would like to run thro... |
b95751d63096ced1b7fa51de1034f7cbcf354556 | beatrizcf2/projeto-camfis | /Projeto3/teste.py | 612 | 4.15625 | 4 | # Fonte: https://www.geeksforgeeks.org/how-to-create-a-countdown-timer-using-python/
# import the time module
import time
# define the countdown func.
def countdown(size, t):
# fica dentro do loop ate t=0
while t>0:
mins, secs = divmod(t, 60) #calcula o n de min e seg
timer = '{:02d}:{:02d}... |
1f2ae3b8353b3606e1388d11dec83f0730815505 | ajbrzoz/How-To-Think-Like-a-Computer-Scientist | /Chapter9/Ex9-22-9.py | 329 | 4.0625 | 4 | # Exercise 9.22.9
# Write a function that recognizes palindromes.
def is_palindrome(my_str):
count = 0
palin = True
while count < len(my_str) and palin:
if my_str[0] == my_str[-1]:
my_str = my_str[1:-1]
is_palindrome(my_str)
else:
palin = False
retu... |
1a192e71c9e315df0bb255cc9d03d766c183b829 | JorgeEspina/Proyecto2s12017_201403632_201503393 | /EDD_Proy2/DRIVE/Drive/AVL.py | 3,322 | 3.625 | 4 | class NodoAVL:
def __init__(self,nombre):
self.left = None
self.right = None
self.nombre = nombre
def __str__(self):
return "%s" % self.nombre
class ArbolAVL:
def __init__(self):
self.nodo = None
self.altura = -1
self.balance = 0
def insertar(self, nombre):
n=NodoAVL(nombre)
au... |
e10810ec080b44b2a780b4b85c346284a0e9cbcc | EvanMisshula/advpy | /10-args.py | 781 | 4 | 4 | ## args and kwargs
def doubler(f):
def g(x):
return 2* f(x)
return g
def f1(x):
return x + 1
g=doubler(f1)
print g(3)
print g(-1)
#doesn't work
def f2(x, y):
return x + y
g = doubler(f2)
print g(1,2) ## Error
def magic(*args, **kwargs):
print "unnamed args:", args
print "keyword ar... |
cd1866983f868264c96817f79030b190ffaa990a | MonterrosaEdair/Portafolio1 | /multiplicarRecursivo.py | 370 | 3.765625 | 4 | #E: 2 números
#S: Multiplicar un número por su factor sin el operando
#R: El numero debe ser entero
def multiplicarRecursivo(num,factor):
if isinstance(num,int) and isinstance(num,int) and num>=0 and factor>=0:
if num==0:
return 0
else:
return num+multi(num,... |
b51834b999f6489e8d6be951f1d28d013d3a2bee | chenlfc/learnPython | /Python编程_从入门到实践/Part 1/Chapter 6 to 11/division.py | 647 | 3.890625 | 4 | # -*- coding: utf-8 -*-
# cretae by o.c. 2018/7/25
from _for_ex import pt_title
pt_title('division.py'.upper())
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number.lower() == 'q':
break
second_number ... |
907efbe3fd6bdbefad75720082110c23a3610b8a | Liliana327/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 637 | 3.78125 | 4 | #!/usr/bin/python3
'''
returns the perimeter of the island described in grid
'''
def island_perimeter(grid):
'''grid is a list of list of integers
'''
width = 0
height = 0
for zone in range(len(grid)):
for water in range(len(grid[zone])):
if grid[zone][water] == 1:
... |
e9e157359728deb97e4a3d4e8187b067cd88e02f | joseph-hurtado/quarg | /examples/trivial3.py | 405 | 4.03125 | 4 | #!/usr/bin/env python3
"""Basic maths functions.
Simple use of the quarg module, with no additional
annotation.
"""
import quarg
def prod(x,y = 1):
"""Multiply two numbers.
This is pretty basic stuff."""
print(x, "*", y, "=", int(x) * y)
def sum(x, y = 0):
"""Add two numbers.
Addition was know... |
f0aa1c289d3d4e98ae59ed0563aeee990d9e0931 | ssola/project-euler | /problem25/fibonacci.py | 351 | 3.609375 | 4 | '''
Problem 25
1000-digit Fibonacci number
https://projecteuler.net/problem=25
'''
def fib(n):
fibValues = [0,1]
for i in xrange(2,n+1):
fibValues.append(fibValues[i-1] + fibValues[i-2])
return fibValues[n]
currentValue = 0
index = 0
while len(str(currentValue)) < 1000:
index += 1
current... |
2a9618088ebd2e4c6bccee23ece591c0c85a0103 | emmjab/flights_analysis | /src/00-FilterFlights.py | 495 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import sys
# It would be more robust to use argparse or click, but we want this to be simple
if len(sys.argv) < 3:
sys.exit("Please invoke with two arguments: input and output paths")
input_path = sys.argv[1]
output_path = sys.argv[2]
# Read in the data... |
9134172bf36ed53c6a2d4403c13887d047846238 | Bency2410/moduleprgrms.py | /checkeven.py | 82 | 3.671875 | 4 | def even(x):
if(x%2==0):
return "even"
else:
return "Odd " |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.