blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
2a23728547323ad14c89e147202f9bf37c1195be | INF1007-2021A/2021a-c01-ch6-1-exercices-Kylianchaussoy | /exercice6.py | 3,835 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def order(values: list = None) -> list:
if values is None:
# TODO: demander les valeurs ici
values = []
while len(values) < 10:
values.append(input('Enter a value: \n'))
values.sort()
num_values = [float(value) for value in ... |
ed2527878b79f75db82f16c90f223922834bd933 | Joyojyoti/intro__to_python | /using_class.py | 618 | 4.21875 | 4 | #Defining a class of name 'Student'
class Student:
#defining the properties that the class will contain
def __init__(self, name, roll):
self.name = name
self.roll = roll
#defining the methods or functions of the class.
def get_details(self):
print("The Roll number of {} is {}.".format(self.name, self.ro... |
1b8ec02bbd1989f623619ad319103425f3f92d45 | AndreyDementiev1989/geekbrains_hw01 | /task5.py | 1,163 | 3.921875 | 4 | # coding=utf-8
'''Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят и сколько между ними находится букв'''
alph_En = 'abcdefghijklmnopqrstuvwxyz'
alph_Ru = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'
char_one = raw_input('Введите первую букву: ').lower()
char_two = raw_input('Введите вторую букву: ... |
bbdd67686747db3ac3579fb4098431a11b3ce532 | leejinseok/python-study | /loops/for-your-string.py | 173 | 4.1875 | 4 | word= "eggs"
for c in word:
print c
word= "A bird in the hand..."
for char in word:
if char=="A" or char=="a":
print 'X',
else :
print char,
|
c60c92e02ee66b42e43dd11128116972b2265742 | iamdarshanshah/python-basics | /date-time/sort-dates.py | 489 | 3.546875 | 4 | import time
from datetime import date
starttime = time.perf_counter()
ldates = []
d1 = date(2021,5,2)
d2 = date(2018,5,2)
d3 = date(2020,5,2)
d4 = date(2024,5,2)
d5 = date(2019,5,2)
ldates.append(d1)
ldates.append(d2)
ldates.append(d3)
ldates.append(d4)
ldates.append(d5)
print(ldates)
ldates.sort()
time.sleep(3)... |
69c02a900d4ac7123a683a3e8da3b2732ecfcb70 | iamdarshanshah/python-basics | /dataStructures/numericTypes.py | 647 | 4.0625 | 4 | a = 13
b = 100
c = -66
print(a, b, c)
# To know a type of variable
print(type(a))
# Complex types
d = 3+5j
print(d)
print(type(d))
# Binary types (start with 0B)
e = 0B1010
print(e)
print(type(e))
# Octadecimal types (start with 0O)
e = 0O16
print(e)
print(type(e))
# Hexadecimal types (start with 0X)
e = 0XFF
pri... |
fa01a2fa6bbafe58f6a8094aab5f7deba4d79761 | iamdarshanshah/python-basics | /hello.py | 342 | 3.796875 | 4 | #Single line comment in python
'''
multi
line
comment
'''
"""
multi
line
comment
"""
print("Python is awesome and easy")
# Pyhton uses indentation to identify block of code.
"""
four spaces of indentation is ideal for writing a block of code
Note :- Indentation needs to be consistent throughout the file in order... |
f24ba71dbec76444c2895e9c5e277edce3dae646 | iamdarshanshah/python-basics | /dataStructures/tupleType.py | 317 | 4.09375 | 4 | """
- Tuple is immutable
- always define list or tuple having only one element with trailing comma
- Operations on tuple
- Indexing [get value from particular index]
- Repetition
- count [occurance of value in tuple]
- index [find out index]
"""
tpl=()
print(tpl)
print(type(tpl))
tpl1=(40,50,"xyz")
print(tpl1) |
bcbc3e318d24944d35e97e8aaa361bfb5fe45b43 | iamdarshanshah/python-basics | /commandLineArgs/demo.py | 343 | 3.609375 | 4 | import sys
lst = sys.argv
for i in lst: print(i)
print(len(lst)) # 1 as by default program locations is passed
# Product of command line arguments
product = 1
count = 1
for i in sys.argv:
if count == 1:
continue
# assert int(i), "Command line arg not parsable to int"
product *= int(i)
coun... |
89fb409befb8deddb4c8eddc9a9020cc75f388e0 | iamdarshanshah/python-basics | /oopConcepts/product.py | 436 | 3.5 | 4 | class Product:
objectCunt = 0
def __init__(self): # Constructor
self.name='iPhone'
self.description='It is Iphone'
self.price=700.0
Product.objectCunt+=1
@staticmethod
def displayCount():
print(Product.objectCunt)
p1 = Product()
print(p1.price)
print(p1.descr... |
682c176a769ddf2b94ce4981c910a4927840ebe3 | iamdarshanshah/python-basics | /ExceptionHandlingLogging/customExceptions2.py | 415 | 3.5625 | 4 | class TooYoungException(Exception):
def __init__(self, msg):
self.msg = msg
class TooOldException(Exception):
def __init__(self, msg):
self.msg = msg
age = int(input("Enter the age :: "))
if age<18:
raise TooYoungException("You are too young, 18 over to apply")
elif age>90:
raise TooO... |
626248060ebbeae2987025d367670a61037c500e | iamdarshanshah/python-basics | /date-time/projectManagementUsecase.py | 943 | 3.640625 | 4 | from datetime import date
class Project:
def __init__(self, name, startDate, endDate):
self.name = name
self.startDate = startDate
self.endDate = endDate
self.tasks = []
def addTask(self, task):
self.tasks.append(task)
class Task:
def __init__(self, name, duratio... |
21872568dc3ceac651b0e25d3eb6897b02f2b6ef | iamdarshanshah/python-basics | /decorators/decoratorChaining.py | 376 | 3.953125 | 4 | # Aplying multiple decorator functions on a given function
def decor1(fun):
def inner(x):
result = fun(x)
return result/2
return inner
def decor2(fun):
def inner(x):
result = fun(x)
return result**2
return inner
@decor2 # will be executed second
@decor1 # will be e... |
864a01eb4152e25e30a64bbbaafa2385f0e9fea4 | zbs881314/Deeplearning | /regression4LP.py | 848 | 4.28125 | 4 | # Linear regression example: linear prediction
# for Lecture 7, Exercise 7.2
import numpy as np
import matplotlib.pyplot as plt
## generated training data set with model x(i)=a x(i-1)+ e(i)
N=5000 # total number of training data
a=0.99
ei=np.random.randn(N)*np.sqrt(0.02) # generate e(n)
xi=np.zeros((N),dtype=np.floa... |
4a73b0232482dd2c60c0d2b361113433f61e5a1d | khoile3009/AlgoScratch | /KD-Tree/Naive/tree.py | 1,043 | 3.546875 | 4 | from data import generate_data_points
from node import Node
import matplotlib.pyplot as plt
class KDTree:
def __init__(self, k=2, initial_data=None):
self.k = k
self.root: Node = None
if initial_data is not None:
print(initial_data)
self.__dimension_check(initial_da... |
40faf3310dbcc81249af6adf57bf50a14465e726 | julianorezenderibeiro/Python | /pythonBrasilExercicios-master/02_EstruturasDecisao/02_positivo_negativo.py | 172 | 4.0625 | 4 | num = int(input('Informe um numero: '))
if (num > 0):
print(num, 'eh positivo')
elif (num < 0):
print(num, 'eh negativo')
else:
print('O numero eh igual a 0')
|
bcce51f4eda3e0493ea6eb81539a59b2a27ae042 | lyulin1995/Python-OOP | /OOP.py | 3,214 | 4.34375 | 4 | # import turtle
x = 5 # x is equal to an instance of the int class, x is an object of type int
y = 'string' # y is equal to an instance of the STR class
#
# # creating a new instance of a turtle object.
# # In the turtle module, there is a class name Turtle.
# # creating a new turtle object and storing it in a var... |
8541498aa51c2133e8bbde532ba446fae364e6bf | snpushpi/P_solving | /216.py | 510 | 4.0625 | 4 | '''
Invert a binary tree.
Example:
Input:
4
/
2 7
/ \ /
1 3 6 9
Output:
4
/
7 2
/ \ /
9 6 3 1
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = No... |
2f660a47d5cc1a928c73056c8062ddc8793fa214 | snpushpi/P_solving | /983.py | 1,114 | 4.0625 | 4 | '''
In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days. Each day is an integer from 1 to 365.
Train tickets are sold in 3 different ways:
a 1-day pass is sold for costs[0] dollars;
a 7-day pass is sold ... |
2eacd9883677846eb5a66d1cd2a75edf2bfc58ca | snpushpi/P_solving | /1023.py | 2,152 | 4.0625 | 4 | '''
A query word matches a given pattern if we can insert lowercase letters to the pattern word so that it equals the query. (We may insert each character at any position, and may insert 0 characters.)
Given a list of queries, and a pattern, return an answer list of booleans, where answer[i] is true if and only if quer... |
d1949a8745c62e119ea2f926902684356b049a7e | snpushpi/P_solving | /isthesametree.py | 841 | 3.984375 | 4 | '''
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: ... |
0df7f56ad62d036dee1dc972a5d35984cfebcbec | snpushpi/P_solving | /preorder.py | 1,020 | 4.1875 | 4 | '''
Return the root node of a binary search tree that matches the given preorder traversal.
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal display... |
1cf2b13e4d9eb7b037fd149658518d322dd9a5f4 | snpushpi/P_solving | /robot_move.py | 596 | 4 | 4 | '''
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
'''
d... |
0d65c6de4db3c2fa23e57d43d35d4be56addb433 | snpushpi/P_solving | /347.py | 543 | 3.96875 | 4 | '''
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2]
'''
def main(nums,k):
frequent = {}
for elt in nums:
if elt in frequent:
frequent[elt]+=1
else:
frequent[elt]=1
import heapq
r... |
d7ae84c9fceffd4bd606dd9423ff02e645aa003d | snpushpi/P_solving | /valid_bst.py | 1,598 | 3.875 | 4 | """
STATEMENT
Given a binary tree, determine if it is a valid binary search tree (BST).
CLARIFICATIONS
- For any root, the max of the left subtree is smaller than the current value and
the min of the right subtree is bigger than the current value. Yes, and both the
left and right subtrees are also BST.
- I am assum... |
2185667fa9b4c965c57fc149fb145dd22546ad12 | snpushpi/P_solving | /1047.py | 1,049 | 4.03125 | 4 | '''
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
Ex... |
c4cd3e7b687b65968f2863e2e19fb4fa303d4612 | snpushpi/P_solving | /1007.py | 1,356 | 4.125 | 4 | '''
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the i-th domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are the ... |
c26eba667f7108c04ea46df2217adf6fdbeb289c | snpushpi/P_solving | /1014.py | 807 | 3.890625 | 4 | '''
Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i between them.
The score of a pair (i < j) of sightseeing spots is (A[i] + A[j] + i - j) : the sum of the values of the sightseeing spots, minus the distance between th... |
9d237dd8ecce58b143c4f5cddfc50778ac0c7cba | snpushpi/P_solving | /1079.py | 1,022 | 4.03125 | 4 | '''
You have a set of tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make.
Example 1:
Input: "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: "AAABBC"
Output: ... |
602dd4b4552f050d3e799cc9bc76fc3816f40358 | snpushpi/P_solving | /next_permut.py | 1,499 | 4.1875 | 4 | '''
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here a... |
7aaf72467e4d4b44d572222b4b1471dbcc15ba9c | snpushpi/P_solving | /binary_sum.py | 821 | 4 | 4 | '''
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
'''
def binary_sum(a,b):
result = ""
carry = 0
l... |
82d7b5ebca2d850aea48cc1a4719ef53f7bd09de | snpushpi/P_solving | /1041.py | 1,536 | 4.25 | 4 | '''
On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:
"G": go straight 1 unit;
"L": turn 90 degrees to the left;
"R": turn 90 degress to the right.
The robot performs the instructions given in order, and repeats them forever.
Return true if and o... |
6a87647d25580d6c0681943d167e3b652c44daff | snpushpi/P_solving | /binary_tree_sum.py | 860 | 4 | 4 | '''
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
... |
7de81ed1859244900a8a59d3f559e0d00d658ccc | snpushpi/P_solving | /253.py | 402 | 3.578125 | 4 | import heapq
def minimumMeetingrooms(Input):
size = len(Input)
if size<=1: return size
heap = []
result = 0
for interval in sorted(intervals):
while heap and heap[0]<=interval[0]:
heapq.heappop(heap)
heapq.heappush(heap,interval[1])
result = max(result,interval[1]... |
9b6d023f110699aee047ab231e17a18989abd40d | snpushpi/P_solving | /search.py | 906 | 4.15625 | 4 | '''
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: t... |
4d1e083c1c57753feeb8ab2f35427c5ad5905e57 | keyvanm/cdm-prog-workshop | /lesson2/get_input.py | 399 | 4.09375 | 4 | # Input and Printing
# player_input = raw_input("Tell me your name: ")
# print "Hello " + player_input + ", welcome."
name = raw_input("Guess my name (hint: it is hector or keyvan): ")
if name == "hector" or name == "keyvan":
print "Right!"
is_cool = True
else:
print "Wrong!"
is_cool = False
if is_co... |
075e8ca04c4036b66bfb7daf749268a3211f7240 | yuanyuhua/1807-2 | /06day/08-老王.py | 316 | 3.5625 | 4 | class showerror(Exception):
def __init__(self,name):
self.name = name
class error():
def my_input(self):
self.name = input("请输入名字")
try:
if self.name == "老王":
raise showerror(self.name)
except showerror as ret:
print("输入%s就报错"%ret.name)
show = error()
show.my_input()
|
55b0991b13fa6391eb8ef3c9fc90016c37cb1c63 | yuanyuhua/1807-2 | /06day/text.py | 187 | 3.734375 | 4 | def jisuanqi(a,b,x):
if x == "+":
return a+b
elif x == "-":
return a-b
elif x == "*":
return a*b
elif x == "/":
if b != 0:
return a/b
else:
print("输入有误")
|
3a776551255177c5173273f901213d858056c2f2 | yuanyuhua/1807-2 | /04day/04-保护对象属性.py | 286 | 3.53125 | 4 | class dog():
def __init__(self):
self.name = "二哈"
self.age = 0
def sleep(self):
print("睡觉")
def setage(self,age):
if age > 15 or age < 1:
print("年龄不符合")
else:
self.age = age
def getage(self):
return self.age
d = dog()
d.setage(100)
print(d.age)
|
f17e7cfa4907ed49baae53d1c0f56d8e8b32e973 | yuanyuhua/1807-2 | /06day/01-单例模式.py | 425 | 3.5 | 4 | class Dog():
__instance = None
__flag = False
def __init__(self,name):
if Dog.__flag == False:
self.name = name
Dog.__flag = True
def __new__(clas,*args,**kwargs):
if clas.__instance == None:
clas.__instance = super().__new__(clas)
return clas.__instance
else:
return clas.__instance
dog = Dog... |
4cc83689c299fae2a615ffdfc20995d1393bdad9 | Vitosh/PythonHB | /Others/FootballTeamExample/football_team.py | 1,463 | 3.640625 | 4 | import json
class FootballTeam:
def __init__(self):
self._teamList = {}
def add_to_team(self, player):
self._teamList[player] = [player._salary]
def change_team_list(self, dict):
self._teamList = {}
self._teamList = dict
def show_team(self):
return self._tea... |
7e6db2a18b87397762c94c645365e307cc6e3992 | Vitosh/PythonHB | /Others/Example02.py | 1,022 | 3.84375 | 4 | from collections import *
wordsInAnalysis = 310
myFile = open('textFile.txt')
text = [word.strip(",.\n?!:;[]()")
for line in myFile for word in line.lower().split()]
words = [word for line in text for word in line.split()]
# print(Counter(words))
print("\n\n")
TopWordsNumber = 0
TopDictionary = Counter(w... |
f0097e595fe9729ba5346454c76f8e6bd43a9385 | Vitosh/PythonHB | /week3/w3a.py | 928 | 3.9375 | 4 | class BankAccount(object):
def __init__(self, name, balance, currency):
self.name = name
self.balance = balance
self.currency = currency
# # self.history1 = []
# self.history1 = self.history1.append("Account was created")
# self.history1 = self.history1.append("Depos... |
9fde89759fb7392057a391387a5f0beee4d50182 | diogodutra/temple_country_notebook | /pytorch_boilerplate/utils.py | 1,262 | 3.703125 | 4 | from datetime import datetime
import pytz
import os
class PrintFile():
"""Prints strings to a local file."""
def __init__(self, parent_folder, *,
filename = 'log.txt',
timezone = 'UTC',
):
"""
Args:
parent_folder (str): Path containing subfolder w... |
b97161fd75494e7bb7c669ea8dc88de2e665d82d | GiovanniCassani/TiMBL_debug | /utilities/pos_tagging/knn.py | 6,407 | 3.90625 | 4 | import numpy as np
from collections import Counter
def get_nearest_indices(cosine_similarities, idx, nn=1):
"""
:param cosine_similarities: a NumPy 2-dimensional array
:param idx: an integer indicating which column to consider
:param nn: an integer indicating the numb... |
b6f17ceaebb3d8e846272eff1313a09e13cefe84 | Zahidsqldba07/codesignal-20 | /FamilyGroup.py | 2,338 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
We’re working on assembling a Game of Thrones family tree.
Example:
Mad King Rickard
/ \ / \
Daenerys Rhaegar Lyanna Ned Catelyn
\ / \ /
Jon Arya
Write a function that returns three collections:
-Peo... |
35de9750f781075b6bb954bfbe6ea73f22f84afe | Zahidsqldba07/codesignal-20 | /firstNotRepeatingCharacter.py | 1,031 | 3.8125 | 4 | '''
Given a string s consisting of small English letters,
find and return the first instance of a non-repeating character in it.
If there is no such character, return '_'.
'''
'''
O(n) solution
1. We loop through the string once.
2. When we come across a new character, we store it in dcontainer with a value of 1, ... |
e3443700f69889e227d9b5b3d8617f3ff4b1811e | avdhesh1512/demoproject | /check_integer.py | 221 | 3.96875 | 4 | def check_int():
val = input("Enter your value: ")
#print(type(val))
#if isinstance(val, int):
if val.isdigit():
print("i am integer")
else:
print("this is not integer")
check_int()
|
b9401748ab04808e5587cec3d3280ae95a10752b | Guimbo/Pesquisa_Ordenacao | /Heap Sort.py | 1,213 | 4.21875 | 4 | #Heap Sort
#Princípio: Utiliza uma estrutura de dados chamada heap, para ordenar os elementos
#à medida que os insere na estrutura. O heap pode ser representado como uma árvore
#ou como um vetor.
#Complexidade no melhor e no pior caso: O(n log2n) é o mesmo que O(n lgn)
from RandomHelper import random_list
def heapSo... |
d3a33d8daaa194e3a1138e4ee449588d006f4f3b | kefirzhang/algorithms | /leetcode/python/easy/p225_MyStack.py | 1,248 | 4 | 4 | import queue
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.helper_data_1 = queue.Queue()
self.helper_data_2 = queue.Queue()
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.he... |
03ebe2f29b094afc6ea4c07246250211070fa283 | kefirzhang/algorithms | /leetcode/python/easy/p1221_balancedStringSplit.py | 413 | 3.65625 | 4 | class Solution:
def balancedStringSplit(self, s: str) -> int:
left, right, total = 0, 0, 0
for i in s:
if i == 'R':
right += 1
else:
left += 1
if left == right and left != 0:
total += 1
left, right ... |
454a873004df75dafd5860bf9e308f5940594d7b | kefirzhang/algorithms | /leetcode/python/easy/p100_isSameTree.py | 718 | 3.890625 | 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 isSameTree(self, p, q):
if p is None and q is None:
return True
elif p is None or q is None:
return Fa... |
48fd1ab20cb10c3ce20f3603279125d25c7ea941 | kefirzhang/algorithms | /sort/quickSort/quickSort.py | 690 | 3.953125 | 4 | unSortedData = [10, 1, 9, 2, 8, 3, 7, 4, 6, 5, 0]
def quickSort(data):
# 基准条件
if (len(data) <= 1):
return data
# 递归条件
pickKey = 0 # 这个key 可以有优化的地方
pickValue = data[pickKey]
# 把这个数组拆分成 三部分
smallerData = []
biggerData = []
for index in range(len(data)):
if (index != pi... |
9c92c02bc56b5be1b1085170f6f3915439459dfe | kefirzhang/algorithms | /leetcode/python/medium/p048_rotate.py | 757 | 3.78125 | 4 | class Solution:
def rotate2(self, matrix) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
new_matrix = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
new_matrix[j][n - i - 1] = ma... |
a0da0865c843e683a75a133197e9a6d15bde4a4e | kefirzhang/algorithms | /leetcode/python/easy/p1175_numPrimeArrangements.py | 790 | 3.578125 | 4 | import math
class Solution:
def numPrimeArrangements(self, n: int) -> int:
if n < 3:
return 1
def isPrime(num):
if num == 1:
return False
if num == 2:
return True
for i in range(2, math.floor(math.sqrt(num)) + 1):
... |
a01ef662ca889dc0d05f2664eee3e98c84529056 | kefirzhang/algorithms | /leetcode/python/easy/p104_maxDepth.py | 518 | 3.734375 | 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 maxDepth(self, p, d=0):
if p is None:
return 0
d = d + 1
d_left = self.maxDepth(p.left, d)
d_right... |
de5eeaca65458dd675d2f40266583fe499647980 | kefirzhang/algorithms | /leetcode/python/easy/p1185_dayOfTheWeek.py | 999 | 3.71875 | 4 | class Solution:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
helper = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
if month == 1 or month == 2:
month += 12
year -= 1
w = (day + 2 * month + int((3 * (month + 1)) / 5)... |
febbc9f7f5f5b47e3fff71112daef60b01babbc0 | kefirzhang/algorithms | /leetcode/python/easy/p374_guessNumber.py | 941 | 3.703125 | 4 | # The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
def guess(num):
if num == 6:
return 0
elif num > 6:
return -1
else:
return 1
class Solution:
def guessNumber(... |
726e1f5bda1a4a1f3cac2a37167ac7fd9205b89e | kefirzhang/algorithms | /leetcode/python/easy/p007_reverse.py | 1,004 | 3.515625 | 4 | # 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 123 321
class Solution:
def reverse(self, x):
reverse_x = 0
INT_MIN = -2 ** 31
INT_MAX = 2 ** 31 - 1
pre = True
base = 10
if x < 0:
pre = False
base = -10
x = abs(x)
while x != 0:
... |
65d7f07e192d45c8aabccb94b70cd7e56251dc0b | kefirzhang/algorithms | /leetcode/python/easy/p844_backspaceCompare.py | 419 | 3.65625 | 4 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
s = ""
t = ""
for i in S:
if i == "#":
s = s[:-1]
else:
s = s + i
for j in T:
if j == "#":
t = t[:-1]
else:
... |
9ee6859a16650a84c4fdaedbe9ae72c0b1ff21c1 | kefirzhang/algorithms | /leetcode/python/easy/p717_isOneBitCharacter.py | 512 | 3.609375 | 4 | class Solution:
def isOneBitCharacter(self, bits):
while len(bits) != 0:
if bits[0] == 0 and len(bits) == 1:
return True
if bits[0] == 1 and len(bits) <= 2:
return False
if bits[0] == 0:
bits.pop(0)
continu... |
cc8c0a49ee4f83876423797b33c403ef6522c518 | kefirzhang/algorithms | /leetcode/python/easy/p703_KthLargest.py | 1,299 | 3.734375 | 4 | class KthLargest:
def __init__(self, k: int, nums):
self.k = k
self.helper = []
if len(nums) > 0:
nums.sort()
self.helper = nums[-k:]
def add(self, val: int) -> int:
if len(self.helper) == 0:
self.helper.append(val)
else:
... |
4d2e8eb076772dc3d0942aa5ee07ac47780a44a0 | kefirzhang/algorithms | /leetcode/python/medium/p022_generateParenthesis.py | 1,330 | 3.734375 | 4 | # 这个代码写的很烂 周末总是不想解决问题 三层嵌套 脑子就不够用了
class Solution:
def addParenthesis(self, str): # 为字符串新增一对括号
b_l = []
for idx, s in enumerate(str):
if s != '(': # 新添加左括号
left_str = str[:idx] + '('
right_str = str[idx:]
for idx_2, s_2 in enumerate(ri... |
6318a705a07bc5aac61bb313a5527a63d87c384b | kefirzhang/algorithms | /leetcode/python/easy/p728_selfDividingNumbers.py | 542 | 3.578125 | 4 | class Solution:
def selfDividingNumbers(self, left: int, right: int) :
def isSelfDivNum(num):
helper = list(str(num))
for i in helper:
i = int(i)
if i == 0:
return False
if num % i != 0:
return Fa... |
b1376d8c972a70563035a5eaca04e806f6cf5026 | kefirzhang/algorithms | /leetcode/python/easy/p706_MyHashMap.py | 1,592 | 3.828125 | 4 | class ListNode:
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.mod = 100
self.data = [None] * self.mod
def put(self, key: i... |
e8a0dc108416f120475585d06815548b64d2f557 | kefirzhang/algorithms | /leetcode/python/easy/p905_sortArrayByParity.py | 480 | 3.5625 | 4 | class Solution:
def sortArrayByParity(self, A):
odd_p, even_p = 0, len(A) - 1
while odd_p < even_p:
if A[odd_p] & 1 != 1: # 奇数
odd_p += 1
elif A[even_p] & 1 != 0: # 偶数:
even_p -= 1
else:
A[odd_p], A[even_p] = A[ev... |
6e68c59384d85981dc1fef2a5db6c4523c99210b | midi0/opentutorials | /WEB2-Python/syntax/module.py | 198 | 3.625 | 4 | '''
import math
#code
print(math.average(1,2,3))
print(math.plus(1,2))
print(math.pi)
'''
from math import average, plus, pi
#code
print(average(1,2,3))
print(plus(1,2))
print(pi)
|
0c26677e25cc00e07b5bd7bec1d38d47dcb314f1 | antonsison/Python-Basics | /loops.py | 1,365 | 3.828125 | 4 | #1 Simple for loop
list = [1, 2, 3 , 4, 5]
for i in list:
print (i)
print("\n\n")
#2 Simple While
b = 10
while b > 0:
print (b, end=' ')
b = b - 1
print("\n\n")
#3
names = ["King", "LeBron", "James"]
for i in range(1, len(names)):
print(names[i])
print("\n\n")
#4
for i in range(0, 11):
if i %... |
4c82db418b80b5feb3781a9017029db4367989fc | antonsison/Python-Basics | /exceptions.py | 2,015 | 3.90625 | 4 | #1
def value_error():
while True:
try:
number = int(input("Input a random number: "))
except ValueError:
print("Not a number! Please Try again!")
else:
print("This is the random number you gave us: {:d}".format(number))
break
value_error()
#2
def import_error():
try:
import daOne
except ... |
fe0176822963934d8988cc2ffd44b7787abf28e5 | hurjmc/HursleyPython | /src/GUIs/frame_demo.py | 1,049 | 3.828125 | 4 | #========================================================#
# (C) COPYRIGHT IBM CORP. 2014 ALL RIGHTS RESERVED #
# #
# Provided for use as educational material. #
# #
# Redistributi... |
db1c972860d423fadb5803e92cbf815167e796cd | hurjmc/HursleyPython | /src/Algorithms/sieve.py | 1,685 | 3.65625 | 4 | '''
Created on 19 Oct 2013
@author: whittin
'''
#========================================================#
# (C) COPYRIGHT IBM CORP. 2014 ALL RIGHTS RESERVED #
# #
# Provided for use as educational material. #
# ... |
3848ad29a1011f3c2301e9f40df26a6b4c15bda3 | trriplejay/Devdraft2014 | /DevDraftFinals5.py | 7,777 | 3.640625 | 4 | #pylint: disable=all
import sys
import unittest
class Address:
def __init__(self, addressLine):
self.addressLine = addressLine
def getStreetAddress(self):
#take everything before the first comma
###devdraft: documentation states that the street address could
### possi... |
c9e51336596434c5305388f7155d6a3693222db0 | SmithaSPrem/Project1 | /div.py | 101 | 3.78125 | 4 | num1=250
num2=25
div=num1/num2;
print("The division of {0} and {1} is: {2}".format(num1,num2,div))
|
101f7b9e37b22819c534e66c6319e363a4cfa99f | Ahmodiyy/Learn-python | /pythonpractice.py | 1,142 | 4.21875 | 4 | # list comprehension
number_list = [1, 2, 3, 5, 6, 7, 8, 9, 10]
oddNumber_list = [odd for odd in number_list if odd % 2 == 1]
print(oddNumber_list)
number_list = [1, 2, 3, 5, 6, 7, 8, 9, 10]
oddNumber_list = [odd if odd % 2 == 1 else None for odd in number_list]
print(oddNumber_list)
# generator as use to get Iterato... |
44bb9822f2cdb8b97c06a39eeb1ab2cc8316229a | anatoliivasylenko/ProjectOG19_Python | /compare 1.py | 530 | 3.9375 | 4 | def compare():
a = int(input("Введите значение 'A' "))
b = int(input("Введите значение 'Б' "))
c = int(input("Введите значение 'В' "))
while a <= b:
a = a + c
if a<b:
print("Число " + str(a) + " меньше " + str(b))
elif a == b:
print("Число " + str(a) + " ... |
f1a84a74058837647a9e4fa253c11169295557fa | hpapucha/Python-Programs | /StudentsUnitTests/test1.py | 466 | 3.546875 | 4 |
from student import Student
#Traditional testing method
#Constructor method
s = Student(111, "Carter", "Marilyn", "312/333/2222", 1)
print(s)
#__repr__ method
s = Student(112, "Snow", "Jon", "312/2222/2222", 2)
#Testing instanced members
print(s.__repr__())
print(s.username)
print(s.first)
print(s.last... |
c2bb3ed43965af0d1fb95ad7fd4f1aec7d4c021b | Pranavtechie/Class-XII-Projects | /Section B/Group - 9 (67,50)/Source Code/guest.py | 943 | 3.5625 | 4 | import src
from os import system
def guest_menu():
print("\n----- GUEST MENU -----\n")
print("Press (1) to see the cars table")
print("Press (2) to see the bikes table")
print("Press (3) to return to main menu")
print("Press (4) to exit the program")
def guest_main(name):
system('cls')
p... |
a5afec05d4332dd5eeec83b7327d3b482f7ad46a | iCodeIN/top-interview-questions | /strings/valid_palindrome/solution1.py | 360 | 3.625 | 4 | class Solution:
def isPalindrome(self, s: str) -> bool:
stripped_str = [char for char in list(s) if char.isalnum()]
s = "".join(stripped_str)
for i in range(len(s)//2):
char1 = s[i].lower()
char2 = s[len(s)-1-i].lower()
if char1 != char2:
... |
8d15254dff7b83f3128b6a41aed5a5fdd89cce17 | bjherger/image_segmentation_labeller | /bin/main.py | 8,940 | 3.59375 | 4 | #!/usr/bin/env python
'''
===============================================================================
Interactive Image Segmentation using GrabCut algorithm.
This sample shows interactive image segmentation using grabcut algorithm.
USAGE:
python grabcut.py <filename>
README FIRST:
Two windows will show u... |
f9c1b213bbc8998ce11f1edd95646b45609b244c | Swistusmen/ResourceManager | /calculations.py | 2,319 | 3.578125 | 4 | import os
def retTheDiffrence(list1 , list2):
if(len(list1)!=len(list2)):
raise Exception ("The sizes of lists are not the same!")
lista=[]
for i in range(len(list1)):
lista.append(float(list1[i])-float(list2[i]))
return lista
def retThePercentage(list1, list2):
if(l... |
03c5ab1a688cdce11359429c90fd3050cfbb2ca8 | Jingliwh/python3- | /py3s.py | 1,882 | 3.640625 | 4 | #sorted高阶函数,排序列表
'''
l1=[-3.4,5,2,37,-8]
l2=sorted(l1)
print(l2[0:len(l2)])
l3=sorted(l1,key=abs)
print(l3[0:len(l3)])
tup1=[('Bob', 75), ('Adam', 92), ('Bart', 66),('Adam', 66), ('Lisa', 88)]
print(tup1[1][1])
#实现对列表里面的元组进行排序,te代表列表中的元组,te[1]代表元组的第二个元素
l4=sorted(tup1,key=lambda te:te[1])
print(l4[0:... |
2b4fae40d15e1b08321040d461b5e797cd0ac2a7 | radian3/Math_Functions | /general/gradecalculator.py | 805 | 3.96875 | 4 | def main():
totalPercent = 0
totalPoints = 0
assignmentType = 1
assignmentValue = 0
assignmentNumber = 0
assignmentPoints = 0
while (totalPercent < 100):
percent = int(input("Put in the percent value of assignments of type " + str(assignmentType) + ": "))
assignmentType += 1
totalPercent+=percent ... |
29d0428070ad1b8220f643748f771c6e50c0017a | thomasballinger/music | /caption.py | 1,573 | 3.5625 | 4 | #!/usr/bin/env python
"""Basic captioning"""
# based on code at
# http://www.linuxquestions.org/questions/programming-9/python-can-you-add-text-to-an-image-in-python-632773/
#
# BrianK
# Senior Member
#
# Registered: Mar 2002
# Location: Los Angeles, CA
# Distribution: Debian, Ubuntu
# Posts: 1,330
#
#
import tem... |
cf33c33bc791baaa909f6a0e53872727ec9b7669 | python-code-assignment/NirajKumar | /program_two.py | 137 | 3.8125 | 4 | a = int(input("Enter a number:"))
dictionary = dict()
for i in range(1, a+1):
dictionary[i] = i * i
print(dictionary)
|
df1181d54a8fe76ea87a58de88cc23b6befffdaa | gilbertorobles24/PythonLoginApp | /DataSet/create_user_dataset.py | 5,021 | 4.0625 | 4 | """THIS PROGRAM CREATES A USER AND SIMPLY STORES ITS INFO IN A TXT FILE TO BE RE-READ BY PYTHON"""
from pip._vendor.distlib.compat import raw_input
import json
from tkinter import *
class User():
'''simulates a user for a social network or pc'''
def __init__(self, first_name, last_name, username, pa... |
5983ec5dc00a439566bf3eba7af545e749019834 | krousk/python-space | /nam kyeong hun 20.06.10.py | 3,140 | 3.75 | 4 | #nam kyeong hun 20/06/10
#교과서 예제 실습
#
#문자열
#"이나 '로 지정.
print("market garden",'\n')
var1="market"
var2='garden'
print(var1)
print(var2)
print(var1,var2,'\n')
print(type(var1),'\n')
var3='summer "day" come'
print(var3,'\n')
var4='''아 먹고살자 장사하자
방실방실 대한민국'''
print(var4,'\n')
#따옴표, 큰따옴표니 주의.
a='python '
b='big data'
c=a... |
0c370be5bb765d895998485494d0b7580a9a5ed3 | krousk/python-space | /NamKyeongHun.20.06.12.py | 2,476 | 4 | 4 | #예제
numbers=[1,2,3,4,5]
square=[]
for i in numbers:
square.append(i**2)
print(square)
square=[i**2 for i in numbers]
print(square)
numbers=[1,2,3,4,5]
square=[]
for i in numbers:
if i >=3:
square.append(i**2)
print(square)
square=[i**2 for i in numbers if i>=3]
print(square)
#f=open('filetest.txt',... |
80753d02f007a5c82e22adf447489e053843278c | t-kubrak/leet-code | /strings/str_str.py | 655 | 3.578125 | 4 | def str_str(haystack: str, needle: str) -> int:
if not needle:
return 0
for i in range(len(haystack) - len(needle) + 1):
for j in range(len(needle)):
if haystack[i + j] != needle[j]:
break
if j == len(needle) -1:
return i
return -1
r... |
6107f7b7008de4befe5989a2eb88d00a76b2b0b6 | t-kubrak/leet-code | /array/two_sum.py | 539 | 3.859375 | 4 | def two_sum_brute_force(nums, target):
for key, num in enumerate(nums):
for key_two, num_two in enumerate(nums[key + 1:]):
if num + num_two == target:
return [key, key_two + key + 1]
return None
def two_sum(nums, target):
dict = {}
for key, num in enumerate(nums):
... |
1986fe0d19e56c2d413d79dcb2195c7ed38bc2a5 | t-kubrak/leet-code | /array/rotate_image.py | 2,725 | 3.75 | 4 | from typing import List
def rotate_1st(matrix: List[List[int]]):
rows = len(matrix)
if rows > 3:
offsets = rows // 2
for offset in range(0, offsets):
rotate_matrix(matrix, offset)
else:
rotate_matrix(matrix)
return matrix
def rotate_matrix(matrix: List[List[int... |
2ac25a63d772b993a7b112db3ff62e466f1cfdab | assem-khaled/codility-solutions | /Lesson 7 Stacks and Queues/Brackets.py | 375 | 3.578125 | 4 | def solution(S):
stack = []
match = {']' : '[', ')' : '(', '}' : '{'}
for i in S:
if i == '(' or i == '[' or i == '{':
stack.append(i)
elif i == ')' or i == ']' or i == '}':
if len(stack) < 1:
return 0
if match[i] != stack.pop():
... |
46023f3db41d839bb6f5ed8ca1e4e9df4138c272 | assem-khaled/codility-solutions | /Lesson 10 Prime and composite numbers/CountFactors.py | 409 | 3.546875 | 4 | import math
def solution(N):
count = 0
i = 1
while(i*i < N):
if (N%i) == 0:
count += 2
i += 1
if (i*i == N):
count += 1
return count
def solution(N):
count = 0
i = 0
for i in range(1, math.ceil(math.sqrt(N))):
if (N%i) == 0:
... |
27f84fe2afc4ccf4453d41dfe3a3d576a6748fd5 | shimmieblum/ML-and-Graph-Algorithms | /ML/DecisionTree.py | 8,179 | 3.921875 | 4 | import random
import numpy as np
from collections import Counter
class TreeNode:
'''this is a simple tree node. it simply contains the feature it represents and its right and left children.
the left child is the result of taking action 0 on feature f and right is action 1 on feature f
there is a method tra... |
7b6d55c5ae715d229632548aff90e7a0d75d9769 | song248/CodingTest-Study | /최재훈/05M04W/백준_1541-잃어버린괄호/source_64ms.py | 699 | 3.53125 | 4 | inputData = list(input())
parsedList = []
number = ''
for data in inputData:
if '-' != data and '+' != data: number += data
else:
parsedList.append(number)
number = ''
parsedList.append(data)
if 0 < len(number): parsedList.append(int(number))
sumValue = 0
addValue = 0
isMinus = False... |
4aea0e1986140525849ba3ae59064d417e121689 | song248/CodingTest-Study | /최재훈/06M03W/프로그래머스_LV1_카카오_키패드-누르기/source.py | 2,095 | 3.625 | 4 | def solution(numbers, hand):
answer = ''
'''
10 == '*'
11 == '#'
'''
phoneDict = {1: [1,1], 2: [1,2], 3: [1,3],
4: [2,1], 5: [2,2], 6: [2,3],
7: [3,1], 8: [3,2], 9: [3,3],
10: [4,1], 0: [4,2], 11: [4,3]}
leftNum = 10
rightNum ... |
7e904e67b0172e735762d1d0782ac3c76359f3e7 | heschmat/data-science-toolkit | /python-oop/Gaussian.py | 3,555 | 4.28125 | 4 | import math
import numpy as np
import matplotlib.pyplot as plt
class Gaussian:
""" Gaussian distribution class for calculating and
visualizing a Gaussian distribution.
Attributes:
mean (float) the mean value of the distribution
stddev (float) the standard deviation of the distributio... |
f0b11d1139219306ef7b6b3041d2710137bab8a5 | diaelhaggar/FullStackDeveloperTrack | /sets.py | 395 | 3.921875 | 4 | groceries = {'milk','cheese','bread','spices','shampoo','bread'}
groceries.add('Tomato')
groceries.remove('full milk')
groceries.remove('cheese')
groceries.clear()
groceries.add('Tomato')
print (groceries) # prints only bread once. sets can not contain dupicates
item=input('Checking item: ')
if item in groceries:
... |
2c3370cfb32e84cc709f9fbeaa99e961aa0a8ce0 | Asresha42/Bootcamp_day25 | /day25.py | 2,902 | 4.28125 | 4 | # Write a program to Python find the values which is not divisible 3 but is should be a multiple of 7. Make sure to use only higher order function.
def division(m):
return True if m % 3!= 0 and m%7==0 else False
print(division(23))
print(division(35))
# Write a program in Python to multiple the element of list by... |
d0f1e4c5434d246faf1d73097a00a8b87af298b4 | anjmehta8/learning_python | /Lecture 1.py | 1,113 | 4.375 | 4 | print(4+3+5)
#this is a comment
"""
hello
this is a multiline comment
"""
#values
#data types
#date type of x is value.
#Eg. 4 is integer. The 4 is value, integer is data type
"""
#integer
4 7 9 15 100 35 0 -3
#float
3.0 4.6 33.9 17.80 43.2
"""
print(6/3)
print(6//3)
print(7/2)
print(7//2)
#// rounds downward
... |
e9be9d1b7c83854e43f5775548c05f2cbb31831c | jainharshit27/C4_AA2_T | /C4 AA2 TeacherCopy.py | 653 | 3.53125 | 4 | import pygame
pygame.init()
screen = pygame.display.set_mode((400, 400))
paddle = pygame.Rect(175, 350, 50, 10)
ball = pygame.Rect(200, 50, 5, 5)
ball_y_change = 1
while True:
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pyga... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.