blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d1ea3b8565e4575d4661566da794357bbe93cf19 | Hardeep097/Learnig_Python | /cal_fibonacci_lru_cache.py | 545 | 4.34375 | 4 | '''
Find fibonacci sequence using recursion {lru_cache }
'''
from functools import lru_cache
@lru_cache(maxsize = 1000)
def fibonacci(n):
#check if input is integer
if type(n) != int:
raise TypeError("Value must be integer")
#check if Value is positive
if n < 1:
raise ValueError... |
0a3dd3aaeb057e1f9310404550f667c8da1391b5 | JerryHu1994/LeetCode-Practice | /Solutions/144-Binary-Tree-Preorder-Traversal/python.py | 1,212 | 4.0625 | 4 | # Recursive
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def helper(self, root):
if root == None: return
self.ret.append(root.val)
self.hel... |
5ae06914c1059b54dbd3b30fb1320a86a09f9228 | armstrong019/coding_n_project | /Jiuzhang_practice/design_hasmap.py | 1,862 | 4.1875 | 4 | # 最直接的解法
class MyHashMap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.container = [-1]*1000000
def put(self, key, value):
"""
value will always be non-negative.
:type key: int
:type value: int
:rtype: Non... |
4c457db9d7f0200bbbe76ff2dffa11afed465ccd | paula-mr/knapsack-problem-comparison | /branch_and_bound.py | 1,886 | 3.5 | 4 | from sort import sort_array
class Node:
def __init__(self, level, profit, weight, bound):
self.level = level
self.profit = profit
self.weight = weight
self.bound = bound
def solve_knapsack_branch_and_bound(weight, items):
items = sort_array(items)
n = len(items)
max_pr... |
8f6151562b5bf201dfe6e5e276fbdbd9167193f5 | agieson/Alex-s-Functions | /storezip.py | 909 | 4.125 | 4 | from zipfile import ZipFile
# Read the file to binary and return the binary
# file should be a single zip file opened in 'rb', which means "read binary"
def filetobinary(file):
"""
:param file: zipfile
:type file file
:return: bytes
"""
bin = file.read()
return bin
# Take the binary and ou... |
becc5165ca62e70199b7899e9e45f504bcb4b9b3 | samuelmutinda/leetcode-practice | /pathsum.py | 1,087 | 3.9375 | 4 | def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
re... |
b607bda023879fc0f77d791fb34b55d7de177dd7 | ivancheng111/Project-Euler-Python | /19 Counting Sundays.py | 2,532 | 4.21875 | 4 | """ Problem 19
Start: Sep/14/2021 12:15pm
Finished: Sep/14/2021 7:20pm
"""
def convert_date(date):
# convert "mm DD yyyy" to [mm, dd, yyyy]
day, month, year = date.split(" ")
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
return [int(day),MONTHS.index(mont... |
3f877c8897bec0adc6495bc223b82e5e0aaaa0fb | iguess1220/py | /class/定义.py | 646 | 4.1875 | 4 | # 创建对象必须先用对应的类
# class Dog: # 定义类,大驼峰命名,首字母大写
# """狗类"""
# def eat(self,arg):
# print("吃%s" % arg) #定义方法和函数类似,但是方法会自动添加第一个形参为self
# # 创建对象
# dog1 = Dog()
# dog2 = Dog()
# # 调用对象方法,不要传递self的实参
# dog1.eat("骨头")
# dog2.eat("肉")
# 属性和变量很类似
class Dog:
pass
# dog1 = Dog()
# # 对象的属性,首次赋值会定义
# dog1.na... |
a3012af7c2e52e31127f3f0d6aefcc1de6b2955a | ModestTheKnight/PythonLessons | /series.py | 221 | 3.671875 | 4 | def factor (x):
if x==0:
return 1
elif x==1:
return 1
else:
return x*factor(x-1)
def fibo (f=1):
if f==1:
return 0,1
else:
a,b = fibo (f-1)
return b,a+b
|
31851f6a0d39856b6801b47d25292a508b2ad27d | Aasthaengg/IBMdataset | /Python_codes/p03524/s918229787.py | 188 | 3.609375 | 4 | from collections import Counter
S = input()
dic = Counter(S)
if abs(dic['a']-dic['b']) > 1 or abs(dic['c']-dic['b']) > 1 or abs(dic['a']-dic['c']) > 1:
print('NO')
else:
print('YES') |
6184d1edad395ab189b894535d4449867c4263c3 | yasharne/Sierpinski-python | /draw_sierpinski.py | 1,039 | 3.84375 | 4 | __author__ = 'yashar'
import turtle
def sierpineski(points, n, t):
color = ['blue', 'red', 'green', 'white', 'GreenYellow', 'violet', 'orange', 'Maroon']
draw_triangle(points, color[n], t)
if n > 0:
sierpineski([points[0], midpoint(points[0], points[1]), midpoint(points[0], points[2])], n - 1, t)
... |
89600dd4b2e09161b16dc51e5d18b61adf47d85e | manuel1alvarez/Python-Problems | /reverse_list.py | 882 | 4.28125 | 4 | """
Write function that reverses a list, preferably in place.
"""
list1 =[1,2,3,4,5,]
list2 =[1,2,3,4,5,6,7,8]
list3 =['d','f','a','w']
def reverse_basic(list):
"""
parameters: list
creates a new list of equal size, traverses the given list in reverse adds these list items to rev_list.
returns: list.
"""
... |
ea5aca5ea29c4f231f5cc6b63512c3df47f638c1 | saka0045/Homework2 | /needleman_wunsch.py | 15,333 | 3.59375 | 4 | """
This script will apply either the Needleman-Wunsch or the anchored Needleman-Wunsch algorithm on a pair of sequences
Discussed homework with Jeannette Rustin
"""
__author__ = "Yuta Sakai"
import argparse
import os
import numpy as np
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
... |
b211307bafd1df8d10a054b7e66549f2bf0e55b6 | Mikayla-Barthelette-1/ICS3U-Unit3-06-Python-Even_Better_Number_Guessing_Game | /even_better_number_guessing_game.py | 1,019 | 4.3125 | 4 | #!/usr/bin/env python3
# Created by: Mikayla Barthelette
# Created on: Sept 2021
# This program creates an even better number guessing game
import random
def main():
# this function creates the game
# input
user_input = input("Enter the number between 0 - 9: ")
# process
random_number = random... |
f38ca1a878a77e7d0644d23b2022e6a051da196f | AndrewAct/DataCamp_Python | /Feature Engineering for Machine Learning in Python/2 Dealing with Messy Data/06_Filling_Continuous_Missing_Values.py | 1,701 | 4.28125 | 4 | # # 7/5/2020
# In the last lesson, you dealt with different methods of removing data missing values and filling in missing values with a fixed string. These approaches are valid in many cases, particularly when dealing with categorical columns but have limited use when working with continuous values. In these cases, it... |
1434bb4749162681a281333b0552be0615511ae8 | grimapatroy/Python_NETACAD | /Modulo5/resumen5.1.9.11/miParte5.1.9.11_5.1.11.11/5.1.11.1_emcriptandoMensajeCESAR.py | 2,275 | 3.71875 | 4 | # Cifrado César
# Te mostraremos cuatro programas simples para presentar algunos aspectos del procesamiento de
# cadenas en Python. Son intencionalmente simples, pero los problemas de laboratorio serán
# significativamente más complicados.
# El primer problema que queremos mostrarte se llama Cifrado César - más det... |
7c132850f9accb9e18f3f02c09248a3e5dbd6428 | geneilson1980/PythonCourse | /#108_Formatando_Moedas_em_Python.py | 486 | 3.796875 | 4 | # Adapte o código do desafio 107 criando uma função adicional chamada moeda() que consgia mostrar os valores como um valor monetário formatado.
import modulos.moeda
preco = float(input('Digite um preço: R$ '))
print(f'A metade de {modulos.moeda.moeda(preco)} é {modulos.moeda.diminuir(preco)}')
print(f'O dobro d... |
2443e1bd7d8fc8e6a1b7ec2e40e7ad36d6b7097c | leggers/python-data-structs-and-algos | /Data Structures/generator.py | 2,843 | 3.953125 | 4 | #!/usr/bin/python
# Author: Lucas Eggers
# Class for generating arbitrary data structures
from graph import *
import random
class Generator:
"""Class that generates various data structures."""
def graph_nb(self, nodes, branching):
"""Generates a random undirected graph with a number of edges
... |
548f7462fd28721d5c4a5aeaeafad27b02c547eb | hanwgyu/algorithm_problem_solving | /Leetcode/Group_Anagrams.py | 1,048 | 3.765625 | 4 | # Solution 1 : Use Hash after sorting string, Time : O(NMlogM), Space : O(NM) (N : number of strings, M : Maximum length of strings)
# Solution 2 : Use Hash . Set string that represents the number of strings as a key. Time : O(NM), Space :O(NM)
class Solution(object):
def groupAnagrams_2(self, strs):
a =... |
049c5723f27ddf9b71ad2bf773160e985de43e14 | smile0304/py_asyncio | /chapter11/progress_test.py | 1,233 | 3.828125 | 4 | #多进程
#耗cpu的操作,用多线程编程,对于io操作来说,用多线程
#1.对于耗费cpu的操作,多进程优于多线程
import time
from concurrent.futures import ThreadPoolExecutor,as_completed
# from concurrent.futures import ProcessPoolExecutor
# def fib(n):
# if n <= 2:
# return 1
# return fib(n-1)+fib(n-2)
#
# print(fib(3))
#
# if __name__ == "__main__":
# ... |
349b5f4a75656b209a0795fe260453ddd6b5871e | hudefeng719/uband-python-s1 | /homeworks/A10119/checkin03/Day5.py | 873 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Xiangwan
#lst是一个列表结构,用[]来囊括所有需要的变量或名单
#for语句是一个循环语句结构,可以用来调用lst的所有变量,在有很多数据要处理的时候会用到,比如名单、数据。
def main():
good1 = '大白菜'
good2 = '空心菜'
#............省略1001个
good100 = '蚌壳'
print '老妈看到了 %s '% (good1)
print '老妈看到了 %s '% (good2)
print '老妈看到了 %s '% (good100)
d... |
2441562678283c2ec4c49f1b1c3d707fd78154bc | gjq91459/mycourse | /03 More on Data Types/Dictionaries/02_accessing_dictionaries.py | 352 | 3.703125 | 4 | ############################################################
#
# dictionary
#
############################################################
empty = {}
months = {"Jan":1, "Feb":2, "May":5, "Dec":12}
seasons = {"Spring":("Mar","Apr","May"), "Summer":("Jun","Jul","Aug")}
print type(empty)
print months["Dec"... |
0cabbcd6774daba9879f5390e13b0add6066ae34 | noobt-tt/problems | /剑指offer/把二叉树打印成多行.py | 708 | 3.515625 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
# write code here
if not pRoot: return []
cur_level, res = [pRoot], []
... |
73225badbd5bfa90ae41819a9114ff91f8d6b310 | phucduongBKDN/100exercies | /100 exercise/no142.py | 258 | 3.953125 | 4 | #Palindrome Number
input = 12321
def reverse(s):
temp_list = list(s)
temp_list.reverse()
return ''.join(temp_list)
def palindromeNumber(input):
str = str(input)
if str == reverse(str):
return True
else:
return False
|
4a752672ade4991d320aaabda914f3ca57339645 | kartiktanksali/Coding_Questions | /stringUniqueness.py | 549 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 18 16:36:20 2019
@author: kartiktanksali
"""
#Check if all the characters of a string are unique
def StrUnique(string):
if len(string) > 256:
return "Not Unique"
else:
lst = [False] * 128
for i in range(len... |
af75c195e5c3f56e5b7b5fdab7405c1ea4bc5f12 | tuongviatruong/hangman.py | /hangman.py | 4,814 | 3.9375 | 4 | from random import choice
def choose_word():
"""randomizes a list of words"""
secret_words = ["postcard", "icecream", "pencil", "hike", "almond", "laptop", "travel", "picture", "island", "adventure", "balloon", "elephant", "computer", "water", "paper", "backpack"]
secret_word = choice(secret_words)
sec... |
e001acabc616a575a6f0c15c2c50f795940070dd | Mostofa-Najmus-Sakib/Applied-Algorithm | /Leetcode/Python Solutions/Strings/ValidParenthesisString.py | 1,914 | 3.625 | 4 | """
LeetCode Problem: 678. Valid Parenthesis String
Link: https://leetcode.com/problems/valid-parenthesis-string/
Written by: Mostofa Adib Shakib
Language: Python
Time Complexity: O(n)
Space Complexity: O(1)
"""
"""
Let diff be count of left parenthesis minus count of right parenthesis.
When we meet:
'(... |
57b21bf7900ce3ba4517844d7416b8e7092c0cbd | yz-/ut | /pdict/manip.py | 1,532 | 3.65625 | 4 | __author__ = 'thorwhalen'
def add_defaults(d, default_dict):
return dict(default_dict, **d)
def recursive_left_union(a, b):
b_copy = b.copy()
recursively_update_with(b_copy, a)
return b_copy
def recursively_update_with(a, b):
"""
Recursively updates a with b.
That is:
It works ... |
8a618ce299aa6d39fee29674d3b5c900f6ba6325 | owari-taro/python_algorithm | /algirthm_and_data_structure/chap8_algorithm_design/dp_pow.py | 1,120 | 3.5 | 4 | from functools import wraps
import time
from typing import Callable, Tuple, Dict
def elapsed_time(f: Callable):
@wraps
def wrapper(*args, **kargs):
st = time.time()
v = f(*args, **kargs)
print(f"{f.__name__} {time.time()-st}")
return v
return wrapper
@elapsed_time
def nor... |
7260a1704032ea1cf612f3d3474b4ca65aef0b6e | landryroni/urban-broccoli | /utils/counting.py | 275 | 3.609375 | 4 | # Some utilities for counting
def factorial(n):
result = 1
for i in range(1, n+1):
result = result * i
return result
def permutations(n, k):
return factorial(n) // factorial(n-k)
def combinations(n, k):
return permutations(n, k) // factorial(k) |
36363eeef3e8f1650d8a74eae79d2658f95bfbc6 | DHBuild002/automate-the-boring-stuff | /elif-tutorial-multiple-outcomes.py | 358 | 4.125 | 4 |
name = 'Bill'
age = 100
if name == 'Alice':
print('Hi Alice')
elif age < 12:
print('You are not Alice')
elif age > 2000:
print('Unlike you, Alice is not an undead Vampire!')
elif age > 100:
print('You are not Alice, grannie.')
print('Enter your name: ')
name = input()
if name:
print('Hi ' + name... |
6c87fb2c57e40246eb0f9c755efb1096a68f9e90 | ZedYeung/fresh_tomatoes | /item_class.py | 4,539 | 3.78125 | 4 | #! python3
"""Define classes which objects will be used to fill the fresh_tomatoes html.
There are four kinds of items -- movie, tv show, music video and book will be
displayed on fresh_tomatoes html. Accordingly, there are four kinds of class
that represent these items.
"""
import webbrowser
class Item():... |
98d57bed11d37f981eee5f1865fd34d53dece1a1 | AaronYXZ/PyFullStack | /MachineLearning/PythonImplementation/LogisticRegression/LogisticRegression.py | 2,421 | 3.59375 | 4 | import numpy as np
import math
from sklearn import datasets
def load_data():
# load iris data from sklearn.datasets
# return X as a n by 3 array and y as a binary (0,1) array
iris = datasets.load_iris()
X = iris.data[:, :2]
y = (iris.target != 0) * 1
np.random.seed(1)
np.random.shuffle(X)
... |
74c48f4ba132374c6052bb594cca3c15433acd9e | MKhurana07/Python_LeetCode | /Data Struct/Dbl_linkedList_reverse.py | 675 | 3.796875 | 4 | class Dbl_ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
self.prev = None
def reverse(head):
if not head:
return
curr = head
while curr:
temp = curr.prev
curr.prev = curr.next
curr.next = temp
curr... |
7fff33692bf4f4aad318681b76b177bb021f6637 | niko-vulic/sampleAPI | /leetcodeTester/q121.py | 1,311 | 4.125 | 4 | # 121. Best Time to Buy and Sell Stock
# You are given an array prices where prices[i] is the price of a given stock on the ith day.
# You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
# Return the maximum profit you can achieve f... |
364f85d3b7e7032a7c2936e9a74a858da88acbf4 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2292/60595/260527.py | 1,510 | 3.703125 | 4 | def max_search_tree(root):
if root is None:
return 0
max_topo_size = max_topo(root, root)
max_topo_size = max(max_topo_size, max_search_tree(root.left))
max_topo_size = max(max_topo_size, max_search_tree(root.right))
return max_topo_size
def max_topo(head, node):
if head is not None and... |
60fc00d4510c7dcb6b67de2ec1a84fcac9c5a0ec | peaky76/advent_of_code | /day_12/movement.py | 984 | 3.703125 | 4 | class Movement():
def __init__(self, eastwards, northwards):
self.eastwards = eastwards
self.northwards = northwards
@classmethod
def specify(cls, compass_code):
COMPASS = {'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0)}
return cls(*COMPASS[compass_cod... |
cdb428f7a1a42dcf95aa62b01889948dbcd84901 | bkoz/flexray | /code/Canvas.py | 1,493 | 3.65625 | 4 | from Color import Color
class Canvas:
def __init__(self, w, h):
self.width = w
self.height = h
self.pixels = []
self.clear(Color(0, 0, 0))
def __str__(self):
return "({0}, {1})".format(self.width, self.height)
def clear(self, c):
self.pixels.clear()
... |
854bd9c3a5c2510d0f498973675fcbfbb1012d9c | leandrotominay/pythonaprendizado | /aula16/ex1.py | 743 | 4.1875 | 4 | # Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso, de zero até vinte
# Seu programa deverá ler um numero pelo teclado (entre 0 a 20) e mostra-ló por extenso
numeros = {'1':'Um','2':'Dois','3':'Três','4':'Quatro','5':'Cinco','6':'Seis','7':'Sete','8':'Oito','9':'Nove','10':'Dez',... |
49d10f77b18bc7b321473e3f717cf7270d99d925 | yangyuxiang1996/leetcode | /剑指 Offer 48. 最长不含重复字符的子字符串.py | 2,055 | 3.578125 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-21 23:07:38
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-21 23:42:45
FilePath: /leetcode/剑指 Offer 48. 最长不含重复字符的子字符串.py
Description:
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
'''
class Solution(object):
def lengthOfLongestSubstring1(self, ... |
3461a8bf1a24b7b330224bdadc5866c16a175dc0 | gsrr/leetcode | /hackerrank/Dynamic Line Intersection.py | 3,070 | 3.5625 | 4 | #!/bin/python
#from __future__ import print_function
import os
import sys
import collections
#
# Complete the dynamicLineIntersection function below.
#
def dynamicLineIntersection1(n):
#
# Write your code here.
#
dic = collections.defaultdict(int)
all = 0
for _ in xrange(n):
line = ra... |
8a6643663863d8b3e53c9a314f0c688e7d2df139 | bulpil-abv/python-study | /examples/invert-array.py | 448 | 4.09375 | 4 | def invert_array(A: list, N: int):
"""
Invert the array A
in range from 0 to N-1
"""
B = [0] * N
for i in range(N):
B[i] = A[N-1- i]
for i in range(N):
A[i] = B[i]
def test_invert_array():
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1000]
invert_array(A, 10)
print(A)
... |
81b9be4e2f5bcf4a2450fb9d4696725f58952f4a | helenajuliakristinsdottir/Tile-Traveller | /Code listing/Code Listing 2.8.py | 559 | 3.796875 | 4 | #while lykkja
x_int=0 #ath alltaf að muna eftir upphafsskilyrðinu!!
while x_int < 10: #ath með tvípunkt
print(x_int, end=' ') # set end og tóman streng til að útkoman úr lykkjunni kemur allt í einni röð
#þá kemur þetta 0 1 2 3 4 5 6 7 8 9 í einni röð í staðin fyrir 10 línur með einu staki í
x_int= x_int ... |
a74cec3e73500b3e6f57e018fd1b2a5eb235b063 | BrendanArthurRing/code | /katas/almost-increasing-sequence-2.py | 1,855 | 3.9375 | 4 | def random_pop(array):
# Removes random element from array.
from random import randint
r = randint(0, len(array) - 1)
#print(f'Array: {array}')
array.pop(r)
#print(f'Array: {array}')
return array
def strictly_increasing(array):
# Checks if the array is strictily increasing.
if len(... |
24e29b35cbfddc136eb812a52019b07bcd14915f | eishk/Python-Soccer-Project | /transfers_scrape.py | 4,694 | 3.671875 | 4 | """
Eish Kapoor & Kunal Bhandarkar
CSE 163 AD
Final Project
This file contains the code that uses the BeautifulSoup library
to scrape the TransferMarkt database for the transfers that occurred
in the British Premier League. Includes transfers in and out, and scrapes
the player's name, position, market value, actual fe... |
4c066c090b14de02354d75468a9bdd4144a242ae | MapleStoryBoy/spider | /python_zero/01_Python基础/hm_09_格式化输出.py | 688 | 3.828125 | 4 | # 定义字符串变量 name,输出 我的名字叫 小明,请多多关照!
name = "大小明"
print("我的名字叫 %s,请多多关照!" % name)
# 定义整数变量 student_no,输出 我的学号是 000001
student_no = 100123456
print("我的学号是 %06d" % student_no)
# 定义小数 price、weight、money,
# 输出 苹果单价 9.00 元/斤,购买了 5.00 斤,需要支付 45.00 元
price = 8.5
weight = 7.5
money = price * weight
print("苹果单价 %.2f 元/斤,购买了 %.3f... |
233d56401f76402bddc612657676fc1ee179651e | AndreiSystem/python_aula | /mundo01/ex027.py | 358 | 3.9375 | 4 | """
Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida
o primeiro e o último nome separadamente
ex: Ana Maria de Souza
primeiro = Ana
último = Souza
"""
n = str(input('Digite seu nome completo: ').strip())
nome = n.split()
print(f"""Analisando o seu nome...
O seu Primeiro nome é {nome[0]}
O... |
3f31a646268c69ec280e021902f8a0a42110e250 | georgemirodelis112/Python | /Άσκηση 9.py | 1,263 | 3.6875 | 4 | def function(x):
myList=list(x)
a=len(myList)
b=1#arxikopio
n=0#metritis
while(a>1):
for i in range(a):
myList[i]=int(myList[i])#metasximatizo se akereo to string
for i in range(a):
b *=myList[i]#vasismeno stin methodo tou paragontikou
if(b>=... |
8514dd691915388b427d0126f9645e84bbbbda99 | kodewilliams/college | /Python/Intro to CS/second_largest_number.py | 883 | 3.84375 | 4 | def GetSecondLargestNumber(nums):
# Returns the second largest unique number in nums.
n = len(nums)
if n < 2:
return None
elif n == 2:
if nums[0] == nums[1]:
return None
else:
# Sort the list in descending order
for c in range(n-1):
... |
22d32ce94ce52852cd939a0c440f2291df11a3be | arvinj1/scmusage | /bin/csvopt.py | 756 | 3.5 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3
''' csv file outputs '''
import csv, json, sys
#if you are not using utf-8 files, remove the next line
#check if you pass the input file and output file
if sys.argv[1] is not None and sys.argv[2] is not None:
fileInput = sys.argv[1]
fileOutput = s... |
3e334332477a79c8ce202e545e053e92b17c6e0e | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/hrdtim002/question2.py | 476 | 4.125 | 4 | """check number of pairs of characters in a string
Tim Hardie
9 May 2014"""
def count_pairs (message):
global num_pairs
if len (message) > 1:
if (message[0] == message[1]):
num_pairs += 1
count_pairs (message[2:])
else:
count_pairs (message[1:])
... |
11bf9cf54ad1dd860de39a4cccad028ba5e66eab | tri2sing/LearningPython | /scope.py | 827 | 3.59375 | 4 | # f = scope.f1()
# f() works
# f = f1()
# f() does not work
# scope.f1()() works
# f1()() does not work
y, z = 1, 2
def f1():
x = 99
print (x)
def f2 ():
x = 88
print (x)
return f2
def all_global ():
global u
u = y + z
print (u)
def maker(n):
def action(k):
return k**n
return action
# f= maker(2)
#... |
e6fef8891014c69cde2cd32c024fbe4d102e3ee4 | Misk77/Python-Svenska-Gramas | /Python svenska - 8 - for loopen.py | 192 | 4.0625 | 4 | for i in range (5):
print(i)
print()
for i in range (1,7):
print (i)
print()
for letter in "Hello World":
print (letter)
print()
x=6
for i in range (11):
value = x*i
print(value)
|
388ac369dd0555df8e7386296dc020fb7f68f741 | brynpatel/Deck-of-cards | /black_jack.py | 2,323 | 3.65625 | 4 | from deck_of_cards import *
def check(card1, card2):
if card1.number == card2.number:
check = True
#Add special cards
elif card1.suit == card2.suit:
check = True
else:
check = False
return check
def turn(myCard, myHand, opponentsHand, deck):
cardplayed = False
w... |
ce8ff6d6f3d7cd0e74afee7b273b0b5136e83953 | fengsy868/HangmanSolver | /tree_generator.py | 3,520 | 4.09375 | 4 | #this programme generate a set of decision trees for Hangman according to all the English words
# I have used Python tree class implemented by Joowani https://github.com/joowani/binarytree
import pickle
from binarytree import tree, bst, convert, heap, Node, pprint
print 'Start reading the dictionary file...'
with ope... |
80f8bb99c5a8dd74d2ff5d547a6c25f1ae9c3a59 | Nimrod-Galor/selfpy | /hangman - 732.py | 1,483 | 3.921875 | 4 | secret_word = "mammals"
old_letters_guessed = []
def show_hidden_word(secret_word, old_letters_guessed):
"""
show user progress
:param secret_word the secret word user have to guess
:type string
:param old_letters_guessed list of the letters user have guessed
:type list
:return string of se... |
7638822d5ba9bcd679a679ff4a86f983aa40d441 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_203/420.py | 1,561 | 3.5 | 4 | # -*- coding: utf-8 -*-
import sys
import os
input_text_path = __file__.replace('.py', '.txt')
fd = os.open(input_text_path, os.O_RDONLY)
os.dup2(fd, sys.stdin.fileno())
T = int(input())
f = open('submit.txt', 'w')
for t in range(T):
R, C = map(int, input().split())
# データ
M = []
for r in range(R):... |
88e067ba658471774221e9726825ec37ff99adaf | 20050924/All-projects | /Assignment 8 Test scores.py | 580 | 3.859375 | 4 | #Michael Li
#Computers 10
#2021/6/7
#calculate test average test scores for each test and students average on diffrent tests
test = [[95,80],[93,82],[92,85],[81,86,]]
list = [1,2,3,4]
list2 = ["A","B"]
for i in range(len(test)):
test_average = 0
for j in range(2):
test_average +=(test[i][j])
print (... |
04b8fefa97b7680199524c8784a9913e8407f86e | YTRoBot/seekingAlphaCrawler | /learnSentimentAnalysis/natural-language-processor.py | 6,078 | 3.53125 | 4 | #!/usr/bin/python
import sys, getopt
from optparse import OptionParser
#import nltk
#from nltk.book import text1
from textblob import TextBlob
from textblob import Word
from textblob.wordnet import NOUN
import random
import sys
def main(argv):
#nltkTest()
textblobTest()
def textblobTest():
blob = TextBlo... |
967a989bffad0dbdaf4514f8ce96f816d6715d51 | aalund2013/cse210-project | /tank-wars/game/score.py | 1,783 | 3.859375 | 4 |
import random
from game.tanks import Tanks
class Score(Tanks):
"""Points earned. The responsibility of Score is to keep track of the player's points.
Stereotype:
Information Holder
Attributes:
_score (integer): The position of the score bar
set_text (Actor): Writes score
Contr... |
adf1a1f78877242faf027136912ef5bd6efa7c7f | zack4114/Amazon-Questions | /CountNumberOfBitsToConvertANumber.py | 400 | 4.09375 | 4 | # Given two numbers ‘a’ and b’. Write a program to count number of bits needed to be flipped to convert ‘a’ to ‘b’.
def countSetBits(number):
count = 0
while (number > 0):
if number & 1 == 1:
count += 1
number //= 2
return count
def bitsNeededToFlip(number1,number2):
return countSetBits(number1^number2)
n... |
9b7e1aeb6746a24b0154964c8ec2d6cd9f548a09 | chenyanqa/example_tests_one | /test_37.py | 1,136 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
'''
题目:对10个数进行排序。
程序分析:可以利用选择法,即从后9个比较过程中,选择一个最小的与第一个元素交换,下次类推,即用第二个元素与后8个进行比较,并进行交换。
'''
#方法1:利用序列本身的sort()方法
# list = [1, 4, 6, 7, 85, 33, 23, 8, 11, 99] #list中 数字加引号就变为了字符,不加 就表示变量或者数字
#
# list.sort()
#
# print(list)
#方法2:选择排序法, 将第一个元素与后面9元元素中选出的最小值 进行交换,然后第二个元素与后面8个... |
4fb872de9abb484d2c0fff1052bc95ad84c70399 | amen619/python-practise | /Week-3/09-factorials.py | 155 | 3.9375 | 4 | def factorial(n):
result = 1
for i in range(1,n+1):
result = i * result
return result
for n in range(1,10):
print(n, factorial(n)) |
b5640cb576fcde7327a05da04fdf2849d1351e76 | DedekindCuts/advent-of-code-2019 | /01/solution.py | 875 | 4.1875 | 4 | import math
def fuelCost(mass):
"""
function to calculate fuel cost for a given mass
"""
return (math.floor(mass / 3) - 2)
def trueFuelCost(mass):
"""
function to calculate fuel cost for a given mass after taking mass of fuel
into account
"""
total = 0
cost = mass
while True:
cost = max(... |
3995771e7632a200ce529910d7de78cf0ce44783 | yash3110/Python-Codewayy | /Python Task-4/Question-2/lists.py | 668 | 3.84375 | 4 | #TASK-4
#Question 2 (a)
#Function for square of a number
def squarefunc():
z=int(input("Enter the number, of which you want to calculate the square: "))
sq = z*z
print("\nThe square of the number is: ", sq)
#Function for min and max number in a list
def minAndMaxFunc():
#For minimum
minNum = createLi... |
247c489622e9466a97e41363c9d6adbbfa34237c | kendalvictor/codeando | /winner/ejer4_Villacorta.py | 1,974 | 3.78125 | 4 | #Victor Villacorta python 2.7
def impresion_ejer4(clock1,clock2,h,m):
if h>10 and m>10:
print'\nHora de inicio: {0}. Duracion: {1}. Hora de fin: {2}:{3}'.format(clock1,clock2,str(h),str(m))
elif h<10 and m>10:
print'\nHora de inicio: {0}. Duracion: {1}. Hora de fin: 0{2}:{3}'.format(clock1... |
f37ca67d08634c07906e915854b061fe2a1587a2 | claytonjwong/leetcode-py | /490_the_maze.py | 1,173 | 3.71875 | 4 | #
# 490. The Maze
#
# Q: https://leetcode.com/problems/the-maze/
# A: https://leetcode.com/problems/the-maze/discuss/806498/Javascript-Python3-C%2B%2B-DFS-solutions
#
from typing import List
class Solution:
def hasPath(self, A: List[List[int]], start: List[int], target: List[int]) -> bool:
seen = set()
... |
c3024557695b955646425e57fb6e04f5356cfef5 | randalpereiradesouza/PythonFound- | /exercicios/exercicio01.py | 1,395 | 4.1875 | 4 | # Criar uma aplicação de Calculo de média
# Entradas:
# nome do aluno
# n1 - nota número 01
# n2 - nota número 02
# n3 - nota número 03
# n4 - nota número 04
# Saída:
# Retornar a média do aluno no formato:
# Nome do aluno
# Nota final
# Retornar resultado do aluno:
# se... |
37edcfb8a8c519d1dfcef5014c4414fa3f8d7f8d | bradsbrown/euler | /001-3and5.py | 284 | 3.96875 | 4 | def listNums(max):
list = []
for x in range(0, max):
if x % 3 == 0 or x % 5 == 0:
list.append(x)
return list
def sumMults(max):
list = listNums(max)
total = 0
for item in list:
total += item
return total
print sumMults(1000)
|
7d3075da71bdb28b77fa1ebaa169d4a4722f576b | guhwanbae/GuLA | /gula/mat.py | 3,371 | 3.625 | 4 | # Author : Gu-hwan Bae
# Date : Sun Jan 28
# Summary : Modeling a matrix.
import gula.vec as gvec
import gula.util as gutil
class matrix:
"""
Modeling a matrix as python class. It has tuple, in constructor as label,
to represent indice of row and column domain. And matrix class represent
a entries... |
bf7b3dfa5218825914210337e0d9bf43c944efa1 | onlyhiphop/Python_learning | /数据提取/hm_11_gushiwen.py | 1,821 | 3.53125 | 4 | """
古诗文网的爬取:使用正则表达式爬取
"""
import requests
import re
def parse_url(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/64.0.3282.167 Safari/537.36'
}
resp = requests.get(url, headers=headers)
text = res... |
4cb6bd96278d44defc6829d6360b8a486d287574 | somrathumayan/numpy-practice | /array_filter.py | 1,250 | 3.796875 | 4 | import numpy as np
print("Create an array from the elements on index 0 and 2")
arr1 = np.array([41, 42, 43, 44])
x1 = arr1[[True, False, True, False]]
print(x1) # printed only true value ans: 41, 43
print("*******************************************************************")
print("Create a filter array that will ret... |
1846831a3e9fbcb418fd8ce923c2953794a7c5a2 | jeklen/todolist | /classmate.py | 1,335 | 3.703125 | 4 | class Classmate:
def __init__(self, name, num, tel, email):
self.name = name
self.num = num
self.tel = tel
self.email = email
def newName(self, name):
self.name = name
def newNum(self, num):
self.num = num
def newTel(self, tel):
self.tel = tel
... |
c930217a6247ba7bc3a1bb29db374fd72e27cc41 | willisman31/sweet-pear | /Alarm.py | 1,277 | 3.625 | 4 | import AMPM
class Alarm:
on = False
repeat = False
name = "Alarm"
def __init__(self, name: str, hour: int, minute: int, ampm: AMPM, repeat: bool):
self.name = name
self.hour = hour
self.minute = minute
self.ampm = ampm
self.on = True
sel... |
bd486d98298304aa9a39785f2f99828ec3e93fcf | Beffa-glitch/Repository1 | /intro.py | 111 | 3.640625 | 4 | number_list=[9,5,7,3,12]
somma = 0
for item in number_list:
somma+=item
print(somma)
print("BEFFA")
|
2c4c6000778afbfc1fc0aeef95a4554bc3bc9222 | vincentiroleh/python-learning-exercises | /challenge/challenge.py | 588 | 4.34375 | 4 | # Write a short program that prints one of several messages to the user based on their input.
# First, prompt the user about whether they want to continue or not.
# If the user responds with either no or n, print the phrase Exiting.
# Match the following output in this no scenario. The user entered no when prompted.... |
58f9c5fd4583b5139c38dac6a04c494aff581238 | renangfs/Python | /15.py | 310 | 3.65625 | 4 | qntkm = float(input("Digite o kilometro percorrido: "))
qntdias = float(input("Digite a quantidade de dias que ele foi alugado: "))
dias=qntdias*60
km=qntkm*0.15
print("O preço a pagar é a quantidade de {} dias mais {} quantidade de km rodados, totalizando em R$:{:.2f}".format(qntdias,qntkm,dias+km))
|
b58afc871d6a59175c5db612faaefa4e5bc98fae | 8basetech/gale-shapley | /data_match.py | 13,911 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from decimal import Decimal, ROUND_HALF_UP
import random
import copy
import matplotlib.pyplot as plt
import math
"""
Created on Sat Nov 24 16:42:54 2018
@author: hosokawaai
"""
# 初期変数
DAYS = 30
# 一日あたりの最低選考リスト人数
DAILY_MIN_MEN_NUM = 2
DAILY_MIN_WOMEN_NUM = 2
# 一日あたりの最高選考リ... |
b0f57c5edbd6658de5fe03181a5070478054087d | oujii/ITsecurity | /ifsnstuff.py | 108 | 3.78125 | 4 | x = input()
if int(x) > 10:
print("Japp de e greater than 10")
else:
print(x + " är lägre än 10") |
74ed493db97bb1f9887f164849daee5ca8c88153 | gasparzds/trabalhodaforca | /modulos/entrada_de_informacao/input_usuario.py | 4,944 | 3.9375 | 4 | def solicitando_nome():
while True:
usuario = input('\033[1;30mDigite seu nome: ')
if usuario.isnumeric():
print('\033[1;31mSeu nome não pode ser números')
print('\033[1;31mTente novamente')
elif len(usuario) <= 1:
print('\033[1;31mSeu nome não pode ser ap... |
e2bf59dd88a1bfc2a5cae2eb476856f462060bbe | fafusha/perceptron | /PerceptronTraining1.py | 3,327 | 3.671875 | 4 | import numpy as np
import matplotlib.pyplot as plt
def training_matrix(n, lbound, ubound):
'''Gerates a training matrix for a two input function
Parameters:
n: number if entries
lbound: lower bound of a matrix entry
ubound: upper bound of a matrix entry
Returns:
out: gene... |
b99f8370fccb56835fe5cb64130af15df051a697 | Sanmarri/HomeWorks | /Homework_1_lesson/GB05.py | 1,617 | 4.3125 | 4 | # Запросите у пользователя значения выручки и издержек фирмы.
# Определите, с каким финансовым результатом работает фирма
# (прибыль — выручка больше издержек, или убыток — издержки больше выручки).
# Выведите соответствующее сообщение.
# Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение п... |
c5dc32ecd4d815056ed0aa3bcc7125a1e81c83a7 | LennertVdS/Thesis-Machine-Learning-In-Finance | /Python_Code/scr/basic_regression_code.py | 650 | 3.71875 | 4 | import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
"""
This code executes a basic polynomial regression
"""
class basicregression:
def __init__(self,X_train, y_train):
self.X_train = X_train
self.y_train = y_train
def pr... |
2c231178f7ba4a98711a1f7ceff43cd858b4d316 | happywyz/data-science-is-software | /src/preprocess/build_features.py | 664 | 3.828125 | 4 | import numpy as np
import pandas as pd
def remove_invalid_data(path):
""" Takes a path to a water pumps csv, loads in pandas, removes
invalid columns and returns the dataframe.
"""
df = pd.read_csv(path, index_col=0)
invalid_values = {
'amount_tsh': {0: np.nan},
'longitude': {... |
6ce7def0005b24fae7e5d869ba90396a7372581f | SarthakU/DailyProgrammer | /Python/Daily149_easy/DisemVowerler.py | 427 | 3.703125 | 4 | ## DISEMVOWELER
##
## challenge #149 (easy)
## http://www.reddit.com/r/dailyprogrammer/comments/1ystvb/022414_challenge_149_easy_disemvoweler/
##
##
## sarthak7u@gmail.com
##
def disemvoweler(text):
vowels = ['a', 'e', 'i', 'o', 'u']
no_vowels, only_vowels = "", ""
for i in text.replace(" ", ""):
i... |
e520e365c3f58f0bb63ded3188393626772c2207 | tcano2003/ucsc-python-for-programmers | /code/lab_14_Magic/welcomer_def.py | 1,555 | 4.09375 | 4 | #!/usr/bin/env python
"""
Another inheritance example, using the previous examples
by importing the old code. This one implements __call__,
__str__, and __del__ and a class attribute."""
import sys, os
sys.path.insert(0, os.path.join(os.path.split(__file__)[0], ".."))
import lab_13_OOP.lab13_3 as employee_def
imp... |
f863aab285d7abf059a3e5ffc10880e02088dbb5 | juanpabloalfonzo/PHY224 | /CompAssign2/CompAssign2.py | 5,399 | 3.75 | 4 | #Juan Pablo Alfonzo
#1003915132
#Comp Assigment 2: Curve Fitting
#Importing needed libraries
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
from scipy.optimize import curve_fit
#Question 1: Reading and Plotting Data
#Importing data for rocket data
r=np.loadtxt('rocket.txt')... |
bb4582c0426f7f0d5b4da85ece5207463ae78d00 | savithri3317/Hybrid-encryption | /GUI/Encoding.py | 983 | 4.34375 | 4 | #my_str = "hello world"
#my_str_as_bytes = str.encode(my_str)
#print(type(my_str_as_bytes) )# ensure it is byte representation
#my_decoded_str = my_str_as_bytes.decode()
#type(my_decoded_str) # ensure it is string representation
#print(my_str_as_bytes)
#print(ord("b"))#ASCII(only character) - ord function
#print(ord("... |
7b01816ce4f571a55854124607f1abe7e8845e82 | jlzhang511/Algorithmic-Toolbox-Coursera | /week4_divide_and_conquer/5_organizing_a_lottery/points_and_segments.py | 3,966 | 3.640625 | 4 | # Uses python3
import sys
import random
def fast_count_segments(starts, ends, points):
cnt = [0] * len(points)
# write your code here
return cnt
def naive_count_segments(starts, ends, points):
cnt = [0] * len(points)
for i in range(len(points)):
for j in range(len(starts)):
i... |
6dea1ce89888072a289d89b8b876d236ffdd44db | MarioDuval/UF2_UF3-Python | /sections.py | 1,517 | 3.796875 | 4 | import pandas #importa la biblioteca pandas
def section1(): #funció per fer la primera opció que si lo dona al usuari que es per mostrar tots el registres
try:
df = pandas.read_csv('C:/Users/mario/PycharmProjects/UF2_UF3-Python/grades.csv') #funció per llegir el fitxer
print(df) #e... |
ba4ae66e5c80e5cd804963e3339a933727e14e1f | everbird/leetcode-py | /2022/huahua_572_Subtree_of_Another_Tree.py | 690 | 3.875 | 4 | #!/usr/bin/env python3
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
r1 = []
preorder(subRoot, r1)
if not root:
return len(r1) == 0
s = [root]
while s:
n = s.pop()
r2 = []
... |
c308c546af049e846325a7c6aa0fde446489afb8 | anggadarkprince/learn-python | /operator/ifelse.py | 159 | 3.9375 | 4 | # simple if else
print("Enter test score: ")
score = int(raw_input())
minimum = 75
if score >= minimum:
print('You passed')
else:
print('You failed')
|
5a25df6c4ee29a0c847438f1a6fc249371232466 | PaisalFatel/python_week | /loop2.py | 95 | 3.734375 | 4 | A=1
B=float(input("Enter a number my friend: "))
while A<=20:
print(A,"x",B,"=",(A*B))
A=A+1
|
17ee2c7f867e5ebef3d2f222ee1f81d16e575c31 | LukaHenriique/Python | /ClasseIntercaoObjeto/clasesNumerosRandomicos.py | 807 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 30 17:45:08 2020
@author: Lucas
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 30 12:23:36 2020
@author: Lucas
"""
import random as rd
lista =[]
class Cauculos():
def __init__(self, lista):
self.lista = lista
def soma(self):
print("somator... |
c7072186ad0f7eb0bc785856d24a59b743ab37ab | jadonk/LEDscape | /walk_pixel.py | 848 | 3.515625 | 4 | #!/usr/bin/python
# Draw images with PIL and send them to the display.
# Dual scrolling example with fixed time on each side and
# the date scrolling around.
#
import Image, ImageFont, ImageDraw
import socket
import time, datetime
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
dest = ("localhost", 9999)
#pri... |
1cebf0e0626a9e832423c9baa10c7638239e22c3 | greatming/datastructure | /maopaosort.py | 316 | 3.609375 | 4 |
def main():
data = [2,6,3,1,8,6,0,4]
ret = []
for i in range(0,len(data)):
for j in range(i+1, len(data)):
if data[j] < data[i]:
tmp = data[i]
data[i] = data[j]
data[j] = tmp
print(data)
if __name__ == "__main__":
main() |
e766d68056163bed1040f7a9581c93bac48d9561 | datafined/homework_gb | /lesson_4/task_3.py | 350 | 4.21875 | 4 | # Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21.
# Необходимо решить задание в одну строку.
# Подсказка: использовать функцию range() и генератор.
print([x for x in range(20, 241) if not x % 20 or not x % 21])
|
091e9e9b082f74e0b76afdff7f4d8a07eb6f2381 | poncheeto/PY4E | /exercise_3_3.py | 654 | 4.25 | 4 | # Write a program to prompt for a score between 0.0 and1.0. If the score is out of range, print an error message. If the score is between 0.0 and 1.0, print a grade using the following table:
# >= 0.9A >= 0.8B >= 0.7C >= 0.6D < 0.6F
try :
grade = float(input('Enter your grade: '))
if grade >= 0.0 and grade... |
af7824493967b17ab8c74504fe98387048b516f9 | raftera/HW3 | /leap_year_error_handle.py | 472 | 4.21875 | 4 | while True:
try:
year = int(input("Enter a number to determine if it was a leap year. "))
except ValueError:
print("Invalid input. Please enter an integer.")
continue
else:
break
switch = 1
if year % 4 == 0:
if year % 100 == 0:
if year % 400 != 0:
... |
e8a7a192e3e65b92cc62d973926857424700d441 | enigdata/coding-drills | /Binary Search/sqrt_x.py | 695 | 4.25 | 4 | '''
Implement int sqrt(int x)
Example 1:
Input: 0
Output: 0
Example 2:
Input: 3
Output: 1
Explanation:
return the largest integer y that y*y <= x.
Example 3:
Input: 4
Output: 2
'''
class Solution():
def sqrt_x(self, x):
if x == 0:
return 0
left, right = 0, x//2 + 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.