blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ee1017a6bd11e9af4ce8564034c7abed186afc2b | Libbybacon/Python_Projects | /Python_Challenges/python_challenge_5_get_file_path.py | 1,563 | 4.03125 | 4 | # Create GUI with button widget and text widget
# Include button function that will invoke dialog modal when called
# Dialog modal will allow users the ability to select a folder directory from their system
# Script will show user's selected directory path in text field
# use askdirectory() method
# When user clicks b... |
ea430a7e7810f0d3cd6966218f1c0595e166b77e | rayraib/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/tests/test_models/test_square.py | 4,890 | 3.828125 | 4 | #!/usr/bin/python3
"""
This file contains external tests for class `Square`
from the module `square`.
To use, impor the class `square` and `unittest`
"""
from models.square import Square
from models.base import Base
import unittest
class TestSquareclass(unittest.TestCase):
'''
Class containing... |
7c8546700a6607025f682b9276fc737aa0f99c2e | fabioHernandezRu/Escuela_data_science | /nivel-basico/POO-con-Python/herencia.py | 913 | 3.65625 | 4 | """
Permite modelar una jerarquia de clases
comparte cosasa comunes en la jerarquia
al padre se le conoce como superclase y al hijo como subclase
----------------------------------------
Vehiculo -> Avanzar, moverse, frenar
___|____
alas<-Aereos Terrestres -> llantas
__... |
9d856912702df519a633a8d08e75bcf3d9f5d78b | Prashant2504/Merge-sort-with-Inversion-count | /inversion.py | 863 | 3.609375 | 4 | import sys
inversion = 0
def mergesort(A):
if len(A) > 1:
mid = len(A)//2
L = A[:mid]
R = A[mid:]
mergesort(L)
mergesort(R)
merge(A, L, R)
def merge(A, L, R):
i = j = k = 0
global inversion
mid = len(A)//2
p... |
ee61dbc8867f7abaf11a358736d289685e87fa14 | billyg88/City-UNI-INM702-MATH-CW | /Submission/Task 5/nn_classifier_dropout_mom.py | 20,546 | 3.78125 | 4 | import pickle
import random # for shuffling the dataset at the start of an epoch
import numpy as np
import matplotlib.pyplot as plt
#from scipy.special import softmax
"""
This version of the NN can also create arbitrary architectures, using the Relu activation and Dropout for
regularization.
"""
with open("Dat... |
90458a0252a22b87117b2e6013fc8f19b2921860 | supersonictan/iterview | /PyCode/python_study/Thread.py | 778 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self... |
9642e991ecc06e85d1ba938373998a8f64f06f7d | cyhkelvin/leetcode | /python/547_NumberOfProvinces.py | 1,531 | 3.53125 | 4 | class Solution:
# sol2: dfs
def findCircleNum(self, isConnected: List[List[int]]) -> int:
rows = len(isConnected)
visited = set()
def dfs(row):
visited.add(row)
for col in range(rows):
if isConnected[row][col] == 1 and col not in visited:
... |
dcc8591f29960be83f3e0a999165852635a01325 | sk7155694/3_vs_3 | /src_code.py | 8,420 | 3.65625 | 4 | # 3 vs 3 game
def display_table(table):
print("===============================================")
print("|| "+table[1]+" || || "+table[2]+" || || " +table[3]+" ||")
print("||===||============||===||==============||===||")
print("|| || || || || ||")... |
a85be392003b61afa982f6a3da5afd592b6787c7 | SSITB/winrar_python | /zip_extract.py | 351 | 3.640625 | 4 | from zipfile import ZipFile
def zip_ex(file_name):
try:
with ZipFile(file_name, 'r') as zip:
k = file_name.split('\\')
t = k[-1]
zip.printdir()
print('Extracting all the files...')
zip.extractall()
print(t,' is Extracted')
except E... |
208f0e0e87336ce81103f18d26a2c2e77380b15b | xulei717/DesignPattern | /StrategyPattern/Strategy.py | 550 | 3.546875 | 4 | # -*- coding:utf-8 -*-
# @time : 2019-12-26 08:56
# @author : xulei
# @project: DesignPattern
import abc
# 创建一个接口
class Strategy(abc.ABC):
def doOperation(self, num1, num2):
""""""
# 创建实现接口的实体类
class OperationAdd(Strategy):
def doOperation(self, num1, num2):
return num1 + num2
class Ope... |
0db911e1ed4448c8b9bdeaf53d020c0c103c49d2 | lin-br/pythonando-do-lin | /studies/coding_dojo/anagram/src/file.py | 1,413 | 3.828125 | 4 | from anagrammer import Anagrammer
class FileAnagrammer:
__slots__ = ['_path', '_full_list']
def __init__(self, path_file: str):
self._path = path_file
self._full_list = self.__get_full_list_words(path_file)
@staticmethod
def __get_full_list_words(path_file: str):
with open(pa... |
39328f03f68fafc07f47679eb96761ef804bc897 | CompPhysics/MachineLearning | /doc/Programs/Reinforcement/reinforcementExample.py | 3,439 | 4.59375 | 5 | """
A simple example for Reinforcement Learning using table lookup Q-learning method.
An agent "o" is on the left of a 1 dimensional world, the treasure is on the rightmost location.
Run this program and to see how the agent will improve its strategy of finding the treasure.
View more on my tutorial page: https://morva... |
6ea259e576a5f194afdb4f5c062556f34d3ae090 | gussygus/1erparcialtopicos | /listas.py | 294 | 4.15625 | 4 | #!/usr/bin/env python
lista = [1,2,'3',('uno','dos',3)]
print(type(lista))
print (lista)
print(lista[0])
print(lista[3][-2])
lista.append('nuevo')
print (lista)
for item in lista:
print(item)
if type(item) == tuple:
for itemnuevo in item:
print(itemnuevo)
|
2c6df1762ccf084856d3bc4642495d8723258830 | dogbutcat/PythonProject | /Base/Tuple.py | 188 | 3.859375 | 4 |
tuple1=(1,2,3,4.5)
tuple2=tuple1
# tuple1[1]=44 #This is not Allowed for Tuple Array
print(type(tuple1))
# This is for tuple insertion
tuple1=tuple1[:3]+('temp',)+tuple1[3:]
print(tuple2) |
02b2cdd802484d68ac97addbacb2f7c29a4d9918 | asyaaamayak/DC_2 | /5.dic.py | 1,392 | 3.6875 | 4 | # **** СЛОВАРЬ ****
# ПАРЫ "ключ:значение"
my_dict = {10:100, 1:100, 2:400, "A":5.14, 'abc':[1, 2, 3]}
a = [
['A', 1000],
["B", 2000]
]
# a = [ ['A', 1000],['B',2000] ]
my_dict_2 = dict(a)
# print(my_dict_2)
# ЧТЕНИЕ ДАННЫХ
item = my_dict['abc'] #10]
# print(item)
# ИЗМЕНЕНИЕ ЗНАЧЕНИЯ
my_dict[10] = 777
# ... |
829a608b6a21c3b7b4b8297a9b7e5f94d2c59ea2 | cddedric/Exercism | /python/bob/bob - Casey.py | 210 | 3.734375 | 4 | def hey(string):
string = string.strip()
if (string == ''):
return "Fine. Be that way!"
elif string.isupper():
return "Whoa, chill out!"
elif (string.endswith('?')):
return 'Sure.'
return 'Whatever.' |
46f83cd2b060f1515e044ac6479d3fe246a2a71b | r96725046/leetcode-py | /20.valid-parentheses.py | 738 | 3.640625 | 4 | #
# @lc app=leetcode id=20 lang=python3
#
# [20] Valid Parentheses
#
# @lc code=start
class Solution:
def isValid(self, s: str) -> bool:
stack=[]
for i in range(len(s)):
char=s[i]
if char=="{" or char=="(" or char=="[":
stack.append(char)
else:
... |
d73dde73a03f0d83857e74689e8267dd4e70f1f9 | ashwindasr/Jet-Brains-Academy | /Python/Tic-Tac-Toe/Stage_3/code.py | 2,129 | 3.921875 | 4 | # write your code here
def print_grid(symbols):
print("-" * 9)
print(
f"""| {symbols[0]} {symbols[1]} {symbols[2]} |\n| {symbols[3]} {symbols[4]} {symbols[5]} |\n| {symbols[6]} {symbols[7]} {symbols[8]} |""")
print("-" * 9)
def create_grid(string):
counter = 0
game = []
for outer_loop ... |
66eb62c6d852a85915a6ebfb96d7c9b178309d9b | TangliziGit/dataquest | /Machine Learning in Python/Logistic Regression/LR_template.py | 13,292 | 4.375 | 4 |
# coding: utf-8
# In[1]:
from __future__ import print_function
# #Machine Learning in Python
# ##Logistic Regression
# ###1: Introduction to the Data
# Every year high school student and college students apply to various universities and programs. Each student has a unique set of test scores, grad... |
29bb228976be48bcc4eeb63d67c4e5e77c1ad33c | JosepMesquida/Python | /ejercicios_con_clases/ejerciciohora.py | 577 | 3.671875 | 4 | class Hora():
hora = 0
minutos = 0
segundos = 0
def setHora(hora, minutos, segundos):
if (hora >= 0 and hora <=24):
Hora.hora = hora
else:
return hora
if (minutos >= 0 and minutos <= 59):
Hora.minutos = minutos
else:
return minutos
if (segundos >= 0 and segundos <= 59):
Hora.segun... |
223ae0071ffca84558d0e050e22c6e4e4f950ed6 | Rost381/learnml | /learnml/utils/pairwise.py | 235 | 3.53125 | 4 | import numpy as np
def euclidean_distances(X, Y):
"""dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y))"""
distance = 0
for i in range(len(X)):
distance += pow((X[i] - Y[i]), 2)
return np.sqrt(distance)
|
3f7ffa36948ac2c5176c8c39242c4534a6551ffe | navboga/web_app1 | /decorator_test.py | 820 | 3.578125 | 4 | from functools import wraps
lst= [1,15,39,88,14,7,33]
lst1= [3,15,8,20,60,13]
def dec_func(func):
idx = 1
@wraps(func)
def cnt(*args, **kwargs):
result_external_func=func(*args,**kwargs)
if result_external_func in lst:
return func(*args,**kwargs)
return 'Числа нет в спи... |
ce0c4780e7273ab5324d625d2b965b66475c603b | renso3x/python-lecture | /forLoops.py | 487 | 3.796875 | 4 | l = [1,2,3,4,5]
list_sum = 0
for num in l:
list_sum += num
if num % 2 == 0:
print 'here are even numbers %s' % num
else:
print 'odd number'
print 'Total sum: %s' % list_sum
s = 'this is a string'
for item in s:
if item != ' ':
print item
#tuple
tup = (1,2,3,4,5)
for t in tup:
print t
l = [(2, 4), (6, 8), ... |
95d12ab72e6e5bc85eb9416a7cb8eb90731986f2 | PragayanParamitaMohapatra/Basic_python | /array/2D-array/access_array_element.py | 308 | 3.734375 | 4 | from array import *
a=([
[1,2,3,4,5,6],[2,3,4,5,6,7],[1,3,5,7,8,9,],[1,2,3,4,7,8],[2,3,4,5,6,7],[2,3,4,5,6,7]
])
print(a[0])
print(a[1][5])
print(a[2][3]+a[3][3])
print(a[2][3]*a[3][3])
if a[2][1]==a[3][2]:
print ( 'True')
else:
print('false')
for r in a:
for d in r:
print(d)
print()
|
3435621c7dac2c09a985a5527b30dfee16823584 | michaelkmpoon/Pandhi_Ayush_-_Poon_Michael_Assignment1_CTA200H | /question_6/space_battle.py | 3,995 | 4 | 4 | import random
class Ship:
"""
This is the main Ship class for all ships, including
standard spaceships, warships and speeders which each have
a name, laser power, shield strength and hull strength.
"""
def __init__(self, name, laser, shield, hull):
"""Basic attributes of each spaceship... |
a145f13609925f4aaf02c9e502803972ddd0c3da | Brayson0215/rps | /calculatorr.py | 2,926 | 3.796875 | 4 | from tkinter import*
global operator
operator=''
def caseClick(numbers):
global operator
operator=operator+str(numbers)
text_Input.set(operator)
def caseClearTextDisplay():
global operator
operator=""
text_input.set("")
def caseEqualsInput():
global operator
sumup=str(eval(operator))
... |
d6d4371898fa818dacf6703d48430236aaf17828 | Daehyun-Bigbread/Bigbread-Python | /python_for_everyone/07B-multi.py | 460 | 3.6875 | 4 | # 숫자 두 개를 입력받아서 곱하는 프로그램
x = input("? ") # 변수 x에 첫 번째 입력을 받습니다. x=문자열
a = int(x) # 문자열 x의 값을 정수(int)로 바꿔서 a에 넣습니다.
x = input("? ") # 변수 x에 두 번째 입력을 받습니다. x=문자열
b = int(x) # 문자열 x의 값을 정수(int)로 바꿔서 b에 넣습니다.
print(a * b) # a와 b를 곱한 결과를 출력합니다.
|
15a176b3c98828cbcfc84f1c1cc34e4a3d6db5bb | w5802021/leet_niuke | /Linked_list/234.回文链表.py | 893 | 3.96875 | 4 | from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def reverseList1(head):
# 初始化res=None代表反转链表的尾结点
p, res = head, None
while p:
p,res,res.next=p.next,p,res
return res
def isPalindrome(head):
if not head or... |
74352beb265c0a18ab1def6f599ea49d0cbacd40 | henrychen222/PYTHON-TECHNOLOGY-DEMO | /Pandas/06_Function_Application.py | 1,012 | 4.375 | 4 | # 1.21 afternoon
# https://www.tutorialspoint.com/python_pandas/python_pandas_function_application.htm
"""
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pipe.html
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html
https://pandas.pydata.org/pandas-docs/stable/ge... |
0fc77f298a56e774fbec396f01577b9d5033c400 | RohiniRG/Daily-Coding | /Day48(Two_sum).py | 797 | 3.796875 | 4 | # Given an array of positive integers and an integer.
# Determine whether or not there exist two elements in A whose sum is exactly equal to that integer.
# Examples:
# Input: arr[] = {0, -1, 2, -3, 1}
# sum = -2
# Output: -3, 1
# If we calculate the sum of the output,
# 1 + (-3) = -2
# Input: arr[] = {1, ... |
eb4d744fe25efdf9e08cde18390085f3eeeffcbd | ytpessoa/python-codes | /00-fundamentos/tupla.py | 352 | 3.671875 | 4 |
# tupla = (element1, elemento2) -> imutavel
# lista = [elemento, elemento2] -> mutavel
# tupla: sequencia imutavel, indexada!
>>> tupla2 = ()
>>> type(tupla2)
<class 'tuple'>
#tupla 1 elemento
>>> tupla = ('uma',)
>>> type(tupla)
<class 'tuple'>
>>> tupla[0]
'uma'
>>> tupla[0] = 'novo'
TypeError: 'tuple' object ... |
5d2947d2d95cd7999e4f40936997dd945fd19637 | Muthulekshmi-99/guvi | /code/hours_minutes.py | 61 | 3.578125 | 4 | m=int(input())
hours=m//60
minutes=m%60
print(hours,minutes)
|
77da197d6e096f8138d828581a7292186e839edd | robcecc27/miscellaneous_code | /Math code/factors.py | 259 | 4.21875 | 4 | # Python implementation of Naive method
# to print all divisors
# method to print the divisors
def printDivisors(n) :
i = 1
while i <= n :
if (n % i==0) :
print(i),
i = i + 1
# Driver method
print("The divisors of 100 are: ")
printDivisors(22)
|
071ab347e3471267e7c397209d6ab78d0992652f | i-aditya-kaushik/geeksforgeeks_DSA | /Graphs/topological.py | 351 | 3.65625 | 4 | def temp_fun(i,visited,graph,stack):
visited[i] = True
for j in graph[i]:
if visited[j]==0:
temp_fun(j,visited,graph,stack)
stack.insert(0,i)
def topoSort(n, graph):
visited = [False]*n
stack = []
for i in range(n):
if visited[i]==False:
temp_fun(i,visite... |
5a7d0aae63510bf7043bd6094da4ad774fa5dc6b | ramlaxman/wdc-2021-jan-intro-python | /WDC — 2021 Feb 10.py | 12,332 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Agenda
#
# 1. Writing functions
# 2. Parameters
# 3. Defaults
# 4. Return values
# 5. Scopes (local, global, and builtin)
# In[1]:
s = 'abcd'
x = len(s)
# In[2]:
x
# In[3]:
type(x)
# In[4]:
x = s.upper()
# In[5]:
x
# In[6]:
type(x)
# In[7]:
x = s.up... |
2ad9cca999b556e2bab48f9c4a65b611170c442b | ridwan098/Python-Projects | /tut 31 - class vs instance variables.py | 302 | 3.90625 | 4 | class Female:
gender = "female"
def __init__(self, name, age):
self.name = name
self.age = age
r = Female("rachel", 16)
l = Female("leah", 21)
print(r.gender)
print(r.name)
print(str(r.age) + "\n")
print(l.gender)
print(l.name)
print(str(l.age) + "\n")
|
56b9c72df3c2ad98056f7430b8d6136094983312 | hanking356/python_practice | /data04/클래스만들기/Truck.py | 499 | 3.78125 | 4 | class Truck:
weight = None
company = None
def move(self):
print(self.weight, '톤의 짐을 실어나르다.')
def own(self):
print(self.company, '회사 소속의 트럭입니다.')
def __str__(self):
return str(self.weight) + ', ' + self.company
if __name__ == '__main__':
truck2 = Truck()
truck2.weig... |
4391ebdd54b13921d9f8a0005a5821a9c9870ce6 | NHigs58/python-challenge | /PyPoll/main.py | 2,309 | 3.6875 | 4 | # Import csv
import os
import csv
# join path
election_csv = os.path.join("Resources", "election_data.csv")
# create lists
total_votes = 0
candidates = ["Khan", "Correy", "Li", "O'Tooley"]
khan = 0
correy = 0
li = 0
otooley = 0
votes = [khan, correy, li, otooley]
# Open Csv
with open(election_csv, newline="") as cs... |
79e4a71fae2fc39d3db5016d10acee5b409aee8c | RobertDurfee/DataStructuresAndAlgorithms | /Sequences/DynamicArray/DynamicArray.py | 3,715 | 4.03125 | 4 | class DynamicArray:
""" Time Complexity: O(1) """
def __init__(self):
self.N = 1
self.left = self.right = None
self.xs = self.allocate(1)
###########################################################################
# Utilities
###############################################... |
db274aff06ba7f72727c84224b6a1de275dee3ef | sahiljajodia01/Competitive-Programming | /interview-bit/two_pointers/remove_duplicates_from_sorted_array.py | 263 | 3.578125 | 4 | def removeDuplicates(A):
count = 0
for i in range(0, len(A) - 1):
if A[i+1] != A[i]:
A[count] = A[i]
count += 1
A[count] = A[len(A) - 1]
count += 1
print(count)
removeDuplicates([1, 2, 2, 2, 4, 10, 10, 20]) |
d4bc4fb15233e4ae84454c3cdfd498b8f685876d | dinhtq/coding_practice | /main.py | 170 | 3.859375 | 4 | def runningSum(nums):
sum = 0
for i in range(len(nums)):
sum = sum + nums[i]
nums[i] = sum
return nums
arr = [1, 2, 3, 4, 5]
runningSum(arr)
print(arr) |
10c8b4decadba8fae1687d06a73190d8eed1e713 | ksayee/programming_assignments | /python/CodingExercises/CousinsBinaryTree.py | 2,879 | 4.15625 | 4 | '''
Check if two nodes are cousins in a Binary Tree
Given the binary Tree and the two nodes say ‘a’ and ‘b’, determine whether the two nodes are cousins of each other or not.
Two nodes are cousins of each other if they are at same level and have different parents.
Example
6
/ \
3 5
/ \ / \
7 8 1 ... |
b0601189bd8f0cead1548b7df3b74f9dc67ffda8 | JuanPyV/Python | /LecturaDeArchivo/Aeropuerto/airlineHackV0.3.py | 1,302 | 3.625 | 4 | import math
ciudad = input("Ciudad: ")
def distancia_aeropuertos_de_ciudad(ciudad):
try:
aeropuerto = open("airports.txt", "r", encoding='UTF8')
ciudadl = []
for linea in aeropuerto:
lineaP = linea.strip()
lin = lineaP.split(",")
if lin[3].strip('"') ==... |
456b0f8bdb03f45f6992e8996ebc66c94a3b92e0 | Hemie143/realpython | /chp14 - Scientific Computing and Graphing/14-213-01.py | 409 | 3.53125 | 4 | import numpy
first_matrix = numpy.arange(3, 12)
first_matrix = first_matrix.reshape(3, 3)
print("Min is", first_matrix.min())
print("Max is", first_matrix.max())
print("Mean is", first_matrix.mean())
second_matrix = first_matrix ** 2
third_matrix = numpy.vstack([first_matrix, second_matrix])
print(numpy.dot(third... |
4e1b7408fdd0858e0883fb5f156aca4c87ff9523 | elston-jja/Personal-Projects | /python/Tkinter/gui_classes.py | 1,495 | 3.890625 | 4 | from Tkinter import *
class application(Frame):
'''Initializes the window and objects'''
def __init__(self, master = None):
Frame.__init__(self,master)
self.grid()
self.create_passwd()
self.create_usrname()
self.register()
'''Sets up UI'''
def create_passwd(sel... |
4a0cbee44a7764de720e88c4171e9d6540cc521c | mayur1101/Mangesh | /Python/Iterators1.py | 2,246 | 4.4375 | 4 | #Iterable- Something that can be looped over.
#e.g List is iterable bcoz we can looped over the list
# we can loop over the tuple,dictornary,,strings, set, generators,files
'''
nums=[1,2,3]
for i in nums:
print(i)
'''
#if something is iterable then it needs to have a special
#method called __iter__()
#To ... |
6d2e1bc8a622e385d4bf944fa38d7b96947d099d | Nuaboc/simple_programs | /converter.py | 328 | 4.09375 | 4 | """
A simple program that convert roman numerals to natural numbers and vice versa.
This module in intended to run as a script.
Author: Gabriel Martinez
Date: August 13, 2020
"""
import roman_functions
ask = input('Give me a roman numeral: ')
y = roman_functions.conversion(ask)
print(ask + ' in natural number is ... |
a7b3063718f3dc206917993ffe0a60d7e8b44c4a | mdamien/dummy-translate | /utils.py | 161 | 3.625 | 4 |
def tokenize(text):
text = text.lower()
for punc in '.;,\'&!/:?"»':
text = text.replace(punc, ' ')
return [x for x in text.split(' ') if x] |
8f18dd9f7631bc4047513fff1b6772b3b9796235 | Ivanknop/proyectoJuegoCervantes | /TimerPrueba.py | 3,878 | 3.90625 | 4 | import time
run = input("Start? > ")
seg = 0
# Only run if the user types in "start"
if run == "ok":
# Loop until we reach 20 minutes running
while seg != 10:
print (">>>>>>>>>>>>>>>>>>>>>" + str(seg))
# Sleep for a minute
time.sleep(1)
# Increment the minute total
... |
bcbbe2589e4c3e9b07f98109004fb09928271bf4 | rahulkumar1m/exercism-python-track | /matching-brackets/matching_brackets.py | 705 | 4.125 | 4 | def is_paired(input_string: str):
# Declaring a stack to store the brackets
bracket_stack = []
# initializing a dictionary to check which bracket correspond to which bracket
bracket_dict = {
'[' : ']',
'{' : '}',
'(' : ')'
}
# Looping through characters to check for... |
30696d805ed2d32065fdc2dbeb693242dc33edf2 | simrangrover5/batch430 | /oops/myclass.py | 425 | 3.671875 | 4 | class Mylist:
def __init__(self,l=[]):
self.l = l
def append(self,value):
self.l.append(value)
def insert(self,index,value):
self.l.insert(index,value)
def pop(self):
self.l.pop()
def getvalue(self):
print("Data : ",self.l)
def __str__(self):
... |
738f3e342cc7e9d8328ca5659bf60938ae59f103 | jimmyblaszkiewicz/CMPSC132 | /HW5/HW5.py | 9,347 | 4.03125 | 4 | #HW 5
#Due Date: 12/07/2018, 11:59PM
########################################
#
# Name: James Blaszkiewicz
# Collaboration Statement: I completed this program using only the class materials.
#
########################################
# ---Copy your code from labs 9 and 10 here (you can remove their comments)
class N... |
86cc55280cfadf1f17da0d2d1a588636dd32f6c5 | wesleyakon/ExerciciosPython | /054.py | 603 | 3.96875 | 4 | from datetime import date
at = date.today().year
totmaior = 0
totmenor = 0
for pess in range(1,8):
ano = int(input('Em que ano a {}° pessoa nasceu? '.format(pess)))
idade = at - ano
if idade >= 21:
totmaior += 1
else:
totmenor += 1
print('ao todo tivemos {} pessoas maiores de idade'.form... |
6246b9bfff1b816eb03f99868f87967589be76aa | summitwolf/PYExplore | /chapter 3/ch3e3.py | 647 | 4.34375 | 4 | #Excercise 3 - Score to Grade
#retrieve score from user
while True:
try:
print('')
score = float(input('Please enter a score between 0.0 and 1.0: '))
if (0.0 <= score and score <= 1.0 ):
break
else:
print('That number is not between 0.0 and 1.0')
... |
8918e12ce694bb581a752d9fbf330d43378daf83 | cveazey/ProjectEuler | /misc.py | 860 | 3.765625 | 4 | # def binomial_coefficient(n,k):
# c = 1
# for i in range(1,k+1):
# c = c * ( (n + 1 - i) / i)
# return c
from fractions import Fraction
from operator import mul
def binomial_coefficient(n,k):
series = [Fraction(n+1-i,i) for i in range(1,k+1)]
result = reduce(mul, series)
return int(result)
def ... |
db18e551808fd32d75588987a6c824c4fc09feb9 | prakashmngm/Lokesh-Classes | /Number-Reverse.py | 962 | 4 | 4 | '''
Take the input number num
length = length(num)
sum = 0
index = 1
Iterate the loop with condition num>0
digit = num%10
sum += (digit*exponent(10,length-index))
sum += digit*(10**(length-index))
num = num//10
index += 1
print(“The reverse of the given number is:”,sum)
'''
def length(num):
if(num == 0):
... |
63461e695f212c70433a3d5c1704af8ee40d7393 | prog4biol/pfb2019 | /problemsets/answers/Python_01_KLG.py | 1,480 | 4.25 | 4 | #!/usr/bin/env python3
import sys
# Python 1 Problem Set
# ==================
# 2. Working with a text editor. Use nano to write a script.
# - Make sure to include `#!/usr/bin/env python3` at the top!!
# - Add code to print out, your name
my_name = sys.argv[1]
print('My name:', my_name)
# ... |
816c1d3e1e6931d218cb81285fea98d747e3e974 | marco9663/Command-line-chess-game | /Queen.py | 1,519 | 3.59375 | 4 | from termcolor import colored
from Coordinate import Coordinate as C
from Move import Move
White = True
Black = False
class Queen:
value = 90
def __init__(self, board, side, coord, movesMade=0):
if side:
self.side = White
self.direction = -1
else:
self.sid... |
bea986de148dc42804fcd3d4ab9465a3136bcf1b | frankieliu/problems | /leetcode/python/660/original/660.remove-9.py | 688 | 3.59375 | 4 | #
# @lc app=leetcode id=660 lang=python3
#
# [660] Remove 9
#
# https://leetcode.com/problems/remove-9/description/
#
# algorithms
# Hard (51.18%)
# Total Accepted: 5K
# Total Submissions: 9.8K
# Testcase Example: '10'
#
# Start from integer 1, remove any integer that contains 9 such as 9, 19,
# 29...
#
# So now,... |
c038d6787cca6df0adc1b016971cb2fa7e3fd764 | liuhuipy/Algorithm-python | /tree/average-of-levels-in-binary-tree.py | 1,794 | 3.71875 | 4 | """
二叉树的层平均值:
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
示例 1:
输入:
3
/ \
9 20
/ \
15 7
输出:[3, 14.5, 11]
解释:
第 0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。
方法1:
BFS。遍历每层并计算平均值。
方法2:
BFS。用两个数组记录每层元素个数和元素之和,最后分别计算平均值。
"""
from typing import List
# Definition for a binary tree node.
clas... |
23cf47bbdbd58fcb97ee6c6f616e86d052f506ae | andsus/python | /word-count/word_count.py | 1,238 | 3.9375 | 4 | """
import re, collections
from collections import defaultdict
not_word_pattern = "[^\'a-zA-Z0-9\"]+"
def count_words(sentence):
words = defaultdict(int)
splitted_words = [i.strip("\'") for i in re.split(not_word_pattern, sentence.lower()) if i != '']
for word in splitted_words:
words[word] +=... |
9a1c7a3cdfe4106da7d610332984fdd5570b529e | ankpandey1/reversi | /main.py | 759 | 3.640625 | 4 | from reversi import *
def main():
board = init_board()
turn = "B"
while (len(getValidMoves(getPlayerPositions(board, turn), board, turn)) != 0) or (len(getValidMoves(getPlayerPositions(board, getOpponent(turn)), board, turn)) != 0):
print(string_board(board))
move = input("It's "+t... |
e73a29b71fb8870f0cb4bbceb40bd1734de9a50b | D-Anilkumar/python-assignmentday4 | /python-day4/assignment-2.py | 900 | 4.71875 | 5 |
# Python code for implementation of isupper()
# checking for uppercase characters
string = 'LETSUPGRADE'
print(string.isupper())
string = 'letsupgrade'
print(string.isupper())
# Python code for implementation of isupper()
# checking for lowercase characters
string = 'letsupgrade'
prin... |
b15cad410e177eb8fd53687d0543a3764aceb97a | Shaunwei/Leetcode-python-1 | /Array/MissingRanges/findMissingRanges.py | 925 | 3.640625 | 4 | #!/usr/bin/python
"""
Missing Ranges
Given a sorted integer array where the range of elements are [0, 99] inclusive,
return its missing ranges.
For example, given [0, 1, 3, 50, 75], return ["2", "4->49", "51->74", "76->99"]
"""
class Solution:
# @param A, a list of integer digits
# @param lower, a integer
... |
beff28147724bcd1421e3b47bcf524dffbdf659c | jspw/Basic_Python | /problems/Codeforces/Palindromic String.py | 77 | 3.65625 | 4 | def rev(s):
return s[::-1]
s=input()
print("YES" if s==rev(s) else "NO")
|
dd0309e9585cff717e0f226725aff1267afc88a6 | wpbindt/sliceable-matrix | /search_matrix_2.py | 1,111 | 3.859375 | 4 | from sliceable_matrix import SliceableMatrix
def search(matrix: SliceableMatrix[int], target: int) -> bool:
"""
Souped up version of binary search for matrix
with ordered columns and rows.
Despite the slicing happening in the return
statement (which normally scales linearly with
the size of t... |
f7709fb9de054a2c48cb8ec267c03de72eef2a06 | zhangshv123/superjump | /interview/facebook/mid/LC173_Binary Search Tree Iterator.py | 2,327 | 4.21875 | 4 | """
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
"""
# Definition... |
5936533d0148ce77f95be77a97efbaebbb6db943 | Angel-cuba/Python-UDEMY | /15_SQLite-DB/Products.py | 556 | 3.640625 | 4 | import sqlite3
connect = sqlite3.connect("Product.db")
cursor = connect.cursor()
cursor.execute('''CREATE TABLE PRODUCTS(
CODIGO_P VARCHAR(10)PRIMARY KEY,
NOMBRE_P VARCHAR(20),
SECCION_P VARCHAR(20)... |
663cdff4b847350df08dd6b6c5c320546dfa73f1 | JBustos22/Physics-and-Mathematical-Programs | /animations/Helium.py | 1,085 | 3.796875 | 4 | #! /usr/bin/env python
"""
This program uses virtual python to animate a Helium atom model. The red spheres are
protons, the blue spheres are neutrons, and the smaller green spheres are electrons.
Jorge Bustos
Feb 17, 2019
"""
from __future__ import division, print_function
import vpython as vp
import numpy as np
r_n... |
89eaee34ec9ad6c95e66d2b015d5b9f0d06b28eb | LsHanaha/PS_Unity | /Base.py | 57,652 | 3.640625 | 4 | # -*- coding: utf-8 -*-
import time
import sqlite3
from sqlite3 import Error
database = "/home/playps/bot/ps_unity.db"
def create_connection(db_file):
""" create a database connection to a SQLite database """
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
wit... |
b33516f458a044abcd6122fabf5938fc3af9241b | mlyangyue/pythoners | /producer_consumer/producr_consumer.py | 1,323 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
'''生产者消费者模式'''
import thread
import threading
import time
import random
import Queue
share_queue = Queue.Queue() # 共享队列
my_lock = thread.allocate_lock() # 队列共享变量,放进锁里防止竞争
class Producer(threading.Thread):
def run(self):
products = range(5)
... |
d32effc54bced3cbb15d8c2cdf9713dae0b13ef7 | ShengQuanZhou/epi-lab | /directed_graph.py | 2,974 | 3.6875 | 4 | #!/usr/bin/anaconda3/bin/python
"""
Created on Tue Sep 4 23:24 2016
An implementation of directed graph
@author: quan
"""
from collections import deque
class DirectedGraph:
""" This is not necessarily the best
implementation - for experiments only """
def __init__(self, edges):
self.edge... |
8b9353d7fee03d50092f40989fa99d4f7ddaaa4e | sengeiou/python-practice | /天气api获取天气.py | 1,053 | 3.515625 | 4 | import requests
#分钟级别降雨预测,付费
html = requests.get('https://api.qweather.com/v7/minutely/5m?location=120.15568361068728,30.325674788822027&key=50ed3b00f6224a5dbd68e0ac73c10dde')
print(html.text)
predic = eval(html.text).get('summary')
print(f'天气预测:{predic}')
#未来24时天气预测,免费
respons= requests.get('https://devapi.qweathe... |
c57d31128bcd9699553af7007fb9b9ce59473119 | aliensmart/week1 | /quiz/readcurrency.py | 811 | 3.515625 | 4 | #!/usr/bin/env python3
import json
#write function readcurrency(filename)
# read file
#Create a dictionary
def readcurrency(filename):
with open(filename) as f:
data = []
list_data= []
dict_data ={}
for line in f:
# print(line, end='')
list_line = line.str... |
1e377751b043febfc992b5726d2a4ad0717d6ece | tomPorter/lettuce_samples | /mymath_behave/factorial.py | 468 | 3.984375 | 4 | def factorial(number):
""" factorial x.
Returns factorial of x
>>> factorial(0)
1
>>> factorial(1)
1
>>> factorial(4)
24
"""
number = int(number)
if (number == 0) or (number == 1):
return 1
else:
return number*factorial(number - 1)
#return numbe... |
00e1156f47476821d644c01e489aa20dd13e76c0 | aleciodalpra/aprendizado | /CursoZ/contaTelefone.py | 332 | 3.96875 | 4 | #calculo da conta com valor de minuto variavel
minutos = float(input('Informe a quantidade de minutos: '))
if minutos < 200:
valor = minutos * 0.20
elif minutos < 400:
valor = minutos * 0.18
elif minutos < 800:
valor = minutos * 0.15
else:
valor = minutos * 0.08
print('O valor da sua conta é: R$ %.2f... |
54a43ed66a7265ae077ab86d9bd1ad7553a71bec | gabriellaec/desoft-analise-exercicios | /backup/user_174/ch23_2020_09_22_02_19_18_023013.py | 125 | 3.75 | 4 | v=float(input("Qual a velocidade do carro")
if v>80:
p=v+5*(v-80)
return(f'p:{p:.2f}')
else:
"Não foi multado"
|
6e6640f9f646f058287d6ec05f9d81df19eb7a93 | zhufengya/Test | /pytest/test1.py | 18,673 | 3.609375 | 4 | import re
def wordlength():
while True:
try:
s = input().strip().split(' ')
print(len(s[-1]))
except:
break
def wordcunt():
while True:
try:
s = input().strip()
s = s.upper()
char = input().strip()
pri... |
ea92fdd72c7a7cff2a0bc1212511b555eac2e2b3 | denamyte/Hyperskill_Python_05_Tic_Tac_Toe | /Tic-Tac-Toe/task/previous/tictactoe2.py | 439 | 3.765625 | 4 | from typing import List
Cells = List[List[str]]
size = 3
size_range = range(size)
dashes = '-' * 9
pipe = '|'
def main():
s = input('Enter cells: ')
cells = parse_input(s)
render(cells)
def parse_input(s: str) -> Cells:
return [list(s[x * size:(x + 1) * size]) for x in size_range]
def render(cel... |
f6499c7b0ee2097a8e1c901a3696a0a7c48c20ee | FelipeVel/Algoritmo-de-Prim | /prim.py | 3,878 | 3.515625 | 4 | def Prim ():
global iguales,op,x,marcados, marcados1, padres, m, temp, temp2, minimos, x
print("Op: "+str(op)+", Iguales: "+str(iguales))
iguales=False
while op !=0:
temp = 99
print("Padres: "+str(padres))
print("Minimos: "+str(minimos))
for i in range(9):
... |
b7e3a50ebd22a12aebb9cd2de3c70d235d63081c | josedembo/Python | /curso python Udemy/Aula17/Exerc01.py | 470 | 4.125 | 4 | '''
Exercicios propostos
'''
numero = input('informe um numero ')
try:
numero = int(numero)
if numero % 2 == 0:
print('O numero digitado e par')
else:
print('O numero digitado nao e par')
except:
print('ERRO')
'''
if not numero.isdigit():
print(f'{numero} não é um número inteir... |
e319e5ca88646817eee6438048cd575532e284dc | shifrud/MineriaDatos | /temp.py | 12,751 | 3.515625 | 4 | import matplotlib.image as mpimg#libreria usada para trbajar con la imgane
import os#libreria para trabajar con el data set
import csv#extendcion de el resultado
#Nombre:Area
#Descripcion:saca el area de las imagenes
#Argumentos:img que es la imagen
#Retorno: la area de la imagen
def Area(img):
[columnas,filas]=... |
bc9a30f8167c377db42975fea8feb60e067b052e | rclarkmorrow/trivia_maze | /proofs_of_concept/game_sounds/game_sounds.py | 1,999 | 3.5 | 4 | """
This class requires the installation of the module 'playsound'
which can be installed with the command:
`python3 -m pip install playsound`
Additional dependencies 'PyObjC' and 'PyObjC-core' may be required
on MacOs and can be installed with the following command:
`python3 -m pip install PyO... |
af07da345089b04ce76aea0e1e1794cc498d1494 | longkx/tc | /main.py | 1,515 | 3.609375 | 4 | # This is a sample Python script.
import json
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi():
# Use a breakpoint in the code line below to debug your script.
# print('Hello world')... |
be4a13846bbd2a68328b674399c294abda7311cf | ruddyadam/prometheus | /project_euler/003_largest_prime.py | 1,086 | 3.71875 | 4 | #prime factors of 600851475143
#finding a factor: when dividing the large number by a whole number, get a whole number.
#finding a prime: a number that is only divisible by itself and 1.
#hint: only need to search factors up to sqrt(target)
import math
target = 600851475143
prime_factors = []
number = 1
def get_fac... |
6fb80f73caf7d642a2925b6bc542228db8ca58b9 | seanandrews/p484 | /radmc3dPy_m/crd_trans.py | 8,508 | 3.578125 | 4 | """
This module contains functions for coordinate transformations (e.g. rotation).
"""
try:
import numpy as np
except:
print 'ERROR'
print ' Numpy cannot be imported '
print ' To use the python module of RADMC-3D you need to install Numpy'
#import scipy.linalg as la
def ctrans_sph2cyl(crd=None, rever... |
ef528f74dc73e2399f12c82830f4745fc83922a6 | smedagli/dog_breed | /models/build_network.py | 1,954 | 3.921875 | 4 | """
This module is used to define the network.
"""
from keras.models import Sequential
from keras.layers import Dense, Dropout, GlobalAveragePooling2D, Conv2D, MaxPool2D
def build_transfer_learning_netwok(input_shape: tuple, n_of_classes: int) -> Sequential:
""" Returns a neural network to use for transfer learni... |
6b07134b18f42078b47153f58c0b4e2743b0d22b | xiaohuanlin/Algorithms | /Leetcode/2110. Number of Smooth Descent Periods of a Stock.py | 1,878 | 4.09375 | 4 | '''
You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day.
A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first d... |
fdd2889d58822fb1ac715eefd720bc2da202b772 | SaiprasanthV/Python_Intermediate_Concpets | /event.py | 465 | 3.78125 | 4 | '''
This module is to understand how the event works and how to trigger the event.
Semaphore restricts the maximum number of access allowed.
'''
import threading
event = threading.Event()
def function():
print('My function is waiting for Trigger ............')
event.wait()
print('Task ABC is finished... |
3c2521742bedc4462758b3d39e80018b15155913 | DryDew/TCP-based-DNS | /local_default_server/local_server.py | 13,336 | 3.59375 | 4 | # encoding = utf-8
# author: Wei Dai
# date: 11/26/2018
"""
# file name: local_server.py
# description:
# 1. This a Python script for query IP address of a domain name, playing a role of DNS default local server.
# 2. The server listen on address (127.0.0.1, 5352). (port: 5352)
# 3. The server receives query in f... |
176ea6270062f1df98595796199707158ea5778a | sinindra/algorithm_problem | /codejam/Qualification Round 2019_Foregone Solution.py | 291 | 3.515625 | 4 | T = int(input())
for test_case in range(1, T + 1):
N = input()
a, b = '', ''
for num in N:
if num == '4':
a += '2'
b += '2'
else:
a += num
b += '0'
print("Case #{}: {} {}".format(test_case, int(a), int(b)))
|
43cd60f676990938695ecf7c219c25a6b19e954f | chenjiahui1991/LeetCode | /P0189.py | 377 | 3.671875 | 4 | class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k = (len(nums) - k % len(nums)) % len(nums)
nums[:] = (nums[k:] + nums[:k])
s = Solution()
print(s.rotate... |
40d9e79aca20cab3aa6e0d2ccd961ef9ce60c7d4 | jchigne/t08_Chigne.Burga. | /Chigne/Indexacion/indexacion12.py | 376 | 3.53125 | 4 | #operacion-INDEXACION_12
# 0 10 20 30 40
# 01234567890123456789012345678901234567890123
str="abcdefghijklmnñopqrstuvwxyz0123456789@#+-*/"
#Estado civil y grupo de sangre
print("Cual es tu estado civil y grupo de sangre?")
print(str.upper()[19]+str[15]+str[11]+str[20]+str[4]+str[18]+s... |
262ad2b2e1f7b00b6a3090b8d57f11d7c2fba761 | Kolhar-Prashant/Coding-club-Linkedin. | /Shift_mat_ele_row_wise_k_times.py | 279 | 3.90625 | 4 | def rotate(row_num):
for _ in range(k):
temp = mat[row_num][1::]
temp.append(mat[row_num][0])
mat[row_num]=temp
mat= [[1,2,3],[4,5,6],[7,8,9]]
k=2
for row_num in range(len(mat)):
rotate(row_num)
for row in mat:
print(row)
|
b7fbb75797c8cad89e27599cb5618f2265e31b62 | Shulamith/csci127-assignments | /Classcode/madlibs.py | 2,149 | 3.640625 | 4 | #lab --make sure to write correct file name!! and folder
##madlib= "<exclamation> he said <Adverb> as he jumped into his <noun> and drove off with his <adjective> wife."
##NOUNS = ["car", "dog", "hammer"]
##def func_that_uses_NOUNS():
## global NOUNS
import random
#could make it more complex that adj and verbs w... |
0991fc9c42caf60963563cfa2b9aff53ca883461 | JustWon/MyKakaoCodingTestSolution | /Quiz3/Quiz3.py | 2,750 | 3.609375 | 4 | class Node:
def __init__(self, _key, _val, _prev=None, _next=None):
self.key = _key
self.val = _val
self.prev = _prev
self.next = _next
class LRUCache:
# @param capacity, an integer
def __init__(self, capacity):
self.counter = 0
self.capacity = capacity
self.dic = dict()
self.head = Node(None, None... |
8e7dc87f71e8a38948761d0fcbdb6dd0efb25340 | PriyankaKhire/ProgrammingPracticePython | /drawClientServer.py | 4,106 | 3.6875 | 4 | from Tkinter import *
class Server(object):
def __init__(self, width, height):
self.x1 = (width/2 + width/16)
self.y1 = (height/2 + height/2.1)
self.x2 = (width/2 - width/16)
self.y2 = (height/2 - height/2.1)
self.textX1 = width/2
self.textY1 = height/2
c... |
7a54758662287222865f679bde0cf644af5e6b82 | Pallav277/Python_Turtle_Graphics | /Spiraling Star.py | 253 | 3.65625 | 4 | import turtle
import random
sp = turtle.Turtle()
col = ["red", "blue", "white", "green", "yellow"]
scr = turtle.Screen()
scr.bgcolor("black")
sp.pensize(3)
for i in range(40):
sp.color(random.choice(col))
sp.forward(i * 10)
sp.right(144)
|
811acd56c331d6dbd7da5216c0df2ad82e6a8393 | jdcheesman/python-nlp | /week1/test/Levenshtein.py~ | 1,526 | 3.625 | 4 | #!/usr/bin/env python
import sys
if __name__ == '__main__':
if len(sys.argv) == 3:
wordI = sys.argv[1].lower()
wordJ = sys.argv[2].lower()
i = 0
j = 0
data = [[0 for col in range(len(wordJ)+2)] for row in range(len(wordI)+2)]
for cI in wordI:
data[i+2][... |
4226648a4c14c8c5f508116b3d6135a5f0bb8705 | MaoningGuan/LeetCode | /剑指 Offer(第 2 版)/constructArr.py | 864 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
剑指 Offer 66. 构建乘积数组
给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B 中的元素 B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。不能使用除法。
示例:
输入: [1,2,3,4,5]
输出: [120,60,40,30,24]
提示:
所有元素乘积之和不会溢出 32 位整数
a.length <= 100000
"""
from typing import List
class Solution:
def constructArr(self, a: List... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.