blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5be22ec67d0e9a344de48401821934f0f103dafe | guyavrah1986/learnPython | /learnPython/classes_and_objects_9/privateMembersExample.py | 3,265 | 3.59375 | 4 | #########################################################################################
#########################################################################################
# 1) In Python, there is no really "private" access specifier for class methods/members.
# The convention, yet, is that a class attribute (m... |
a3442b662cab575e1cb7f35547927a5e31048324 | guyavrah1986/learnPython | /learnPython/questions/getFirstKNumbersInArrayThatAppearsMost.py | 2,173 | 4.125 | 4 | '''
Given an array of integers and number K, find the K numbers that appears most in the array and return
them according to descending order
'''
def get_descending_order_k_digits_array_that_appears_most_in_orig_arr(k: int, arr: list) -> list:
print("got the original array of number:" + str(arr) + ", and number k:... |
3019e10ea51c9ea06ef094f48cc6d52a9a89e89c | guyavrah1986/learnPython | /learnPython/passingByAssginment/passingArgumentsExample.py | 3,310 | 4.46875 | 4 | ###########################################################################################################
# Pass by assignment:
# In contrast to other programming languages, such as Java/C++, in Python there is NO really pass by
# reference mechanism. Here it is called (and performed) as pass by assignment.
# 1) If t... |
fee5687b81006514b5e45b0e6f4bf210713a0248 | guyavrah1986/learnPython | /learnPython/trainingNotes/iteratorExample.py | 2,263 | 4.40625 | 4 | # the motivation to implement an iterator for a custom class is that if, for example,
# this custom class contains a certain collection among its data members, the iterator
# will enable the "user" of this class to "iterate" over this collection in a "native"
# manner - i.e. - as if it would have iterate over any Pytho... |
24095765a961e2ba008ac4ba69604a875581421f | guyavrah1986/learnPython | /learnPython/questions/balancedBracketsString.py | 2,229 | 4.375 | 4 |
def check_balanced_brackets_string(s: str) -> bool:
print("the given string is:" + s)
brackets_stack = []
open_curly_braces_counter = 0
open_brackets_counter = 0
open_parentheses_counter = 0
# optimization: check if the length of the string is even (if not return 0)
if len(s) % 2 != 0:
... |
2c9921a54b2f9321c0eec15f547dc2c2c2eef40b | guyavrah1986/learnPython | /learnPython/questions/permutionSubString.py | 1,220 | 3.984375 | 4 | '''
Given two strings, A and B such that B isn't longer than A, return True or False if B is a
sub-string permutation of A.
'''
from learnPython.questions.questionsUtils import create_sub_string_chars_dict
def permutation_sub_string(str1: str, str2: str) -> bool:
print("got str1:" + str1 + ", and str2:" + str2)
... |
f89f19e5439e0771beb0ec2c49cd06a571568c9f | guyavrah1986/learnPython | /learnPython/trainingNotes/tupleDemo.py | 273 | 3.828125 | 4 | # differently from collection, tuples can not be modified
# highly used as a return value form function that needs to return more than a single value.
def ret_tuple(num1, num2):
my_tuple = (num1, num2)
return my_tuple
my_tuple = ret_tuple(12,45)
print(my_tuple)
|
aa4cd4e1564998726f18edf01575beb5ac21e86e | AlexUmnov/5_lang_frequency | /lang_frequency.py | 498 | 3.90625 | 4 | import re
from collections import Counter
MOST_COMMON_WORDS_COUNT = 10
def load_data(filepath):
with open(filepath, 'r') as text_file:
return ' '.join(text_file.read().splitlines())
def get_most_frequent_words(text):
words = re.findall(r'\w+',text.lower())
return Counter(words)
if __name__ == '... |
29bb9a3fd6c233a21343e1d8a9ba0c77c4794ab9 | kmustyxl/DSA_final_fighting | /NowCoder/Binary_Tree/EXAM_IfBalanceBinaryTree.py | 1,163 | 3.5625 | 4 | from NowCoder.Binary_Tree import Define_Binary_Tree as BT
class Node:
def __init__(self,val=None,lchild=None,rchild=None):
self.val = val
self.lchild = lchild
self.rchild = rchild
class returnans:
def __init__(self, ifB=None, h=None):
self.ifB = ifB
self.h = h
def IfBalan... |
9029dafbb12df950d1bac0a6c7addc6f90db1875 | kmustyxl/DSA_final_fighting | /NowCoder/Array_Sort/Merge_Sort.py | 995 | 3.890625 | 4 | def merge_sort(arr, L, R):
if L == R:
return
else:
mid = int((L +R) / 2)
merge_sort(arr, L, mid)
merge_sort(arr, mid+1, R)
return merge(arr, L, mid, R)
def merge(arr, L, mid, R):
help = []
p1 = L
p2 = mid + 1
while p1 <= mid and p2 <= R:
if arr[p1... |
f61460d41cf0e9dd0f1b4eb95e2e9f876486f93a | kmustyxl/DSA_final_fighting | /NowCoder/linked_list/EXAM_BackText.py | 1,504 | 3.796875 | 4 | class ListNode:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
def Use_stack(head):
stack = []
cur = head
while cur:
stack.append(cur.next)
cur = cur.next
while head:
if head.val != stack.pop().val:
return False
he... |
40f3266406e6edef2bf36beb94341e63c04702ca | kmustyxl/DSA_final_fighting | /NowCoder/二刷/顺时针旋转矩阵(正方形).py | 1,123 | 3.65625 | 4 | '''
将一个正方形数组矩阵顺时针旋转90度
tips:
从外层,一层一层旋转,只需搞定最外层即可同理
'''
import sys
def read_input():
try:
input_martix = []
while True:
line = sys.stdin.readline().strip()
if line == '':
break
input_martix.append(list(map(int,line.split())))
except:
... |
4b40bacd9cb84724d07f119aa8be1b11dd51495e | jeschauer/Moisture-Sensor | /mayday.py | 3,043 | 3.8125 | 4 | #!/usr/bin/python
# Start by importing the libraries we want to use
import RPi.GPIO as GPIO # This is the GPIO library we need to use the GPIO pins on the Raspberry Pi
import time # This is the time library, we need this so we can use the sleep function
from twilio.rest import Client
import os
# Your Account SID fro... |
491527a683111795aa0562f38d148794b393eb50 | Friendktt/My-work | /over.py | 393 | 3.8125 | 4 | """Over"""
import math
def main():
"""mainfunction"""
numx1 = float(input())
numy1 = float(input())
rad = float(input())
numx2 = float(input())
numy2 = float(input())
rad2 = float(input())
var = math.sqrt(((numx2-numx1)**2) + ((numy2-numy1)**2))
var2 = rad+rad2
if var... |
6984aa0231d9ff634cd8228938dc2712f8fe2440 | Friendktt/My-work | /kuy.py | 296 | 3.703125 | 4 | """look e mam"""
def main():
"""kuy"""
text1 = input()
text2 = input()
num1 = int(input())
num2 = int(input())
text1re = text1[::-1]
text2re = text2[::-1]
char1 = text1re[(num1-1)]
char2 = text2re[(num2-1)]
print(ord(char1)+ord(char2))
main()
|
18a10533430490dbc89a295b805b57df9eb388a0 | Friendktt/My-work | /STT.py | 441 | 3.84375 | 4 | """St"""
def main():
"""St"""
prod = input()
price = int(input())
weigh = int(input())
code = input()
day = int(input())
mont = int(input())
year = int(input())
year1 = int(input())
year2 = year + year1
print("Name:\t%s" %prod)
print("Price:\t%d" %price)
... |
2a0467204267636356cb3cb128f453f578e81db4 | udaykumarbpatel/HackerRankKit | /Product_of_2d_array.py | 388 | 3.6875 | 4 | a = [[1, 2, 3], [4, 5, 6]]
b = [[1, 2, 3], [4, 5, 6], [2, 3, 4]]
def product_of_array(a, b):
if len(a[0]) != len(b):
return "Not Possible"
c = [[0] * (len(b[0])) for i in range(len(a))]
for i in range(len(a)):
for j in range(len(a[0])):
for k in range(len(b)):
... |
b420f18d344ca209274d5f18dda0ed79c7d29ab0 | udaykumarbpatel/HackerRankKit | /Arrays_hourglassSum.py | 1,046 | 3.625 | 4 | # Complete the function hourglassSum in the editor below. It should return an integer, the maximum hourglass sum in the array.
#
# 1 1 1 0 0 0
# 0 1 0 0 0 0
# 1 1 1 0 0 0
# 0 0 2 4 4 0
# 0 0 0 2 0 0
# 0 0 1 2 4 0
import sys
def calculate_sum(arr, i, j):
return arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + ... |
eb33b6bc99ab1da9365a20c74e2001bcbd549fea | udaykumarbpatel/HackerRankKit | /ParenthesesTest.py | 890 | 3.828125 | 4 | class Stack:
def __init__(self):
self.stack = list()
def push(self, data):
self.stack.append(data)
def pop(self):
if len(self.stack) <= 0:
return "Stack Empty"
else:
return self.stack.pop()
def size(self):
return len(self.stack)
def ch... |
8937f888a9840014a28d6a559bc639eae54f2a64 | wesshih/astr427 | /hw1/interpolate.py | 6,390 | 4.3125 | 4 | import numpy as np
# import matplotlib.pyplot as plt
'''
Wesley Shih
1237017
Astr 427 Homework 1
4/11/17
Problem 3: Interpolation
This problem asks us to implement a program that can read in a data file and interpolate
between the given values. We begin by implementing a linear interpolator, and then move
on to usi... |
c8d42762f1ba5f26bd5112890d47ecaef5bed717 | wesshih/astr427 | /hw1/MachineConstants.py | 3,934 | 3.609375 | 4 | import numpy as np
'''
Wesley Shih
1237017
Astr 427 Homework 1
4/11/17
Problem 1: Machine Constants
The first problem of the homework asks us to empirically determine several
machine constants related to floating point numbers. These include the smallest number
epsilon that can be successfully added to or subracted ... |
85583679289dcad5eec530c84a0c380a15d1e324 | KepAlex-404/MND_Gryshyn | /lab01/src/scripts.py | 2,102 | 3.5 | 4 | import time
from random import *
from copy import deepcopy
def time_of_function(function):
""""Функция-декоратор для замера времени"""
def wrapped(*args):
start_time = time.time()
res = function(*args)
time_of_work = time.time() - start_time
print(f"Час виконання - {time_of_wor... |
1654c8235aa45abf509d82f418234e366cb5f1e2 | duongyen24/python-master | /tik tak toe.py | 474 | 3.6875 | 4 | board = ["-","-","-",
"-","-","-",
"-","-","-",]
def display_board():
print(board[0],board[1],board[2])
print(board[3],board[4],board[5])
print(board[5],board[6],board[7])
display_board()
def play_game():
display_board()
handle_turn()
def handle_turn():
position= input("ch... |
dfe027cfc14bb5ea4753ac360d7303a66190360d | nikhenry2212/geeksforgeeks. | /exercicio.py | 1,710 | 3.84375 | 4 | # Programa Python3 para encontrar o máximo
# produto de um subconjunto.
# def para encontrar o máximo
# produto de um subconjunto
def minProductSubset(a, n):
if (n == 1):
return a[0]
# Encontre a contagem de números negativos,
# contagem de zeros, valor máximo
# número negativo, valor mínimo
# núme... |
4ad32f26474866dca5d29d83e738c2f7c6bf5e65 | jonatasvcvieira/pythonbasicoavancado | /aula5/aula5.py | 403 | 4.03125 | 4 | # Operadores Aritiméticos
'''
+, -, *, /, //, **, %, ()
'''
print(10 // 3) # Divisão arrendondar para inteira
print(2 ** 10) # Potenciação
print(10 % 5) # Resto da divisão
print(5 + 2 * 10) # Alterar a precedência dos operadores
print((5 + 2) * 10) # Alterar a precedência dos operadores
print(20 * 'A')
print(20... |
5f1e1d8c06d0ae06ca7de9fd925913aff1d617b0 | jonatasvcvieira/pythonbasicoavancado | /aula9/aula9.py | 201 | 3.921875 | 4 | '''
Condições IF, ELIF, ELSE
'''
if False:
print('Verdadeiro.')
elif False:
print('Agora é verdadeiro.')
elif False:
print('Mais uma verdadeira.')
else:
print('Nada é verdadeiro.')
|
3ff1a064a2415dcbc665d337272f21cd83ea51cc | LKaMe/Machine_Learning | /code/tensorflow2.0/05 TensorFlow进阶/数据限幅.py | 275 | 3.671875 | 4 | import tensorflow as tf
x = tf.range(9)
tf.maximum(x,2)#下限幅到2
tf.minimum(x,7)#上限幅到7
#基于tf.maximum函数,实现ReLU函数
def relu(x):#ReLU函数
return tf.maximum(x,0.)#下限幅为0即可
x = tf.range(9)
tf.minimum(tf.maximum(x,2),7)#限幅为2~7
|
5c300be9381193494ccef5b6824161d22b06719f | rhettg/Tron | /tron/utils/timeutils.py | 1,332 | 3.90625 | 4 | """Time utilites"""
import datetime
import time
# Global time override
_current_time_override = None
def override_current_time(current_time):
"""Interface for overriding the current time
This is a test hook for forcing the app to think it's a specific time.
"""
global _current_time_override
_... |
cc3c54e50001a955e391e6e61b10fbd1787274ce | ercchy/project_euler | /problem_2.py | 757 | 4.4375 | 4 | import sys
def get_fibonacci(limit):
ret_val = []
a, b = 0, 1
while a <= limit:
a, b = b, a + b
ret_val.append(a)
return ret_val
def main():
limit = int(sys.argv[1])
sequence = get_fibonacci(limit)
"""
The Fibonacci series is:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610...
Now, replac... |
8c7a6d8a94cdbd44f052c829a59d4089d8c937c9 | tri2sing/IntroPython | /Conditionals.py | 468 | 3.875 | 4 | import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument ('-n', '--num', type=float, default=float('-inf'), help='a number of your choice')
args = parser.parse_args()
num = args.num
if num == float('-inf'):
print('You should have made a choice')
... |
96b61851dca2a19f353faf0bc716dfcc5932f445 | tri2sing/IntroPython | /Dictionaries02.py | 1,064 | 4.03125 | 4 |
if __name__ == '__main__':
# Dict as a sparse list
print('\n')
L1 = {0: 'are', 5: 'you', 99: 'home'}
print(L1)
print(L1[0])
print(L1[5])
print(L1[99])
if 77 not in L1:
print("Key Missing")
# By default is you use a list
# Then 0 -> are
# but 1 -> you instead of our ... |
ca024691c12e55b84b3fb1bc7eb3e47089cc4695 | tri2sing/IntroPython | /Dictionaries01.py | 2,385 | 4.03125 | 4 |
if __name__ == '__main__':
# Dict as a map from keys to values
D1 = dict()
D1['a'] = 1
D1['b'] = 2
D1['c'] = 3
print(D1)
D2 = {}
D3 = {}
start = ord('a') # get ASCII code of character
end = ord('z')
# Creating a dictionary automatically and its reverse too
for i in ... |
e9a90d70872f817c8d36b06842fb093109b7dd56 | ChuixinZeng/PythonStudyCode | /PythonCode-FatherandSon/示例代码/Listing_16-4.py | 649 | 3.78125 | 4 | # Listing_16-4.py
# Copyright Warren & Carter Sande, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# Draw a circle in the middle of the window
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.f... |
72a4882a1d43db1abd7191a58fe2823dadd70383 | ChuixinZeng/PythonStudyCode | /PythonCode-OldBoy/Day4/随堂练习/2_装饰器准备_函数即变量.py | 1,632 | 4 | 4 | # -*- coding:utf-8 -*-
# Author:Chuixin Zeng
# 第一段代码,无法运行,没有定义bar
# 相当于bar没有对应的房间,只有门牌号
# def foo():
# print("in the foo")
# bar()
# foo()
# 第二段示例代码,可以运行
# bar有房间了,也有门牌号
# def bar():
# print("in the bar")
# def foo():
# print("in the foo")
# bar()
# foo()
# 第三段示例代码,可以运行
# Python是解释运行的语言,所以定义x=1,... |
7f560ce843bc6859f079c375b81aaf92cc83c13a | ChuixinZeng/PythonStudyCode | /PythonCode-OldBoy/考核/16_字典操作.py | 1,613 | 3.796875 | 4 | # -*- coding:utf-8 -*-
# Author:Chuixin Zeng
# 字典 dic = {'k1': "v1", "k2": "v2", "k3": [11,22,33]}
# a. 请循环输出所有的 key
dic = {'k1': "v1", "k2": "v2", "k3": [11,22,33]}
for i in dic.keys():
print("key:",i)
# 请循环输出所有的 value
for i in dic.values():
print("value:",i)
# 请在字典中添加一个键值对,"k4": "v4",输出添加后的字典
# Python 字典 s... |
7ea0b4770e9edd5e9a63a51bdaa8031ea3eb705f | ChuixinZeng/PythonStudyCode | /PythonCode-OldBoy/考核/1_用户登录3.py | 663 | 3.8125 | 4 | # -*- coding:utf-8 -*-
# Author:Chuixin Zeng
# 实现用户输入用户名和密码,当用户名为 seven 或 alex 且 密码为 123 时,显示登陆成功,否则登陆失败,失败时允许重复输入三次
for i in range(3):
username = input("username:")
password = input("password:")
if username == "seven" or username == "alex":
if password == "123":
print("success")
... |
f79c084b2d115629a4abb9121c971366d56d9991 | ChuixinZeng/PythonStudyCode | /PythonCode-OldBoy/Day5/随堂练习/random模块/random生成随机验证码.py | 723 | 3.671875 | 4 | # -*- coding:utf-8 -*-
# Author:Chuixin Zeng
import random
# checkcode用于保存最终要生成的字符串类型的数据,就是保存验证码的
checkcode = ''
# 设置验证码长度为4位
for i in range(4):
# 0,1,2,3
current = random.randrange(0,4)
# 猜测的值的结果,如果current随机的值不等于i的值,则temp当前loop的值为字母
if current != i:
# chr用于ASCII码转换为字母
# 65-90是大写字母从A到Z... |
a488e11009186427e8ad6d3d00518bd85b52158f | ChuixinZeng/PythonStudyCode | /PythonCode-OldBoy/Day3/随堂练习/作用域、局部与全局变量_2.py | 974 | 4.03125 | 4 | # -*- coding:utf-8 -*-
# Author:Chuixin Zeng
# 下面直接在函数里面强制声明一个全局变量,也是可以的
# 但是不要这么干,global不建议用,下面的用了就可能被开除,呵呵
# 原因这么干了之后,函数会在程序的很多地方调用,很难找到哪个地方调用了global,很难调试,无法调试,程序就乱了
# 切记:不要在函数里面改全局变量,如果非要改的话,就按照《作用域、局部与去全局变量_1》里面的用,里外都有定义
'''
def change_name():
global name
name = "alex"
change_name()
print(name)
'''
sch... |
568ae05a14cec775e9a3b1230afd7a8b01befc6f | pankhurikumar23/artificial-intelligence | /assignment1/npuzzle.py | 13,740 | 3.984375 | 4 | """
Artificial Intelligence - Programming Homework 1
Implement and compare different search strategies
for solving the n-Puzzle, which is a generalization of the 8 and 15 puzzle to
squares of arbitrary size.
@author: PANKHURI KUMAR (PK2569)
"""
import time
def state_to_string(state):
row_strings = [" ".join([st... |
32bca54cfb078c442ccf8fb5b2a75f8bbc328227 | sameerreddy13/LFD_MachineLearning_Code | /h1_pla.py | 3,138 | 3.875 | 4 | import numpy as np
'''
In this problem f is a random line representing the decision boundary.
Points above this line are 1's and points below are -1's.
We are using the PLA to learn this decision boundary from already classified points.
The training dataset consists of points randomly picked from D = [-1, 1] x [-1, 1... |
d46399b6d1670e6d72ed393951acecd7f113f8f3 | joshuasearle/ds-and-algs | /adts/dynamic-array.py | 2,950 | 3.734375 | 4 | class DynamicArray(object):
"""
Array class that resizes dynamically.
Will treat the python array as a static array.
"""
initial_capacity = 8
@staticmethod
def generate_empty_array(n):
return [None for _ in range(n)]
def __init__(self):
self.capacity = Dynam... |
bb98a074410b3a642e99997cbf13dab4b614c253 | IliyanAntov/TrafficSign | /TrafficSignCode/Secrets/ChangeUserPassword.py | 1,863 | 3.5 | 4 | import hashlib
import os
import yaml
users = {} # Available users dictionary
# Open the Users.yaml file as a readable stream
with open("Users.yaml", "r") as stream:
try:
# Convert the contents of the file to a python object
loaded = yaml.safe_load(stream)
# Add every loaded entry to the u... |
d49e3ef87efd50dc6bd53ec74e4805f0e952a577 | OrchaniousS/codewars_katas | /7_kyu/Python/Highest and Lowest.py | 208 | 3.53125 | 4 | # Link : https://www.codewars.com/kata/554b4ac871d6813a03000035
def high_and_low(numbers):
numbers = numbers.split(' ')
numbers = [int(x) for x in numbers]
return f"{max(numbers)} {min(numbers)}" |
fa67167496252ea0e5d5d1368011c41df6d0a97d | denniswittich/dw | /dw/files.py | 1,841 | 3.640625 | 4 | """
Created on Oct 10 2018
Last edited on Oct 10 2018
@author: Dennis Wittich
"""
import os
def crawl_do(root, condition, action, skip=None, verbose=False):
"""Recursively crawls folders and performs action on files which fulfil a condition
Parameters
----------
root : str
Pa... |
1f61949fd99793766d735b9b783be74d94e4ae87 | zjroth/game-of-life | /python/game_of_life.py | 8,177 | 4.125 | 4 | # ========================================================================
# Imports
# ========================================================================
# This is for creating a randomized board (which really only exists for the
# purposes of the demo in demo.py)
import random
# ===============================... |
3724f33950996911eb0b16c8c66791e5d5162453 | Snubia/tictactoe | /game.py | 2,506 | 4.125 | 4 | #first we need a list comprehansion with 9 space. because we are lazy we won't make 9 spaces but just run a for loop
board = [" " for i in range(9)]
#we will define a function to print the rows
def print_board():
row1 = "|{}|{}|{}|".format(board[0], board[1], board[2])
row2 = "|{}|{}|{}|".format(board[3], b... |
c66939e8f2e7238fd43e0d7f1e206e41e4f53ad4 | dondropo/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 205 | 3.5625 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
new_mtx = []
for j in matrix:
support_list = list(map(lambda x: x ** 2, j))
new_mtx.append(support_list)
return(new_mtx)
|
ad4c949037a0ab6b4a75dbabe2a1c9aca5d539db | dondropo/holbertonschool-higher_level_programming | /0x0A-python-inheritance/2-is_same_class.py | 306 | 3.890625 | 4 | #!/usr/bin/python3
"""
returns True if the object is exactly
an instance of the specified class;
otherwise False
"""
def is_same_class(obj, a_class):
"""checks if the object is an instance of
the specified class"""
if type(obj) is a_class:
return True
else:
return False
|
e510f0a2b42e2b2ab6407eb53ae36b4ac7622939 | Veselin-Stoilov/softuni-projects-python-basics | /conditional_statements_advanced_exercise/hotel_room.py | 745 | 3.640625 | 4 | month = input() # May, June, July, August, September, October;
nights = int(input())
studio_rate = 0
apartment_rate = 0
if month in ('May', 'October'):
studio_rate = 50
apartment_rate = 65
if 7 < nights <= 14:
studio_rate *= 0.95
elif nights > 14:
studio_rate *= 0.7
elif month in ('June'... |
b7984076da6661ddb8ac34de5d93610e12e6020a | Veselin-Stoilov/softuni-projects-python-basics | /cond_statements_project/time_plus_15_min.py | 874 | 3.859375 | 4 | hour_input = int(input())
minutes_input = int(input())
hour_output = hour_input
minutes_output = minutes_input + 15
if minutes_output >= 60:
hour_output = hour_input + 1
minutes_output = minutes_output - 60
if minutes_output < 10:
if hour_output < 24:
print(f'{hour_output}:0{minutes_out... |
50c125d7d3f3ba9a33c4f174d3029dcc06a36e91 | lucasfonseca19/EP1-Desoft | /EP1.py | 6,178 | 3.796875 | 4 | #Importando biblioteca para o sorteio randômico de dados
import random
#Declarando lista de 1 a 6 representando os dados
dado1=[1,2,3,4,5,6]
dado2=[1,2,3,4,5,6]
#Estabelecendo o valor inicial de fichas para o jogador
fichas=100
#Declarando contadores utilizados ao longo do código
n=1
z=0
point=0
#Declarando variáveis u... |
aab2996e9c0b8a1fcc7a20aca4724773385bb894 | hcjun-dev/Python_College | /src/file0306.py | 1,212 | 3.90625 | 4 | ##
# Hyungchol Jun
# 2014-03-01
# p6.4 hij
def hfunc(mainlist): # checking if the list is in order
if (mainlist == sorted(mainlist)) or (mainlist == sorted(mainlist, reverse=True)): # in order or in reverse order
return True
return False # if not in order, return False
def ifunc(mainlist): # Dup... |
48a04907057bce1709a0989ecee9753d9e0b379f | hcjun-dev/Python_College | /src/file0414_2classCar.py | 853 | 3.59375 | 4 | # This is a car class done in the 10:00 section of IT 210
"""
cost
stickerPrice
year
make
model
color
inv_number
"""
class Car:
_invNumber = 1000 # Class Variable
def __init__(self, make, model, year, cost):
self._make = make
self._model = model
self._year = str(year)
self._cost = cost
Car._invNumber +=... |
307d7eacb2cbc3fcefec544a944e640d0ae6dd96 | hcjun-dev/Python_College | /src/file0410.py | 684 | 3.625 | 4 | ## Hyungchol Jun
# 2014-04-10
# P_9.5
'''
implement a class SoadCan with methods getSurfaceArea() and getVolume(). In the constructor, supply the height and radius of the can
'''
from math import pi
from random import randint
class SodaCan(object):
def __init__(self, height, radius):
self._height = height
self.... |
26d619f1cc5e9e404811d116fefe8d56bd33621c | online-developer/cicd-buzz | /tests/test_generator.py | 566 | 3.828125 | 4 | #!/usr/bin/env python
import unittest
from buzz import generator
def test_sampling_single_word():
words = ('foo', 'bar', 'foobar')
word = generator.sampling(words, 1)
assert word in words
def test_sampling_multiple_word():
words = ('foo', 'bar', 'foobar')
word = generator.sampling(words, 2)
... |
232b26d152a746d15534c4100d36b94eadced2a6 | statunited/LC | /LC272.py | 2,587 | 3.625 | 4 | """
Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.
Note:
Given target value is a floating point.
You may assume k is always valid, that is: k ≤ total nodes.
You are guaranteed to have only one unique set of k values in the BST that are closest to the t... |
86875b76bd130728f3fb881c3a1a70423acdd616 | phmartinsconsult/curso_python_3_luis_otavio | /Aula_24_Split_Join.py | 205 | 4 | 4 | '''
SPLIT, JOIN, ENUMERATE
'''
string = 'O Brasil é penta.'
lista = string.split()
string2 = " ".join(lista) ### Join é para juntar elementos de uma string.
print(string)
print(lista)
print(string2)
|
217daa4c7cdb3221406c4dc43a0a9851bf56a3f3 | phmartinsconsult/curso_python_3_luis_otavio | /DCC-Aula-1-d-Métodos_Públicos_e_Privados.py | 870 | 4.28125 | 4 | '''
Encapsulamento - Ocultação de Classes
Podemos restringir o que pode ser acessado fora da Classe
Encapsulamento proporciona ABSTRAÇÕ - PROTEÇÃO
'''
import math
class Circ:
def __init__(self, x=0.0, y=0.0, r=1.0):
########(self, x, y=0.0, r=1.0):
self.x = x # atributos do método
self.y =... |
26db2d4378dc057a6185caea7963dcce884b8c39 | phmartinsconsult/curso_python_3_luis_otavio | /Aula_33_Programa_Perguntas_e_Respostas.py | 1,691 | 3.578125 | 4 | '''
PROGRAMA DE PERGUNTAS E RESPOSTAS
'''
print()
print('************************************************************')
print("Leia as seguintes perguntas e indique as respostas corretas")
print('************************************************************')
perguntas = {
'Pergunta 1': {
'pergunta': 'Quant... |
009abd8756043788207ae7838c6ac2193af9b18c | phmartinsconsult/curso_python_3_luis_otavio | /Aula_16_Formatação.py | 868 | 4.3125 | 4 |
def divisao():
print('************************************')
print('***** PROGRAMA DE FORMATAÇÃO *******')
print('************************************')
print(" ")
nome = input('Nome: ')
numero1 = int(input("Primeiro número: "))
numero2 = int(input("Segundo número: "))
divisao = numero... |
b6233ac08c0a6080eaefc8538a59ac51cd1ebbd7 | phmartinsconsult/curso_python_3_luis_otavio | /Aula_41_Try_Except_2.py | 379 | 3.765625 | 4 |
def divide(n1,n2):
try:
return n1/n2
except ZeroDivisionError as error:
print('Log:', error)
raise
# Erro: tentar dividir por zero.
try:
print(divide(2,0))
except ZeroDivisionError as error:
print(error)
# Desenvolvedor não coloca mensagens sem sentido para usuário final.
# P... |
b5c0b908f8a7ca8640be77ef161712c9df5a2616 | phmartinsconsult/curso_python_3_luis_otavio | /Aula_25_Enumerate.py | 427 | 3.671875 | 4 | '''
ENUMERATE - Dúvidas
DESEMPACOTAR COM ENUMERATE - Gerando tuplas
'''
lista = [
['Paulo', 'Geraldo', 'Luis'],
['Guilherme', 'Bolsonaro', 'Filho04'],
['Lula', 'Paulinho', 'Jesus']
]
for v1, v2 in enumerate(lista):
print(v1, v2)
print("**********************")
for v1, v2 in enumerate(lista, 53):
... |
31a4ff3e279fa7394591d6591b36cd1ce8093554 | phmartinsconsult/curso_python_3_luis_otavio | /Aula_22_For_True_False.py | 365 | 3.65625 | 4 | '''
FOR e ELSE podem ser utilizados.
'''
variavel = ['Paulo', 'Alberto', 'Jorge', 'Carlos']
comeca_com_j = False
for valor in variavel:
if valor.lower().startswith('j'):
print(f'{valor} começa com J')
comeca_com_j=True
print(f'A palavra {valor} começa com J')
continue
#else:
... |
2eb276f50c1277657afc8786106a6a9be7119554 | phmartinsconsult/curso_python_3_luis_otavio | /Pratica_List_Comprehension_If_Ternário1.py | 189 | 3.765625 | 4 |
print('List Comprehension')
lista = [1,2,3,4,5,6,7,8,9]
ex1 = [v+2 for v in lista if v%2==0]
print(ex1)
print()
print('If ternário')
x=90
ex2 = ['Par!' if x%6==0 else 'Impar!']
print(ex2) |
d16714635d5f1f5fb78cb6a0b2ae4d45128ffbf6 | phmartinsconsult/curso_python_3_luis_otavio | /Aula_14_Documentacao.py | 533 | 4.09375 | 4 | '''
Funções:
string.isnumeric()
string.isdigit()
'''
print('******************************')
print('*** CALCULADORA PROGRAMADA ***')
print('******************************')
# Não deixar o usuário caminhar se não digitar números corretamente.
num1 = input("Primeiro número: ")
num2 = input("Segundo número: ")
if num1.i... |
521db944f02dcccd6eab73d43d1e5a241ae5d119 | huuugh18/Programming-In-Python | /Module 3 - Retrieving Web Data/regex_tutorial.py | 486 | 4.15625 | 4 | ## regex cheat sheet
## https://cheatography.com/mutanclan/cheat-sheets/python-regular-expression-regex/
## using ctrl+f to find in VSC then ALT+R to search using regex
text = 'something'
numbers = 1234
sentence = 'This is a sentence'
import re
#email validation
pattern = '[a-zA-Z0-9]+@[a-zA-Z]+\.+(com|edu|net)'... |
26c5ed01b1f91c4c083a706358b717770cd08f2e | naveed125/coding-challenges | /add-two-nums.py | 1,147 | 3.640625 | 4 | from utils.LinkedList import *
class Solution(object):
def convertToNum(self, head):
lst = []
while head:
lst.append(head.val)
head = head.next
ret = 0
i = 1
while lst:
ret += lst.pop(0) * i
i *= 10
return ret
... |
43d2ad43d9992e7a69a514299e0b5445c2ee6024 | elderlima/python_fundamentals | /aulas/oldbank/oldbank.py | 2,828 | 4.1875 | 4 | #!/usr/bin/python3.6
# -*- coding: utf-8 -*-
# class classe(): #Declarando a Classe. O ":" indica vamos iniciar o bloco
# def __init__(self): #O __init__ é o Construtor. Será chamdo sempre que criarmos objetos da classe "classe"
# self.atributo1 = '1o Atributo'
# self.atributo2 = '2o Atributo'
# ... |
abf51541bd4415a117ec4e44062ba0c2e66ced9d | ganesh-al/py4e | /type_conversion.py | 454 | 4.3125 | 4 | '''Bottom line of this excercise - using int() or float() or str(), data type can be converted. Input when read is always string'''
#assigning string value of 123 to i.
i='123'
print (i)
print(type(i)) #printing the type of i. This will be a string
i = int(i) #converting to integer
j=float(i)
print(type(j))
print(j)
k=... |
741cfbc651555199251d09e9aff5112a1fc5cd61 | Prakti/striptease | /striptease/numbers.py | 4,401 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
striptease.numbers
~~~~~~~~~~~~~~~~~~
Defines Tokens for handling numbers. The base-implementations of this
module heavily rely on the std-lib module struct for de-/encoding python
numbers into and out of bytestrings. This module just harbors the basic
implementation... |
bf79c97ec9d5b0bc3eb52168d09a2960e7c0ba56 | rrohrer1/PythonNRES | /week7_Rodney_Rohrer.py | 4,640 | 3.71875 | 4 | # 1. Use Pandas to repeat the Week 5 Exercise 5.7
# Hint1: Use pd.read_csv(url, ...) to read the USGS online gauge data.
# Hint2: Use df.set_index() to set the datetime column and df.resample() to calculate the monthly and annual statistics
import pandas as pd
import os
##############################################... |
fc07c71b74e30350d7b20e22d2779664109ae1f7 | shanksms/ideserve | /binary_tree/binary_tree_traversal.py | 2,262 | 3.71875 | 4 | ##code to be written
from binary_tree import BinaryTree
def pre_order_traversal(root):
print(root.data, end=' ')
if root.left != None and root.right != None:
pre_order_traversal(root.left)
pre_order_traversal(root.right)
def in_order_traversal(root):
if root.left != None:
in_or... |
76825b86b160b37825cbe0dcea5ad1ef161fd77c | nisabzahid/data-structure-and-algorithm | /selection_sort.py | 266 | 3.90625 | 4 | def find_smallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if smallest > arr[i]:
smallest = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
sorted_arr = []
|
0f17faaac3e3d8c91226168d0b5ff3fb6b4ebb9b | sujalgera01/Hacktoberfest_2021-1 | /Python/Sorting Algorithms/bubble_sort.py | 453 | 4.28125 | 4 | #bubble sort implementation in python
def bubble_sort(arr):
for i in range(len(arr)-1):
for j in range(len(arr)-i-1):
if arr[j]>arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]
if __name__=="__main__":
arr=[5,4,9... |
5878122914744d25483f6c40d4523713bb3e5f97 | MakeSchool-17/twitter-bot-python-choncou | /work/sampling.py | 1,559 | 3.546875 | 4 | import sys
import re
import random
def histogram(filename):
file_source = open(filename, encoding='utf-8')
big_word_list = file_source.read()
regex = re.compile("[^a-zA-Z']")
sub = regex.sub(' ', big_word_list)
sub = sub.lower()
big_word_list = sub.split()
dictionary = {}
for i in ra... |
c3156065ed40051514830e8e88097a3fbca993bd | calvincruzader/pythonPractice | /reverseWords.py | 165 | 3.578125 | 4 | class Solution:
def reverseWords(self, words):
return " ".join(list(reversed(list(words.split(" ")))))
s = Solution()
print(s.reverseWords("test hey there")) |
2470516c513ae453506d416b3357d7fe5f46834f | DarkSchokolade/SortingVizualized | /SelectionSort Algorithm/selectionsort.py | 722 | 3.71875 | 4 | #selection sort algorithm
import time
import csv
x=[]
field_names = ['x_value', 'y_value']
def selection_sort(A):
for k in range(1, len(A)+1):
x.append(k)
for i in range(0, len(A)-1):
minIndex = i
for j in range(i+1, len(A)):
if A[j] < A[minIndex]:
minIndex = j
if i != minIndex... |
43506550f91012f6bd065cdcbd2cac61767c37ea | shantanusarkar/my_practiced_codes | /hackerearth_solutions/palindrome.py | 331 | 3.625 | 4 | def palindrome(num):
if num[::-1] == num:
return True
else:
return False
n = int(raw_input())
for x in range(0, n):
a = raw_input()
a = a.split()
m = int(a[0])
n = int(a[1])
count = 0
for y in range(m, n+1):
if palindrome(str(y)) == True:
count += 1
... |
94eedf8195b29e881205b3d646fe18e28bcd99e8 | shantanusarkar/my_practiced_codes | /codechef_solutions/levy.py | 1,484 | 3.8125 | 4 | ##Levy's conjecture, named after Hyman Levy, states that all odd integers
##greater than 5 can be represented as the sum of an odd prime number and an
##even semiprime. To put it algebraically, 2n + 1 = p + 2q always has a
##solution in primes p and q (not necessary to be distinct) for n > 2.
##In this problem, given a... |
6016504658d7c8e0048056d6981ce2025c2f0427 | peaks-cc/cryptocurrency-samplecode | /05/p2p/edge_node_list.py | 2,037 | 3.84375 | 4 | import threading
class EdgeNodeList:
"""
Edgeノードのリストをスレッドセーフに管理する
"""
def __init__(self):
self.lock = threading.Lock()
self.list = set()
def add(self, edge):
"""
Edgeノードをリストに追加する。
param:
edge : Edgeノードとして格納されるノードの接続情報(IPアドレスとポート番号)
"""... |
762342ce14e4d197a92b53064bce548c3c07d5db | peaks-cc/cryptocurrency-samplecode | /02/03/p2p/core_node_list.py | 1,665 | 3.6875 | 4 | import threading
class CoreNodeList:
def __init__(self):
self.lock = threading.Lock()
self.list = set()
def add(self, peer):
"""
Coreノードをリストに追加する。
param:
peer : Coreノードとして格納されるノードの接続情報(IPアドレスとポート番号)
"""
with self.lock:
print('A... |
514116e8f062b5024ad0353bed6c718dde647c6c | j3nn1/memoPython | /muistikirja.py | 2,706 | 3.5 | 4 | import time
import pickle
def tallenna(tallennettava):
tiedosto = open("muistio.dat","wb")
pickle.dump(tallennettava,tiedosto)
tiedosto.close()
def lue():
try:
tiedosto = open("muistio.dat", "rb")
luettu = pickle.load(tiedosto)
tiedosto.close()
return luettu
except ... |
18081302a93e40c650409f4a7167d92219aef64b | liukai-tech/Python_Study | /VsCodePython/file_write_read/replace_string.py | 1,664 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# replace strings in text
import os
def Replace(file_name, rep_word, new_word):
with open(file_name) as f:
content = []
count = 0
for eachline in f:
if rep_word in eachline:
count += eachline.cou... |
2fa7ad1fa7e2045e5f64491196201cfa15e3faec | liukai-tech/Python_Study | /VsCodePython/socket/server.py | 1,032 | 3.609375 | 4 | #!/usr/bin/python3
# 文件名:tcp server.py
# 导入 socket、sys 模块
import socket
import sys
import threading
import time
COD = 'utf-8'
def tcplink(sock, addr):
print('Accept new connection from %s:%s...' % addr)
sock.send(('Welcome').encode(COD))
while True:
data = sock.recv(1024)
... |
25d87e73ed3fad1bdf763a48ddb2da6c9f6f00b2 | liukai-tech/Python_Study | /while.py | 167 | 3.921875 | 4 | #! /usr/bin/env python3
print("Hello World!")
if True:
print("True")
else:
print("False")
i = 10
while i > 0:
print("%d" % i)
i -= 1
|
f354b6f769ea494288df3778629490bec1d3d6b5 | liukai-tech/Python_Study | /BMI.py | 1,038 | 3.5 | 4 | #!/usr/bin/env python3
'''
BMI 指数(即身体质量指数,简称体质指数又称体重,英文为 Body Mass Index,简称BMI),
是用体重公斤数除以身高米数平方得出的数字
'''
print('----欢迎使用BMI计算程序----')
name=input('请键入您的姓名:')
height=eval(input('请键入您的身高(m):'))
weight=eval(input('请键入您的体重(kg):'))
gender=input('请键入你的性别(F/M)')
BMI=float(float(weight)/(float(height)**2))
#公式
... |
4566ee93284c8690903bcdd83a506a75c9eeb3c7 | Gabriel-RdS/CodeWarsResolutions | /ConvertStringToCamelCase.py | 539 | 3.5625 | 4 | """
link: https://www.codewars.com/kata/517abf86da9663f1d2000003/train/python
"""
def to_camel_case(text):
return text[:1] + text.title()[1:].replace('_', '').replace('-', '')
print(to_camel_case("the-stealth-warrior"))
print(to_camel_case("the_stealth_warrior"))
print(to_camel_case('the stealth warrior'))
prin... |
1c876dcf70016b77fd2f4a59cba892ba567f5d49 | yin-hong/cs231n-assignment | /cs231n-assignment1/softmax_classfier.py | 3,190 | 3.9375 | 4 | import numpy as np
def softmax_loss_naive(W,X,y,reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array... |
c50b469a105e6f0d32501e4f3d32a411413049ad | mrinal-roy/LCM | /lcm.py | 1,587 | 4.375 | 4 | def lcmOfTwoNos(a,b):
'''
This function finds the LCM of two numbers and returns the value of this LCM to the
the calling section of the program
'''
num1_MultipleList = []
num2_MultipleList = []
commonMultipleList = []
for i in range(1,b+1):
num1_MultipleList.append(a*i)
... |
c17d2b1abf77cad08c7928e304cf974d11389d25 | gabibu/genetic | /createimage/entities/shapes/circle.py | 935 | 3.515625 | 4 |
from abc import ABC, abstractmethod
from entities.shapes.shapestypes import ShapeType
class Shape(ABC):
def __init__(self, color):
self.color = color
super().__init__()
@abstractmethod
def draw(self, image):
pass
@abstractmethod
def copy(self):
pass
@abstrac... |
afe9e972f33b9b5fe6bc98a2488e262c26d75d4e | iampujan/ProjectEuler | /Find the sum of all the even-
valued terms in the Fibonacci sequence
which do not exceed four million/Find the sum of all the even-
valued terms in the Fibonacci sequence
which do not exceed four million.py | 329 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 18 08:57:44 2018
@author: pujan
"""
#Find the sum of all the even valued terms in the Fibonacci sequence which do not exceed four million.
e = 4000000
sum = 0
a = 1
b = 1
if b<e:
if(b % 2 ==0):
sum = sum+b
c = a+b
a=b
b=c
pr... |
e95b55eb12c9eae48a73c22b5b80284610cbfa50 | ashrafmohiuddin/Python_Projects | /sudoku_solver.py | 1,308 | 3.84375 | 4 | def get_empty_place(arr,l):
for i in range(9):
for j in range(9):
if(arr[i][j]==0):
l[0]=i
l[1]=j
return True
return False
def check_row(arr,row,val):
if val in arr[row]:
return False
return True
def check_column(arr,col,num):
... |
213d7474358294f4d3b636b4d6c26499630794e8 | RyanC3194/chess | /main.py | 8,216 | 3.8125 | 4 | from board import *
from tkinter import Canvas, Tk, Frame, Label, Entry, Button
class game():
def __init__(self, fen=None):
self.piece = None
self.BOARD_LENGTH = 600
self.PIECE_SIZE = int(self.BOARD_LENGTH / 10)
self.window = Tk()
self.window.title('Chess!')
self.... |
c09252d283ccea8675171f0c95dd3d3cfc980105 | joeyLewis/HighSchoolPortfolio | /2015/Database/pyTK/model/calculate.py | 14,340 | 3.859375 | 4 | #------------------------------------------------------------------------------
# calculate module
# -- functions for handling data input, output, and caclulations
#------------------------------------------------------------------------------
import math
from statlib import stats
from team import *
from ent... |
1d260de10591db339ec2ff650c5bf6181b6866c4 | HarshalGoyal/Python | /data_structures/linked_list/singly_linked_list.py | 4,547 | 4.1875 | 4 | class Node: # create a Node
def __init__(self, data):
self.data = data # given data
self.next = None # given next to None
def __repr__(self): # string representation of a Node
return f"Node({self.data})"
class LinkedList:
def __init__(self):
self.head = None # initial... |
776118741caaa7f15f00e95d0f25d1c1d6cb8e28 | Sanket64/mycaptain | /project1_mycaptain.py | 120 | 4.3125 | 4 | r=float(input("the radius of the circle:"))
area = 3.14*r*r
print("The area of the circle with radius",r,"is:",area)
|
eefbf28c2f554e4906bb33cf898a9df29a742a99 | chalmerlowe/jarvis_II | /sample_puzzles/22_interleave/interleave_solution_BobHiltner.py | 2,918 | 4.15625 | 4 | # TITLE: interleave >> your_code_here_interleave.py
# AUTHOR: Chalmer Lowe
# DESCRIPTION:
# You are given a file (interleave.txt) with two lines.
# Each line contains numbers separated by semicolons.
# You will need to interleave the values from the two lines and calculate
# the difference between each sequential... |
c850a51adcd76b9303b721a92c86066facc6e915 | chalmerlowe/jarvis_II | /sample_puzzles/26_water/your_code_here_water.py | 1,071 | 3.734375 | 4 | # TITLE: water >> your_code_here_water.py
# AUTHOR: Aidan Lowe and Chalmer Lowe
# DESCRIPTION:
# You work for a water distribution company and have a file (water.txt) with
# data for each customer's water usage in gallons.
# Your job is to find the five customers with the highest usage.
# The file: water.txt, ha... |
822d2f5d01ce1a95e302c740036db87ec0a406ab | chalmerlowe/jarvis_II | /sample_puzzles/17_quad_vowels/solution_quad_vowels.py | 1,575 | 3.9375 | 4 | # TITLE: quad_vowels >> solution_quad_vowels.py
# AUTHOR: Chalmer Lowe
# DESCRIPTION:
# Read all the values from the file: words.txt.
# Each line contains a word.
# Each word has one or more vowels
# Deduplicate the words, so only a single copy remains
# of any words that might have duplicates and count
# all t... |
5b69d86920febf15728a6784d6ed6d4c9a2596b1 | chalmerlowe/jarvis_II | /sample_puzzles/22_interleave/solution_interleave.py | 1,625 | 4.09375 | 4 | # TITLE: interleave >> solution_interleave.py
# AUTHOR: Chalmer Lowe
# DESCRIPTION:
# You are given a file (interleave.txt) with two lines.
# Each line contains numbers separated by semicolons.
# You will need to interleave the values from the two lines and calculate
# the difference between each sequential pair ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.