blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ff3cddcfc9506ed3399d5f8a8e049220718879a6 | HughesZhang73/Python-Master | /Python-Foundation/Python Overview/07 Python 装饰器类应用.py | 505 | 3.984375 | 4 | # coding=utf-8
"""
装饰器:
1.用于拓展原来函数的功能的一种函数
2.返回函数的函数
3.在不使用原来函数的代码的前提下给函数增加新功能
"""
# 定义一个装饰器
from functools import wraps
def eat(cls):
cls.eat = lambda self: print("{0} need eat something".format(self.name))
return cls
@eat
class Cat(object):
def __init__(self, name):
self.name = n... |
9e741dba9db4c3730ee2df2442185b9d1e35ef5f | pikkaay/leetcode | /src/2_maximal_square.py | 1,870 | 4 | 4 | '''
221. Maximal Square
Average Rating: 4.86 (172 votes)
July 14, 2016 | 199.2K views
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
Summary
We need to find th... |
08cad54ff604dd63a7db5419e242bf91ae952932 | rccoder/2013code | /Python/practice/乘法口诀/乘法口诀.py | 329 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 12 18:43:37 2013
@author: yangshangbin
"""
print " Multiplication Table"
for j in range(1,10):
for i in range(1,10):
if i<=j:
print i,"*",j,"=",format(i*j,"2d")," ",
else:
print("\n")
a=eval(raw_input())
... |
7513846856bdb052d400d68a69324a2bba3cfde0 | siam1251/algorithms | /interviewbit/sum_tree.py | 670 | 3.875 | 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 sum_path(self,A,s_total,B):
if A.left == None and A.right == None:
if s_total+A.val== B:
return 1
else:
return 0
if... |
bba7c765f9739b3629cf9dedbad399e565488f1c | Aasthaengg/IBMdataset | /Python_codes/p03385/s776904035.py | 58 | 3.640625 | 4 | print("Yes" if sorted(input()) == ['a','b','c'] else 'No') |
76a4fbe20bbc4f26df3a5b4a9f4da8f29e0ed5b2 | yideng333/Code_Interview | /Code_interview/41.py | 1,335 | 3.875 | 4 | '''
数据流中的中位数
'''
import heapq
# 使用两个大小堆实现
def get_midden(array):
min_list = []
max_list = []
i = 0
while i < len(array):
insert(array[i], min_list, max_list)
i += 1
if len(min_list) + len(max_list) & 1 == 1:
midden = min_list[0]
else:
midden = ((max_list[0] * ... |
0685dc5195610af30d9daf2eb4b67f7e88ea0da1 | jhhsu8/coursera-python-intro-interactive-programming | /IIPP-part-one/guess-number-game.py | 1,679 | 4.09375 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import random, simplegui, math
# helper function to start and restart the game
def new_game():
global count, secret_number
secret_number = random.randrange(0... |
1c7beeb1b856052bf12a22248319c0308e070509 | SleepwalkerCh/Leetcode- | /214_2.py | 1,037 | 3.84375 | 4 | #214. Shortest Palindrome
# 每一字节check会超时
# 用数组切片直接比对会加快速度
class Solution:
def shortestPalindrome(self, s: str) -> str:
self.s=s
if len(s)<2:
return s
left=(len(s)-1)/2
while left>=0:
if self.check(round(left-0.6),round(left+0.6)):
return self.m... |
70debd09e4920708fa2f1826e0edea31aefd733d | kyle-mccarthy/maze-traversal | /vertex.py | 351 | 3.609375 | 4 | class Vertex:
def __init__(self):
self.row = None
self.col = None
self.adj = [] # for BFS
self.visited = False # for BFS
self.start = False
self.end = False
self.successor = None
self.cost = None
# add an adjacent edge
def add_adjacent(self,... |
b56a2872dd51d8241ec4d23accdc9df6cd277ee1 | thar/TuentiChallenge2 | /Reto11/scrab.py | 5,120 | 3.734375 | 4 | #!/usr/bin/python
#########################################################################
# Program will create words for scrabble given letters and words already
# Date Created: 6/15/11
# Date Finished: TBA
# FileName: Scrabble.py
#########################################################################
#Modificad... |
604a8ed4e3f5e9da7a40255465afbe659bc3b813 | shadunts/data_structures | /max_queue.py | 993 | 4 | 4 | from collections import deque
class MaxQueue:
def __init__(self):
self.__size = 0
self.__data = []
self.__max_values = deque()
def __len__(self):
return self.__size
def enqueue(self, value):
# delete all the items in max_values which are less than the value we add... |
a3b1c4a92b5c42a29ce03bf3dc864514c26db250 | shubhamjante/python-fundamental-questions | /Programming Fundamentals using Python - Part 01/Assignment Set - 04/Assignment on string - Level 1 (puzzle).py | 986 | 4.21875 | 4 | """
Write a python program to display all the common characters between two strings.
Return -1 if there are no matching characters.
Note: Ignore blank spaces if there are any. Perform case sensitive string comparison wherever necessary.
=========================================================
| Sample Input ... |
005e83c68dd415df33603b64f826b9b178f73495 | itsmac/1337C0D3_journey | /Average Salary Excluding the Minimum and Maximum Salary.py | 406 | 3.703125 | 4 | '''
No: 1491.
Title: Average Salary Excluding the Minimum and Maximum Salary
'''
class Solution:
def average(self, salary: List[int]) -> float:
val = 0
max_val,min_val = max(salary),min(salary)
for i in salary:
val += i
return (val-max_val-min_val)/(len(salary)-2)
... |
92fcdeca91eaee9bd82dc56ca775883e1a752c96 | lepisma/audi | /src/custom.py | 2,769 | 3.515625 | 4 | """
Custom cnversion of data to music
"""
import numpy as np
import pyaudio
def modulate(data):
"""
Modulates the data given to be transferred via audi.
Modulation works as described below
- Change each uint8 element (byte) in the given array to
binary representation
- Form a wave byte by... |
491d6840ca782a721308df26d9bf22438d3f0b24 | George-lewis/Golf | /py/fact.py | 560 | 3.59375 | 4 | #
# For comparing the speed of a regular recursive factorial to a cached recursive factorial
#
import time, sys
sys.setrecursionlimit(10**6)
cache = { 0 : 1, 1 : 1 }
# cached
def cfact(n):
if n in cache:
return cache[n]
res = n*fact(n-1)
cache[n] = res
return res
# regular
def fact(n):... |
40377317b5c1c8e707f186b07e9c79c6f4b40696 | fengor/adventofcode | /2015/d5c1.py | 538 | 3.65625 | 4 | with open('d5_input.txt') as f:
strings = f.readlines()
forbidden = ('ab', 'cd', 'pq', 'xy')
vowels = 'aeiou'
nice_strings = 0
for string in strings:
vowel_count = 0
double = False
nice = True
for bad in forbidden:
if bad in string:
nice = False
if not nice:
continue
for i, char in enumerate(string... |
8a4ae3b87c5cf4eacbef91bda3279275280b6d06 | Prashant-Bharaj/A-December-of-Algorithms | /December-09/python_Raahul46_IS_THIS_URL.py | 409 | 4.15625 | 4 | #!python3
"""
Hi there.
This file doesn't contain any code.
It's just here to give an example of the file naming scheme.
Cheers!
"""
import validators
def isurl(link):
value=validators.url(link)
if(value==True):
print("It is a URL")
else:
print("It is not a URL")
def main():
string=str(in... |
64e3d67b68202a779c65588a88c691c3c36f2afe | MisterKitty1210/Choose-Your-Own-Adventure-Per-3 | /Choose Your Own Adventure Per 3.py | 51,706 | 3.640625 | 4 | import time
import random
import sys
def type(text):
wait = 0
for c in text:
sys.stdout.write(c)
time.sleep(random.randrange(5, 10)/500.0)
def main():
type("The Tale of Gladion Knit3blad3: A Choose Your Own Adventure!\n"
"By Nicholas Eng, Period 3"
"(You'll never beat t... |
43a792c87adb26fd5ffd2da072443061211323ba | Ramyaveerasekar/python_programming | /primeno.py | 559 | 3.515625 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: vino
#
# Created: 23/03/2018
# Copyright: (c) VINO 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
def... |
02a8fc4f9fe3428b3bd6770000ea8ae6d1038387 | sheff-slava/jetBrains_dominoes | /dominoes.py | 6,317 | 3.875 | 4 | from itertools import chain
import random
stock = list()
computer = list()
player = list()
def determine_first(computer_pieces, player_pieces):
for i in range(6, -1, -1):
if [i, i] in computer_pieces:
return 0, [i, i]
elif [i, i] in player_pieces:
return 1, [i, i]
ret... |
4074ff4810f9fc8add3f07b385e4d2e982e74620 | vgsprasad/Python_codes | /year.py | 1,236 | 3.5625 | 4 | cal_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31]
cal_nonleap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31]
conv_leap = [31, 16, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31]
conv_nonleap = [31, 15, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31]
def leap_year(year):
if year % 4:
return 0
else:
if year%100:... |
b1e95844fd50ed83d8047603ba318ddbf914ca6d | poowoo/leetcode_questions | /191_Number_of_1_Bits.py | 455 | 3.859375 | 4 | class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
sum = 0
while(n >= 1):
if int(n) & 1 == 1:
sum += 1
n /= 2
return sum
def main():
input = i... |
d8d521731799e278b1f204976123de44c4162b3f | jopela/cityinfo | /cityinfo.py | 2,384 | 3.546875 | 4 | #!/usr/bin/env python3
import json
import argparse
import sys
import logging
import iso3166
# takes a guide file and returns it's city name and country.
def main():
parser = argparse.ArgumentParser(
description="extract city name and bounding box from"\
" a guide.")
parser.add_argum... |
53c83f21657d5d364d3d45d2d7ff003a22ae194c | kobeding/python | /2016/do_fork.py | 960 | 3.859375 | 4 | #!/usr/bin/python3.5
#fork()系统调用,调用一次返回两次(复制一份子进程)
#一个父进程可以fork出很多子进程,所以父进程需要记住每个子进程的ID
#而子进程只需要调用getppid()就可以拿到父进程的ID
#有了fork,一个进程在接到新任务时就可以复制出一个子进程来处理新任务
#apache服务器就是由父进程监听端口,子进程处理新的http请求
import os#os封装常见的系统调用
print('Process (%s) start ...' % os.getpid())
pid = os.fork() #子进程永远返回0,父进程返回子进程的ID
if pid == 0:
print('... |
148953ae8841f2d8b9e67a972b0ad50c19dea465 | joshuathompson/ctci | /stacks/sort_stack.py | 561 | 3.796875 | 4 | unorderedStack = [5, 4, 6, 4, 3, 12, 23, 10, 5, 10, 3, 12]
orderedStack = []
pop = None
hold = None
while len(unorderedStack) > 0:
pop = unorderedStack.pop()
if hold is None:
hold = pop
elif pop >= hold:
for item in reversed(orderedStack):
if pop > item:
moveBa... |
1d93b4feeb9497592605413421e1615ad98ed0d5 | shiny0510/DataStructure_Python | /Algorithm analysis/prefixAverage.py | 684 | 3.625 | 4 | from time import time
def prefix_average1(S):
n = len(S)
A = [0]*n
for j in range(n):
total = 0
for i in range(j+1):
total += S[i]
A[j] = total / (j+1)
return A
# Looks Better
def prefix_average2(S):
n = len(S)
A = [0]*n
for j in ra... |
96e8a52cd581f6c3d5f1cdbbf185dc35ba04a50f | jaugustomachado/Curso-Next-Python | /Aula4 - Vetores e estrutura de repetição/media.py | 310 | 4.125 | 4 | #Faça um programa que calcule o mostre a média aritmética de N notas.
n=int(input('informe o número de notas, para cálculo da média: '))
notas = [ ]
soma=0
for i in range(n):
notas.append(float(input('informe a nota do aluno: ')))
soma=soma+notas[i]
print( ' a média das notas é : ', soma/n) |
5924aaba2bb6fbcf835a45215b65c12a917e06f1 | bioCKO/science | /python workshop/.svn/text-base/flow.py.svn-base | 1,191 | 4.1875 | 4 | if True:
print("TRUE!")
else:
print("FALSE!")
if False:
print("TRUE!")
else:
print("FALSE!")
if 1:
print("TRUE!")
else:
print("FALSE!")
if 5:
print("TRUE!")
else:
print("FALSE!")
if 0:
print("TRUE!")
else:
print("FALSE!")
if None:
print("TRUE!")
else:... |
a63a895f8338c247ffd7bcf49ab014727f460ccc | safelyafnan/Muhammad-Safely-Afnan_I0320070_M-Wildan-Rusydani_Tugas-4 | /Soal 2.py | 197 | 3.875 | 4 | pertama= int(input('Masukkan Angka Pertama: '))
kedua= int(input('Masukkan Angka Kedua: '))
print(" ")
print('Angka pertama bisa dibagi oleh angka kedua sebanyak {} kali'.format(pertama//kedua)) |
c3a90f14740eb23907da2539b2c045f5322451dd | vsapronova/BackToBack | /nearest_repeated_entries.py | 533 | 3.75 | 4 | def nearest_distance(sentence):
if len(sentence) < 2:
return None
last_seen_repeated = {}
closest_dist = []
for i in range(len(sentence)):
word = sentence[i]
if word in last_seen_repeated:
closest_dist.append(i - last_seen_repeated[word])
last_seen_repeated[wo... |
c7c70a59fbf74a502539bbafd01cd4f9f66cab29 | onedreamxmm/Recursion2 | /50. Pow(x, n).py | 771 | 3.9375 | 4 | '''
Implement pow(x, n), which calculates x raised to the power n (i.e. xn).
time complexity: O(log2(n))
space complexity: O(log2(n))
'''
class Solution:
def myPow1(self, x, n):
if n == 0:
return 1
if n < 0:
return 1 / self.myPow1(x, -n)
half = self.myPow1(x, n//2... |
1426d6e06644f26b42985f2a3bb69e9c481c3665 | pepeArenas/PythonFundamentals | /chapter/collections/CopiesAreShallow.py | 776 | 4.1875 | 4 | numbers = [[1, 2, 3], [4, 5, 6]]
ages = numbers[:]
print("Both list: numbers and ages has the same values", numbers == ages)
print("Both list: numbers and ages has not the same identity", numbers is ages)
print(
"If we reassign ages[0] it will make a new reference for that index and it will be "
"independent ... |
ce85a7bd6513ca1243aa469c2e864c70baba1a8a | mastermind2001/Problem-Solving-Python- | /deficient_numbers.py | 3,057 | 4.3125 | 4 | # Date : 24-05-2018
# Deficient Numbers
# main function for telling a number is deficient or not
def is_deficient(num):
"""
:param num: a positive integer value
:return: a string indicating a number is deficient or not
"""
store_sum = 0
# iterate over an entire range, range = num+1
for int... |
6fa1bf4053ca041fec53d21b73da21aff03694d3 | mecomontes/Python | /Fundamentos Python/Matrices_2.py | 767 | 3.6875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Creación de una Matriz, de manera aleatoria
# Hacer un programa que llene la matriz de manera aleatoria
# Encontrar:
# El valor mayor
# El valor menor
# El valor promedio
# Generar aleatoriamente:
# El numero de filas que tiene la matriz
# El numero de columnas... |
c75abaf694657502f69ee78603278f2517dc23c9 | akaushal123/Project-Euler | /6. Sum Square Difference.py | 904 | 4.21875 | 4 | """
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""
def sum_square_natural_number(n):
return (n * (n + 1) * (2 * n + 1))/6
def sum_natural_number(n):
return n * (n + 1)/2
def sum_difference(l):
sum_squares = sum_square_natural_n... |
c20180d6bd542014f0891d429a8e3f7a349a5a73 | coder-dipesh/Basic_Python | /labwork2/leapyear.py | 257 | 4.0625 | 4 | year=int(input('Enter year to check :'))
if (year%4)==0:
if (year%100)==0:
if (year%400)==0:
print('Leap Year')
else:
print("Not Leap Year")
else:
print("Leap Year")
else:
print("Not Leap Year")
|
0f63de8752cbb846f3b7687c72a33e2d1e1e3195 | tcollins2011/rosalind | /Perfect_matchings_and_rna_secondary_structures/index.py | 968 | 3.65625 | 4 | # Separates fasta file to a single DNA string
from math import factorial
def clean_data(fasta):
cleaned = []
data_set = fasta.strip().split('>')
for dna in data_set:
if len(dna):
i = dna.split()
target = ''.join(i[1:])
cleaned.append(target)
return cleaned
... |
809f52d51770ebdd6aebae79b6872ce0c588c55c | 283938162/FirstPython | /com/tlz/python-base/python-match.py | 823 | 3.5 | 4 | import re
'''
match.group([group1, ...])
获得匹配后的分组字符串,参数为编号或者别名;
group(0)代表整个字符串,group(1)代表第一个分组匹配到的字符串,
依次类推;如果编号大于pattern中的分组数或者小于0,则返回IndexError。
另外,如果匹配不成功的话,返回None;如果在多行模式下有多个匹配的话,返回最后一个成功的匹配。
'''
m = re.match(r'(\w+)\s+(\w+)', 'Isaac Newton, physicist')
print(m)
print(m.group())
print(m.group(0))
print(m.... |
670a2d7e699fa4440bd996a65e50f846146b5e24 | robomojo/pyxml_clean_edit | /pyxml_clean_edit/test/test_pyxml_clean_edit.py | 8,386 | 3.515625 | 4 | '''
tests for the various ways we might want to add things to an xml file.
'''
import os
from os import unlink
import xml.etree.ElementTree as ET
import tempfile
import xml.dom.minidom
from .. import xml_helpers
from . import utils
def test_add_element():
# make an xml
xml_root = ET.Element('root')
xml_pa... |
50aa30650c0f4697e04c63485eb3c84044d9c70d | duwn55/coding-practice | /python/반복문/while_with_time.py | 257 | 3.703125 | 4 | # 시간과 관련된 기능 가져오기.
import time
# 변수 선언
number = 0
# 5초 동안 반복
target_tick = time.time() + 5
while time.time() < target_tick :
number += 1
# 출력
print("5초 동안 {}번 반복했습니다.".format(number))
|
8c06e8191631c2c83e794236db7628b771cf504b | Shirhussain/Advance-python | /Fluent_python/Data_Structures.py | 8,522 | 3.8125 | 4 | #List Comprehensions and Readability
symbols = '$¢£¥€¤'
code = []
for symbol in symbols:
code.append(ord(symbol))
code = [ord(syembol) for syembol in syembols]
print(code)
#Listcomps No Longer Leak Their Variables
a = 'my precious'
data = [a for a in 'KLM']
print(a)
m = "KLM"
dummy = [ord(m) for m in m... |
4076d6f5676385a963c16856d6e156cc6db99bc5 | Intenfas/Intenfas | /EX1.py | 2,629 | 4.0625 | 4 | from functools import partial
class Set:
def __init__(self, values=None):
self.dict = {}
if values is not None:
for value in values:
self.add(value)
def __repr__(self):
return "Set: " + str(self.dict.keys())
def add(self, value):
self.dict[valu... |
efec55f2b46b35d7f154cf7abe625e2d628739c4 | mathankrish/Python-Programs | /Company_ques/Arithematic series-1.py | 491 | 4 | 4 | # Arithematic series for 0,0,7,6,14,12,21,18,28 find the 15th term in the series
number_of_term = int(input("Enter the nth term: "))
List = number_of_term * [0]
even_place = 0
odd_place = 0
List[0] = 0
List[1] = 0
for i in range(2, number_of_term):
if i % 2 == 0:
even_place += 7
List[i]... |
286bcf7ea35235779ad4a6ae0f526cd7d927199e | TetianaSob/Python-Projects | /test_Unit_Testing.py | 965 | 4.15625 | 4 | # test_Unit_Testing.py
import unittest
from Unit_Testing import circle_area
from math import pi
#create a class from the subclass
class TestCircleArea(unittest.TestCase):
def test_area(self):
#Test areas when radius >= 0
self.assertAlmostEqual(circle_area(1), pi)
self.asse... |
844356a2192778c71be640abf926993895cb23c8 | jameswmccarty/PythonChallenge | /31.py | 1,767 | 3.625 | 4 | """
http://www.pythonchallenge.com/pc/ring/grandpa.html
title: Where am I?
photo: http://www.pythonchallenge.com/pc/ring/grandpa.jpg
(shows a rock on a lake)
Next link: http://www.pythonchallenge.com/pc/rock/grandpa.html
username: island
password: country
Searching for 'Grandfather's Rock'
http://www.kosamui.com/lam... |
9c5ef28e14a88197a7ebd2dfa599b4924d437a9f | Radek011200/Wizualizacja_danych | /Zadania_lista_nr5/5_9.py | 246 | 3.515625 | 4 | def parzyste(wyraz):
for index in range(0,len(wyraz),2):
yield wyraz[index]
prz=parzyste("Zadanie")
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
|
e03075ba7bc4578199b2ecab6da5f1e59695d872 | valentina-zhekova/Hack-Bulgaria-Programming-101 | /week0/part 2/sudokuSolved.py | 1,239 | 3.984375 | 4 | def sudoku_solved(sudoku):
return (correct_matrix(sudoku) and check_rows(sudoku)
and check_columns(sudoku) and check_3x3(sudoku))
def check_rows(matrix):
m0 = matrix
m = list(map(lambda x: condition(x), m0))
if len(set(m)) == 1 and m[0]:
return True
return False
def check_col... |
ed639ec272a6fd484a007002f7a95d300f416f11 | Zovengrogg/ProjectEuler | /Euler37_TrancatablePrimes.py | 816 | 3.671875 | 4 | # Truncatable Primes https://projecteuler.net/problem=37
from math import sqrt
def isPrime(n):
if n > 1:
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True
return False
answers = []
for n in range(11, 1000001, 2):
if not ... |
35d4b96ab956d7fea3d88b1d8a640cc97ab4e68e | Naheuldark/Codingame | /Puzzles/Easy/AChildsPlay.py | 1,124 | 3.625 | 4 | import sys
import numpy as np
def is_obstacle(m, pos):
return m[pos[0]][pos[1]] == '#'
w, h = [int(i) for i in input().split()]
n = int(input())
m = []
for i in range(h):
line = input()
m.append(line)
if 'O' in line:
# Found initial pos
pos = np.array([i, line.index('O')])
# Initia... |
1468e6e47cabf7cde204bda9417785b8059a4a8b | Sheretluko/LearnPython_homeworks | /lesson3/3_2_datetime.py | 638 | 3.96875 | 4 | # Напечатайте в консоль даты: вчера, сегодня, 30 дней назад
# Превратите строку "01/01/25 12:10:03.234567" в объект datetime
from datetime import datetime, date, time, timedelta
dt_now = datetime.now()
print(f"Сегодня: {dt_now.strftime('%d.%m.%Y')}")
print(f"Вчера: {(dt_now - timedelta(days = 1)).strftime('%d.%m.%Y')}... |
09f51b5d201473b3b4ecfc529154337a2fd9f740 | leiz2192/Python | /exercise/permutations/permutations.py | 611 | 3.828125 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
class Solution:
"""
@param: nums: A list of integers.
@return: A list of permutations.
"""
def permute(self, nums):
if not nums:
return [[]]
nums_size = len(nums)
if nums_size == 1:
return [nums]
res =... |
906da6df99ea8fcb8d19fea549e5c88b083af69f | avikd1001/TrainingSDET | /Python/activity2_4.py | 352 | 4.25 | 4 | # Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
def fibo (num):
if num <= 1:
return num
else:
return (fibo(num-1) + fibo (num-2))
userInput = int(input("Enter the desired number to generate the fibonacci series: "))
for i in range(use... |
54b7cca3aa91ac93ddb4755f93ebb6d6dd22c130 | HaiZukon/HaiZuka-1 | /Files/Gon.py | 140 | 3.796875 | 4 | print(a)
b = []
for i in range(len(a)):
c = []
c.append(a[i])
b.append(c)
print(b)
print(b[0][0])
print(b[1][0])
print(b[2][0])
|
b6c5a50aea10b14f8a278ff10524b38bd0bf2f25 | lekhav/LC-practice | /String/Reverse String .py | 1,118 | 3.546875 | 4 | class Solution:
def reverseString1(self, s):
# O(2N) time; O(N) space
# Append all characters to a stack; Pop them and add them to result
res = [] # EXTRA SPACE SOLUTION
l = len(s)
for i in range(l):
res.append(s.pop())
return res
def reve... |
20426eba9a85ee81eb6817942e50fe6f05652eb4 | SZTerminator/Unic-Word-finder | /Word_finder.py | 2,378 | 3.734375 | 4 | def clear_from_simbols(data):
import re
data = data.replace("-","_") # Спасаем дефисы для некоторых слов как "как-нибудь" или "fourty-five"
regex = re.compile('\W') # Хз зачем но без этого не работает
data = regex.sub(' ',data) # Собственно удаление спец. символов
data = data.replace("_","-")... |
c9d95a53a7d91e4b1b5e869087d44c05b0b26c85 | theprogrammer1/Random-Projects | /watercheck.py | 425 | 4.09375 | 4 | # Just a simple water check!:)
print("Welcome to WaterCheck")
goal = input("How much ml of water do you plan to drink today? ")
print("Come after a day and then enter how much you drank")
water = input("How much ml of water have you drank today? ")
if goal > water:
print("You have completed your goal")
if goal < wat... |
88179acc181529fde3c01de45ba26d0f0bb764d1 | actlienholding/ttrpy | /ttrpy/util/midpri.py | 930 | 3.953125 | 4 | # Author: joelowj
# License: Apache License, Version 2.0
import pandas as pd
def midpri(df, high, low, midpri, n):
"""
The Midprice returns the midpoint value from two different input fields. The
default indicator calculates the highest high and lowest low within the look
back period and averages the... |
a2acb8ad8dd2d999c86e84eaef6b23ab99cc3db1 | microease/Python-Tip-Note | /013ok.py | 457 | 3.75 | 4 | # 光棍们对1总是那么敏感,因此每年的11.11被戏称为光棍节。小Py光棍几十载,光棍自有光棍的快乐。让我们勇敢地面对光棍的身份吧,现在就证明自己:给你一个整数a,数出a在二进制表示下1的个数,并输出。
# 例如:a=7
# 则输出:3
# bin() 返回一个整数 int 或者长整数 long int 的二进制表示。
a = 7
n = 0
for i in bin(a):
if i == "1":
n += 1
print(n)
|
ec4e9797da063bee52346b31f5fbe680367d5e55 | alexandraback/datacollection | /solutions_2700486_0/Python/bigOnion/B.py | 3,245 | 3.546875 | 4 | directory = 'C:/users/hai/my projects/google code jam/2013/round1b/B/'
from decimal import Decimal
from fractions import Fraction
def factorial (n):
s = 1
for i in range(1,n+1):
s *= i
return s
def binomial (n,k):
if k > n:
print ('oh no!')
return 0
retu... |
8cab57cf42c0c43ee2d59c5f1201b60c4e40549b | huangyisan/lab | /python/jiechen.py | 285 | 3.578125 | 4 | from functools import reduce
from operator import mul,iadd
def fact(n):
return reduce(lambda x,y:x*y, range(1,n+1))
print(fact(10))
def factmul(n):
return reduce(mul, range(1, n+1))
print(factmul(10))
def addadd(n):
return reduce(iadd, range(1,n+1))
print(addadd(100)) |
582021fbdf2bb065bc4d8064f832fe97d52e4578 | mshsarker/PPP | /Turtle Graphics/66.py | 484 | 3.921875 | 4 | ## My solutions to the 150 Challenges by Nichola Lacey
## Get this wonderful book to know with the explanations and quick tips.
## 066 Draw an octagon that uses a different colour (randomly selected from a list of six possible colours) for each line.
import random
import turtle
turtle.pensize(3)
for i in range(... |
31626ec8578aadd9b28572bb25785dcd51b82771 | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise15_13.py | 373 | 3.921875 | 4 | def main():
s = input("Enter a string: ").strip()
print("The uppercase letters in " + s + " is " + str(countUppercase(s)))
def countUppercase(s):
return countUppercaseHelper(s, len(s) - 1)
def countUppercaseHelper(s, high):
if high < 0:
return 0
else:
return countUppercaseHelper(s,... |
def53c33a41fb92bac0462c756393b1ca2872e4c | Tquran/Python-Code-Samples | /M4P2BTQ.py | 307 | 4.25 | 4 | # Tamer Quran
# 7/29/2021
# This program prints each number and its square on a new line
# 12, 10, 32, 3, 66, 17, 42, 99, 20
myList = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in myList:
print(i ** 2)
# I squared each item on the list by using ** and the program did the rest by going down the list.
|
6f80d1132e651ae834415d6fec2432290c392828 | HIT-jixiyang/offer | /不用成分算等差数列.py | 322 | 3.734375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
self.s=0
self.add(n)
return self.s
def add(self,n):
self.s = self.s + n
return n > 0 and self.add(n - 1)
if __name__ == '__main__':
S=Solution()
print(S.Sum_Solution(5)... |
b4862baea3871ebb8a2240e5e1794627c936b42b | nikpil/Python-HW2 | /HW2_3.py | 785 | 4.125 | 4 | number = int(input("Введите неомер месяца: "))
if number <= 12 and number >= 1:
month_dict = {1: 'Зима',
2: 'Зима',
3: 'Весна',
4: 'Весна',
5: 'Весна',
6: 'Лето',
7: 'Лето',
8: 'Лето',
... |
afc2b21d9c431313e976515e2f07166498b947e5 | wangxiao4/programming | /Num9/_9_17_AnimationDemo.py | 993 | 3.734375 | 4 | from tkinter import *
class AnimationDemo:
def __init__(self):
window=Tk()
window.title("Animation demo")
width=250
height=150
canvas=Canvas(window,width=width,height=height)
self.testText_x=10
self.testText_y=10
testText=canvas.create_text(self.te... |
cdf3b373b7c30d16e6a1d424a638a74e3583e2f6 | ishtiaq2/python | /beginner/Bird.py | 353 | 3.84375 | 4 | class Bird(object):
def __init__(self):
print("Bird")
def whatIsThis(self):
print("This is bird which can not swim")
class Animal(Bird):
def __init__(self):
super(Bird,self).__init__()
print("Animal")
def whatIsThis(self):
print("THis is animal which can swim")... |
f30f2b63215fc092ed5d7edd92e11dddb154a618 | Aborigenius/python | /List Comprehensions/listComprehension.py | 140 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 16 16:48:27 2020
@author: spiridiv
"""
lst = []
lst=[x**3 for x in range(1,11)]
print(lst) |
4513cdbfe3703945e0ab9e023858b5705ca41635 | Djdev7/NewGame | /engine.py | 1,035 | 3.515625 | 4 | #The character starts in a dark room.He notices that he is strapped to a table.
#------------------------------------------------------------------------------#
#This is where i was place what needs to happen at this point
# 1. Opening scene
# 2. How to play
# 3. Look at surroundings
# 4. Descision tree
# 5. ... |
795941231f9bb1840957baeb164342d70dbd66b3 | godwinreigh/web-dev-things | /programming projects/python projects/tkinter practice/7. Build an Image Viewer App.py | 2,748 | 3.546875 | 4 | from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title("My simple image viewer")
root.iconbitmap('C:/Users/godwi/Downloads/myicons/Sbstnblnd-Plateau-Apps-image-viewer.ico')
#creating images
my_img1= ImageTk.PhotoImage(Image.open("C:/Users/godwi/Desktop/collected pictures from fb/reactions/angry_re... |
2b7bec056a4eaa735d35ae6cda1cbd7f8131d985 | leecheng28/COMP20008-2016S1 | /create-datafile.py | 2,111 | 3.609375 | 4 | # This Python file uses the following encoding: utf-8
# Data Pre-processing and Integration
# Author: Li Cheng. ID: 688819.
import csv
# Procedures for data pre-processing---
# Read data, from the business-count.csv file, in column C(CULE small area) and column X(Total establishments in block), to store the number o... |
5a7f7c23c8b0e9eb82f5f3b2d28852d51c9b12a2 | srikanthpragada/PYTHON_30_AUG_2021 | /demo/ds/common_chars_v2.py | 135 | 3.875 | 4 | st1 = "Abcdefde"
st2 = "dexyzd"
chars = []
for c in st1:
if c not in chars and c in st2:
print(c)
chars.append(c)
|
ec27ff8435a449f20aafc26496b6a3487456e4bc | dogbyt3/Data-Science-Projects | /Evolutionary Algorithms/pso.py | 8,497 | 3.796875 | 4 | """
* File: pso.py
* Purpose: This module contains the declaration and implementation of the
particle swarm optimization algorithm for knapsacks.
Example Use:
from pso.py import *
from knapsack_generator.py import *
# create a knapsack generator
... |
2f3b8d8b825a6d52272950cd0febba23e1b65c10 | kongzhidea/leetcode | /Palindrome Linked List.py | 1,306 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return T... |
62d6a28867972760988e7dd8140debce11c91647 | metinkanca/Lectures | /CNG111-IntroductionToComputerEngineeringConcepts/1-Assignment1/q8.py | 466 | 3.96875 | 4 | #$ python q8.py
n = int(raw_input("Enter> "))
i = 0.0
j = 1.0
print "Seeking the square root of {}".format(n)
while j*j < n:
j*=2.0
print "For j = {}, square of j exceeds {}".format(j, n)
g = 0.0
while True:
g = (i+j)/2
d = g*g-n
if d < 0:
d *= -1
if d < 0.001:
print "The square root ... |
c58f7314cc792a5a8adcfa535fe6b1c9143e8b62 | schmit/sheepherding | /sheepherding/ai/ai.py | 2,441 | 3.984375 | 4 | from ..world.location import Location
from learning import QLearner
class AI:
def __init__(self, learner):
self.learner = learner
self.rewards = []
self.actions = []
self.done = False
# keep track of which sheep are done
self.sheep_done = set([])
def setLearne... |
f6bbebecc87f42c17c540428e556938b4c289f97 | bran0144/mars-explorer-hackerank | /mars_explorer.py | 374 | 3.609375 | 4 | # Completed Hackerrank Mars Exploration
def marsExploration(s):
count = 0
n = 3
out = [(s[i:i+n]) for i in range(0, len(s), n)]
for sos in out:
if sos != "SOS":
if sos[0] != "S":
count +=1
if sos[1] != "O":
count +=1
if sos[... |
f68764f56102e25cc8cd5a58ff9cde21084f54b7 | annapeterson816/PythonPrograms | /Comp Sci Labs-2018/sierpinskiTriangle.py | 751 | 3.765625 | 4 | from Tkinter import *
def drawTriangle(p1,p2,p3):
the_canvas.create_polygon([p1,p2,p3], fill = 'blue', width=5)
def sierpinskiHelper ( n , p1, p2, p3 ) :
if n == 1 :
drawTriangle(p1, p2, p3)
else :
p4 = ((p1[0]+p2[0])/2,(p1[1]+p2[1])/2)
p5 = ((p2[0]+p3[0])/2,(p2[1]+p3[1])/2)
p6 = ((p... |
0a01138103efb14021b32168ecbe2af83a264873 | cuonghtran/mapreduce | /reducer.py | 966 | 3.515625 | 4 | #!/usr/bin/python
import sys
import collections
def main():
current_word = None
current_count = 0
word = None
top_counter = collections.Counter()
for line in sys.stdin:
# parse the input we got from mapper.py
word, count = line.strip().split('\t', 1)
# counting
t... |
5d4537eef6fb5723f830f374789092a822a680c3 | Threathounds/skripts | /single-char-xor.py | 1,725 | 3.96875 | 4 | #!/usr/bin/python3
# author: ide0x90
import sys
import re
if len(sys.argv) != 3:
sys.exit("Usage: single-char-xor.py <ciphertext_file> <keyword>")
# keyword is the plaintext we want to search for. Convert it to bytes
keyword = bytes(sys.argv[2], encoding="utf-8")
# create a regular expression matching pattern. T... |
7ad12f72a600be42492637dbfb301af022b23382 | Sharma30042000/DSA-_Solutions | /string/underscore.py | 665 | 3.8125 | 4 | def underscore(s,sub):
l=list(s.split(" "))
print(l)
ans=""
for i in l:
if len(i)<len(sub):
ans=ans+i+" "
if len(i)>len(sub):
if i[0:len(sub)]==sub and i[-len(sub):]!=sub:
ans=ans+"_"+sub+"_"+i[len(sub):]+" "
elif i[-len(sub):]==sub and... |
512d9b462d910b048bd30c1b2107210192256ec2 | corinnelhh/code_eval | /easy/sum_of_integers.py | 529 | 4.03125 | 4 | # https://www.codeeval.com/open_challenges/24/
# Sum of Integers from File
# Challenge Description:
# Print out the sum of integers read from a file.
# Input sample:
# The first argument to the program will be a path to a filename
# containing a positive integer, one per line. E.g.
# 5
# 12
# Output sample:
# Pri... |
ba1297e6d8923a0f1b72380adec983d5cb3aef95 | monilj/RestAPITestingUsingPython | /ReadNWriteToJsonFilesNParsingUsinPythonMethods/ParseJsonString.py | 308 | 3.5625 | 4 | import json
courses = '{"name":"Rahul", "languages": [ "Java","Python"]}'
dict_course = json.loads(courses)
print(type(dict_course))
print(dict_course)
print(dict_course['name'])
print(dict_course['languages'])
list_languages = dict_course['languages']
print(list_languages[0])
print(list_languages[1])
|
7040abcffe4c60a2e72c91527852b9d623dd416f | evozkio/Aprendiendo | /agenda.py | 957 | 3.84375 | 4 | agenda=[["adolfo","11"],["pepe","12"],["ana","13"],["maria","44"]]
hacer = input("Añadir un numero /Consultar numero (A/C)")
while hacer != "FIN":
if hacer == "A":
nombre = input("Nombre :")
telefono = input("Telefono :")
agenda.append([nombre,telefono])
elif hacer == "C":
consu... |
d1dd9f17d2b0d6aee646c1bc078e73319089a923 | chandrikakurla/inserting-node-at-the-end-of-the-linkedlist | /linkedlist inserting node at the end of list.py | 1,099 | 4.03125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def insert(self,Newnode):
if self.head is None:
self.head=Newnode
else:
lastnode=self.head
while Tru... |
9fe3cc21f79061d82bb9194b2cf1abcead6b7d38 | Christoph5782/CS4830---Hack-Week-Project | /Chat-Room/client.py | 5,184 | 3.5625 | 4 | #----------Christopher Foeller-----Lab 3-----5/1/19----------#
# Description: This is a simple chat room using a server and client
# made using socket. It supports login/logout, making a
# new account, and sending messages to all users in the
# chat room. You can also look up all of the commands by
# ... |
6d32aa8d35a7b4bbeb64084cdd491cb9e523f238 | Mishrak/DevelopLogic | /Language/Python/AreaOfTriangle.py | 204 | 3.96875 | 4 | l_base = float(input('Enter the base value of the triangle = '))
l_height = float(input('Enter the height value of the triangle = '))
l_area = 0.5 * l_base * l_height
print('Area of triangle = ', l_area)
|
b92f6247d6a881e6af1a9b5bf51a3c9ce7b5db46 | DesislavaDimitrova/HackBulgaria | /week0/2-Python-harder-problems-set /05.Reduce_file_path.py | 376 | 3.625 | 4 | #Rturning the reduced version of the path
def reduce_file_path(path):
path = path.replace('//', 'd/')
path = path.split('/')
for index in range (0, len(path)):
if "d" in path:
path.remove('d')
if ".." in path:
i = path.index('..')
path.remove('..')
path = path[:i-2] + path[i:]
if '.' in path:
... |
6e4f8a250ba650714d3db2244bf566358d848b74 | ksommerh94/MIT_Python | /exercise2/ps1b.py | 1,019 | 4 | 4 | import numpy
import pylab
from matplotlib import pylab
from pylab import *
# input variables
annual_salary=float(input("Enter your annual salary: "))
portion_saved=float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost=float(input("Enter the cost of your dream home: "))
semi_annual_raise=... |
2bba16e4235d64d56b5a18da1614d2299bbd18b4 | regnart-tech-club/programming-concepts | /course-2:combining-building-blocks/subject-4:all together now/topic-2:ETL/lesson-5.0:sum of squares puzzle.py | 268 | 3.640625 | 4 | # Using `map` and `reduce`,
# write a function or lambda, `sum_square`,
# that has one parameter, a list,
# and returns the sum of the squares of the elements of the list.
# For example, given the list [1, 2, 3], the function should return 14
# since 14 is 1 + 4 + 9.
|
e4bcf37656a7c7d208dea7645dcd724bb2ab38ed | kamit28/python-stuff | /src/com/amit/algo/sorting_algos.py | 1,447 | 4.09375 | 4 | #!/usr/bin/python
'''
partition method to find pivot.
to be used by quicksort
'''
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] < pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i + 1... |
58d3faab933a79ecdb91f8992a12a5ca356d92d0 | htietze/capstone_lab8 | /bitcoin.py | 1,711 | 3.6875 | 4 | import requests
def main():
bitcoins = get_bitcoin_amount()
bitcoin_rate = get_current_BTC_rate()
# if it successfully returned a bitcoin rate, then it'll convert and print, otherwise alerts the user to an issue.
if bitcoin_rate:
converted = convert_BTC_to_USD(bitcoins, bitcoin_rate)
pr... |
6ce691cf50d48836f4e45545c0fb2623cb7d8d0b | abboliwit/kompendietoliver | /kompendie/kompendie/kap.3/3.2.py | 397 | 4.0625 | 4 | male = ["erik","Lars","Karl","Anders","Johan"]
female = ["Maria","Anna","Margareta","Elisabeth","Eva"]
print(male[0],female[2],female[-1],male[1])# printar det första från men och tredje objektet från female sista från female och andra från male
male.pop(2)# tar bort ett namn
female.pop(0)
print(male)
print(fema... |
5c950b07317b5e0c5fbebecbc26f977947bc7ca3 | abocz/school-python | /cgi_script_web_form/loan_class.py | 1,068 | 3.765625 | 4 | class Loan(object):
# computes the remaining balance
def remainingBalance(self, month):
if month < 1:
raise ValueError("month must be positive")
elif month == 1:
return self.balance
else:
temp_bal = self.balance
return self.remainingBalance(month-1) + self.interestAccrued(month-1) - self.payment
# ... |
189eb4a19c0410ff4a7e58528a562ff14be3f06a | Rawkush/Python_Programs | /basics/5. Function.py | 538 | 3.59375 | 4 | # creating a function
def function_name():
"explainatory string ius wriiten here, it is smilar to comment" # it is optional
print("created the function and inside the function cui=rrently")
return
#global variable
age=17
def newFunction():
age=12 ## this age is local variable
print(age)
... |
79d137cb283148c64fd87e8b4d1c156cf5f8dff6 | piyushgairola/daily_code | /max_subarray.py | 195 | 3.5 | 4 | def maxSubarray(nums):
curr_sum = ans = nums[0]
n = len(nums)
for i in range(1,n):
curr_sum = max(curr_sum+nums[i], nums[i])
ans = max(ans, curr_sum)
return ans |
49d9ccee5280cc91bd9da3c9565ed613e1833aad | JCharlieDev/Python | /Python Programs/TkinterTut/TkinterHello.py | 262 | 4.09375 | 4 | from tkinter import *
# Mostly everything is a widget
# Main Window
root = Tk()
# Creating label widget
myLabel = Label(root, text = "Hello world")
# Putting it on the screen
myLabel.pack()
# Event loop, loops the application to stay open
root.mainloop() |
67b4bd22df3c1036af38a66f73b03e4a6e87dd26 | scalpelHD/Study_python | /课堂/8.4传递列表.py | 1,095 | 3.546875 | 4 | def greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg='Hello,'+name.title()+'!'
print(msg)
usernames=['jerry','lucy','megrite']
greet_users(usernames)
#在函数中修改列表
def print_models(unprintfed_designs,completed_models):
"""
模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移到列表complete... |
394a05ef47ccc494d517376a290af3bf6b1b700c | Orion3451/python_scripts_basicos | /examenes/0-examen_funciones_anidadas.py | 618 | 3.859375 | 4 | '''def division(num_uno, num_dos):
def validacion():
return num_uno > 0 and num_dos > 0
if validacion():
return num_uno / num_dos
else:
print ('No se puede dividir')
resultado = division(10,2)
print (resultado)'''
# APLICANDO CLOUSTER
def creando_funcion(num_uno, num_dos):
def v... |
58d6dbc6a6e35ee7a746994fe0e847feb575c24a | K-AlfredIwasaki/job_hunting_made_easy | /startup_db_recommendation/data_collection_preprocessing/company_from_title.py | 2,046 | 3.984375 | 4 | def get_company_from_title(title):
"""
algorithm to extract a company name to tech cruch article title
"""
import re
# remove "word word word: "
regex_intro = re.compile(r'\w+(\s+\w+)*\s*:\s')
title = re.sub(regex_intro, "", title)
# remove ", word word word,"
regex_middle = re.compile(r',\s.+,')
title = re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.