blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
1d62f92da7f667c74a6cca60e9fa6dcc723cb27b | vasuharish/CodingTheMatrix | /Politics Lab/politics_lab.py | 8,045 | 4.15625 | 4 | voting_data = list(open("voting_record_dump109.txt"))
## Task 1
def create_voting_dict():
"""
Input: None (use voting_data above)
Output: A dictionary that maps the last name of a senator
to a list of numbers representing the senator's voting
record.
Example:
>>> creat... |
98a3d44f4689ca58a03ca3ef65f554237512d639 | troberson/exercises-exercism | /python/meetup/meetup.py | 1,798 | 3.953125 | 4 | import calendar
from datetime import date
from typing import Callable, List
class MeetupDayException(ValueError):
pass
def which_date(day_list: List[int], which: str,
failure_invalid: Callable,
failure_does_not_exist: Callable) -> int:
day_safe: List[int]
which_n: List[str... |
ef83c525428ecd7287c07fcd35dcc84e723fa8d0 | lucaspereirakonrath/somabackend | /nome.py | 123 | 3.859375 | 4 | numero1=int ( input ("digite um numero"))
numero2 =int (input("digite outro numero"))
soma = numero1+numero2
print (soma)
|
9b2e0c4abee56c752678101d9aa89429c38f03bc | binchen15/leet-python | /bits/prob338.py | 755 | 3.578125 | 4 | class Solution(object):
"""10% solution... hmm."""
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
ans = [0]
for n in range(1, num+1):
cnt = 0
while n > 0:
bit = n & 1
if bit:
... |
6a117862b14b7ecb1feaa44a28b36970aed8d02c | zhengrchan/rep01 | /pythonpractive/insert_sort.py | 655 | 3.96875 | 4 | from sort import Sort
class InsertSort(Sort):
def insert_sort(self):
'''
Sort the list
and calculate the compare times as well as jump times
input: list
store: self.compare_time, self.jump_time
'''
list = self.list
lenth = len(list)
... |
8c1e53923bf375fbd257a5934b16044a79df0208 | azizij4/tuto | /1.datatypes/list.py | 1,348 | 4.03125 | 4 | #create a list of students subjects
form4_sub = ['chemist','physics','bios','history','maths','civics','Geo','kiswahil','English']
#loop the list
#for subjects in form4_sub:
# print(subjects)
collage_sub = ['com skills','Enterprenuership','Algorithms','Data structure','C programming','python','c++']
#append method
#a... |
23ccacf8a4818e0764bcebdbfe816f5bb3d0197c | layshidani/learning-python | /lista-de-exercicios/listas python org/2.1-Maior-Numero.py | 317 | 3.984375 | 4 | print('===Faça um Programa que peça dois números e imprima o maior deles===')
n1 = int(input('\n\nInsira um número inteiro qualquer: '))
n2 = int(input('Insira outro número inteiro qualquer: '))
if n1 > n2:
print('\nO maior número é {}' .format(n1))
else:
print('\nO maior número é {}' .format(n2)) |
d07e74042a9cf7baaec901761913ef9deb5e5e32 | taraspiotr/python_course | /my_solution/lab1/zadania_inst2.py | 2,475 | 3.609375 | 4 | def test(fun, *args):
print "".join(['-' for i in range(40)])
print fun.__name__[:-1].upper()+" "+fun.__name__[-1]
res = fun(*args[:-1])
if isinstance(args[0], str):
decoded = "".join([chr(i) for i in args[-1]])
if res == decoded:
print "Yes, "+decoded.replace("my","your")
... |
b2d69137f0f2ba8b320c89a17247ac2b48d59bb6 | LennyDuan/AlgorithmPython | /HackerRank Interview Preparation Hash Tables: Ice Cream Parlor/answer.py | 539 | 3.5625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
from collections import defaultdict
def whatFlavors(cost, money):
res = []
# Write your code here
dic = {}
for i, c in enumerate(cost):
if dic.get(c) is not None:
r... |
58e88dc960eeab6d3ed9f0196adf34ca8baea621 | dhirensr/Ctci-problems-python | /leetocde/sortByBits.py | 577 | 3.75 | 4 | def int_to_binary(num):
k=0
count = 0
while num > 2**k:
k+=1
if num == 2**k:
count =1
else:
for i in range(k-1,-1,-1):
if num >= 2**i:
count+=1
num = num - 2**i
return count
def sortByBits(arr):
output = []
for i in a... |
56bd2e97d9577a7410f38dfa71c2e3cad80e1665 | twopiharris/230-Examples | /python/demos/imgDemo.py | 737 | 3.65625 | 4 | """ imageDemo.py
demonstrates using images in Tkinter
"""
from Tkinter import *
class App(Tk):
def __init__(self):
Tk.__init__(self)
#photoImage file type must be gif or pgm !!?!
#convert and resize in image editor as needed
#be sure to save each image as a member va... |
f62cd92d4b64bd9b44304bb8afc139d791188582 | hipema/python | /ejemplos/prueba03_lectura_escritura_archivo.py | 1,406 | 3.765625 | 4 | """
Prueba de lectura / escritura de un archivo
Los ficheros se utilizan para guardar información de manera persistente.
"""
import os
# print(os.system("pwd")) --> sirve para ver en que posición se encuentra para ejecutar Python y desde donde va la ruta.
f = open("github/ejemplos/prueba03.txt", "r+") # open (cadena_no... |
47edb4eb16b771df7faaab42dffd46585cac3d8b | nnamon/ctf101-systems-2016 | /lessonfiles/compromise/1-denialofservice.py | 985 | 3.828125 | 4 | #!/usr/bin/python
import socket
def main():
HOST, PORT = "localhost", 0
# Create the server, binding to localhost on a free port
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(10)
# Print the connection information
print "Please connect... |
f21a57f8b58be339a0f51d3a34120fd1b8185cc9 | dianaparr/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 227 | 4.28125 | 4 | #!/usr/bin/python3
""" Define a class called Square """
class Square:
""" Constructor method to initialize the attributes of the
instantiated object 'size' """
def __init__(self, size):
self.__size = size
|
9b5694d8e3a23efc046a896945a8969ce3dbfd97 | adamklemm96/modifyCSV | /createcsv.py | 1,300 | 3.78125 | 4 | #!/usr/bin/env python3
import pandas as pd
import sys, os, csv, random
def clean():
os.system("clear")
path1 = sys.argv[1]
while True:
try:
password_lenght = int(input("What is the minimum lenght of hash?:"))
except:
print("You didn't enter integer")
continue
else:
bre... |
f9cf7b0fce3277d54ee90427a6228e082fd51f22 | PaulGuo5/Leetcode-notes | /notes/0222/0222.py | 1,400 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def countNodes1(self, root: TreeNode) -> int:
self.res = 0
def dfs(root):
if not root:
return... |
111af7cd924e3ebec7d39b0a7a457bfac6b349a0 | BarryZM/UVloger | /doc/UVLOGER实验报告九/4人kwic/04-pipes-filters/kwick/output.py | 362 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'mejty'
class Output:
def __init__(self, filename):
self.filename = filename
def save_to_file(self, sorted_lines):
with open(self.filename, "w") as file:
for line in sorted_lines:
file.write("{line}\n".fo... |
96e7851fecf5806d41c9eeb8894dfcdbb1f656c2 | Nicholas-Ferreira/Impacta | /semestre_3/analise_modelagem_sistemas/classes.py | 768 | 3.5625 | 4 | class Ingresso:
valor = 10
def __str__(self):
return str(self.getValor())
def getValor(self):
return self.valor
class IngressoVIP(Ingresso):
valor_adicional = 5
def getValor(self):
return self.valor + self.valor_adicional
class ControllerIngresso:
def __init__(self):
i = Ingresso()
... |
4848a318d4bbefc3ec7d1a3ce359bb4d22f5dc31 | shariefsmm/AI-LAB | /LAB12/UCB.py | 2,090 | 3.734375 | 4 |
# The below program uses standard UCB algorithm. So, no separate info file has been provided but instead comments
# has been included wherever appropriate.
import matplotlib.pyplot as plt
import numpy as np
import sys
print("____________Multi-armed bandit with bernoulli-distributed rewards____________")
K = 10 ... |
53cd4c0fee8bb31db7c08187f8ecbbab5324ed88 | tomoya7/python | /python_id.py | 362 | 3.71875 | 4 | #a = 'tomoya'
#b = 'tomoya'
a=[1,2,3]
b=[1,2,3]
#a=(1,2,3)
#b=(1,2,3)
print(id(a)==id(b))
print(a==b)
if ( a is b ):
print ("1 - a 和 b 有相同的标识")
else:
print ("1 - a 和 b 没有相同的标识")
a=b=[1,2,3]
print(id(a)==id(b))
if ( a is b ):
print ("1 - a 和 b 有相同的标识")
else:
print ("1 - a 和 b 没有相同的标识") |
068417cc870bba5657cdb2bbe896cccc9a79a430 | ilante/programming_immanuela_englander | /simple_exercises/lanesexercises/py_if_and_files/16_repeat_complement.py | 706 | 4.0625 | 4 | # 16. ask the user for two strings
one = input('Give me one word please! ')
two = input('Give me another one. ')
# 17. check if one string is the complement of the other (i.e. “AC” and “TG” -> yes)
bases = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
def complement(seq1, seq2, di):
pattern = ''
for i in range(len(seq... |
6f93c2b231deeaf88d91fec26af479e1869b7206 | eflipe/python-exercises | /codewars/kata_8_class_count.py | 2,065 | 4.1875 | 4 | '''
We need a method in the List Class that may count
specific digits from a given list of integers.
This marked digits will be given in a second list.
The method .count_spec_digits()/.countSpecDigits()
will accept two arguments, a list of an uncertain amount
of integers integers_lists/integersLists
(and of an uncertai... |
db5344c4ea5091b5e56555a58ff024c3d97ed28a | jalasem/genetic_algorithms | /game_template.py | 2,916 | 3.65625 | 4 | from your_suborganism_class import SubOrganism as Organism
import utility
from random import random
class YourGameName():
def __init__(self, population, num_game_turns):
self.name = "Your Game Name"
self.population = population
self.num_game_turns = num_game_turns
self.actions = [... |
220e5d313bc485a85ebb2834e4c36960198786e9 | ethframe/aoc_2017 | /day17.py | 563 | 3.5 | 4 | from adventlib import *
DAY = 17
class n:
__slots__ = ("v", "n")
def __init__(self, v, n):
self.v = v
self.n = n
def after(self, v):
c = n(v, self.n)
self.n = c
return c
def main():
inp = store_input(DAY)
if inp is None:
return
inp = int(inp... |
0ce25823bda77aa82e3a488b95d04d671764fc32 | a961634066/django | /operation/utils/thread_lock.py | 2,566 | 3.875 | 4 | # -*- coding:utf-8 -*-
import threading
import time
from threading import Lock
# class Foo:
# def __init__(self):
# self.firstJobDone = Lock()
# self.secondJobDone = Lock()
# self.firstJobDone.acquire()
# self.secondJobDone.acquire()
#
# def first(self, printFirst: 'Callable[[],... |
c7619142475a809e4dccd5a2e9e0006238eb1f79 | kangsup/maybler0 | /day2_P.py | 332 | 3.734375 | 4 | #Ex10_Program_Excercise_Random_games
#game1-1
### 정답입니다 오답입니다
import random as r
input('엔터를 누르면 문제가 나옵니다')
a = r.randint(1, 9)
b = r.randint(1, 9)
c = a*b
print(a, '*', b, '= ?')
x = input()
d = int(x)
if d == c:
print('정답입니다')
else:
print('오답입니다') |
dd3369740ebc8c41df92f6848a4dfe4faa3d96d7 | dearfeife/Adventure-Game | /adventure_game.py | 3,592 | 4.09375 | 4 | import time
import random
monsters = ("Troll", "Gorgon", "Wicked fairie", "pirate")
monster = random.choice(monsters)
def print_pause(string):
print(string)
time.sleep(2)
def intro():
print_pause("You find yourself in a dark dungeon."
"In front of you are two passageways.")
print_pa... |
964fbb3165f2fc2626e3f481429c6b43dc84a5c8 | ccruzp/IngenieriaDeSoftware | /EjerciciosLaboratorio/descomponerPrimos.py | 1,160 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#######################################################
# #
# descomponerPrimos.py #
# Recibe un numero y lo descompone en factores primos #
# Autores: Carlos Cruz 10-10168 ... |
1aaf8b6efccf570c297e9da7c49f21e27a3c97f9 | mmillervedam/SudokuSolver | /Python2_version/StackClass.py | 998 | 3.9375 | 4 | """
Stack class
"""
class Stack:
"""
A simple implementation of a LIFO stack.
"""
def __init__(self):
"""
Initialize the stack.
"""
self._items = []
def __len__(self):
"""
Return the number of items in the stac.
"""
return len(self.... |
96954a599a00d44ce016ec924fdfdacc28720042 | SteveJSmith1/leetcode-solutions | /Solutions/485_Max_Consecutive_Ones.py | 1,426 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 12 14:41:39 2017
@author: SteveJSmith1
"""
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
Given a binary array, find the maximum number
of consecutive 1s in this array.
:type nums: ... |
5c6ce8379d2c4dc702b20cb252db1d584af6f997 | 215836017/PythonDemos | /DemoReptile/01_urllib/001_urllib_urlopen.py | 1,821 | 3.515625 | 4 | import urllib.request as request
import urllib.parse as parse
'''
最基础的HTTP库有:urllib, httplib2, requests, treq等
'''
response = request.urlopen('https://www.python.org/')
print('test 111 : ', response)
# print('test 222 : ', response.read().decode('utf-8')) # 结果跟网页源代码是一样的
print('test 333 : ', type(response))
# test... |
d12cc5851b519b91d74fff3d924d43527e85dacd | andrefacundodemoura/exercicios-Python-brasil | /exercicios_python_brasil/lista01_estruturas_sequenciais/ex12peso_ideal_h12.py | 305 | 3.828125 | 4 | '''
12. Tendo como dados de entrada a altura de uma pessoa,
construa um algoritmo que calcule seu peso ideal, usando a seguinte fórmula: (72.7*altura) - 58
'''
alt= float(input('Qual sua altura em mts: '))
pesoh= (72.7*alt)-52
print(f'Baseado na sua altura de {alt}mt seu peso ideal é {pesoh :.2f}kg') |
9d56f320781135c911c0747fcdcef901a2bcd980 | tienluils1996/practice-python | /oop/ldtt/081.py | 150 | 3.640625 | 4 | import math
n = int(input("nhap n:"))
x = int(input("nhap x:"))
S = 1/x
M = x
i = 1
while(i <= n):
M = M*(x+1)
S = S+1/M
i = i+1
print(S)
|
bc024e7aca92eb08f03cf650967c0af7090bdd5c | abhi1998das/MMHAREnsemNet | /Preprocessing/Filter.py | 5,585 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 9 23:06:44 2020
@author: taichi10
"""
import os
import scipy.io
import numpy as np
import math
import numpy
def smooth(x,window_len=11,window='flat'):
"""smooth the data using a window with requested size.
This method is based on t... |
b2f3d22aa7ccbdf780b493e2b01f778ef0c9967b | CalebJTipton/ProjectWOPR | /PuzzleCube-R10.py | 36,129 | 3.6875 | 4 | #########################PROJECT: PuzzleCube#################################
##
##PuzzleCube - Pseudocode
##(Python)
##
##START
##
##Import Serial Library
##Import OS Library
##Import Time Library
##Import Turtle Library
##
##Define function for serial servo control taking in string value
## Define variable and set e... |
905be6ed80639c1bebfe0e54ba0f3e338c763cd2 | jinurajan/Datastructures | /LeetCode/easy/min_distance_between_bst_nodes.py | 2,428 | 3.828125 | 4 | """
783. Minimum Distance Between BST Nodes
Easy
Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.
Example :
Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.
T... |
d55768e5735d6d4db6b12b403f9afbbd89af930b | shenlong2010-unregular/probs | /challenge-expert/LongestPeak.py | 735 | 3.640625 | 4 | # O(n) time| O(1) space
def longestPeak(array):
longestPeakLength = 0
i = 1
while i < len(array) - 1:
isPeak = array[i-1] < array[i] and array[i] > array[i+1]
if not isPeak:
i += 1
continue
leftIdx = i - 2
while leftIdx >= 0 and array[leftIdx] < ar... |
bb9877ee3c1dbb70103f1722c99346121fe1c93c | JonathanAlderson/3DRenderer | /code0.3.py | 9,509 | 4.09375 | 4 | import tkinter,math,time
def matMul(a,b):
"""Will multiply two matricies together that are 3x3 and return the sum"""
c = []
# All these calculcations return the product of any two matricies A * B
#print("Mat mul called")
#print("A = ",a)
#print("B = ",b)
c.append(a[0] * b[0] ... |
ef4161174aada166fa0156f12acdb2f1acb35e3c | paraker/sololearn_python | /9Regular_Expressions.py | 8,751 | 4.53125 | 5 | #################################################
# #
# Regular Expressions #
# #
#################################################
# Regular Expressions in python are accessed in the "re" module.
imp... |
d9180d83830cc627c82f1162042fa608996ffced | WeiYongqiang55/leetcode | /python/414.py | 358 | 3.921875 | 4 | class Solution:
def thirdMax(self, nums):
"""
:type n: int
:rtype: int
"""
nums=list(set(nums))
nums=sorted(nums,reverse=True)
if len(nums)>=3:
return nums[2]
else:return nums[0]
if __name__ == "__main__":
so = Solution()
nu... |
1a9d5bb73d472c9a5ad0c261899da2672ea71b54 | ksayee/programming_assignments | /python/CodingExercises/LeetCode233.py | 704 | 3.859375 | 4 | '''
233. Number of Digit One
Hard
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Example:
Input: 13
Output: 6
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
'''
def CheckOnes(n):
while n!=0:
rem=n%10
... |
56b379ada8eed307af8d79f920e04e815d93726c | Fgsj10/Python_Trainning | /Classes/Class_Three.py | 773 | 3.953125 | 4 | """
Author = Francisco Junior
"""
#Creating class
class Rectangle():
"Structure of rectangle"
def __init__(self, base, height):
self.setBase(base)
self.setHeight(height)
def setBase(self, base):
self.setBase = base
def getBase(self):
return self.base
#Now for he... |
cefac6a7b86eee090267254d047269c4fda7fada | jaeyun95/Algorithm | /basic_code/heap_sort.py | 576 | 3.796875 | 4 |
def heapify(lst, index, size):
parent = index
child = 2 * index + 1
if child < size and lst[child] > lst[parent]:
parent = child
if (child + 1) < size and lst[(child + 1)] > lst[parent]:
parent = (child + 1)
if parent != index:
lst[parent], lst[index] = lst[index], lst[paren... |
10155606fe6ad63443bf92e8284f533fa6e60e01 | jdfadams/explore | /explore.py | 4,077 | 4.0625 | 4 | # Thinking of the internet as a directed graph, we draw a ball of a given radius.
# For our purposes, vertices are top-level domains, and directed edges are links.
# There is a "distance" induced by following directed edges.
# Starting from center = "somewebsite.com", we follow links to other top-level domains.
# We bu... |
8955d5b267702c8e09232958d4c5da998001d36d | mushtaqmahboob/CodingPractice | /LeetCode/Easy/ReverseOnlyLetters.py | 1,406 | 3.921875 | 4 | '''
run a pointer 'i' from the beginning and another one 'j' from the end
when any alphabet is encountered we swap the values
when anything other than alphabet is encountered we ignore that and increment i pointer or decrement j
depending on where it occurred
'''
class Solution:
def reverseOnlyLetters(self, s) -... |
70ef327915a4c768bd802c5f9a1ad3d0b3c4d674 | martintvarog/practicepython | /exercises/odd_or_even.py | 328 | 3.890625 | 4 | number = input("Input number: ")
mod = int(number) % 2
multiply_of_4 = int(number) % 4
if mod >0:
print("u picked odd number")
else:
print("u picked even number")
if multiply_of_4 >0:
print("u picked number is NOT multiplied by 4")
else:
print("u picked number multiplied by 4")
#print(isinstance(... |
7c7cdc8624d360d166b320e9b2d87305d274046c | lijinfeng0713/graph | /graphs/graph.py | 2,712 | 3.84375 | 4 | """
Undirected Graph
Author: lijinfeng
Date: 207-07-14
Version: 1.0
"""
class Graph(object):
# init member variables
def __init__(self):
self.nodes = {}
self.edges = {}
# add node to the graph
def add_node(self, i):
if self.nodes.get(i) is not None:
... |
7007e3eddd95c18a844f5611856d719554eb5309 | Shreejichandra/September-Leetcode | /179_largest_number.py | 494 | 3.703125 | 4 | # Given a list of non negative integers, arrange them such that they form the largest number.
class Solution:
def largestNumber(self, nums: List[int]) -> str:
if len(nums) == 0:
return ""
def compare(a, b):
return int(str(b)+str(a)) - int(str(a)+str(b))
... |
36f48f06603b8ce943a91c5a8b75cd1e994a7de9 | martakedzior/python-course | /04-functions/funkcje_zadanie4.py | 638 | 3.984375 | 4 | # 4▹ Napisać funkcję, która wypisze wszystkie parzyste z przekazanej listy elementów (wykorzystać funkcje z zadania 2)
def check_if_even_number():
counter = int(input('Ile liczb chcesz podać? '))
user_list_of_numbers = []
for i in range(counter):
user_input = int(input('Podaj liczbę całkowitą: '... |
b812cdff4294624f541fa5d93ac7c6f3866a1e04 | abstractlyZach/pluralsight-python-unit-testing | /phonebook/phonebook.py | 887 | 3.75 | 4 | class Phonebook:
def __init__(self):
self._entries = dict()
self._is_consistent = True
def add(self, name, number):
self._check_consistency_of_added_number(number)
self._entries[name] = number
def _check_consistency_of_added_number(self, number):
self._check_duplica... |
e51b54ea853e0ea19288887e868ef5a6b9bdfcf3 | wangyendt/LeetCode | /Contests/301-400/week 305/2370. Longest Ideal Subsequence/Longest Ideal Subsequence.py | 583 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author: wangye(Wayne)
@license: Apache Licence
@file: Longest Ideal Subsequence.py
@time: 2022/09/04
@contact: wang121ye@hotmail.com
@site:
@software: PyCharm
# code is far away from bugs.
"""
import collections
class Solution:
def longestIdealString(se... |
005ec47121083c6e1cc237283ac2e2ebff89e8c7 | mcclayac/LearnSmart1 | /Class8Exceptions/GeneralExceptionExample.py | 1,013 | 3.5625 | 4 | __author__ = 'anthonymcclay'
__project__ = 'LearnSmart1'
__date__ = '7/23/16'
__revision__ = '$'
__revision_date__ = '$'
def divisionByZero():
x = 90 * (1/0)
def stringExample():
x = '75' + 25
def nameexample():
x = 75 + vara * 30 # (nameError: vara is not defined
def trycatchExample1():
while ... |
517a654dbdb6e70d24dcf9fd9dd4a97e43f05c93 | asperaa/back_to_grind | /array/subarray_sum_equal_k.py | 713 | 3.546875 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through."""
"""560. Subarray Sum Equals K
"""
class Solution:
def subarraySum(self, nums, k):
prefix_sum = []
summ = 0
count = 0
for i in range(len(nums)):
summ += nums[i]
pre... |
508fb041a87d4ced2f3438397023244635d82a90 | viszi/codes | /CodeWars/8kyu/Python/001-get-the-mean-of-an-array.py | 1,026 | 3.640625 | 4 | # https://www.codewars.com/kata/563e320cee5dddcf77000158/
# Return the average of the given array rounded down to its nearest integer.
# The array will never be empty.
import math
def get_average(marks):
sum = 0
for i in range(len(marks)):
sum += marks[i]
return math.floor(sum/len(marks))
def ... |
7dcae12c7e9ac8dbf39cc891ae273dd45ad7bc09 | shobhit-nigam/qberry | /day3/flow_control/2_if.py | 179 | 3.578125 | 4 | varx = 30
vary = 40
if varx < vary:
# code
print("good morning")
print("hey")
elif varx == 30:
print("namaste")
print("salaam")
else:
pass
print("hello")
|
a6bf9371a8ae079c029ceccf9ce3ccb77b94b6bc | Maquiavelosan/Python-cousre | /5 Condiciones/Tarea 5-2.py | 788 | 4.25 | 4 | """ 2 - Crea una lista con los numeros (tipo entero) del 1 al 9.
Itera la lista y crea una cadena de if-elif-else dentro del ciclo, para imprimir el numero ordinal, por ejemplo para el 1 -> primero, 2 -> segundo, etc.
Cada numero se debe imprimir en una linea diferente. """
numeros= [1,2,3,4,5,6,7,8,9]
for co... |
3a6b2dd73c05accdcfcdf053d024b4f483a512bc | AdamZhouSE/pythonHomework | /Code/CodeRecords/2629/60870/313760.py | 174 | 3.859375 | 4 | num_test = int(input())
num_list = []
for i in range(num_test):
num = int(input())
num_list.append(num)
for i in range(num_test):
num = num_list[i]
print(num) |
0dbc7f2001edf98d372fa5e2af7fb30ac7b69ae6 | alexcolombari/Python-Scripts | /folder_bot.py | 741 | 3.875 | 4 | # ------------------------------------------------------------
# Author: Alex Colombari (http://github.com/alexcolombari)
# Date: 2019-10-12
# Create random folders in directory
# ------------------------------------------------------------
import os
import random
import string
def randomName(stringLength = 5):... |
9ca1160dedbfabf38e1f1243ad15dc2f677ef756 | AlexSTM2/TP-N-1 | /Ejercicio 10 LINO Alexis.py | 386 | 3.84375 | 4 | #Ejercicio 10
def lost_char(txt, n):
if n == 0:
new_txt = txt[1:]
print(new_txt)
elif n == len(txt):
new_txt = txt[0:n-1]
print(new_txt)
else:
new_txt = txt[0:n] + txt[n+1:]
print(new_txt)
txt = str(input("Write a text string: "))
n = int(input("Write the in... |
7d60d561f98fa3abfb47c51529bb1baba2bd2a39 | zhangpengGenedock/leetcode_python | /099. Recover Binary Search Tree.py | 1,501 | 3.5625 | 4 | """
https://leetcode.com/problems/recover-binary-search-tree/
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
"""
# Definition for a binary tre... |
3aabb8f5583274473282c2e3a3652c50ea3f2cc1 | mani-9642/mani-9642 | /number tio digit.py | 155 | 4 | 4 | n=int(input("Enter the Number : "))
def digit(n):
if n<10:
print(n,end=" ")
else:
digit(n//10)
k=n%10
print(k,end=" ")
digit(n) |
c7b79a8f6d17a71d774bf7ee0effa505413f91fe | lianglee123/leetcode | /剑指Offer/31~40/38.字符串的排列.py | 664 | 3.671875 | 4 | from typing import *
from collections import deque
class Solution:
def permutation(self, s: str) -> List[str]:
res = set()
self.dfs(s, [], deque(s), res)
return list(res)
def dfs(self, s, path, charDeque, res):
if len(path) == len(s):
res.add("".join(path))
... |
798802e5c1546fb3917e27861761f600f7a8f224 | YW-Ma/UDACITY-Algorithm-Project_2 | /problem_3.py | 7,090 | 3.890625 | 4 | import sys
import heapq
class Node(object):
def __init__(self, left = None, right = None):
self.left = left
self.right = right
def traverse(self, code = None):
if code is None:
code = ""
if isinstance(self.left[2], Node):
self.left[2].trav... |
9d4cd661281d7a770367893769152dd60693f0f3 | Hik1/bucleswhile | /Bucle while 1-7.py | 708 | 3.96875 | 4 | #coding: utf-8
num1=input("Introduce un número:")
num2=input("Introduce un número mayor que "+str(num1)+": ")
while num1>=num2:
num2=input(str(num2)+" no es mayor que "+str(num1)+" intentalo de nuevo: ")
num3=float(input("Introduce un número entre "+ str(num1)+" y "+str(num2)+": "))
count=0
while num1<=num3<=num2:
... |
99cd48199f937b9a153d085f5fa53c3a5948a46a | lihude/yolov4-jetson-azure-edge-solution | /scripts/generate_key_for_local.py | 262 | 3.859375 | 4 | import base64
chars = str(input("Enter an 8-character string: "))
if len(chars) != 8:
print("Enter a charater with a length of 8")
exit()
chars = chars * 8
encoded_chars = base64.b64encode(chars, 'utf-8')
print(len(encoded_chars))
print(encoded_chars)
|
88b234b6cbd04a50ef4d8c92267f2196d90069d4 | madrascode/basic-python-code | /functions/sum_natural_numbers_recur.py | 158 | 3.828125 | 4 | def sum_natural_numbers(num):
if num <= 1:
return num
else:
return num + sum_natural_numbers(num - 1)
print(sum_natural_numbers(16)) |
6c33840e9d69121f7bb22cbbec19a918980b43dd | HotsauceLee/Leetcode | /Categories/DP/RRR_L_430.Scramble_String.py | 3,067 | 4 | 4 | """
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of s1 = "great":
great
/ \
gr eat
/ \ / \
g r e at
/ \
a t
To scramble the string, we may choose any non-leaf nod... |
d922622ebb88d66898dab12fd58cb0ff66532fe3 | jjuny0113/DataStructures_and_Algorithms | /data_structure/Hash.py | 1,488 | 4.03125 | 4 | # hash_table = list([0 for i in range(8)])
# def get_key(data):
# return hash(data)
# def hash_function(key):
# return key % 8
# def save_data(data, value):
# hash_address = hash_function(get_key(data))
# hash_table[hash_address] = value
# def read_data(data):
# hash_address = hash_func... |
a43ca50fb8942bde5070132b810807623c6879c5 | Azaro1805/python- | /pandas.py | 1,477 | 3.5 | 4 | import pandas as pd
df = pd.read_csv('assignment_inspections11.csv')
#-------------------------------------------------df info----------------------------------------#
#print(df.info())
#print(df.shape)
#print(df.columns)
#-----------------------------------------------set df------------------------------... |
ebdffa434b929d4b2802ae0031ce8b77ddd5be62 | mal33ina/Home | /book/chapter 5/pologitelnoe chislo.py | 700 | 3.8125 | 4 | print('Vvedite 6 naturalnix chisela')
sum = 0
n = 0
chislo = int(input("Введите чило: "))
if chislo > 0:
sum += chislo
n += 1
chislo1 = int(input("Введите чило: "))
if chislo1 > 0:
sum += chislo1
n += 1
chislo2 = int(input("Введите чило: "))
if chislo2 > 0:
sum += chislo2
n += 1
chislo3 = int(in... |
1a0d8000cfbd6dc8c8d621900c76eb0dc69c3c59 | EachenKuang/LeetCode | /code/109#Convert Sorted List to Binary Search Tree.py | 1,557 | 4.125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findMiddle(self,... |
9e62d5942ff506f598c666b67fb78cb391bc536d | igrapel/Python | /lottery.py | 788 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 8 09:28:48 2020
@author: 323917
"""
import datetime
import random
import matplotlib as plt
class lottery:
def __init__(self, year, month, day):
self.date = datetime.datetime(year, month, day)
self.tickets = []
def lottery_run(self,... |
374a5c8ec924d143200cadf8ad46242e3c1e4bd2 | CurtisSHiscock/Bit-Plane-Complexity-Segmentation-Steganography | /libs/complexity.py | 1,978 | 4.125 | 4 | #complexity.py
import numpy as np
## Methods for determining complexity of squares
def checkerboard(shape):
'''
returns a checkerboard
'''
return np.indices(shape).sum(axis=0) % 2
def array_xor(array):
'''
returns XOR of an array and a checkberboard of the same shape
'''
checker = chec... |
080b559936ca77ef80402361e08d85a120b254e2 | Turtledorm/projeto-pokemon | /projeto/pokemon.py | 7,264 | 3.640625 | 4 | """Contém a classe Pokemon."""
import os
import sys
import time
from tipo import get_tipo, get_num_tipos
from ataque import Ataque, get_struggle
from batalha import is_debug, cor
from ia import melhor_ataque
class Pokemon:
"""Representa um Pokémon que batalha no jogo."""
def __init__(self, dados, cpu=False... |
44f2aa029d9e3161be497ca313be81bd195661e4 | jasonyu0100/General-Programs | /2019 Programs/Progcomp/question_1/problem.py | 609 | 3.703125 | 4 | keypad = ["ABCDEFG","HIJKLMN","OPQRSTU","VWXYZ"]
def find(char):
for i,row in enumerate(keypad):
if char in row:
return i,row.index(char)
out = open("output.txt", "w")
with open("input.txt") as f:
for line in f:
line = line.strip()
line = line.upper()
valid = True
for prev,cur in zip(line... |
8325c95827aed30d392d381dd313d08b806c0ab5 | CaiqueAmancio/exerciciosPython | /exerc_43_secao_4.py | 827 | 3.859375 | 4 | """
Escreva um programa de ajuda para vendedores. A partir de um valor total lido, mostre:
- o valor total a pagar com desconto de 10%;
- o valor de cada parcela, no parcelamento de 3x sem juros;
- a comissão do vendedor, no caso de venda a vista (5% sobre o valor com desconto)
- a comissão do vendedor, no caso de vend... |
a32a07fd64312bf427e43cc6384c2f73f3cfe102 | anricoj1/CSC152 | /Lab8a/Initials.py | 342 | 4.03125 | 4 | #Initals
# Ask user for FULL NAME
# display initals J.M.A
def main():
name = input("Type your FULL NAME and press ENTER/RETURN: ")
name_list = name.split()
print(name_list)
first = name_list[0][0]
second = name_list[1][0]
last = name_list[2][0]
print(first.upper(),".",second.upper(),".", ... |
dab565b2e260dadc9fb14543fee9df41c84c904a | Vandeilsonln/Python_Automate_Boring_Stuff_Exercises | /Chapter-9_Organizing-Files/renamepictures.py | 1,491 | 3.8125 | 4 | #! python3
# renamepictures.py - The code will go through a directory tree and will rename all the pictures
# based on it's creation date.
# For now the code will just identify '.jpg' files. Any other formats will remain unchanged, although
# their filenames will be written in the 'rejected.txt' file. By doing this, y... |
6778a669c30e796db05dbe1ce85ccd24cc0865bf | pankajyadav0/pythonFFTW | /2d_to_1d.py | 1,234 | 3.796875 | 4 |
nx = 3
ny = 4
g = []
for i in range(nx):
g.append([])
for i in range(nx):
for j in range(ny):
g[i].append(j)
g[i][j] = 0.0
for i in range(nx):
for j in range(ny):
g[i][j] = j + i*ny
#print ("Using range...")
for i in range(0,nx):
output = "" #setting outpu... |
9247ae41b50e1b471af2a3caef52503c10323c1e | FrockConnor317/Connor-Frock-s-Project-1 | /proj01_ifelse/proj01.py | 1,614 | 4.375 | 4 | # Name:
# Date:
# proj01: A Simple Program
# Part I:
# This program asks the user for his/her name and grade.
#Then, it prints out a sentence that says the number of years until they graduate.
Name = raw_input('What is your name?')
Grade = int(raw_input("what grade are you in?"))
print str(Name[0].upper() + Name[1:... |
9d83771891c314f1eb05f48c968bb5416f8ad2c0 | liangsongyou/python-crash-course-code | /chapter9/ice_cream_stand.py | 1,385 | 3.90625 | 4 | class Restuarant():
"""A very basic representation of a restuarant."""
def __init__(self, name, cuisine):
"""Initialize the restuarant's attributes."""
self.name = name
self.cuisine = cuisine
def describe_restuarant(self):
"""Describe the restuarant."""
print("{} of... |
e097985027f3b458d03c829c4dac0f999e32bebc | crescent-and-sheezer/python_text1 | /employee.py | 334 | 3.65625 | 4 | # _*_ coding:utf-8
# 作者:凡
# @Time: 2021/2/12 20:50
# @File: employee.py
class Employee():
def __init__(self,firstname,lastname,salary):
self.firstname=firstname
self.lastname=lastname
self.salary=int(salary)
def give_raise(self,increase=''):
if increase!='':
self.salary+=int(increase)
else:
self.sala... |
6f6defd1588bc6de6da5f3c5c54515df47858554 | wait17/data_structure | /10.6/02.代码练习.py | 5,332 | 4 | 4 | from typing import List
# ###########################练习加笔记###########################
# 链表:
# 1.增(插入)
# 1-1 插入单独数据
# 1-1-1 从头插入
# 1-1-2 从尾插入
# 1-1-3 从中间插入
# 1-2 插入列表(目前所学为将列表直接创建为链表)
# 1-2-0 在某个位置插入列表????? --> 我觉得可以实现(见03 多练)
# 2.删
# 2-1 删除头
# 2-2 删除尾
# 3.返回值(表示方法)
# 4.反转链表
# 5.查(查相应位置的节点)
# 6.改(更改目标节点的值)
class Nod... |
1598fe895186b333d9f47772dd1b749bff664432 | dletk/PythonPersonal | /algorithmClass/midTerm/insertionSort.py | 548 | 3.875 | 4 | def insertionSort(inArr):
lenA = len(inArr)
for i in range(lenA):
nextEle = inArr[i]
if i == 0:
pass
else:
for index in range(i):
if nextEle <= inArr[index]:
inArr = inArr[:i] + inArr[i + 1:]
inArr.insert(i... |
f72f0c193233b639c500609b99dac19889846d10 | semoren/learn_python | /regex/regex.py | 450 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
r = r'^\d{3}\-\d{3,8}$'
if re.match(r, '010-12345'):
print('ok')
else:
print('faild')
print(re.split(r'[\s\,]+', 'a,b,c d'))
print(re.split(r'[\s\,\;]+', 'a,b;; c d'))
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
print(m)
print(m.group(0))
print... |
f2094c4c3617886a14c5ba26174814785dc52c38 | kargamant/education | /Algorithms and data stractures in python/lesson3/les_3_task_5.py | 1,093 | 3.625 | 4 | '''
5. В массиве найти максимальный отрицательный элемент.
Вывести на экран его значение и позицию в массиве.
Примечание к задаче: пожалуйста не путайте «минимальный» и «максимальный отрицательный».
Это два абсолютно разных значения.
'''
from random import randint
# Инициализация основного списка и
# переме... |
7cd042563e2fcaf07b04f87d641b3cfecece0fc6 | etothemanders/going-postal-django | /goingpostal_app/xml_dict.py | 1,696 | 3.625 | 4 | """
Helpers functions to convert nested dicts/lists to and from XML.
For example, this XML:
<foo>
<bar>
<baz>what</baz>
<quux>hello</quux>
</bar>
<sup>yeah</sup>
<goodbye>no</goodbye>
</foo>
Will be transformed to and from this dict:
{
'foo': {
'ba... |
1334943fae3d2c9bb5a2b647e5f410cb9525ba32 | UeivaM/estudos-python-guppe | /guppe/mapas.py | 949 | 4.40625 | 4 | """
Mapas -> Conhecidos em Python como Dicionários.
Dicionários em Python são representados por chaves {}
#Iterar sobre dicionários:
for chave in receita:
print(chave)
# Ou:
for chave in receita:
print(receita[chave])
for chave in receita:
print (f'\n Em {chave} recebi R$ {receita[chave]} \n')
# Aces... |
391c83ca64fd2490f6343483e5a12aa26621cc7b | Sayeem2004/CodingBat | /Python/p291874.py | 95 | 3.625 | 4 | def countDigits(n):
if n < 0:
return len(str(n)) - 1
else:
return len(str(n))
|
6d05f120165c0c81e3e96bcc34a7d3ef1a05783a | cseydlitz/practice | /StacksAndQueues/animalqueue.py | 1,017 | 4 | 4 | class Node:
def __init__(self, age, next_animal=None):
self.animal = animal
self.next_animal = next_animal
class AnimalList:
"""Prompt: Create a queue which is strictly FIFO for animal adoption
Additional requirements: People can choose between a cat or dog
"""
def __init__(sel... |
0a8b906510c40f8da2fce360ea1b2c62fe8eb6d6 | bemihai/video-reid | /processing/video_file_reader.py | 3,064 | 3.5 | 4 | import cv2
import time
import threading
class VideoFileReader:
"""
A video reader that internally reads the frames in a separated thread at the right fps,
and returns the latest (current) frame when read is called.
"""
def __init__(self):
self.file_name = None
self.cap = None
... |
096f9340248a45a11eb78b8af1d6617df61c4be6 | bunshue/vcs | /_4.python/__code/Python GUI 設計活用 tkinter之路/ch3/ch3_26.py | 749 | 3.765625 | 4 | # ch3_26.py
from tkinter import *
window = Tk()
window.title("ch3_26") # 視窗標題
lab1 = Label(window,text="標籤1",relief="raised")
lab2 = Label(window,text="標籤2",relief="raised")
lab3 = Label(window,text="標籤3",relief="raised")
lab4 = Label(window,text="標籤4",relief="raised")
lab5 = Label(window,text="標籤5",relie... |
ae8091f89db2167da66dd8850eb33b556c9b87c1 | BerilBBJ/scraperwiki-scraper-vault | /Users/C/christian/wdei-ue2-d2.py | 1,044 | 3.78125 | 4 | # Attach to D1 Scraper
sourcescraper = 'd1'
import scraperwiki
# Headline
print "Master Studies at Vienna University of Technology:"
# Attach to database from D1 and select all data from the default table
scraperwiki.sqlite.attach("d1")
data = scraperwiki.sqlite.select( '''* from swdata''' )
# Print out HTML table... |
4623960f9f9fc940a5e4edd5941bf52c4121b913 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2371/60763/248468.py | 284 | 3.703125 | 4 | T = int(input())
for i in range(T):
s = input().lower()
t = ''
for i in range(len(s)):
if ord(s[i]) >= ord('a') and ord(s[i]) <= ord('z'):
t +=s[i]
a = reversed(list(t))
if list(a) == list(t):
print('YES')
else:
print(' NO') |
64f5bd4e48ce4e2ff85747f513a26ac81c6bd396 | TheWolvesTech/PyCodingBasic | /practice6.py | 497 | 4.1875 | 4 | """
TRY IT YOURSELF
3-8. Seeing the World: Think of at least five places in the world you’d like to
visit.
Store the locations in a list. Make sure the list is not in alphabetical order.
"""
good_places = sorted(['new zealand','canada','japon','usa','america']) #Using sorted() --> temporaly sort()
print(good_places)... |
87d283f1f70ea0939c66adfb276e4c15bc691ceb | ragestack/EC-Point-Operations | /EC_Math.py | 3,522 | 3.578125 | 4 | # -*- coding: utf-8 -*-
#
# Elliptic curve point operations (Python 2.7)
# Copyright (c) Denis Leonov <466611@gmail.com>
#
def OnCurve(x,y): # Check if the point is on the curve
A = (y*y)%P
B = (x*x*x)%P
C = False
if A == (B + 7):
C = True
return C
def legendre_symbol(a,p):
... |
b9a576a767b000e56291d845ca4b5c493f0aa9a8 | shezadaibara/project_euler | /scripts10-19/problem_17.py | 2,370 | 3.84375 | 4 | #problem 17
'''
If the numbers 1 to 5 are written out in words: one, two, three, four, five,
then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand)
inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens.
For... |
618ce5829bd784eef637026e6dcecd5761d6d244 | Cunarefa/AVADA | /Patterns/creational/prototype/prototype_harder.py | 1,173 | 3.890625 | 4 | import copy
class Prototype:
def __init__(self):
self._objects = {}
def add_obj(self, name, obj):
self._objects[name] = obj
def remove_obj(self, name):
del self._objects[name]
def clone(self, name, **kwargs):
obj = copy.deepcopy(self._objects.get(name))
obj._... |
955471348978e55ca0d14cd791d51866fae2e648 | trongpl94/Homework2 | /SeriousEx2_b.py | 1,905 | 4.09375 | 4 | choic = input("Welcome to our shop, what do u want?(C, R, U, D)").upper()
item = ['T-Shirt','Sweater']
if choic =="R":
print("Our Items: ",*item)
choic = input("Welcome to our shop, what do u want?(C, R, U, D)").upper()
if choic =="C":
new_item = input("Enter new Item: ")
item.append(new_item)
print... |
39cf84e30807555f505355a3b74c22f286b218a6 | shalakatakale/Python_leetcode | /Leet_Code/242ValidAnagram.py | 1,062 | 3.75 | 4 | # 242 Valid Anagram
# O(n) complexity Hash Map
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
s_hash = {}
for letter in s:
if letter in s_has... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.