blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d951942fc4b24f11d03fc1c7bbfce6e22125c9c8 | deepkumar6376/CityEnergyAnalyst | /cea/analysis/sensitivity/sensitivity_demand_samples.py | 8,732 | 3.625 | 4 | """
Create a list of samples in a specified folder as input for the demand sensitivity analysis.
This script creates:
- a samples folder with the files `samples.npy` and `problem.pickle` to be used by the scripts
`sensitivity_demand_count.py`, `sensitivity_demand_simulate.py` and `sensitivity_demand_analyze.py`.
T... |
a412529ee52d3938c4f71ac94cc0b53875e0e38b | tachyon777/PAST | /PAST_1/C.py | 220 | 3.578125 | 4 | #第一回 アルゴリズム実技検定
#C
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
lst1 = list(map(int,readline().split()))
lst1.sort(reverse=True)
print(lst1[2])
|
d42a78a6bab647b3da62c282bdbacb9a6164d028 | fazozela/Ejemplo-Proyecto-Final | /Citas.py | 1,013 | 3.796875 | 4 | class Persona:
def __init__(self, nombre):
self.nombre = nombre
def saludar(self):
print(f"Hola soy {self.nombre}")
class Doctor(Persona):
def saludoDoctor(self, especialidad):
print(f"Hola soy {self.nombre}, voy a ser tu doctor de cabecera, y mi especialidad es {especialidad}")
e... |
d9ee2506d5e6b0c0418e86b73e8755515602d9ca | mayankmahajan/datavalidation | /learnPython/prime.py | 476 | 4.0625 | 4 | def getDivisors(num):
a = []
for i in range(1,(num/2)+1):
if num % i ==0:
a.append(i)
a.append(num)
return a
def checkPrime(num,divisors):
print str(num) + ' is prime' if len(divisors) <= 2 else str(num) + ' is not prime'
if __name__ == '__main__':
num = 0
while True:
... |
d332b605caba4b7a4ef3245aa66cb2f787042763 | bayramcicek/language-repo | /p048_special_sequences.py | 2,565 | 4.625 | 5 | #!/usr/bin/python3.6
# created by cicek on 13.09.2018 15:07
'''
There are various special sequences you can use in regular expressions. They are written as a backslash followed by another character.
One useful special sequence is a backslash and a number between 1 and 99, e.g., \1 or \17. This matches the expression o... |
3079f6d8b88de75dced9c2afc8903405a66c0110 | RashikAnsar/everyday_coding | /python_exercises/basics/6_sets.py | 1,313 | 3.734375 | 4 | languages = {'c', 'java', 'python'}
print(languages)
# Add another language `typescript` to the languages set
languages.add('typescript')
print(languages)
# Add more than one language at a time to languages set
languages.update(['javascript', 'dart', 'go', 'rust'])
print(languages)
# remove a language 'dart' from la... |
9bdae96cfffa4f0e96b4715f17ff8f1da4d3422a | RanchoCooper/HackerRank | /Python/strings/capitalize.py | 284 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author : Rancho Cooper
# @date : 2016-11-24 23:10
# @email : ranchocooper@gmail.com
string = input()
for word in string.split():
string = string.replace(word, word.capitalize())
# print(input().title())
# wrong-input:
# 12sdf --> 12Sdf
|
edfb334757ad95d7dd372ffeb43f64d0e8cce54d | PoelsDev/Quetzal | /ADTs/TwoThree/TwoThreeTree.py | 61,708 | 3.84375 | 4 | from copy import deepcopy
class Node:
def __init__(self):
self.root = []
self.parent = None
self.left = None
self.left2 = None
self.mid = None
self.right2 = None
self.right = None
def find(self, key):
if len(self.root) == 1:
if self.r... |
0ba870e083610baf28c87fc3e15feea986797ce9 | jocelynthiojaya/ITP_Assignments | /Kulkas.py | 6,933 | 4.25 | 4 | #Kulkas
endprogram = False
topshelf = {}
midshelf = {}
botshelf = {}
fridge = [topshelf, midshelf, botshelf]
topspace = 20
midspace = 20
botspace = 20
class foodItems():
name: str
volume: int
def __init__(self, name = '', volume = 0):
self.name = name
self.volume = volume
... |
188c344ff0db03b18222fa1a76758c20baf9e5cf | sreshna10/assignments | /L9-set of operations.py | 1,001 | 4.4375 | 4 | # set of operators allowed in expression
Operators=set(['','-','+','%','/','*'])
def evaluate_postfix(expression):
# empty stack for storing numbers
stack=[]
for i in expression:
if i not in Operators:
stack.append(i) #This will contain numbers
else:
a=stack... |
48749361898325ad04a6813b12eedf79039a75dd | zzz686970/leetcode-2018 | /606_tree2str.py | 1,064 | 3.828125 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
if not t: return ""
stack = [t]
result = ""
while ... |
bacaa1de8c0126aa6c2b3b3a077c49bd9f7992be | shuheeeei/cracking-the-coding-interview | /4_binary_tree/4-4.py | 1,764 | 4.125 | 4 | """
平衡チェック:
二分木が平衡かどうかを調べる関数を実装してください。
平衡木とは、すべてのノードが持つ2つの部分木について、高さの差が1以下であるような木であると定義します
"""
import unittest
from collections import defaultdict
from linked_list import LinkedList
from tree import Node
class NewNode(Node):
def has_child(self):
return self.left or self.right
def is_equilibrium(binary... |
5f6110c2fae887c3fa362a1ebfd19e2a33662030 | hyunro19/Algorithm | /src/py/pg/prbm_sort/BiggestNum.py | 1,007 | 3.65625 | 4 | from functools import cmp_to_key
def compare(x, y):
if str(x)+str(y) > str(y)+str(x) :
return 1
else :
return -1
# elif str(x)+str(y) < str(y)+str(x) :
# return -1
# else :
# return 0
def solution(numbers):
numbers.sort(key=cmp_to_key(compare), reverse=True)
an... |
5c20ab59088eac4df99d8dc7e1a6193026882cb5 | gozdekurtulmus/mineSweeperBoard | /mineField.py | 1,990 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 26 22:01:52 2020
@author: HP
"""
import random
def isBomb(myArray,a,b):
if ( myArray[a][b] == "#"):
return True
return False
def letsCheck(myArray,a,b):
c=0
if (myArray[a][b] != "#"):
if ( a!=0 ):
... |
4a98ce5df9307452051371c43b1b25dfef873d71 | christos-dimizas/Python-for-Data-Science-and-Machine-Learning | /pythonDataVisualization/Seaborn/distributionPlots.py | 3,830 | 3.609375 | 4 | import matplotlib.pyplot as plt
import seaborn as sns
tips = sns.load_dataset('tips')
# ------------------------------------------------------------ #
# ------ Distribution Plots ------ #
# Let's discuss some plots that allow us to
# visualize the distribution of a data set. These plots are:
# - ... |
3d88a6b006a6a8d3fe05708b475030c3c559ac8f | BitPunchZ/Leetcode-in-python-50-Algorithms-Coding-Interview-Questions | /Interview Questions solutions/Binary Tree Level Order Traversal/index.py | 817 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
ans = []
if(root is None):
... |
3dd95ed9e603029c49562eaa7f7bcdbb51f06467 | daniel10012/training | /03_more_datatypes/2_lists/03_11_split.py | 407 | 4.4375 | 4 | '''
Write a script that takes in a string from the user. Using the split() method,
create a list of all the words in the string and print the word with the most
occurrences.
'''
string = input("input a string")
words_list = string.split()
occurences = {}
for word in words_list:
occurences[word] = words_list.coun... |
c46642d17570f1e397853825e7b433af1f100287 | NareshBairam/6.00.1x | /Week2/pset2p3.py | 1,479 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 2 17:43:57 2017
@author: naresh
"""
#balance = 4773
#annualInterestRate = 0.2
#Monthly_interest_rate = (annualInterestRate) / 12.0
#Monthly_payment_lower_bound = balance / 12
#Monthly_payment_upper_bound = (balance * (1 + Monthly_interest_rate)**... |
68fd9312c021e1a6ba57cfb0d8c06ea37f98bb6b | XWran/yida | /dict/1.py | 108 | 3.765625 | 4 | a = {"fir":"1", "sec":"2"}
for key in a.keys():
print key, a[key]
for key in a:
print key, a[key]
|
8a6832e2fdb9e29b44697188245c1ab41dc43f0c | xanxerus/UVa-Problems | /UVa 10006 - Carmichael Numbers/Main.py | 319 | 3.875 | 4 | #!/usr/bin/env python3
def isCarmichael(n):
return n in {561, 1105, 1729, 2465, 2821, 6601, 8911, 10585, 15841, 29341, 41041, 46657, 52633, 62745, 63973}
while True:
q = int(input())
if q == 0:
break
if isCarmichael(q):
print("The number %d is a Carmichael number." % q)
else:
print("%d is normal." % q)
|
a6623d594a01169d46d97bbbcf1c9bc6b87f3dcd | eaniyom/python-challenge-solutions | /Aniyom Ebenezer/Phase 2/STRINGS/Day_29_Challenge_Solution/Question 3 Solution.py | 517 | 4.21875 | 4 | """
Write a Python program to get a string made of the first 2 and last 2 chars from a given string.
If the string length is less than 2, return instead of the empty string
Sample String: 'codedladies'
Expected Result: 'coes'
Sample String: 'co'
Expected Result: 'coco'
Sample String: 'c'
Expected Result: Empty string
... |
51c4bbe17ca54f9232f1643c441a5bc630975f67 | marcw1/Project | /AbstractPlayer.py | 423 | 3.703125 | 4 | from Board import Board
from abc import ABC, abstractmethod
class AbstractPlayer(ABC):
def __init__(self, colour):
self.colour = colour
self.board = Board()
# returns an action (placement or movement)
@abstractmethod
def action(self, turns):
pass
# updates t... |
459adab63044ab46c02caea1c00d6847135a2273 | wanxu2019/PythonPractice | /sword_to_offer/implementStack.py | 2,283 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/6/22 4:47
# @Author : Json Wan
# @Description :
# @File : implementStack.py
# @Place : dormitory
'''
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
思路:压栈时检查是否为最小值,弹栈时若将最小值弹出去了则重新计算最小值;
最佳思路:维持一个栈与一个最小值栈,弹栈时若把最小值弹出去了则还有后面的次小值顶上,不用重新算,用空间换时间。
... |
0f9ee4251f4b6cd11d176c670e35c63e47f264e7 | anzunming/pythonCode | /4-1.py | 797 | 3.921875 | 4 | #!/usr/bin
# encoding=utf-8
# 一个简单的数据库
# 将一个人名用作键的字典,每一个人都用一个字典表示
# 字典包含phone和address他们分别与电话号码和地址相联
people={
'Alic':{
'phone':'17716632963',
'address':'fjkdhk vkjdsvk'
},
'Bobu':{
'phone':'255825',
'address':'vnm sjvcs'
}
}
# 电话和地址描述性标签,供打印输出是使用
labels={
'phone':'pho... |
d5a9d67936b0128ae5a74bea5a82be738537b224 | chinmairam/Python | /list_mul1.py | 365 | 3.625 | 4 | ##n = int(input())
##for i in range(n):
## N = input()
## for i in range(int(N)):
## arr = input().split()[:int(N)]
## product = 1
## for num in arr:
## product *= int(num)
## print(product)
##
for x in range(int(input())):
_ = input()
mul = 1
for y in input().s... |
cff8ab9659c5517511cb0191986f4c411ab4a477 | sethau/Short_Programs | /Practice/HammingList.py | 1,849 | 4.25 | 4 | #This program calculates the Hamming Distance of each pair of binary strings.
#Two methods of doing this have been implemented:
#one through string interpretation, and the other through arithmetic analysis
#converts binary string to int
def valueOf(str):
n = 0
value = 1
i = len(str) - 1
while i >= 0:
... |
de6e1ffbd868f2e0f4a7f01a433d55c4ee6f532e | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/Selection_sort.py | 271 | 3.78125 | 4 | def selectionSort(array):
n = len(array)
for i in range(n):
minimum = i
for j in range(i+1, n):
if (array[j] < array[minimum]):
minimum = j
temp = array[i]
array[i] = array[minimum]
array[minimum] = temp
return array |
a8791d159472e684d5fe1b784b93063fd69b3ba7 | Dormanus/python | /jour_1/juste_prix.py | 437 | 3.921875 | 4 | import random
number = random.randint(1, 10)
print("Votre nombre:\n")
player = input()
score = 1000
while int(player) != number:
if int(player) < number:
print("Le nombre à trouver est plus grand")
score -= 5
elif int(player) > number:
print("Le nombre à trouver est plus ... |
6ec803bfaecfbe47f7fe64dda7567ee7de0d0ff4 | hector-han/leetcode | /binary_search/prob0240.py | 2,467 | 3.578125 | 4 | """
搜索二维矩阵 II
medium
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
"""
class Solution:
def searchMatrix(self, matrix, target):
"""
类似于二分查找,把矩阵分成4块
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
def ... |
58feafa09bf7206fdb31ea0b6e386c2f3a10ef2e | Python-aryan/Hacktoberfest2020 | /Random number generator.py | 3,672 | 3.875 | 4 | import random
choice = input('enter your choice H OR T \n ')
x= random.choice('TH')
print ('the toss is ', x)
sum = 0
m = 0
s = 0
m1 = 0
s1 = 0
if choice is x:
print('you won the toss')
while sum <100:
print('its your choice')
m = int(input('enter the no between 1 and 9\t'))
if m <= 100-... |
503ef5b934e28dd4e55162902cc8d7781dd51475 | imgeekabhi/HackerRank | /python/validating-the-phone-number.py | 185 | 3.515625 | 4 | import re
n = int(input().strip())
for _ in range(n):
tel = input().strip()
pattern = '^[789][0-9]{9}$'
print("{}".format("YES" if bool(re.match(pattern, tel)) else "NO")) |
e99d9d3e492fe8dd10e335f5b8c03a66ee804e56 | daniel-reich/ubiquitous-fiesta | /dZhxErwMfyWymXbPN_14.py | 124 | 3.5625 | 4 |
def hangman(phrase, lst):
return ''.join(x if x.lower() in ''.join(lst)+' ,.!' or x.isdigit() else '-' for x in phrase)
|
ca0c84528da9bcaaf0cc16e3de1240c126246e8e | Gereks123/prog_alused- | /1/Kontrolltöö_katse3.py | 1,473 | 3.546875 | 4 | from random import *
sammud = []
def Kilomeetrid(sammud, sammud_meeter):
kilomeetrite_arv = (sammud * sammud_meeter) / 1000
return(kilomeetrite_arv)
sammud_meeter = (input("Sisestage sammude pikkus meetrites: "))
for i in range(7): #tsükkel, mis lisab suvalist 7 arvu vastavas vahemikus
s... |
80a074ef8ae4b15c998d2f541d66531edaeaa1a5 | Ukabix/python-basic | /core ideas/objects/math sqroot.py | 144 | 3.625 | 4 | print ("Oto prosty program do potęgowania.")
while True:
print("Proszę podać liczbę.")
x = input()
a = int(x)
print(a*a)
|
a32a9fb5bdf0c102bc38454e4893c1761bddac89 | srath2014/Python_Practice | /NareshExamples/SmallestDivisor.py | 228 | 4.09375 | 4 | # Wap to find the smallest divisor of any given number.
n= int(input("Enter the given number to be tested"))
a =[]
for i in range(2,n+1):
if(n%i == 0):
a.append(i)
a.sort()
print("Smallest divisor of n is",a[0]) |
d535dd4582f7b57c6192b2902105dd4b2c95edb1 | marswierzbicki/corposnake | /classes/benefit.py | 709 | 3.671875 | 4 | from pygame.sprite import Sprite
class Benefit(Sprite):
"""A single Benefit stored by object Benefits"""
def __init__(self, image, position_x, position_y, price, speed_multiplier, lifetime, is_penalty):
"""Initialize Benefit"""
super(Benefit, self).__init__()
self.image = ima... |
8ae8c0cfbd8f957e90e763caaa93c42ba643b78e | erossiter/PythonCourse2016 | /Day2/Labs/lab2_clock.py | 1,613 | 4.09375 | 4 | class Clock(object):
def __init__(self, hour, minutes):
self.minutes = minutes
self.hour = hour
@classmethod
def at(cls, hour, minutes=0):
return cls(hour, minutes)
def __str__(self):
return "The time is %s:%s" % (self.hour, self.minutes)
def __add__(self, minutes... |
7f6739da42a8a26cb246150be5345bac371dc8d6 | grivanov/python-basics-sept-2021 | /I.06-repainting.py | 500 | 3.53125 | 4 | nylon_amount = int(input()) + 2
paint_amount = int(input())
paint_amount = paint_amount + (paint_amount * 0.10)
thinner_amount = int(input())
hours = int(input())
bags_price = 0.40
nylon_sum = nylon_amount * 1.50
paint_sum = paint_amount * 14.50
thinner_sum = thinner_amount * 5
materials_sum = nylon_sum + paint_sum +... |
6a1d5d1c98d807493b4068be7b05cf8d68a1f4ba | TheAlgorithms/Python | /bit_manipulation/binary_count_setbits.py | 1,110 | 4.125 | 4 | def binary_count_setbits(a: int) -> int:
"""
Take in 1 integer, return a number that is
the number of 1's in binary representation of that number.
>>> binary_count_setbits(25)
3
>>> binary_count_setbits(36)
2
>>> binary_count_setbits(16)
1
>>> binary_count_setbits(58)
4
... |
d9abf4ae91c6a153f3b01c6bc7e91982de9b6d4a | moonisme/Dictionary_practice | /dictionary.py | 949 | 3.625 | 4 | import json
from difflib import get_close_matches
data = json.load(open('dict.json'))
def get_def(word):
word = word.lower()
if word in data:
return data[word]
elif word.title() in data:
return data[word.title()]
elif word.upper() in data:
return data[word.upper()... |
a5d5b7ff0598db1bef3eb382429d2187d0ea6382 | bekzod886/Python_darslari | /Funksiyalar/Funksiya 2/123.py | 86 | 3.5625 | 4 | n = int(input("n= "))
for i in range(1, n+1):
a=n%i
if a==0:
print (i) |
b34d00a7a7a5201a3cc26c0811918a1d001b0886 | ZoeQiu/IBI1_2019-20 | /Practical10/Alignment.py | 1,179 | 4.15625 | 4 | #import sequence
human='MLSRAVCGTSRQLAPVLAYLGSRQKHSLPDLPYDYGALEPHINAQIMQLHHSKHHAAYVNNLNVTEEKYQEALAKGDVTAQIALQPALKFNGGGHINHSIFWTNLSPNGGGEPKGELLEAIKRDFGSFDKFKEKLTAASVGVQGSGWGWLGFNKERGHLQIAACPNQDPLQGTTGLIPLLGIDVWEHAYYLQYKNVRPDYLKAIWNVINWENVTERYMACKK'
mouse='MLCRAACSTGRRLGPVAGAAGSRHKHSLPDLPYDYGALEPHINAQIMQLHHSKHHAAYVNNLNA... |
c9d276ad35bf3f5e0778bdfcf31fdfd4833220ac | MU-Enigma/Hacktoberfest_2021 | /Problems/Level-1/Problem_5/Kanishk_Problem_5.py | 656 | 4 | 4 | '''
Kanishk's Solution for Problem 5
# Problem 5
Make a function that takes a list of numbers and returns the sum of all prime numbers in the list.
'''
ans="n"
while ans == "n" :
L1 = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
e = int(input())
L1.append(e)
prin... |
d2d8c9cb9201f7a97ddce49e154f22245964d0d9 | SachinHg/python-exercises | /recursive_sum.py | 461 | 3.515625 | 4 | def recursive(arr):
if len(arr) == 1:
print(arr[0])
return
else:
s = 0
arr_dup = arr[:]
arr_dup = [int(x) for x in arr_dup]
s = sum(arr_dup)
arr = str(s)
recursive(arr)
n,k = input().split(' ')
print("////",n)
#multiply n k times and send the prod... |
b232bcc8a55fb85b29e3b97823784b454a3d91e0 | Larissa-D-Gomes/CursoPython | /introducao/exercicio059.py | 1,630 | 4.375 | 4 | """
EXERCÍCIO 059: Criando um Menu de Opções
Crie um programa que leia dois valores e mostre um menu como o abaixo na tela:
[ 1 ] Somar
[ 2 ] Multiplicar
[ 3 ] Maior
[ 4 ] Novos Números
[ 5 ] Sair do Programa
Seu programa deverá realizar a operação solicitada em cada caso.
"""
def main():
operacao = 0
try:... |
8d6304d3efb14c505ba3cd0ff08cf7f47e603201 | terabyte/SomePackage | /somepackage/fibonacci.py | 713 | 3.53125 | 4 | ''' impl for class Fibonacci '''
#pylint: disable=R0903,R0201
class Fibonacci(object):
''' this module provides a method for calculating fibbonacci numbers in
amortized linear time '''
def __init__(self):
pass
@_memoize
def fib(self, num):
''' returns the num-th fibonacci number ... |
76420ad4194b8f6e1521ab9a522703a4d3d424bf | rwilmar/Python-DL-Tests | /test_preprocImage.py | 1,924 | 3.53125 | 4 | import numpy as np
import cv2
def preproc(input_image, height, width):
image = cv2.resize(input_image, (width, height))
image = image.transpose((2,0,1))
image = image.reshape(1, 3, height, width)
return image
def pose_estimation(input_image):
'''
Given some input image, preprocess the image s... |
5afd7a13d20e0f76223ce7d9e9a1e1bb800b65b9 | Silex-Axe/TelloML | /src/data_out.py | 968 | 4 | 4 | class Out(object):
'''
This class handles the output to the device that's being controlled by the system.
We assume that this is a Drone or a mobile system right now and so we have functions
to move on a 3D space
'''
BASE_SPEED = 30
def __init__(self):
self.speed = self.BASE_SPEED
... |
8edddc14a99c6b7625747e5c5f46567b19c72eef | Drlilianblot/tpop | /TPOP Python 3.x Practicals/tpop_2015_16_practical08/shopping_app.py | 4,702 | 3.59375 | 4 | '''
Created on 12 Jan 2016
@author: Lilian
'''
class Item(object):
def __init__(self, barcode, name, ppu, vat, description = '', units = 1):
self._uid = barcode
self._name = name
self._desc = description
self._units = units
self._ppu = ppu
self._vat = vat
... |
8ed2b7fae3a595fd93b6ff02b32533131be83dc1 | robertwija1033/belajar-program | /tugas.py | 11,120 | 3.96875 | 4 | # def angka_terbesar(a, b, c) :
# terbesar = a
# if a > b > c :
# terbesar = a
# elif b > c > a :
# terbesar = b
# else :
# terbesar = c
# return terbesar
# total = 3
# while total == 3 :
# x = input('nilai a :')
# y = input('nilai b :')
# z = input('nil... |
e351d760b734e82d6ef3c6f5bb5413696b5386bf | MR989/MyCode | /arrays.py | 859 | 3.828125 | 4 | """ data science webinar """
import numpy as np
# a=np.array([1,2,3])
# print(type(a))
# print(a.dtype)
# print(a.size)
# b= np.array([[1.3,3.4],[0.3,4.1]])
# print(b)
# print(b.size,b.ndim,b.shape)
#intrinsic creation of array
#we cannot create this for 2 or 3s
# x=np.zeros((3,3))
# print(x)
# y=np.ones((3,3))... |
179394fbb090f85e47771d5707557b1d2f8288e6 | rajkhub/cert | /LeetCode/TrimABinarySearchTree.py | 328 | 3.6875 | 4 | #Trim a Binary Search Tree between two numbers
def TrimBinary(tree,Min,Max):
tree.left = TrimBinary(tree.left,Min,Max)
tree.right = TrimBinary(tree.right,Min,Max)
if Min <= tree <= Max:
return tree
if Min < tree:
return tree.left
if Max <= tree:
return tree.right
... |
2f5b6efe69307bb3b0af4b297c80ad1816e2a185 | zjplearn/PythonOOP | /pythonObject.py | 3,435 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 15:04:17 2020
@author: ASUS
"""
# =============================================================================
# import math
# class Point:
# def move(self, x, y):
# self.x = x
# self.y = y
#
# def reset(self):
# self... |
c3458212839169e6b7e0258098c92b327daf5497 | SimonFans/LeetCode | /LinkedList/L138_CopyListWithRandomPointer.py | 1,981 | 4.15625 | 4 | A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
"""
https://www.cnblogs.com/zuoyuan/p/3745126.html
首先,在原链表的每个节点后面都插入一个新节点,新节点的内容和前面的节点一样。比如上图,1后面插入1,2后面插入2,依次类推。
其次,原链表中的random指针如何映射呢?比如上图中,1节点的random... |
a4774749d2ff57f9265991b5bcbd9519ef2a235f | priyankamadhwal/Python-Practice | /Automate the Boring Stuff with Python/Table Printer.py | 610 | 3.921875 | 4 | def printTable(table):
# Find maximum column widths
colWidth = [max([len(x) for x in innList]) for innList in table]
# No. of rows and columns
nRow, nCol = len(table[0]), len(table)
# Transpose table
table = list(zip(*table))
# Print the table
for i in range(nRow):
fo... |
7c07437edf4b3dca1fec096d38acfc880b75fe41 | spirit1234/location | /python_work/基础/第四章 操作列表/4-13动手试一试.py | 717 | 3.671875 | 4 |
'''自助餐 : 有一家自助式餐馆, 只提供五种简单的食品。 请想出五种简单的食品, 并将其存储在一个元组中'''
resturant = ('food1','food2','food3','food4','food5')
#使用一个for 循环将该餐馆提供的五种食品都打印出来。
for i in resturant:
print(i)
print('\n')
#尝试修改其中的一个元素, 核实Python确实会拒绝你这样做。
#resturant[0] = 'food6'
#餐馆调整了菜单, 替换了它提供的其中两种食品。 请编写一个这样的代码块: 给元组变量赋值, 并使用一个for 循环将新元组的每个元素都打印出来。
r... |
198a9455067af0cebbf55aea15b0bafeea9098f0 | sharanya-code/String-Based-Programs | /number of special characters.py | 482 | 3.875 | 4 | #NUMBER OF SPECIAL CHARACTERS IN A STRING
def sent():
s=input('ENTER A STRING')
count=0
sm=0
for i in s:
if i in ('AEIOUaeiou'):#TO COUNT NUMBER OF VOWELS
count+=1
print('the number of vowels are ', count)
for j in s:
if j in ('!@#$%^&*()-_+={}[]:;"<>?,./1... |
33f68988f253efd5ee0a3335d4305025cdcaf3ee | ProEgitim/Python-Dersleri-BEM | /Ogrenciler/Varol/atm.py | 913 | 3.9375 | 4 | print("********************\nATM sistemine hoşgeldiniz\n********************")
print("""
İşlemler:
1. Bakiye Sorgulama
2. Para Yatırma
3. Para Çekme
Programdan 'q' tuşu ile çıkabilirsiniz.
""")
bakiye = 1000 # Bakiyemiz 1000 lira olsun.
while True:
işlem = input("İşlemi giriniz:")
if (işlem == "q"):
... |
d12ae801dba4c7585deb820365a4c4b4cf6e2685 | samlee916/A-Beginner-s-Journey-To-Computers-and-Python | /PythonExample2.py | 2,045 | 4.21875 | 4 | #Python Example 2
#conditional statements
favoritelanguage = "python"
if favoritelanguage == "python":
print("Yes it is.")
else:
print("No it isn't.")
#else if statement
favoriteanimal = "tiger"
if favoriteanimal == "lion":
print("Lions are not my favorite animal.")
elif favoriteanimal == "snake":
pr... |
55b3134e0212ad9af70ff18c9b0365527165534e | Andresgmn/MechaTest | /operaciones.py | 996 | 3.5625 | 4 | import string
def calcTLetras(lista):
l1 = list(string.ascii_uppercase)
dobles = ['á', 'é', 'í', 'ó', 'ú', 'ö']
for i in range (len(l1)):
dobles.append(str(l1[i]))
#print(dobles)
auxiliar = 0
numItems = 0
#print("Esta es la lista que re recive: ", lista)
... |
db31ddcaabc8dc5625c3a002171e8fcbc22a6525 | ggkevinxing/leetcode-solutions | /binaryTreeLevelOrderTraversal_II.py | 654 | 3.546875 | 4 | class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return []
result = []
stack = [root]
while stack:
toAdd = []
for node in stack:
... |
d53fe0c76a81aaeea46a5a7d62437546adcea2aa | ArBond/ITStep | /Python/lessons/lesson10_function/main5.py | 940 | 4.59375 | 5 | # 5. Напишите функцию capitalize(), которая принимает слово из маленьких латинских букв
# и возвращает его же, меняя первую букву на большую. Например, print(capitalize('word')) должно печатать слово Word.
# На вход подаётся строка, состоящая из слов, разделённых одним пробелом. Слова состоят из маленьких латинских б... |
93810759457ec7030d5a3e04d4705c0a92860eb1 | saisaranyaatti/100_days-coding-challenge | /26.check_n(n+1)_is_perfect_square.py | 117 | 3.59375 | 4 | def check(n):
n=int(str(n)+str(n+1))
k=n**0.5
return k.is_integer()
n=int(input())
print(check(n))
|
3782f6e10fa1917f3520ec787ca3755545957577 | congshanru/Tutorial | /1.11命名切片.py | 1,066 | 3.765625 | 4 | # 如果你的程序包含了大量无法直视的硬编码切片,并且你想清理一下代码。
###### 0123456789012345678901234567890123456789012345678901234567890'
record = '....................100 .......513.25 ..........'
cost = int(record[20:23]) * float(record[31:37])
print(record[20:23], record[31:37], cost)
SHARES = slice(20, 23)
PRICE = slice(31, 37)
co... |
7e0c3c32b1c076fa4a430982a94d1ea12d9daf19 | kiriphorito/PythonPractice | /a_level/BST.py | 2,245 | 4.125 | 4 | class Node:
def __init__(self, newValue):
self.value = newValue
self.right = None
self.left = None
class BST:
def __init__(self):
self.rootnode = None
#
# # two appends so that I can return self.rootnode=node without
# # pointing self.rootnode to something else and then... |
103a918d6f9462faa1d4fee1313966a8025f6f91 | iggy18/data-structures-and-algorithms | /python/python/stacks/queue_with_stack.py | 1,657 | 3.90625 | 4 | class InvalidOperationError(Exception):
pass
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.top_of_stack = None
def push(self, value):
new_node = Node(value)
new_node.next = self.top_of_stack
... |
d0d6f4c9128a5d73c66110bc9021166d4a866e7b | SagnikAdusumilli/PycharmProjects | /writefile.py | 484 | 3.8125 | 4 | #outFile = open("out.txt","w")
#outFile.write("this is line 1\n")
#outFile.write("this is line 2\n")
# python creates a buffer and writes data on the buffer
# only upon closing the buffer data is transferred
#outFile.close()
#print("data was written")
outFile = open('grades.txt', 'w')
grades = "0"
print("enter a grade... |
eb5e21160a7d74e3cef9b922a373acb6d5ca8d98 | devbit-algorithms/snakepong-my-name-is-jeff | /canvas.py | 774 | 3.53125 | 4 |
class Canvas:
def __init__(self, width,height):
self.width = width
self.height = height
self.screen = [['' for i in range(height)] for j in range(width)]
self.clearCanvas()
def clearCanvas(self):
for y in range (0,self.height):
for x in range (0,se... |
622085d608c30b068c8550f67ebc85d066d45a14 | cpe202spring2019/lab0-c0caDJ | /planets.py | 372 | 3.796875 | 4 | def weight_on_planets():
# write your code here
normalWeight = int(input("What do you weigh on earth? "))
marsWeight = normalWeight * 0.38
jupiterWeight = normalWeight * 2.34
print("\nOn Mars you would weigh {} pounds.\nOn Jupiter you would weigh {} pounds." .format(marsWeight, jupiterWeight))
... |
6494687162251aad9ac42b22454220dc12a6caf8 | smahamkl/ScalaSamples | /oct2020challenge/SortList.py | 1,920 | 3.984375 | 4 | from typing import List
'''
Given the head of a linked list, return the list after sorting it in ascending order.
Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?
'''
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = nex... |
b5621ebf20d5c979547a9991c1609b780c51fe4f | blparker/challenges | /python/challenge_59_easy.py | 875 | 3.828125 | 4 | """
Write a program that given two strings, finds out if the second string is contained in the first, and if it is,
where it is.
I.e. given the strings "Double, double, toil and trouble" and "il an" will return 18, because the second
substring is embedded in the first, starting on position 18.
NOTE: Pretty much eve... |
f74703adf9da5cc37ef469c9ef1cd14621cfe14b | divyatejakotteti/100DaysOfCode | /Day 59/itertools.combinations_with_replacement.py | 1,573 | 4.0625 | 4 | '''
itertools.combinations_with_replacement(iterable, r)
This tool returns
length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will ... |
26b2e1b7a0443863f5f10c875bd5a9dad424003d | caiicaii/DeepLearning | /Machine_Learning_A_Z/Part 2 - Regression/Section 7 - Support Vector Regression (SVR)/my_svr.py | 1,250 | 3.546875 | 4 | # Support Vector Regression (SVR)
# Imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Importing Dataset
dataset = pd.read_csv('Machine Learning A-Z New/Part 2 - Regression/Section 7 - Support Vector Regression (SVR)/Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.ilo... |
2535f5c605edbe474027cd9663e96acc692a37b8 | isaacteoh25/Hyperskill-1 | /Multilingual Online Translator/translator_stage_2.py | 1,986 | 3.5 | 4 | import requests
from bs4 import BeautifulSoup
print('Type "en" if you want to translate from French into English, or "fr" if you want to translate from English into French:')
dst_lang = input()
print('Type the word you want to translate:')
word = input()
print(f'You chose "{dst_lang}" as the language to translate "{wo... |
e4eb0accca1496c5fe51ab5dde0c653cbf83f5b9 | coro-elio/TP | /pep8arreglo.txt | 581 | 3.921875 | 4 | #lo primero es crear una lista con un valor adentro de 0
fibonacci = [0]
#crear dos variables que sera x ,y que tendran valor de 0 y 1
#otra variable con la catidad de sumas a realizar
x = 1
y = 0
num = 30
#hacer una funcion que recorra la lista con un rango determinado
for n in range(num):
#agregar la suma del las var... |
1e61e4dfa5c92d39c83c5826310c629138ef660f | carnesca/GenderTool | /gendertool_v2.py | 1,497 | 3.953125 | 4 | import nltk
import random
#Defines a list of male names and female names
male_names = nltk.corpus.names.words("male.txt")
fem_names = nltk.corpus.names.words("female.txt")
#Reads .txt file here
file = input("Enter the name of your .txt file: ")
open_file = open(file).read()
#Tokenizes words from file
tokenize = nltk... |
cc3488a18d9920aefa5c5293b29269aa2aabe5a1 | OtacilioMaia/calculadora-next | /calculadora.py | 727 | 3.9375 | 4 | # Equpes de 4 pessoas, uma pessoa cria o branch develop, faz git push.
# A partir de então a equipe se alinha qual função cada membro vai implementar
# Cada pessoa criará um branch com "feature/nome-da-operacao" e irá implementar a respectiva funcao
# Depois cada membro irá abrir um Pull Request para o branch develop ... |
ab4ea70b3b1240285f192db2019e1acf9b3b656e | romulovieira777/Curso_Rapido_de_Python_3 | /Seção 07 - Dicionários/dicionario.py | 306 | 3.796875 | 4 | # Criando um Dicionário
aluno = {
'nome': 'Pedro Henrique',
'nota': 9.2,
'ativo': True
}
print(type(aluno))
# Acessando um Valor Específico do Dicionário
print(aluno['nome'])
print(aluno['nota'])
print(aluno['ativo'])
# Contando Quantos pares Associados dentro do Dicionário
print(len(aluno))
|
66665faaae598a60b8cea4fd9b3946845e10b51b | tonianev/data-structures | /src/min_heap.py | 1,314 | 3.8125 | 4 | class MinHeap:
def __init__(self):
self.heap = []
def insert(self, value):
self.heap.append(value)
self._heapify_up(len(self.heap) - 1)
def remove_min(self):
if not self.heap:
return None
min_value = self.heap[0]
self.heap[0] = self.heap[-1]
... |
0e367b739c69b7e7725aba46d0f2cb94d7953d63 | Khmer495/atcoder | /abc142/d.py | 795 | 3.703125 | 4 | def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
divisors.sort()
prime_divisors = []
for i, _divisors in enumerate(divisors[::-1]):
for _remain_diviso... |
5f242e8bfd3624f6061e709a6f349e6f3cdf8a00 | Leo-hw/psou | /anal_pro3/classification/ex2_logistic.py | 1,860 | 3.5625 | 4 | # Logistic Regression : 날씨 예보(비가 올까?)
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
import numpy as np
from sklearn.model_selection._split import train_test_split
data = pd.read_csv('https://raw.githubusercontent.com/pykwon/python/master/testdata_utf8/weather.csv')
pr... |
3ffc3954d2da796fc22930b6a2868aa644323910 | stephfz/taller-python-set18 | /stephanie/bloque_5/2_calculadora.py | 490 | 3.875 | 4 |
def suma(a,b):
suma = a+b
print("Suma: {0}".format(suma))
def resta(a,b):
resta = a-b
print("Resta: {0}".format(resta))
def multiplicacion(a,b):
producto = a*b
print("Multiplicacion: {0}".format(producto))
def division(a,b):
division = a/b
print("Division: {0}".format(division))
num... |
d1e12b7a4c2701425f6b656beae8a8040f9218d0 | mateusrmoreira/Curso-EM-Video | /Aula12/main.py | 283 | 4.09375 | 4 | nome = str(input('Qual é seu nome? ')).title()
if nome == 'Mateus':
print('Que nome bonito você tem!')
elif nome == 'Piter' or nome == 'Mat' or nome == 'Hélio':
print('Seu nome é bem normal aqui no brasil')
else:
print('Tudo bem! ')
print(f'tenha um bom dia {nome}') |
c9831e8278dd6628378a94464404823bbaa8cbe0 | CoderBoi7450/pass_manager | /pass_manager.py | 8,115 | 3.546875 | 4 | from cryptography.fernet import Fernet
import json
from selenium import webdriver
PATH = "C:\Program Files (x86)\chromedriver.exe"
def add_data():
var = bytes("\n", encoding='utf-8')
# getting key from file
key_file = open("key.key", "rb")
key = key_file.read()
f = Fernet(key)
key_file.close(... |
54be57520d5d159aa9f9852501648a621dcbbb17 | KarthikeyaSarma30/Python-LabPrograms | /12_2.py | 400 | 3.578125 | 4 | #insert record into table of database
import sqlite3
con=sqlite3.connect("D:\\ab.bd")
def sql_insert(con,entities):
curobj=con.cursor()
curobj.execute("INSERT INTO employees(id,name,salary,department,position,hireDate)VALUES(?,?,?,?,?,?)",entities)
print("1 row inserted")
con.commit()
entities=(... |
b4e56b8ba7e679ac84673adb25759852b3aad3a9 | xuleoBJ/stock2015 | /secretary/restInWorkReminder.py | 896 | 3.75 | 4 | # -*- coding:utf-8 -*-
## 提醒休息
import time
from datetime import datetime
from tkinter import messagebox
from datetime import timedelta
if __name__ == "__main__":
_today = datetime.today()
_start_time = time.time()
print( "开始工作时间: " + time.strftime("%H:%M:%S") )
iMin = 15
intervalSecond = 60*iMin
... |
a40d200c43703e940d1dfda0b8fc844f89d62078 | gquirozm/works | /MachineLearning/pandas01.py | 393 | 3.53125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('/Users/javier/Documents/2016ITAMOtono/MachineLearning/DataForPandas.csv')
#aqui se crea una columna
df['bono'] = df.saldo * 0.25
#df.bono
#print df
#aqui se cuentan renglones
#(unos, dos, tres, cuatro,cinco)
unos, dos, tres, cuatr... |
ac4b233c75788159bbf9bca93150886973feb543 | Mortuie/Python-Projects | /TicTacToe/Board.py | 1,719 | 3.671875 | 4 | import pygame
import Constants
import Pieces
"""
@author lb809 on 1/4/2017
"""
class board:
def __init__(self, frame):
self.frame = frame
self.dimensions = 3
self.currentBoard = [[], [], []]
def createBoard(self):
coordX = 50
coordY = 50
for width in range(3)... |
7b8b09ecf6b8bee1c8ce88adc15cc892382d77f7 | new-mentat/takeapath | /leetcode/staircase.py | 763 | 3.671875 | 4 | class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
ways = {}
return self.climb_helper(n, ways)
def climb_helper(self, n, ways):
if n <= 0:
return 0
elif n == 1:
return 1
elif n =... |
0884ec84206a58823613007380682d5ca8383313 | rlsharpton/tocando | /practicefunctions.py | 856 | 3.9375 | 4 | __author__ = 'tocando'
MAX_VALUE = 9
def instructions():
'''This is the doc statement.'''
print('This is the instructions:')
def ask_yes_or_no(question):
responce = None
while responce not in ('y', 'n'):
responce = raw_input('Enter y or no ').lower()
return responce
def a... |
17028039aa64ecb55b4e7801f3dd0a38ec2e268d | chenxu0602/LeetCode | /1038.binary-search-tree-to-greater-sum-tree.py | 2,349 | 3.53125 | 4 | #
# @lc app=leetcode id=1038 lang=python3
#
# [1038] Binary Search Tree to Greater Sum Tree
#
# https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/description/
#
# algorithms
# Medium (80.66%)
# Likes: 968
# Dislikes: 107
# Total Accepted: 56.2K
# Total Submissions: 69.1K
# Testcase Example: '[... |
56d18777e0711c61e6e5c364b0c97026256059de | donaldjvillarreal/Python | /Lectures/Lecture 8 Files - Project Structure and GUIs/gui2.py | 261 | 4.28125 | 4 | from tkinter import Tk, Button
def simple_callback():
print("Hello world")
container = Tk()
button = Button(container, text="Say hello", command=simple_callback) # Create a button
button.pack() # Add the button to the top container
container.mainloop()
|
4da645b290ab5705589c70dd47d4b72ce14e71d0 | KnightZhang625/Stanford_Algorithm | /Course_1/Week_04/1_randomized_selection.py | 813 | 3.546875 | 4 | # coding:utf-8
import random
def partition(array):
length = len(array)
i = 0
j = length - 1
pivot_idx = random.choice(range(length))
pivot = array[pivot_idx]
while i < j:
while i < j and array[i] < pivot:
i += 1
array[pivot_idx] = array[i]
pivot_idx = i
while i < j and array[j] > pivot:
j -= 1
... |
40ed227465ad476452cb8d302f6930a4cee99889 | Zahidsqldba07/PythonExamples-1 | /functions/vogais_first.py | 514 | 3.703125 | 4 | # coding: utf-8
# Aluno: Héricles Emanuel Gomes da Silva
# Matrícula: 117110647
# Atividade: Vogais primeiro
def vogais_primeiro(frase):
vogal = ""
consoantes = ""
vogais = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
for i in range(len(frase)):
evogal = False
for v in vogais:
if frase[i] == v:
ev... |
73f36184471dfc53c2f8e7fc25d3331dc5da4661 | Zandahlen/introduktion | /exercises/introduction.py | 3,088 | 3.953125 | 4 | """Övningar på introduction."""
def repeat(string, num):
"""Repeterar en sträng (arg 1) num (arg 2) gånger.
Returnerar en ny sträng eller en tom sträng om num är negativt.
"""
if num > 0:
return(string * num)
else:
return(string * 0)
def bouncer(items):
"""Tar bort alla värd... |
c3b0cbb005e6698494ca4f3010329091c966ecd3 | jcass77/pybites | /pybites_bite99/sequence_generator.py | 173 | 3.5 | 4 | from itertools import chain, cycle
from string import ascii_uppercase
def sequence_generator():
return cycle(chain.from_iterable(enumerate(ascii_uppercase, start=1)))
|
816c51b868c1afec86dad0b487d17519a9b1daf3 | wudi306/SmartCar-laneDetection | /scripts/utility/Polyfit2d.py | 2,547 | 3.78125 | 4 | """
参考:
https://blog.csdn.net/u011023470/article/details/111381695
https://blog.csdn.net/u011023470/article/details/111381298
"""
from math import sqrt
class Polyfit2d:
"二次曲线拟合类"
def reset(self) -> None:
"重置状态"
self.n = 0
self.x = self.y = self.x2 = self.x3 = self.x4 = self.xy = self.... |
beed74d06b151081b01051d0654e4a1cafd96e66 | LeandroMontanari/simulador-mega-sena-python3 | /mega_sena.py | 7,977 | 3.84375 | 4 | ################################################
##### PROGRAMADO POR: LEANDRO L. MONTANARI #####
################################################
# Importações
from random import randint
# Variáveis Iniciais
listadechutes = []
sorteio = 0
### SORTEIO INICIAL ###
# Lista de Bolas
listadebolas = []
... |
162816ae5bf07f1be53950d4b5d210d5ba460ab8 | OAAcostaM/Problemas-Python | /MÓDULO 01/scripts/Problema2.py | 1,300 | 3.5 | 4 | import re
abecedario_mayus = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','Ñ','O','P','Q','R','S','T','U','V','W','X','Y','Z']
abecedario_minus = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','ñ','o','p','q','r','s','t','u','v','w','x','y','z']
clave = input("Introduza las letras clave: ")
lo... |
7f9f060852899f4087e4c201fa8dd838a8c5429f | kaushikreddy25/firstPythonRepo | /MyPython/SelfLearning/OopProgram.py | 1,497 | 3.953125 | 4 | '''
Created on 26-Apr-2019
@author: guruk
'''
#! python 3
#Program to perform mathematical ops on complex numbers
class Complex:
def __init__(self,r,i):
self.real = r
self.imag = i
def display(self):
print('Complex number is ', self.real, ',',self.imag)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.