blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
7907574293ccefef00b3a19517699f3b97caf46c | IvanPLebedev/TasksForBeginer | /Task8.py | 480 | 3.953125 | 4 | '''
Напишите проверку на то, является ли строка палиндромом. Палиндром — это слово
или фраза, которые одинаково читаются слева направо и справа налево
'''
def polindrom(string):
return string == string[::-1]
a = 'asdfdsa'
b = 'reewer'
for x in [a,b]:
if polindrom(x):
print(x,': polindrom')
else:
... |
e804e54379de9827b7a521ef0627afbc270982bd | agin0634/my-leetcode | /solution-python/1000-1499/1013-partition-array-into-three-parts-with-equal-sum.py | 412 | 3.5 | 4 | class Solution(object):
def canThreePartsEqualSum(self, A):
"""
:type A: List[int]
:rtype: bool
"""
target = sum(A)/3
temp,part = 0,0
for a in A:
temp += a
if temp == target:
temp = 0
part += 1
i... |
b8a84b7f2c8fa026b8004ae443a465e6e12cb8e4 | agin0634/my-leetcode | /solution-python/0000-0499/0143-reorder-list.py | 958 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
... |
4ace81cf22287a59177ccc3b70b5bb1a258115d3 | agin0634/my-leetcode | /solution-python/0000-0499/0019-remove-nth-node-from-end-of-list.py | 624 | 3.71875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
temp,... |
62e43748e944ce09643e3c4c943e3efe88e9e92b | agin0634/my-leetcode | /solution-python/0500-0999/0500-keyboard-row.py | 387 | 3.5 | 4 | class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
roa, res = [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')], []
for w in words:
word = set(w.lower())
for i in roa:
if wor... |
4e5399de763865da945d2157ec2ab5737e104a9e | agin0634/my-leetcode | /solution-python/0000-0499/0113-path-sum-ii.py | 761 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def pathSum(self, root, s):
"""
:type root: TreeNode
:type sum: int
... |
bf92d64a05ccf277b13dd50b1e21f261c5bba43c | NikitaBoers/improved-octo-sniffle | /averagewordlength.py | 356 | 4.15625 | 4 | sentence=input('Write a sentence of at least 10 words: ')
wordlist= sentence.strip().split(' ')
for i in wordlist:
print(i)
totallength= 0
for i in wordlist :
totallength =totallength+len(i)
averagelength=totallength/ len(wordlist)
combined_string= "The average length of the words in this sentence is "+str(ave... |
0de13dc0bcc711f7dbc68efdfd0aee2cdbaf94af | NikitaBoers/improved-octo-sniffle | /studentsdictionary2.py | 618 | 3.546875 | 4 | import json
filename = 'students (1).csv'
students= {}
with open(filename) as file:
file.readline()
for line in file:
split= line.strip().split(',')
other= {}
other['LastName']=split [1]
other['Adjective']=split[0]
other['Email']=split [3]
students[split[2]] = ot... |
ca820fc2d0a2ee0dee559ca8185ef4ede2620c65 | maximrufed/Mirrows | /geoma.py | 3,820 | 3.765625 | 4 | import math
eps = 1e-7
class point:
x: float
y: float
def __init__(self, x_init, y_init):
self.x = x_init
self.y = y_init
def set(self, x, y):
self.x = x
self.y = y
def len(self):
return math.sqrt(self.x * self.x + self.y * self.y)
def normalize(self, len):
tek_len = self.len()
self.x = self.x ... |
292ad196eaee7aab34dea95ac5fe622281b1a845 | LJ1234com/Pandas-Study | /06-Function_Application.py | 969 | 4.21875 | 4 | import pandas as pd
import numpy as np
'''
pipe(): Table wise Function Application
apply(): Row or Column Wise Function Application
applymap(): Element wise Function Application on DataFrame
map(): Element wise Function Application on Series
'''
############### Table-wise Function Application ####... |
e45c11a712bf5cd1283f1130184340c4a8280d13 | LJ1234com/Pandas-Study | /21-Timedelta.py | 642 | 4.125 | 4 | import pandas as pd
'''
-String: By passing a string literal, we can create a timedelta object.
-Integer: By passing an integer value with the unit, an argument creates a Timedelta object.
'''
print(pd.Timedelta('2 days 2 hours 15 minutes 30 seconds'))
print(pd.Timedelta(6,unit='h'))
print(pd.Timedelta(days=2)... |
3d9b7186764bfd5dd51a24a6e23769f229b8b9e8 | LJ1234com/Pandas-Study | /01-Series.py | 1,531 | 4.03125 | 4 | import pandas as pd
import numpy as np
'''
Series is a one-dimensional labeled array capable of holding data of any type.
The axis labels are collectively called index.
A pandas Series can be created using the following constructor:
pandas.Series( data, index, dtype, copy)
- data: data takes various forms li... |
4c4d5e88fde9f486210ef5bd1595775e0adce53c | aiworld2020/pythonprojects | /number_99.py | 1,433 | 4.125 | 4 | answer = int(input("I am a magician and I know what the answer will be: "))
while (True):
if answer < 10 or answer > 49:
print("The number chosen is not between 10 and 49")
answer = int(input("I am choosing a number from 10-49, which is: "))
continue
else:
break
factor = 99 - ... |
6f240b1f578b18a0e3572187fa31e2bf5d48f772 | a1a1a2a4/100knock | /otani/python/1/05.py | 285 | 3.71875 | 4 | from pprint import pprint
def Ngram(string, num):
ngram = [0 for i in range(len(string) - num + 1)] # 初期化
for i in range(len(string) - num + 1):
ngram[i] = string[i:(i + num)]
return ngram
string = "ketsugenokamisama"
ngram = Ngram(string, 3)
pprint(ngram)
|
d8e1ab0778a17030a2ee03eccba776743384747f | Bolodeoku1/PET328_2021_Class | /group 6 project new.py | 503 | 3.625 | 4 | B_comp = float (input('What is the bit cost?'))
CR_comp = float (input('What is the rig cost per hour?'))
t_comp = float (input('What is the drilling time?'))
T_comp = float (input('What is the round trip time?'))
F_comp = float (input('What is the footage drill per bit?'))
# convert inputs to numerals
# the formula... |
de46cb4081b386006c47ad7f16849cd0c95d4e30 | lamolivier/EPFL-MLBD-Project | /notebooks/helper_functions.py | 743 | 4 | 4 | import pickle
def save_to_pickle(var, filename, path_write_data):
"""
Parameters
----------
var : any python variable
variable to be saved
filename : string
Name of the pickle we will create
path_write_data : string
Path to the folder where we write and keep intermediat... |
a71c9875f51651370970f8c61280d7305bfad02f | klaundal/lompe | /lompe/model/data.py | 12,751 | 4.03125 | 4 | """
Lompe Data class
The data input to the Lompe inversion should be given as lompe.Data objects. The Data
class is defined here.
"""
import numpy as np
import warnings
class ShapeError(Exception):
pass
class ArgumentError(Exception):
pass
class Data(object):
def __init__(self, values, coordi... |
d65ac8ccbf22813eb3be92d127b316cb3b735e9d | tammytdo/SP2018-Python220-Accelerated | /Student/tammyd_Py220/Py220_lesson09/concurrency.py | 1,014 | 4.0625 | 4 | import threading
import time
import random
# simple threading
def func(n):
for i in range(n):
print("hello from thread %s" % threading.current_thread().name)
time.sleep(random.random() * 2)
# run a bunch of fuctions at the same time
threads = []
for i in range(3):
thread = threading.Thread(t... |
4c118860c69f31cc8d10182c9f7bb3027c5942be | tammytdo/SP2018-Python220-Accelerated | /Student/tammyd_Py220/Py220_lesson07/assignment7/mailroom_model.py | 1,821 | 4 | 4 | """
Simple database example with Peewee ORM, sqlite and Python
Here we define the schema
Use logging for messages so they can be turned off
"""
import logging
from peewee import *
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("One off program to build the classes from t... |
053294e9f40e9d67b652c013c84cc443106a6187 | obryana/data-science-projects | /Google FooBar/google_fuel_injection.py | 975 | 3.625 | 4 | def peek(num_pellets):
operations_peek = 1
while num_pellets % 2 == 0:
num_pellets /= 2
operations_peek += 1
return (operations_peek, num_pellets)
def answer(num_pellets):
num_pellets = int(num_pellets)
operations = 0
while num_pellets > 1:
if num_pellets % 2 == 0:
... |
5608d39b85560dc2ea91e943d60716901f5fe88b | longroad41377/selection | /months.py | 337 | 4.4375 | 4 | monthnames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
month = int(input("Enter month number: "))
if month > 0 and month < 13:
print("Month name: {}".format(monthnames[month-1]))
else:
print("Month number must be between 1... |
b84a8ac32b9e866639fdf804a1acc3f561863339 | artem-chyrkov/hist-detector | /base/ring_list.py | 922 | 3.609375 | 4 | class RingList:
def __init__(self):
self._max_size = 0
self._ring_list = []
self._index_to_replace = -1
def init(self, max_size):
self._max_size = max_size
self.clear()
def add(self, x): # TODO optimize
if len(self._ring_list) < self._max_size: # usual add... |
21219f7ddb8f074e9f811f4c5d3bcdb34712a761 | da1x/cs50-2018 | /pset6/mario/mario.py | 535 | 3.921875 | 4 | from cs50 import get_int
while True:
# prompt user
height = get_int("Height: ")
# Make sure the number is more then 0 and less then 24
if height < 24 and height >= 0:
break
# Print
for i in range(height):
# First part
for j in range(height - i - 1):
print(" ", end="")
for ... |
182e95b294e0c4341a8e6dc9fb90b61885bf2022 | ccsourcecode/python-data-analysis | /00原始代码【无笔记纯享版】/00-01-3pandas常用内容速成简记/demo04筛选DataFrame中的数据/demo04-4布尔索引:补充示例/example布尔索引-04-4-1筛最高评分中的最低价格/example布尔索引-04-4-1.py | 876 | 3.59375 | 4 | import pandas as pd
from pandas import DataFrame
resourceFile = "bestsellers.csv"
# 取出表数据
data = pd.read_csv(filepath_or_buffer=resourceFile)
# Index(['书名', '作者', '评分', '被查看次数', '价格', '年份', '体裁'], dtype='object')
# print(data.columns)
# 最高评分“中”的最低价格(基于最高评分接着细粒度筛,千万注意这里不是重新筛)
# 筛选数据结果result从原始data开始。深拷贝,不是浅拷贝。
resu... |
f8679f7a1aa887cbd492d94ffdcc54bbc1c05fc1 | ccsourcecode/python-data-analysis | /00原始代码【无笔记纯享版】/00-09线性回归预测分析/补充案例/00-09-1单一自变量线性回归预测分析/demo_singleLR1-自热火锅价格销量相关性分析/demo_singleLR1.py | 402 | 3.515625 | 4 | import pandas as pd
from pandas import DataFrame
# 探究价格与销量的关联系数
# 读取文件
df = pd.read_excel(io="自热火锅.xlsx", sheet_name=0) # type: DataFrame
# print(df.columns)
# Index(['category', 'goods_name', 'shop_name', 'price', 'purchase_num', 'location'], dtype='object')
# 计算相关系数
corrPriceNum = df["price"].corr(other=df["purcha... |
4adb4a10b451e7c7e41c85d5f59d7ab0732f56ef | Letthemknow/school | /Stanford/CS109/cs109_pset3.py | 3,303 | 3.5 | 4 | # Name:
# Stanford email:
########### CS109 Problem Set 3, Question 1 ##############
"""
************************IMPORTANT************************
For all parts, do NOT modify the names of the functions.
Do not add or remove parameters to them either.
Moreover, make sure your return value is exactly as
described in th... |
d0df4da84b7a6d75240e62c41569c4b471b2699e | Letthemknow/school | /Stanford/CS109/cs109_pset5_coursera.py | 7,343 | 3.703125 | 4 | # Do NOT add any other import statements.
# Don't remove these import statements.
import numpy as np
import copy
import os
# Name:
# Stanford email:
########### CS109 Problem Set 5, Question 8 ##############
def get_filepath(filename):
"""
filename is the name of a data file, e.g.,
"learningOutcomes.csv".... |
718944b33bc36198a7942be3db1204adec0b47ac | joseluisquisan/hello-world | /devnet/devnet/data_estructures.py | 485 | 3.53125 | 4 | def legalAges():
lifeEvent = {
"drivingAge": 16,
"votingAge": 18,
"drinkingAge": 21,
"retirementAge": 65
}
print("The legal driving age is " + str(lifeEvent["drivingAge"]) + ".")
print("The legal voting age is " + str(lifeEvent["votingAge"]) + ".")
print("T... |
e821232eb26f19e46699cec48e7165e461f14578 | joseluisquisan/hello-world | /python_basico/disccionarios.py | 636 | 3.90625 | 4 | def run():
mi_diccionario = {
'llave1': 1,
'llave2': 2,
'llave3': 3,
}
# print(mi_diccionario['llave1'])
# print(mi_diccionario['llave2'])
# print(mi_diccionario['llave3'])
población_paises = {
'Argentina': 44_938_712,
'Brasil': 210_147_125,
'Colombia': 50... |
65280e232d355a12c8bbb7122a17a0be72f381fd | joseluisquisan/hello-world | /codigocurso/bohemian.py | 336 | 3.9375 | 4 | # def run():
# for i in range(6):
# if i == 3:
# print("Figarooo")
# continue
# print("Galileo")
def run():
for contador in range(101):
if contador % 2 != 0:
print("Impar")
continue
print("Par ", contador, "")
if __name__ == '__ma... |
c56b0a62664f03485da1fb9bd35f119e26dfe008 | rajeshwerkushwaha/python_learning | /file_readwrite/file_readwrite.py | 720 | 3.75 | 4 | # read all at one shot
f = open('sample.txt', 'r')
print(f.read())
# read line by line when file is small
f = open('sample.txt', 'r')
for line in f:
print(line)
# read line by line when file is big
f = open('sample.txt', 'r')
while True:
line = f.readline()
print(line)
if ("" == line):
break;
# new file crea... |
4ca20b2b026a7985dbb4e0fe140c458d87625132 | AllanWong94/PythonLeetcodeSolution | /Y2017/M8/D8_NeedRevision/Convert_BST_to_Greater_Tree_NeedRevision/Solution_naive.py | 1,186 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from Y2017.TreeNode import TreeNode
class Solution(object):
#TLEed. Passed 211/212 test cases.
#A naive method that wasted the feature of BS... |
6f8546778e855972ede401231ae059607e306ca2 | AllanWong94/PythonLeetcodeSolution | /Y2017/M8/D11/Find_Mode_in_Binary_Search_Tree_NeedRevision/Solution_improved_dict.py | 887 | 3.640625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from Y2017.TreeNode import TreeNode
class Solution(object):
# Runtime: 108ms Beats or equals to 40% (Fastest)
def findMode(self, root):
... |
0950827093e06c37a71d0b016c73b174b787ce79 | AllanWong94/PythonLeetcodeSolution | /Y2017/M9/D5/Increasing_Triplet_Subsequence/Solution.py | 875 | 3.515625 | 4 | # Runtime: 39ms Beats or equals to 55%
class Solution(object):
def increasingTriplet(self, nums):
val1=[]
val2=None
for i in nums:
if not val1 or i>val1[-1]:
val1.append(i)
if len(val1)==3:
return True
elif val1:
... |
6d814302839f5517aeb31a243085f1ecf451d1cf | AllanWong94/PythonLeetcodeSolution | /Y2017/M8/D19_NeedRevision/Subtree_of_Another_Tree/Solution_naive.py | 541 | 3.546875 | 4 | # Runtime: 442ms Beats or equals to 32%
# Reference: https://discuss.leetcode.com/topic/88520/python-straightforward-with-explanation-o-st-and-o-s-t-approaches
class Solution(object):
def isMatch(self, s, t):
if not (s and t):
return s is t
return s.val == t.val and self.isMatch(s.left,... |
bb101b61facff7835475f521e96043e58ccbcf11 | AllanWong94/PythonLeetcodeSolution | /Y2017/M8/D19_NeedRevision/Subtree_of_Another_Tree/Solution.py | 1,408 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from Y2017.TreeNode import TreeNode
#TLEed.
class Solution(object):
def isSubtree(self, s, t):
return self.helper(s,t,False,t)
def ... |
087a85027a5afa03407fed80ccb82e466c4f46ed | ch-bby/R-2 | /ME499/Lab_1/volumes.py | 2,231 | 4.21875 | 4 | #!\usr\bin\env python3
"""ME 499 Lab 1 Part 1-3
Samuel J. Stumbo
This script "builds" on last week's volume calculator by placing it within the context of a function"""
from math import pi
# This function calculates the volumes of a cylinder
def cylinder_volume(r, h):
if type(r) == int and type(h) == int:... |
c2c12efe187c133fee08b987e911772b0054fcbd | ch-bby/R-2 | /ME499/Lab_1/words.py | 461 | 3.765625 | 4 | #!\usr\bin\env python3
"""ME 499 Lab 1 Part 5
Samuel J. Stumbo
13 April 2018"""
def letter_count(string_1, string_2):
count = 0
string_1 = str(string_1).lower()
string_2 = str(string_2).lower()
for i in string_1:
#print(i) # Print for debugging purposes
... |
39bebab706b7e5bccee7fe7ae212831fe5279e5e | ch-bby/R-2 | /ME499/lab2/filters.py | 1,312 | 3.921875 | 4 | #!/usr/bin/env python3
"""
ME 499: Lab 2
Samuel J. Stumbo
20 April 2018
Filters Function
This function reads in random data (or any data, really) and normalizes it
"""
from sensor import *
import numpy as np
import matplotlib.pyplot as plt
def mean_filter(l1, width = 3):
unfiltered = []
w = width // 2... |
d571d28325d7278964d45a25a4777cf8f121f0ce | ch-bby/R-2 | /ME499/Lab4/shapes.py | 1,430 | 4.46875 | 4 | #!/usr/bin/env python3#
# -*- coding: utf-8 -*-
"""
****************************
ME 499 Spring 2018
Lab_4 Part 1
3 May 2018
Samuel J. Stumbo
****************************
"""
from math import pi
class Circle:
"""
The circle class defines perimeter, diameter and area of a circle
... |
fbe33499711988c0d0f888d1dfc6626fe90c017a | yvvyoon/learn-python | /multi_pro1.py | 239 | 3.640625 | 4 | import time
start_time = time.time()
def count(name):
for i in range(1, 200001):
print(f'{name}: {i}')
num_list = ['p1', 'p2', 'p3', 'p4']
for num in num_list:
count(num)
print(f'*** {time.time() - start_time} ***')
|
79531c1658c717a945851ef9bf19bca4d70d6118 | yvvyoon/learn-python | /team-study/generator/generator04.py | 988 | 3.96875 | 4 | class Tree(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def inorder(self):
if self.left:
for x in self.left.inorder():
yield x
yield self
if self.right:
... |
9c9ae4a120558d23b1f70f1e581b08cb5112f6cc | soja-soja/LearningHTML | /Python/Session-1.py | 565 | 3.890625 | 4 | print('\n============ Output ===========')
# condition if-else
a = int(input('please enter A:'))
b = int(input('please enter B:'))
c = input('enter the operator:')
if c == '+': # b == 0 b<0 b>0 b<=0 b>=0 b!=0
print('A+B is: {} '.format(a+b) )
else:
print('A-B is: {} '.format(a-b) )
# a = 1 # integer
# ... |
b47ed30acdcc89e7fca0545648aca5e0511f9585 | xychen1015/leetcode | /offer/27.py | 1,014 | 3.859375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/9/24 上午11:36
# @Author : cxy
# @File : 27.py
# @desc:
"""
方法一:递归。不需要使用额外的变量存储结果,直接就地进行翻转。
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def mirror... |
486253055276e69f69bc83f3180f7339908d0c75 | xychen1015/leetcode | /offer/59.py | 1,469 | 3.75 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/9/3 下午3:13
# @Author : cxy
# @File : 59.py
# @desc:
"""
由于题目要求max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。因此不能直接使用max方法,需要使用一个暂存数组来存放当前元素之后的最大元素的值
"""
class MaxQueue:
def __init__(self):
from collections import deque
self.q = deque()
self.mx = ... |
3a6a87ea881449029996ce4d5603be93a85854bf | subin97/python_basic | /exercise/gugudan.py | 310 | 3.703125 | 4 | while True:
print('구구단 몇 단을 계산할까요(1~9)?')
num = int(input())
if num not in range(1, 10):
print('구구단 게임을 종료합니다.')
break
print(f'구구단 {num}단을 계산합니다.')
for i in range(1, 10):
print(f'{num} X {i} = {num*i}') |
8497d12e91e7e5964459332a8cc28ace8e101980 | subin97/python_basic | /mycode/10_pythonic/list_comprehension.py | 173 | 3.640625 | 4 | result = [x for x in range(10) if x%2 == 0]
print(result)
my_str1 = "Hello"
my_str2 = "World"
result = [i+j for i in my_str1 for j in my_str2 if not (i==j)]
print(result)
|
ea3348c0dd35ba8c60d8dc3b75f04703501931d2 | retropleinad/Chess | /pieces/knight.py | 1,697 | 3.828125 | 4 | from pieces.piece import Piece
class Knight(Piece):
# Inherited constructor
# Update the piece value
def __init__(self, color, column, row, picture):
super().__init__(color, column, row, picture)
self.val = 3
# Is the square in a 2 by 3 or a 3 by 2?
# Is there a frien... |
4211efe86175e8a6425c117f4869ca5239b15727 | ytxka/nowcode-codes | /二叉搜索树的后序遍历序列.py | 1,256 | 3.546875 | 4 | # -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# 二叉搜索树的后序遍历,最后一个元素为root,前面必可以分为两部分
# 一部分(左子树)小于root,一部分(右子树)大于root
# 递归判断左右子树
if not sequence:
return False
if len(sequence) == 1:
return True
root = sequ... |
82d094ce4f9018cd3f2b6777e68ce691a2436c3e | ytxka/nowcode-codes | /二叉搜索树的第k个结点.py | 608 | 3.765625 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
# write code here
self.res = []
self.MidSearch(pRoot)
if 0... |
13238ec3b96e2c1297fa1548f14d19860fbe222d | GeeB01/Codigos_guppe | /objetos.py | 1,007 | 4.3125 | 4 | """
Objetos -> São instancias das classe, ou seja, após o mapeamento do objeto do mundo real para a sua
representação computacional, devemos poder criar quantos objetos forem necessarios.
Podemos pensar nos objetos/instancia de uma classe como variaveis do tipo definido na classe
"""
class Lampada:
def __init__(s... |
94c0aa3a85162c6642450b3eb51fbf258b9a2f64 | GeeB01/Codigos_guppe | /sistema_de_arquivos_manipulação.py | 874 | 3.578125 | 4 | """
Sistema de Arquivo - manipulação
# Descobrindo se um arquivo ou diretorio existe
#paths relativos
print(os.path.exists('texto.txt'))
print(os.path.exists('gb'))
print(os.path.exists('gb/gabriel1.py'))
#paths absolutos
print(os.path.exists('C:\\Users\\Gabriel'))
# criando arquivo
# forma 1
open('aruivo_teste.txt'... |
a99fc4de820a1c0ac22c88be6b3ee4317a9234e7 | GeeB01/Codigos_guppe | /leitura_de_arquivos.py | 561 | 4.0625 | 4 | """
Leitura de arquivos
para ler o conteúdo de um arquivo em Python, utilizamos a função integrada open(), que literalmente significa abrir
open() -> Na forma mais simples de utilização nos passamos apenas um parametro de entrada, que neste caso é
o caminho para o arquivo à ser lido. Essa função retorna um _io.TextIO... |
a5a1bd8efaf5d8bbed35197d34a402acb5a46084 | GeeB01/Codigos_guppe | /len_abs_sum_round.py | 698 | 4 | 4 | """
len, abs, sum, round
#len
len() retorna o tamanho(ou seja, o numeor de itens) de um iteravel
print(len('Gabriel'))
#abs ela retorna o valor absoluto de um numero inteiro ou real, de forma basica , seria o seu valor real sem o sinal
print(abs(-5))
print(abs(3.53))
#sum recebe como parametro um iteravel podendo rec... |
219a68a96463790053489586c1714b7a27f66388 | Reiji-A/python_package | /正規表現re/test.py | 1,321 | 3.625 | 4 | import re
regex = r"ab+"
text = "abbabbabaaabb"
pattern = re.compile(regex)
matchObj = pattern.match(text)
matchObj
matchObj = re.match(regex,text)
matchObj
# matchのサンプルコード
data = "abcdefghijklmn"
# パターン式の定義(aで始まりcで終わる最短の文字列)
pattern = re.compile(r"a.*?c")
match_data = pattern.match(data)
print(match_data.group()... |
2ccfacec48b1716f13ca9bd75dd39008c749b0f4 | aryanguptaSG/Data_Structure | /data_structures/dequeue/dequeue_using_array.py | 839 | 3.953125 | 4 | class dequeue():
"""docstring for dequeue"""
def __init__(self, size=5):
self.size = size
self.front = self.rear = -1
self.array = size*[None]
def pushfront(self,value):
if(self.front-1==self.rear):
print("dequeue is full")
return 0;
elif(self.front ==-1):
self.front=self.size-1
else:
self.f... |
d8e32ee5aed3b8c943bbaf05545f547e2f27d464 | AnnKuz1993/Python | /lesson_02/example_03.py | 1,893 | 4.25 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict.
month_list = ['зима', 'весна', 'лето', 'осень']
month_dict = {1: 'зима', 2: 'весна', 3: 'лето', 4: 'осень'}
num_month = int(input("Введите... |
62e23d990a25f1115e87984698d4af54ab11b3e1 | AnnKuz1993/Python | /lesson_04/example_06.py | 465 | 3.875 | 4 | # итератор, генерирующий целые числа, начиная с указанного
from itertools import count
for el in count (3):
if el > 10:
break
else:
print(el)
# итератор, повторяющий элементы некоторого списка, определенного заранее
from itertools import cycle
c = 0
for el in cycle("ABBY"):
if c > 7:
... |
96cd937cfe7734c8fae5348b53517271e3c59321 | AnnKuz1993/Python | /lesson_03/example_01.py | 791 | 4.125 | 4 | # Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def num_division():
try:
a = int(input("Введите первое число: "))
b = int(input("Введите второе число: "))
ret... |
3bb991b7c0d7cd43ff00f35c15e114792246bc8e | AnnKuz1993/Python | /lesson_01/example_06.py | 324 | 3.953125 | 4 | a = float(input("Введи результат пробежки в 1-ый день: "))
b = float(input("Введи желаемый результат пробежки: "))
day = 0
while a < b:
a = a * 1.1
day += 1
print("Ты достигнешь желаемого результата на ",day,"-й день")
|
1bba11b294f8ab6e4c63481028eeb7ed4ad69f92 | AreebaKhalid/ComputerVisionPractis | /Program7Rotations.py | 715 | 3.59375 | 4 | import cv2
import numpy as np
image = cv2.imread('./images/input.jpg')
height, width = image.shape[:2]
#cv2.getRotationMatrix2D(rotation_center_x, rotation_center_y,angle_of_rotation,scale)
#angle is anti clockwise
#image is cropped by putting scale = 1
#put = .5 it will not crop
rotation_matrix = cv2.getR... |
1d519743918f89d13492af1c920356e056787ddd | pythonclaire/pythonpractice | /financing_assistant.py | 3,514 | 3.625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from sys import exit
#终值计算器
def finalassets():
print("信息输入样式举例")
print("""
请输入本金<元>:10000
请输入年化收益率<如5%>:5%
请输入每月追加投入金额<元>:1000
请输入投资年限:30
""")
A=int(input("请输入本金<元>:"))
r=input("请输入年化收益率<如5%>:")
m=int(input("请输入每月追加投入金额<元>:"))
n=int(input("... |
393dffa71a0fdb1a5ed69433973afd7d6c73d9ff | neelismail01/common-algorithms | /insertion-sort.py | 239 | 4.15625 | 4 | def insertionSort(array):
# Write your code here.
for i in range(1, len(array)):
temp = i
while temp > 0 and array[temp] < array[temp - 1]:
array[temp], array[temp - 1] = array[temp - 1], array[temp]
temp -= 1
return array
|
0e81f90bd31a9a378d2d4923176d4705d9d0f84a | jpecci/algorithms | /graphs/bfs.py | 1,454 | 3.734375 | 4 | from collections import deque
from sets import Set
def bfs(graph, start):
explored={} #store the distance
queue=deque()
queue.append(start)
explored[start]=0
while len(queue)>0:
tail=queue.popleft()
#print "%s -> "%(tail),
for head, edge in graph.outBounds(tail).items():
if head not in explored:
que... |
da3e119bb80133d329bedf3cde0cae09f12d4866 | jpecci/algorithms | /graphs/dfs.py | 827 | 3.75 | 4 | from Queue import Queue
from sets import Set
def dfs(graph, start):
explored=set() #store the distance
stack=[]
stack.append(start)
explored.add(start)
while len(stack)>0:
tail=stack.pop()
#print "%s -> "%(tail),
for head, edge in graph.outBounds(tail).items():
if head not in explored:
stack.append(... |
dc1116924017c9359798f1bb89e5f12424d21a93 | jpecci/algorithms | /sorting/bubblesort.py | 309 | 4 | 4 |
def swap(a,i,j):
temp=a[i]
a[i]=a[j]
a[j]=temp
def bubble_sort(a):
for i in range(len(a)):
swapped=False
for j in range(1, len(a)-i):
if a[j-1]>a[j]:
swap(a, j-1, j)
swapped=True
#print a
if not swapped:
break
if __name__=="__main__":
v=[0,5,2,8,3,4,1]
bubble_sort(v)
print v |
4af657b9bc471f8e6750e3c263e1a4ec43c5086a | vonkoper/pp3 | /zadania domowe/trojkat.py | 807 | 3.84375 | 4 | '''
Napisać program który sprawdzi czy z podanych przez użytkownika długości boków jest możliwość stworzenia trójkąta i oblicza jego pole.
'''
a=float(input("Podaj dlugosc pierwszego boku trojkata: "))
b=float(input("Podaj dlugosc drugiego boku: "))
c=float(input("Podaj dlugosc trzeciego boku: "))
dlugosci_bokow = ... |
1862fd92995dbb1f72b17543ba52fa53c1c65e82 | Czarne-Jagodki/labs | /lab1/ex1.py | 4,802 | 4.4375 | 4 | def print_matrix(matrix):
"""
Function shows a matrix of neighbourhood of graph.
:param list: it's a not empty array of arrays
:return: None
"""
i = 0
for row in matrix:
i = i + 1
print(i, end='. ')
print(row)
def print_list(list):
"""
Functio... |
39012923982f1cca9660d1cea01faac7cef24257 | cw02048/python-numpy-pandas | /test4.py | 368 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 19:19:18 2019
@author: cw020
"""
def main():
n_list = []
n = int(input())
i = 0
while i < n:
tmp = input()
n_list.append(tmp[0:len(tmp)-3])
i += 1
for n in sorted(n_list):
... |
3b087e39202ceefc8516e889161b06de68fd45d3 | Anastasijap91/RTR105 | /test20191010.py | 307 | 3.8125 | 4 | inp = raw_input("Enter a number between 0.0 and 1.0:")
score = float(inp)
if (score >=1.0):
print("Jus nepildat instrukcijas:")
exit()
elif (score >=0.9):
print("A")
elif (score >=0.8):
print("B")
elif (score >=0.7):
print("C")
elif (score>=0.6):
print("D")
else:
print("F")
|
a57688d3afbc2a044eae489a2a475db55bddbfe3 | orcl/coding | /algorithm/Stack/queueWithStack/queueWithStack.py | 670 | 3.828125 | 4 | class Queue:
#initialize your data structure here.
def __init__(self):
self.inbox = []
self.outbox = []
#@param x, an integer
#@return nothing
def push(self,x):
self.inbox.append(x)
#@return nothing
def pop(self):
if len(self.outbox) == 0:
while len(self.inbox) > 0:
self.o... |
5b9f9de8f78a512a5a023539fbe770e54c0679e6 | orcl/coding | /algorithm/Stack/stackWithQueue/stackWithQueues.py | 1,805 | 3.96875 | 4 | #!/usr/bin/python
#
#
class Stack:
#initialize your data structure here.
def __init__(self):
self.queue1 = []
self.queue2 = []
#@param x, an integer
#@return nothing
def push(self,x):
if not self.queue1:
self.queue2.append(x)
else:
self.queue1.append(x)
#@return nothing
def... |
730901965676d61fb26179be80b1e8ab0a6bbcc9 | ryankapler/Statbook | /Rando.py | 355 | 3.875 | 4 | #Random number generator
#to be done
amount = raw_input("How many random numbers do you need: ")
Num_max = raw_input("What is the max value you need: ")
Num_min = raw_input("What is the min value you need: ")
num_list = []
from random import randint
for i in range(int(amount)):
num_list.append(randint(int(Num_min),... |
81bf34bd0e8841eb9dba5da8b1c2cfc8005cfb24 | vagerasimov-ozn/python18 | /Lessons/lesson 6/class_testing/AninimSurvey.py | 738 | 3.53125 | 4 | class AnonimSurvey:
"""Собирает анонимные ответы на опросник"""
def __init__(self,question):
"""Содержит вопрос, и подготавливает список для ответа"""
self.question = question
self.responses = []
def show_question(self):
"""Показать вопрос"""
print(self.question)
... |
5b550f916aa21eb985c444582751b57c3baf9ec6 | vagerasimov-ozn/python18 | /test.py | 149 | 3.515625 | 4 | spi = ['volvo','suzuki','bmv']
#for i in range(5):
# print(barsuk)
#for i in range(len(spi)):
# print(spi[i])
for car in spi:
print(car) |
fa021815ff156a454f6f8a2c18fa7720aa536d95 | vagerasimov-ozn/python18 | /rusruletka.py | 624 | 3.640625 | 4 | # Давайте напишем программу русской рулетки
import random
amount_of_bullets = int(input("Сколько патронов? "))
baraban = [0,0,0,0,0,0]
# 0 - пустое гнездо
# 1 - гнездо с патроном
for i in range(amount_of_bullets):
baraban[i] = 1
print("Посмотрите на барабан", baraban)
how_much = int(input("сколько раз вы соби... |
3530861eb47f9b665eb10a3ddc24f65c886f7288 | rihu897/study-03-desktop-01-master | /search.py | 1,072 | 3.578125 | 4 | import pandas as pd
import eel
### デスクトップアプリ作成課題
### 課題6:CSV保存先をHTML画面から指定可能にする
def kimetsu_search(word, csv):
# トランザクション開始
try :
# 検索対象取得
df=pd.read_csv("./" + csv)
source=list(df["name"])
# 検索結果
result = ""
# 検索
if word in source:
result = "... |
4e50b816c598d0e1b226da7a067cf5cd7cd0764e | ijekel2/projects | /StoneQuest/StoneQuest/scenes/Introduction.py | 921 | 3.75 | 4 | from sys import exit
class Introduction(object):
def enter(self):
##
## Print the game title and description.
print("\n\n\n\n\n\n\n\n\n\n")
print(" *****************")
print(" ** STONE QUEST **")
print(" *****************")
p... |
b56b3f5d3c9b9ffd5aaee009288e30f908045249 | ijekel2/projects | /StoneQuest/StoneQuest/scenes/MirrorOfErised.py | 5,185 | 3.75 | 4 | class MirrorOfErised(object):
def enter(self):
##
## Print the introductory narrative for Level 6
print("\n")
print(" *************************************")
print(" ** LEVEL SIX: THE MIRROR OF ERISED **")
print(" *************************************")
... |
ffc720c4cc661893ee61c92899e255f3a093ef24 | DimmeGz/green_lantern | /lantern/tdd/lonely_robot.py | 4,943 | 3.765625 | 4 | class Asteroid:
def __init__(self, x, y):
self.x = x
self.y = y
class Robot:
compass = ['N', 'E', 'S', 'W']
def __init__(self, x, y, asteroid, direction, obstacle):
self.x = x
self.y = y
self.asteroid = asteroid
self.direction = direction
self.obsta... |
51640e43dbe3038b807c52fb2d65462cad9e226b | ultimabugger/python_homework | /func_num.py | 463 | 3.609375 | 4 | def div(*args):
try:
arg_1 = float(input("Укажите число x: "))
arg_2 = float(input("Укажите число y: "))
res = arg_1 / arg_2
except ValueError:
return "Что-то пошло не так :) Попробуйте еще раз"
except ZeroDivisionError:
return "На ноль делить нельзя!"
... |
6a1bd810422f098ca321fab3dfe9afa4a284e9a0 | lukkwc-byte/CSReview | /Queues.py | 894 | 3.84375 | 4 | #Init of a Queue
#Enqueue
#Dequeing
from LinkedLists import *
class QueueLL():
def __init__(self):
self.LL=LL()
def __str__(self):
return str(self.LL)
def Enqueue(self, node):
LL.AddTail(self.LL, node)
return
def Dequeue(self):
ret=self.LL.head
... |
f308cd2e7a7c979ab741b91fdc859b338ec453c9 | sency90/allCode | /acm/python/1850.py | 157 | 3.515625 | 4 | def gcd(b,s):
if s==0: return int(b)
else: return gcd(s,b%s)
a,b = map(int, input().split())
g = gcd(a,b)
i = 0
for i in range(g): print(1, end='')
|
721e5d6a05f065535b8fdec251e728310ecb9748 | neeraj1909/100-days-of-challenge | /project_euler/problem-1.py | 448 | 3.796875 | 4 | #!/bin/python3
import sys
def sum_factors_of_n_below_k(k, n):
m = (k -1) //n
return n *m *(m+1) //2
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
total = 0
#for multiple of 3
total = total + sum_factors_of_n_below_k(n, 3)
#for multiple of 5
total = total + sum... |
02a7e4eafa99a2c99c8c54e45846ef23e6358522 | konnomiya/algorithm021 | /Week_02/589.N-ary_Tree_Preorder_Traversal.py | 553 | 3.578125 | 4 | class Solution:
# iteration
def preorder(self, root: 'Node') -> List[int]:
stack, res = [root,], []
while stack:
node = stack.pop()
if node:
res.append(node.val)
stack.extend(node.children[::-1])
return res
# recursive
def ... |
08e72c506ad7c81b8295b6e3a2d16ff46cb3236d | sayanm-10/py-modules | /main.py | 3,660 | 3.5 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
__author__ = "Sayan Mukherjee"
__version__ = "0.1.0"
__license__ = "MIT"
import unittest
import os
from datetime import datetime, timedelta
from directory_analyzer import print_dir_summary, analyze_file
def datetime_calculator():
''' A helper to demonstrate the datetim... |
df11433519e87b3a52407745b274a6db005d767c | jtquisenberry/PythonExamples | /Interview_Cake/hashes/inflight_entertainment_deque.py | 1,754 | 4.15625 | 4 | import unittest
from collections import deque
# https://www.interviewcake.com/question/python/inflight-entertainment?section=hashing-and-hash-tables&course=fc1
# Use deque
# Time = O(n)
# Space = O(n)
# As with the set-based solution, using a deque ensures that the second movie is not
# the same as the current movi... |
e7d72e428f84364bde9130e8bcecc818ee628a94 | jtquisenberry/PythonExamples | /Interview_Cake/arrays/merge_meetings.py | 2,921 | 4.09375 | 4 | import unittest
# https://www.interviewcake.com/question/python/merging-ranges?course=fc1§ion=array-and-string-manipulation
# Sort ranges of tuples
# Time: O(n * lg(n)) because of the sorting step.
# Space: O(n) -- 1n for sorted_meetings, 1n for merged_meetings.
# First, we sort our input list of meetings by star... |
8eeff2df65c400e2ae316070389736e46dc1fc2b | jtquisenberry/PythonExamples | /Jobs/bynder_isomorphic_strings.py | 1,227 | 3.609375 | 4 | import unittest
def is_isomorphic(str1, str2):
if len(str1) != len(str2):
return False
character_map = dict()
seen_values = set()
for i in range(len(str1)):
if str1[i] in character_map:
if str2[i] != character_map[str1[i]]:
return False
... |
dbfbd24fa14eeef9f495b3e6c08b428e8274159f | jtquisenberry/PythonExamples | /Simple_Samples/list_comprehension_multiple.py | 104 | 3.578125 | 4 | X = [['a','b','c'],['z','y','x'],['1','2','3']]
aaa = [word for words in X for word in words]
print(aaa) |
e1c7953b7d1f52122d545583785a842e187a7bd7 | jtquisenberry/PythonExamples | /Simple_Samples/array_to_tree.py | 2,656 | 3.734375 | 4 | import math
from collections import deque
class Node():
def __init__(self, value, left_child = None, right_child = None):
self.value = value
self.left = None
self.right = None
def __str__(self):
return str(self.value)
nodes = [1,2,3,4,5,6,7,8]
current_index = 0
unlinked_nodes =... |
5e5c7d41a7344b9eb94f9f9dbde5dbe48390b5f6 | jtquisenberry/PythonExamples | /Interview_Cake/trees_and_graphs/graph_coloring.py | 6,495 | 4.3125 | 4 | import unittest
# https://www.interviewcake.com/question/python/graph-coloring?section=trees-graphs&course=fc1
# We go through the nodes in one pass, assigning each node the first legal color we find.
# How can we be sure we'll always have at least one legal color for every node? In a graph with maximum degree DDD, ... |
fcbb62045b3d953faf05dd2b741cd060376ec237 | jtquisenberry/PythonExamples | /Jobs/maze_runner.py | 2,104 | 4.1875 | 4 | # Alternative solution at
# https://www.geeksforgeeks.org/shortest-path-in-a-binary-maze/
# Maze Runner
# 0 1 0 0 0
# 0 0 0 1 0
# 0 1 0 0 0
# 0 0 0 1 0
# 1 - is a wall
# 0 - an empty cell
# a robot - starts at (0,0)
# robot's moves: 1 step up/down/left/right
# exit at (N-1, M-1) (never 1)
# length(of the shortes... |
ba8395ab64f7ebb77cbfdb205d828aa552802505 | jtquisenberry/PythonExamples | /Interview_Cake/arrays/reverse_words_in_list_deque.py | 2,112 | 4.25 | 4 | import unittest
from collections import deque
# https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1
# Solution with deque
def reverse_words(message):
if len(message) < 1:
return message
final_message = deque()
current_word = []
for i ... |
37506921175e5dfec216a7b8c0433d421e0cdbd1 | jtquisenberry/PythonExamples | /numpy_examples/multiplication.py | 365 | 3.703125 | 4 | import numpy as np
X = \
[
[3, 2, 8],
[3, 3, 4],
[7, 2, 5]
]
Y = \
[
[2, 3],
[4, 2],
[5, 5]
]
X = np.array(X)
Y = np.array(Y)
print("INPUT MATRICES")
print("X")
print(X)
print("Y")
print(Y)
print()
print("DOT PRODUCT")
print(np.dot(X, Y))
print()
print... |
8236247559f5951c95d1bd1a5074393c8feb8967 | jtquisenberry/PythonExamples | /Leetcode/triangle4.py | 488 | 3.640625 | 4 | from functools import lru_cache
triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
class Solution:
def minimumTotal(self, triangle):
@lru_cache()
def dfs(i, level):
if level == len(triangle):
return 0
left = triangle[level][i] + dfs(i, level + 1)
right = ... |
6abe6859f0ce87b6a8d6cdd400a0c910246b0f0d | jtquisenberry/PythonExamples | /Leetcode/1342_number_of_steps_to_reduce_a_number_to_zero.py | 408 | 3.71875 | 4 | from typing import *
class Solution:
def numberOfSteps(self, num: int) -> int:
steps = 0
while num > 0:
# print(num, bin(num))
if num & 1:
steps += 1
steps += 1
num = num >> 1
# print(steps)
if steps - 1 > -1:
... |
83cf3df4820c5d6a21118a51a2869080067a7870 | jtquisenberry/PythonExamples | /Interview_Cake/combinatorics/find_duplicated_number_set.py | 1,037 | 3.984375 | 4 | import unittest
# https://www.interviewcake.com/question/python/which-appears-twice?course=fc1§ion=combinatorics-probability-math
# Find the number that appears twice in a list.
# This version is not the recommended version. This version uses a set.
# Space O(n)
# Time O(n)
def find_repeat(numbers_list):
#... |
9adfabfbc83b97a11ee5b2f23cea5ec2eb357dd5 | jtquisenberry/PythonExamples | /Interview_Cake/sorting/merge_sorted_lists3.py | 1,941 | 4.21875 | 4 | import unittest
from collections import deque
# https://www.interviewcake.com/question/python/merge-sorted-arrays?course=fc1§ion=array-and-string-manipulation
def merge_lists(my_list, alices_list):
# Combine the sorted lists into one large sorted list
if len(my_list) == 0 and len(alices_list) == 0:
... |
2950d12a2c1981f470e285bb6af54e51bdc6fa94 | jtquisenberry/PythonExamples | /Pandas_Examples/groupby_unstack.py | 1,464 | 3.890625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
# https://stackoverflow.com/questions/51163975/pandas-add-column-name-to-results-of-groupby
# There are two ways to give a name to an aggregate column.
# It may be necessary to unstack a compound DataFrame first.
# Initial DataFrame
d = {'timeIndex': [1, 1, 1, 9, 1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.