blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
544d3c0a091fde03311fbdfa061d7b98b6119c41 | zqianl/accumulate | /python/Tkinter/multiThread.py | 1,464 | 3.5 | 4 | import threading
import time
import ctypes
import inspect
class timer(threading.Thread): # The timer class is derived from the class threading.Thread
def __init__(self, num, interval):
threading.Thread.__init__(self)
self.thread_num = num
self.interval = interval
self.thread_stop = False
def run(self): # ... |
21a41f83edef363f4cbc456571103e3670c9ef69 | rheehot/Algorithm-53 | /Programmers/Level2/전화번호 목록.py | 829 | 3.859375 | 4 | def solution(phone_book):
phone_book.sort()
for num1, num2 in zip(phone_book, phone_book[1:]):
if num2.startswith(num1):
return False
return True
def solution(phone_book):
hash = {}
# 종류를 해시에 넣어줌
for num in phone_book:
hash[num] = 1
for num in phone_book:
... |
a4cd01e1ddceec437c47d21ea2eda894039b3fae | rgbeing/OsuMapToHeatmap | /point.py | 1,498 | 3.65625 | 4 | class Point:
''' 2-dimensional vector.'''
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '({:4f}, {:4f})'.format(self.x, self.y)
def __eq__(self, obj):
return isinstance(obj, Point) and self.x == obj.x and self.y ==... |
29eb9d8e0813309c3250a91b853e640fa36138d6 | arahal81/data-structures-and-algorithms | /python/fizz_buzz_tree/fizz_buzz_tree.py | 2,409 | 3.640625 | 4 |
from stack_and_queue.stack_and_queue import Queue
# from trees.trees import BinaryTree
import copy
class Node:
def __init__(self, value):
self.value = value
self.children = []
class Tree:
def __init__(self, root=None):
self.root = root
def fizz_buzz_tree(tree):
if not tree.roo... |
47e9c22c376ab3a9d2d20169ecf323d97eb89e24 | IswaryaJ/Practice | /Dictionary/Prog1.py | 243 | 3.859375 | 4 | #program on getting sorted dictionaries
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
item1 = sorted(d.items(),key = operator.itemgetter(0))
item2 = sorted(d.items(),key = operator.itemgetter(0),reverse = True)
print(item1)
print(item2)
|
3b0fa92117f1f53d9d7cab6d5ac0f1279b7ed7cb | izzayaqoob/calculating-sum-og-n-numbers-entered-by-user-using-function-in-python | /github.py | 215 | 3.890625 | 4 | def sum():
sum=0
extent=int(input("Enter limit: "))
for i in range(0,extent):
num=int(input("Enter number: "))
sum=sum+num
return sum
def main():
print(sum())
if __name__=="__main__":
main()
|
f28e21d4319a1bbf26be42ae1788d003cea8aa8d | elrossco2/LearnPython | /CH9/HW/spencerj/Ex7.py | 852 | 3.875 | 4 | from random import randrange
def main():
print("Craps Dice simulation")
numGames = eval(input("Number of games to simulate: "))
#print(numGames)
win = 0
for i in range(numGames):
die1 = randrange(1,7)
die2 = randrange(1,7)
total = die1 + die2
if total == 7 or total ==... |
f523ca151e3b3862ca8ad69f6fd1a647834792ec | cylinder-lee-cn/LeetCode | /LeetCode/3.py | 1,260 | 3.65625 | 4 | """
3. 无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
"""
class Solution... |
e4ddd739d6727884f1482fc8f3e2145a2e44923a | wam730/Eternity-Python | /输入十进制得到其二/输入十进制得到其二、八、十六进制数.py | 261 | 3.875 | 4 | while True:
x = input("请输入一个整数:")
try:
eval(x) == int(x)
except:
print("输入错误请重新输入:")
else:
x = eval(x)
print("\n{}={}={}={}\n".format(int(x),bin(x),oct(x),hex(x)))
break |
57f3f5ce710b63914a245556b0d905cec1ea4ff9 | natilindinha/binario | /dec_bin.py | 742 | 4.1875 | 4 | def transformando_em_binario():
import math
#define uma variavel
par = ''
x = float(input('digite um número: '))#pede o numero a ser transformado
#estrutura de repeticao para ate que o numero seja maior que 0
while x > 0:
#estrutura para definir se o proximo numero em binario eh 0 ou 1
if x % 2 == ... |
5913ba77b5f51669f6d50e92d80f6837c99ead9d | alejoriosm04/ST0245 | /code/final-delivery/src/dijkstra.py | 1,514 | 3.703125 | 4 | import heapq
def shortest_safest_path(graph, start, target):
distances = {node: float('inf') for node in graph}
distances[start] = 0
previous = {node: None for node in graph}
priority_queue = [(distances[start], start)]
while len(priority_queue) > 0:
distance, current = heapq.he... |
7e9917e34219e2c6ae6ed79e94840eac0dcf9ed4 | 610yilingliu/leetcode | /Python3/240.search-a-2-d-matrix-ii.py | 862 | 3.640625 | 4 | #
# @lc app=leetcode id=240 lang=python3
#
# [240] Search a 2D Matrix II
#
# @lc code=start
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return... |
b0c2eaa90bf2faf4147f2fe4a488226c27c2595f | Anamikaswt/loop-files | /break.py | 77 | 3.75 | 4 | num=1
while num<10:
print(num)
if num==8:
break
num=num+1 |
4c4784167061ab628c6e474b0bfabe84dfd99187 | Gzoref/holbertonschool-web_back_end | /0x00-python_variable_annotations/100-safe_first_element.py | 372 | 3.953125 | 4 | #!/usr/bin/env python3
'''
Duck typing - first element of a sequence
'''
from typing import Iterable, List, Sequence, Tuple, Union, Any
# The types of the elements of the input are not know
def safe_first_element(lst: Sequence[Any]) -> Union[Any, None]:
'''
Return first element in list
'''
if lst:
... |
1e7ec897b89d2a8c582dc7d3e230eaf83a1a8562 | nemanjaunkovic/SolutionsMurachPythonProgramming | /ch02/test_scores.py | 771 | 4.4375 | 4 | #!/usr/bin/env python3
# display a welcome message
print("The Test Scores program")
print()
print("Enter 3 test scores")
print("======================")
# get scores from the user and add them to total score
total_score = 0 # initialize the variable for accumulating scores
score1 = int(input("Enter ... |
f5463f70473ce3103472cdc3aca232cf892c9b30 | amomin/programming-praxis | /python/NearlySquareDivisors.py | 1,445 | 3.734375 | 4 | ###################### Nearly-Square Divisors ##########################
##################### August 05, 2016 #########################
#
# Given positive integers n, a and b such that n = a * b with a >= b,
# find a and b such that the difference a - b is as small as possible.
#
# Your task is to write a program to ... |
efe54118974ce7d091af46d3d0619ffb99e368f5 | hugechuanqi/Algorithms-and-Data-Structures | /Interview/pratical_interview/pdd_04、二维表第k大数.py | 369 | 3.59375 | 4 | ## 题目:
## 类型:
## 题目描述:
## 核心:
## 思路:
def getKnum(n,m,k):
res = []
for i in range(n):
for j in range(m):
tmp = (i+1)*(j+1)
res.append(tmp)
res = sorted(res)
return res[-k]
if __name__ == "__main__":
n,m,k = list(map(int, input().split()))
res = getKnum(n,m,k)
... |
a8bbd86af5507c228e6578cce4bc08c6b621313b | ericyeh1995/lpthw | /ex43_2.py | 2,694 | 3.96875 | 4 | from sys import exit
class Scene(object):
def enter(self):
print "This scene is not yet configured"
exit(1)
class Engine(object):
def __init__(self, scene_map):
print "initializing game..."
self.scene_map = scene_map
def play(self):
print "game begin!"
... |
1bc4c8da46e838ed266d9f944b3cdb5d3dcb0937 | KIRANKUMAR-ENUGANTI/python_basics | /py_basics/dict.py | 6,295 | 3.640625 | 4 | print('1♥')
d1=dict({1:'a',2:'b',3:'c'})
print(d1) # dict() expects atmost one arg so same dict
d1=dict([(1,'a'),(2,'b'),(3,'c')])
print("list of tuples to dictionary: ",d1)
d1=dict(((1,'a'),(2,'b'),(3,'c')))
print("tuple of tuples to dictionay: ",d1)
d1['new_list']=[1,2,3]
d1['new_dict']={'nested_dit': 1}
pri... |
dd7f0109b333acbb385afb3e4e02a6edd808b956 | rcollmenendez/UOC_WebScraping_WPT | /Código/WPT_PlayersRanking.py | 6,442 | 4.1875 | 4 | """
Estudios: Máster universitario de Ciencia de Datos de la UOC
Asignatura: (M2.851) Tipología y ciclo de vida de los datos - Aula 3
Actividad: Práctica 1 - Web Scraping
Estudiante: Rubén Coll Menéndez
"""
# -------------------------------
# Configurando el entorno
# -------------------------------
import time
from ... |
d4801d0e6b6731ec010744d841e3e582fd6ffc0f | BrunoBross/Desafio-Dev-Web-Full-Stack | /duodigit_test.py | 503 | 3.875 | 4 |
# script para testar a funcao verificadora de duodigito
def SmallDuodigit(digit):
for num in range(2, 101):
multiple = int(digit) * num
if Duodigit(multiple):
return multiple
def Duodigit(number):
value = str(number)
repeated = []
distinct = 0
for num in value:
... |
cfb2e33c1a95f36395e621d23d1ff9073350e69e | AlexeyAG44/python_coursera | /week_6/4_shoe_shop.py | 743 | 3.765625 | 4 | # В обувном магазине продается обувь разного размера.
# Известно, что одну пару обуви можно надеть на другую,
# если она хотя бы на три размера больше.
# В магазин пришел покупатель.Требуется определить,
# какое наибольшее количество пар обуви сможет предложить ему продавец так,
# чтобы он смог надеть их все одновремен... |
bedd9b342db5ccd1f704391afec2bf68ae268bef | julie-ngu/Unit4-06 | /strings.py | 632 | 4.1875 | 4 | # Created by: Julie Nguyen
# Created on: Nov 2017
# Created for: ICS3U
# This program checks to see if two strings the user inputs are the same
def check_if_true(first_string, second_string):
# user enters two strings, function checks if strings are the same and returns either True or False
first_string =... |
3e07dc3760b1689dfd1299dac2ab6ef88325beb9 | VishnuprakashSelvarajan/DailyCoding | /ValidateIP.py | 2,203 | 4.15625 | 4 | '''
Validate IP Address
Given a string IP, return "IPv4" if IP is a valid IPv4 address, "IPv6" if IP is a valid IPv6 address or "Neither" if IP is not a correct IP of any type.
A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi cannot contain leading zeros.
For example, "192.168.1.1" ... |
9031dd895f5f54a7954e66d495a1f344314277b9 | rachel-benh/reserach_methods_in_software_engineering | /most_significant_digit.py | 3,123 | 4.3125 | 4 | ''' This function receives a list as an input, an outputs the most significant digit for all the
numbers in the list which are in the range of (small_num,large_num) and are divisible by
include_factor and are not divisible by exclude_factor. The result should be in string form, with
commas separating the different digi... |
8514ff71a7e3d9b0577276235af47631c9a8b6ac | starkworld/Python-Course-work | /source code/Fractions_calc.py | 10,662 | 3.859375 | 4 | """Created on Sun Feb 17 18:18:57 2020
@author: nkalyan🤠
Implementing fraction calculator by using classes and functions, which takes fractions as inputs,
and performs arithmetic operations"""
def GCD(a, b) -> float:
"""Fucntion that perform the GCD operation and return the GCD of value... |
2cbe098d81d1cbcc1f28a2db5896d736f8a75039 | ronrest/convenience_py | /ml/plot_grid_array.py | 1,934 | 3.6875 | 4 | from matplotlib import pyplot as plt
import numpy as np
__author__ = 'Ronny Restrepo'
# ==============================================================================
# PLOT_GRID_ARRAY
# ===================================================================... |
d3f8517a192620b31fb8c12630c0e3fc149546ec | saeedali32/MyFirstRepo | /W2/animals.py | 860 | 3.8125 | 4 | class Animal:
def __init__(self, name):
self.name = name
self.age = 42
def speak(self):
print(f'My name is {self.__do_something_secret()} and I am {self.age}')
def __do_something_secret(self):
return self.name
class Dog(Animal):
def __init__(self, name, breed):
... |
3ca81c96c30024cbd3db0c4aa298b7a6235585c9 | dwaq/advent-of-code-solutions | /2017/02/2-even.py | 1,044 | 3.546875 | 4 |
# open file and split into lines
with open('in1.txt') as f:
content = f.readlines()
checksum = 0
for c in content:
# split line by whitespace and convert to ints
# https://stackoverflow.com/a/6429930
line = map(int, c.split())
#print line
# store length
l = len(line)
# compare the... |
c4c88d8da13131e1c4311ac18f8929b5f9dd5330 | Muhammadshamel/Investigating-Texts-and-Calls | /Task0.py | 984 | 4.1875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 0:
What is the first record of text... |
dbfebefa8742063b5492eb0e60b475c675579053 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/String/SortCharactersByFrequency.py | 1,403 | 4.0625 | 4 | """
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input:
"tree"
Output:
"eert"
Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Example 2:
Input:
"cccaaa"
Output:
"... |
9637e973f7a2e54ab76f355a318587f05fcff7fb | MudOnTire/python3-learning | /5. calc the area of a circle.py | 129 | 4.21875 | 4 | radius = input('Enter the radius of your circle (m): ')
area = 3.142 * int(radius)**2
print('the area of your circle is: ', area) |
790424291eaac9e620524701001b6f96c373a1d4 | emanuellemoco/aleta | /aula18.py | 538 | 3.5625 | 4 | # -*- Coding: UTF-8 -*-
#coding: utf-8
import math
import numpy as np
import matplotlib.pyplot as plt
alpha = 0.0001 #m2/s
dX = 0.05 #m
dT = 5 #s
t_list = [0,20,20,20,20,20,20,20,20,20,0]
x = [0,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50]
####
beta=alpha*dT/(dX**2)
n = 0
aux = t_list[:]
wh... |
e027e6ec5465e28eb9c4e1e6493ee87e6ad96df1 | moni310/Loops_questions | /average.py | 521 | 4 | 4 | # i=0
# sum=0
# while i<=10:
# num=int(input("enter the number"))
# sum=sum+num
# i=i+1
# print(sum//10)
#(1)
# def show_number(limit):
# i=0
# while i <=(limit):
# if i%2==0:
# print(i,"even")
# else:
# print(i,"odd")
# i=i+1
# show_number(100)
#(2)... |
0333d634329ff2706f74352b721f9fa1ba93d898 | gitshangxy/tutorial | /L10数据库基础和sqlite/测试1.py | 809 | 3.921875 | 4 | import sqlite3
connect = sqlite3.connect("testsqlite.db")
cursor = connect.cursor()
cursor.execute("""
SELECT * FROM student3;
""")
student3s = cursor.fetchall()
print(student3s)
cursor.execute("""
SELECT * FROM student3 WHERE age = '11';
""")
student3s = cursor.fetchall()
print(student3s)
cursor.execute("""
... |
d11a29598907b0a724e931d9587f46d738071f45 | jf1130/Programas | /Ejercicio9.py | 171 | 3.6875 | 4 | m = int(input('ingrese la masa de el objeto en Kg'))
Us = float(input('ingrese el coeficiente de rozamiento'))
a = Us * 9.8
F = m * a
print("la fuerza es de " + str(F))
|
314f40c75983783ddc12990bb462a434291e1853 | cristian-aldea/auto-made-it | /topic_ranking.py | 1,634 | 3.8125 | 4 | """
Topic Ranking Sorter
This script takes in an .csv file with the topic rankings done in Google Forms and prints out the preference order of the topics.
It puts a higher weight on lower rankings. If a topic got a lot of 1st rank votes but wasn't the first pick, it will most likely be the second pick.
"""
import cs... |
47eda0cc49c8a51db47fcff7ec9a0ff332aded6e | vinicius-gadanha/python-courses-cev | /MUNDO 2/ex040.py | 563 | 3.515625 | 4 | n1 = float(input('\033[1;36mPrimeira nota:'))
n2 = float(input('\033[1;36mSegunda nota:'))
me = (n1 + n2) / 2
print('\033[40m{}\033[m'.format(' ' * 15))
print('\033[1;30mA média das notas é {:.1f}.'.format(me))
if me < 5.0:
print('Média abaixo de 5.0\n\033[1;31m'
'REPROVADO')
elif 5.0 <= me <= 6.... |
57d3f250ab3a4feb7d809530708875a239f63593 | damade/PythonPro | /Exception/GuessGameWithModes.py | 4,137 | 4 | 4 | import random
def easyMode():
easyRandomValue = random.randrange(1, 10)
count = 1
totalNumber = 6
while (count <= totalNumber):
try:
userInput = int(input("What is the number? "))
if (userInput == easyRandomValue):
print("\nYou guessed right")
... |
36adb5a1d614876f546bcfa18a2ac63732b447c2 | yayunl/RubikCubeSolver | /Solver.py | 61,458 | 3.796875 | 4 | from Cube import Cube
import copy
debug = True
class Algorithm:
"""The algorithm of solving the rubik's cube.
And it returns a solution.
"""
def __init__(self, cube):
"""Initialize an alogrithm instance by inputing a cube.
@param cube: cube is an instance of class Cube.
"""
... |
601b73a3cb6e4fe0094e90b4aab18dae9a1b7ecd | hexinyu1900/webauto | /day01/day5/06_assert_kz.py | 445 | 4.03125 | 4 | """
目标断言扩展:
两种实现方式:
1.使用unittest框架中的断言
2.使用Python自带断言
"""
# 使用Python自带断言,判断两个字符串是否相等
# assert "hello" == "hello"
# assert "hello" == "hello1"
# 第二个字符串是否包含第一个字符串
# assert "e" in "hello"
# assert "ea" in "hello"
# 判断是否为True
# assert True
# assert False
# assert 0
# assert 1 |
a475e1e2e98c159cd85ba8cc6f4dd9beae5ff427 | mihirkelkar/hackerrank_problems | /binary_tree_vertical_sum.py | 1,591 | 3.8125 | 4 | #!/usr/bin/python
""" %%%% Calculate the vertical sum in a binary tree %%% """
class node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class binarytree:
def __init__(self):
self.root = None
self.vd = {}
def add_node(self, value, counter =0 , root = None):
root = se... |
5149d6c05f39e2e424eafe956a262c21076f2be7 | marcobakos/library | /lst_double_index.py | 216 | 3.734375 | 4 | #Write your function here
def double_index(lst, index):
if index < len(lst):
lst[index] = lst[index] * 2
return lst
#Uncomment the line below when your function is done
print(double_index([3, 8, -10, 12], 2)) |
3ee17e6ad0020dd53d0bfb54c11355626a8b9118 | arthurperng/eulerthings | /triangle_illuminati12.py | 408 | 3.609375 | 4 | from math import *
trianglenumber=1
countup=2
def divisors(number):
things=0
for hi in range(1, int(sqrt(number))+1):
if number%hi==0:
if number/hi==hi:
things+=1
else:
things+=2
return things
while True:
if divisors(trianglenumber)>500:
... |
15a510e48df53f3d98e4089808c529fe7a95f7bb | LN4rkot1k/Peremennie-Types | /Otvet/lab2-2.py | 1,035 | 4.40625 | 4 | # Целые числа и числа с плавающей точкой являются одними из самых распространенных в языке Python
number = 9
print(type(number)) # Вывод типа переменной number
float_number = 9.0
# Создайте ещё несколько переменных разных типов и осуществите вывод их типов
bool_number = False
str_number = '9'
print(type(bool_n... |
7ec94cda7ca70f828225ea15653a642a6d48ec39 | Mew1859/git_python | /ex5.py | 232 | 3.75 | 4 | #type coversion
x = 10
y = 3.09
z = "10"
print(type(x))
print(type(y))
print(type(z))
#result = x+z
#conversion
result = x+int(z)
print (result)
result2 = str(x)+z
print(result2)
#string to float
result3 = float (z)+y
print(result3) |
96d7661308c48dcb7d785f87e1b880e076b59910 | asimokby/algorithmic-interviews-sheet | /level_1/Keyboard.py | 399 | 3.53125 | 4 | def create_keyboard():
keyboard = {}
chars = '0qwertyuiop0asdfghjkl;0zxcvbnm,./0'
for i in range(1, len(chars)-1):
keyboard[chars[i]] = chars[i-1], chars[i+1]
return keyboard
def solve():
keyboard = create_keyboard()
direc = 0 if input() == 'R' else 1
new_s = []
for i in input()... |
cbb4fd8b5e67517c599da6ca09c69203565edd49 | Edywang/Curated-Schoolwork | /CSE30MSI/quizzes/quiz10/quiz10.py | 2,089 | 3.6875 | 4 | # Simple pygame program
# Import and initialize the pygame library
import pygame
import numpy
from random import randint
BLACK = (0, 0, 0)
class Dot(pygame.sprite.Sprite):
# Setters for each of the values
def __init__(self, color, width, height, screen = None):
super().__init__()
# Pass in t... |
d96080e7b30a12d1132abdbdd8d522ffc1ece804 | RookieLinLucy666/Codewar | /Ones and Zeros.py | 235 | 3.890625 | 4 | def binary_array_to_number(arr):
result = 0
length = len(arr)
for index in range(length):
result += pow(2, index) * arr[length - 1]
length -= 1
return result
print(binary_array_to_number([1,1,1,1]))#15
|
53b945610c84aa7fa4657a2a42c69b9c3cf9ac9c | xiao-a-jian/python-study | /month01/day11/day11/review.py | 1,570 | 4.15625 | 4 | """
复习
函数参数
实参:如何与形参进行对应
位置实参:顺序 [作用:传递所有形参简单高效]
序列实参:拆分 [作用:使用容器思想管理实参]
关键字实参:名字 [作用:通过名字指定个别形参]
字典实参:拆分 [作用:使用容器思想管理实参]
形参:约束实参的传递方式
默认形参:可选 [作用:实参可以不传递]
位置形参:必填 ... |
91737069720a20d4b421ed0a25ab6240a6691543 | macconsolabe/Base | /FINAL.py | 2,674 | 4.28125 | 4 |
# Write a simple program to average three exam scores.-
#Get user inputs for three scores-
#Write a function to calculate the average-
#Print the average value
def average():
print("Welcome to our average program")
first_number = int(input("Please Enter your first number here : "))
second_number = int(... |
c56bd13d2972e502aee20fd4fd814d93c51cad90 | D4rk3l/interactive-text-games-hacktoberfest | /text-base-tic-tac-toe/text-base-tic-tac-toe.py | 3,743 | 3.953125 | 4 | from random import randint
def show_board(grid):
print("Board: ")
for i in range(3):
for j in range(3):
print("\t", grid[i*3 + j], end=" ")
print()
def check_win(grid, check):
if grid[0:3] == [check]*3 or grid[3:6] == [check]*3 or grid[6:9] == [check]*3:
return True
... |
525b16355f45e16e7cef4ec4ad51081bde73b336 | pulinghao/LeetCode_Python | /动态规划/322. 零钱兑换.py | 663 | 3.734375 | 4 | #!/usr/bin/env python
# _*_coding:utf-8 _*_
"""
@Time :2020/4/26 10:59 下午
@Author :pulinghao@baidu.com
@File :322. 零钱兑换.py
@Description :
"""
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
... |
18891d4ab0d065a73a32bc29db6e632a2623b4e0 | weilyu/MuleTools | /csv_diff/csv_diff.py | 1,326 | 3.53125 | 4 | # author: weilyu
import csv
from itertools import chain
def is_float(value: str) -> bool:
try:
float(value)
except ValueError:
return False
return True
def compare_value(exp_val: str, act_val: str) -> bool:
if is_float(exp_val) and is_float(act_val):
return float(exp_val) == ... |
7d49b80275ac4e1dc826696d915f0e4fe1aa1669 | zcliang97/toy-social-media | /startClient.py | 4,274 | 3.625 | 4 | from Client import Client
def login(client):
while True:
print 'WELCOME TO SOCIAL MEDIA'
# LOGIN/CREATE USER
print "===== To create user [0]"
print "===== To login to existing user [1]"
action = raw_input()
if action == "0":
firstNam... |
97f9a7912144c2aa9a5f5c71e730df4ce02f69c4 | Ajay2521/Python | /BASICS/While loop.py | 1,084 | 4.28125 | 4 | #In this program lets see about "Loop" concept in Python.
#Loops are the once which is used to repeat certain code for certain number of times.
#Thus loops will be executed for number of times or till the condition gets fails.
#ADVANTAGES of LOOPS:
#1) Loop is used for code re-usability.
#2) By using loo... |
8cf4eae11ef9685db59628a272f34ca0a0bdbcc5 | 482-932-csce-capstone-sp-2019/Swimming-Wearable | /json_read.py | 4,001 | 3.9375 | 4 | '''
read the workout-pre.json
sleep (short_time); buzz to tell swimmer that program is now going
turn workout-pre.json into known timestamps with data that it uses
'''
import json
import time
def main():
with open('workout-pre.json') as json_data:
data = json.load(json_data)
print ("-------------- 1... |
564bd8bc2e33ce1154f76a0c5d0cf65b654a6f39 | Youngiyong/Python | /Algorism/크라마/Longest Chain.py | 825 | 4.03125 | 4 | def longestChain(words):
maxLength = 0
minLength = 1
mintemp = []
for word in words:
if len(word) <= minLength:
mintemp.append(word)
print(mintemp)
for word in words:
if len(word) > minLength:
for test in mintemp:
if word.find(test)!=-1 an... |
a18d8739fe1e4db6e4c358bb6b26e9a01581d772 | animeshramesh/interview-prep | /Python/DP/EASY_MAX_SUBARRAY_SUM.py | 358 | 3.53125 | 4 | """
[-2,1,-3,4,-1,2,1,-5,4] -> 6
Kadane's Algorithm
O(n) time and O(1) space
"""
class Solution(object):
def maxSubArray(self, nums):
if not nums: return 0
max_sum, cur_sum = nums[0], nums[0]
for num in nums[1:]:
cur_sum = max(num, cur_sum + num)
max_sum = max(max_... |
ff26ed28cdf81c3cc4a57ffa025a13f5c4239def | Pavan144/10DaysofCode-VVCE | /Day-7 challENGE.py | 584 | 3.71875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countSort function below.
def countSort(n, arr):
for l in arr:
l[0] = int(l[0])
for i in range(n//2):
arr[i][1] = "-"
output = [[] for _ in range(n)]
for l in arr:
... |
c11d7447d6396c235823861da44ccd43489b5cd3 | Shin-jay7/LeetCode | /0035-Search_Insert_Position.py | 558 | 3.59375 | 4 | from __future__ import annotations
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
for i in range(len(nums)):
if nums[i] == target or nums[i] > target:
return i
# print(i)
# return
return len(nums)
# ... |
82328be850523605548a6ffc02e8afd5bfc6d410 | ivan-yosifov88/python_basics | /Exams -Training/06. Vet Parking.py | 567 | 3.953125 | 4 | number_days = int(input())
number_hours = int(input())
price_for_parking = 0
total_sum = 0
for days in range(1, number_days + 1):
current_sum = 0
for hours in range(1, number_hours + 1):
if days % 2 == 0 and hours % 2 == 1:
price_for_parking = 2.5
elif days % 2 == 1 and hours % 2 == ... |
7b9198607334105c81bdaae9221684317b19006e | Hyacinth-OR/Regex-String-Acceptance | /GUImain.py | 13,961 | 3.59375 | 4 | '''
CS454 Final Project
By: Colin Dutra
Problem 9
Problem:
Implement a program that tests membership of a given string w in a regular expression R.
Specifically, your program will take as input a regular expression (such as (a+a.b)*.(a+ε)
and a string w = abaab, and outputs ‘yes’ if w is in L(R), ‘no’ else. Three step... |
90423a473e51e7288a7e20fe1696dbd589d9b99e | rushtang/exercise | /data_structure/array.py | 1,119 | 3.90625 | 4 |
L=[1,"3",None,True,1.22,1,1]
#查找元素的序列
L.index('3')
#list遍历
for index,ele in enumerate(L):
a=L[index]
L.reverse()
L.count(1)
L.extend([1,2,3])
#方法有:初始化、插入、删除、查找、修改、出现次数计算、排序、反转、复制、清空、合并
#iterable的区别:序列和键值对
d={1:2,3:4}.items()
ll=list(d)
#链式储存,插入和删除效率高,适合用于队列和栈
from collections import deque
#链式队列;入队、出队
cla... |
7f0e1815777bd182f5208fafe60f497f328222e1 | allenXyGao/Python_leetcode | /Leetcode 133. Clone Graph.py | 1,330 | 3.734375 | 4 | # Leetcode 133. Clone Graph
'''
Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
'''
"""
# Definition for a Node.
class Node(object):
def __init__(self, val = 0, neighbors = []):
self.val = val
self.neighbors = neighbors
"""
class ... |
96a9996c6e476fe7750255b26e8f4dde8d50b9a6 | Carolinacapote/holberton-system_engineering-devops | /0x04-loops_conditions_and_parsing/prueba.py | 382 | 3.5625 | 4 | #!/usr/bin/python3
def perfect_num(list):
perfect_num = 0
for i in list:
counter = list.count(i)
if i == counter:
tmp = i
if tmp > perfect_num:
perfect_num = tmp
if perfect_num != 0:
return perfect_num
else:
return -1
list = [2, 2, 3, ... |
ca1edd39409290e6b7202550dddf1495569f1e3d | jcsuscriptor/labs_inteligencia_artificial | /Detectar_Circulos_Imagen/contar.circulos.py | 841 | 3.53125 | 4 | # import the necessary packages
import numpy as np
import argparse
import cv2
# Load an color image in grayscale
# 0 o cv2.IMREAD_GRAYSCALE : Loads image in grayscale mode
image = cv2.imread('img3.jpg') #,0)
#Display an image
#cv2.imshow('image',image)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
output = image.copy()
g... |
368ad6ac5edc47776f5c767951b17798762e4003 | ogheat/Disappearing_Text_Writing_App | /MAIN.py | 1,474 | 4.03125 | 4 | from tkinter import *
from tkinter import messagebox
text = ""
new_text = ""
sec = 0
x = True
def info():
messagebox.showinfo(title="info",message="info will be there")
def quit():
global x
x = False
def reset():
email_entry.delete(1.0, END)
email_entry.focus()
def timerupdate():
global sec... |
e1555e3cd96ad25ec0fd044452ae03442e907bcf | tuxnotes/python_notes | /python3_programming_tricks/ch06/6-3.py | 807 | 3.609375 | 4 |
from xml.etree import ElementTree
# 解析xml文件
et = ElementTree.parse('demo.xml')
# 从字符串中解析使用:ElementTree.fromstring
# 获取根元素
root = et.getroot()
# 根元素的属性与方法
root.tag
root.attrib
# 一个元素是一个可迭代对象,每次迭代出来的就是子元素
c1 = list(root)[0]
c1.attrib
c1.get('name')
year = list(c1)[1]
year.text
c1.text
year.tail
c1.tail
# 在一个元... |
68e09f9a1a8bd0f08d9f9119c8b332038e603a4c | lyl0521/lesson-0426 | /lesson/exercise/_02_.py | 325 | 3.71875 | 4 | # 判断101-200之间有多少个素数,并输出所有素数。
# 素数:只能被1和它本身整除的正整数(1不是素数)
counter = 0
for i in range(101,201):
for j in range(2,i):
if i % j ==0:
print(str(i)+'不是素数')
break
else:
print(str(i)+'是素数') |
69b1a2fbdaca74304636a963b0a4abe0392892da | Oliver-yao/multiprocessing | /08.py | 1,550 | 3.953125 | 4 | import time
import threading
def loop1():
# ctime 得到当前时间
print("Start loop1 at ", time.ctime())
# 睡眠多长时间,单位是秒
time.sleep(4)
print("End loop1 at ", time.ctime())
def loop2():
# ctime 得到当前时间
print("Start loop2 at ", time.ctime())
# 睡眠多长时间,单位是秒
time.sleep(2)
print("... |
d022c0386e47eaa8cfa4cfafdc39095fe139a100 | basharkh9/python-tutorial | /lists/app.py | 1,335 | 4.21875 | 4 | # Lists
# same as array in other languages
# Lists are mutalble
mylist = [1, 2, 3, 4]
print(mylist)
mylist = [1, "String", True, [1, 2, 3, 4]]
print(mylist)
# Length of the list
print(len(mylist))
mylist = ['a', 'b', 'c', 'd', 'e']
print(mylist[0])
print(mylist[1])
print(mylist[-1])
print(mylist[1:])
print(mylist[:3... |
4646e384aba8c7a10f2d1eb316ea9f8bea07bfdf | chefmohima/DS_Algo | /rotate_matrix.py | 1,372 | 3.8125 | 4 | # All array rotations are a combination of
# transpose, reverse rows and reverse columns
# helper
def transpose(A):
row,col = len(A),len(A[0])
# create empty matrix colxrow
T = [[0]*row for i in range(col)]
for i in range(row):
for j in range(col):
T[i][j] = A[j][i]
r... |
180ea9640fa1ea85f49d3c035e64890a2dd4217d | duncandc/custom_utilities | /cython_utilities/pairs.pyx | 11,577 | 3.515625 | 4 | #!/usr/bin/env python
# cython: profile=False
#Duncan Campbell
#August 22, 2014
#Yale University
#Calculate the number of pairs with separations less than r.
from __future__ import print_function, division
cimport cython
cimport numpy as np
import numpy as np
__all__=['npairs','wnpairs']
from libc.math cimport sqrt... |
723b43d1e04f67642488cd1c999ec861f6973d6f | uhspres/fellas | /src/Character.py | 1,149 | 3.515625 | 4 | import pygame
from SoundPlayer import SoundPlayer
# Character class inherits from the pygame sprite class
class Character(pygame.sprite.Sprite):
def __init__(self, width, height, image):
super().__init__() # call the super constructor
self.soundPlayer = SoundPlayer()
# -- sprite configurat... |
fd8c2f1e38a9a66e86d97da929dd7276b7983651 | wpy-111/python | /DataAnalysis/day04/demo06_agg.py | 294 | 4.0625 | 4 | """
轴向汇总
"""
import numpy as np
data = np.array([[88,88,88,88],
[99,88,68,77],
[99,85,77,98]])
print(data)
# 轴向汇总
def func(data):
return np.mean(data),np.max(data),np.min(data)
result = np.apply_along_axis(func,0,data)
print(result)
|
0e89d50349b3d57ad7a5dedc06188f7c6889765c | moontree/leetcode | /version1/312_Burst_Balloons.py | 1,494 | 4.0625 | 4 | """
Given n balloons, indexed from 0 to n-1.
Each balloon is painted with a number on it represented by array nums.
You are asked to burst all the balloons.
If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins.
Here left and right are adjacent indices of i. After the burst, the left an... |
b82323ef7c305ad9a8928f3a1247ce24caee9e0a | ProtKsen/Pythonboost | /task 10/drawing.py | 1,260 | 3.9375 | 4 | import turtle
from itertools import product
from constants import SIZE_OF_CELLS
def draw_labyrinth(input_lst: list) -> None:
"""
Рисует лабиринт, стены отмечены красными кружками (почему то очень долго рисуются( )
Args:
input_lst: список, представляющий лабиринт
"""
height, width = len(in... |
c7b2f765dfbd7de976f5ad410c32da972af6ee72 | djcolantonio/PythonProjects | /zodiac_list.py | 517 | 3.84375 | 4 | while True:
try:
year = int(input('Enter your birth year: '))
yearNumber = (year - 2000) % 12
zodiac = ['Dragon', 'Snake', 'Horse', 'sheep', 'monkey', 'rooster', 'dog', 'pig', 'rat', 'ox', 'tiger', 'hare']
print('Your sign is ' + zodiac(yearNumber))
askAgain = in... |
f944022d77ebff1213d0f3a215433beda8ec59e8 | Julien-Verdun/Project-Euler | /problems/problem102.py | 1,964 | 4.3125 | 4 | # Problem 102 : Triangle containment
# file which contains the triangle coordinates
triangle_file = "triangle.txt"
# read the triangle coordinates
with open(triangle_file, "r") as triangleFile:
triangles = triangleFile.read()
# creation of a list of lists which includes the 3 points coordinates (tuples)
triangles ... |
10786f694ceedd92b3d7a924c7438f067e917d7c | SamPusegaonkar/ENPM661 | /Project5/Code/PyGame/RRT_OldMap.py | 15,695 | 3.734375 | 4 | import pygame
import math
import heapq
import time
import functools
import random
# Defining Graph Constants
HEIGHT = 300
WIDTH = 400
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
BLACK = (0, 0, 0)
MAGENTA = (255, 0, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
class Node:
"""
Node class : Th... |
aa9dc2a4e4fbf50e4e8e6e07c0cd3f3b36d8c9e7 | rasta5man/learning-python | /GrafikaTkinter_cvicenia2/#14stvorceRastuce.py | 369 | 3.515625 | 4 | #14 Program nakreslí vedľa seba 10 štvorcov, ktoré sa navzájom dotýkajú stranou, ich spodná strana leží na jednej priamke a ich veľkosti sa postupne zväčšujú: 15, 20, 25, 30, 35, ...
import tkinter
canvas = tkinter.Canvas()
canvas.pack()
x, y, s = 10, 100, 15
for i in range(10):
canvas.create_rectangle(x, y-... |
841cf35bac956e298dcf8e544c32eaca765a252e | WorkRock/python_lab | /lab2_6.py | 647 | 3.5 | 4 | """
주제: 튜플(tuple)
작성일: 17. 09. 18.
작성자: 201632023 이지훈
"""
# t에 (2, 4, 6, 8, 10)을 저장한 후 출력한다.
t = (2,4,6,8,10)
print(t)
# t의 2번째 요소를 출력한다.
print(t[2])
# t의 2번째 요소에 -9값을 저장한다. 가능한가? <- 불가능하다
# t[2] = -9 <- immutable함 그래서 reverse, sort도 불가능함.
# t에서 10 값의 위치를 출력하라.
print(t.index(10))
# t의 길이를 출력하라.
print(len(t))
# t를... |
71c1a382d382f202592e5648b1bfaab19d49c5bf | kmykoh97/Basic-Programming-SJTU | /School/python/5rd lesson/2.py | 1,283 | 3.8125 | 4 | # Shangji Practice No 2
# Meng Yit Koh
# 517030990022
<<<<<<< HEAD
=======
# return greatest value in list x
>>>>>>> revision2
def greatestValue(x,y):
# x is list y is index
for i in range(len(x)):
if y == i: continue
elif x[y] >= x[i]:
maximum = x[y]
else:
retur... |
1e7c8389b42c00be1e7d81a764fd67346584ca93 | zonghui0228/rosalind-solutions | /code/rosalind_bfs.py | 1,524 | 3.75 | 4 | # ^_^ coding:utf-8 ^_^
"""
Breadth-First Search
url: http://rosalind.info/problems/bfs
Given: A simple directed graph with n≤103 vertices in the edge list format.
Return: An array D[1..n] where D[i] is the length of a shortest path from the vertex 1 to the vertex i (D[1]=0). If i is not reachable from 1 set D[i] to −... |
0746513e09b87aefd4c459c914042de9f76c5a37 | Jindorian/Solution--Introduction-to-Programming-Using-Python-by-Y.Daniel-LIANG | /Chapter8/Ch8Q13.py | 671 | 3.796875 | 4 | def prefix(s1,s2):
s = str()
if(s1[0]==s2[0]):
l1 = len(s1)
l2 = len(s2)
if(l1>=l2):
for i in range (l2):
if(s1[i]==s2[i]):
s = s+s1[i]
else:
for i in range (l1):
if(s2[i]==s1[i]):
... |
637c81cc7ea3a4319014bd62ba3e08479f1fa740 | QuentinDuval/PythonExperiments | /classics/MinStack.py | 786 | 3.890625 | 4 | """
https://leetcode.com/problems/min-stack/
"""
class MinStack:
"""
Store the mins for every values... but then look at what it looks like
=> get rid of everytime you store the min different than the current val
"""
def __init__(self):
self.stack = []
self.mins = []
def push... |
c1e8be72bf701aaecb76f59c6065f85ac1dfda37 | acmill/comparison-complex | /algorithms/hybridsort.py | 444 | 3.5625 | 4 | import sys
from algorithms import insertionsort
from algorithms import quicksort
sys.setrecursionlimit(5000)
## Adapted from:
## https://www.geeksforgeeks.org/python-program-for-quicksort/
## Python program for implementation of HybridSort
def HybridSort(data, hi, lo):
if(lo >= hi):
return
elif((hi... |
a8753340ec9b92462b715d0d51a61bf8a7248190 | feblues/python | /ex007.py | 175 | 3.671875 | 4 | nome = input('Digite seu nome: ')
n1 = float(input('Digite sua n1: '))
n2 = float(input('Digite sua n2: '))
media = (n1+n2)/2
print ('{}, sua media é {}!'.format(nome,media)) |
5ec298bbde1a954314ddc42b57b88c68813001b2 | alperguzel/python-challenge | /PyBank/main.py | 1,384 | 3.859375 | 4 | # first i need to read our data to analyse that
import os
import csv
# we want to use our script for all csv file. that's why i give a variable
#that represent our file. so we would just need to change filename
file_name = "budget_data_1.csv"
datapath = os.path.join('raw_data', file_name)
with open(datapath, 'r') a... |
2a19d0b53bc0ac998175055fe06d11d8cb7aba4a | Cola1995/Py | /LL/guess.py | 358 | 3.90625 | 4 | Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> num=1
guess=2
while guess!=num:
guess=int(input("请输入你猜的数字:"))
if guess==num:
print("对了")
elif guess<num:
print("小了")
elif guess>num:
print("大了"... |
2ebb39f05f83b09d1e29361eb2abe2e5660dc0dd | PalinaUsovich/python_demo | /functions/for_loop.py | 354 | 3.921875 | 4 |
friends = ["Kris", "Kate", "Lera"]
for friend in friends:
print(friend)
for num in range(10, 20):
print(num)
for index in range(len(friends)):
print(friends[index])
for index in range(len(friends)):
print(index)
for i in range(5):
if i == 0:
print("first iteration")
else:
... |
1c3a9c08539e4becc6a5f4ebf40490b08a4b601f | shnlmn/Rhino-Grasshopper-Scripts | /IronPythonStubs/release/stubs.min/System/Drawing/__init___parts/SizeF.py | 4,664 | 3.953125 | 4 | class SizeF(object):
"""
Stores an ordered pair of floating-point numbers,typically the width and height of a rectangle.
SizeF(size: SizeF)
SizeF(pt: PointF)
SizeF(width: Single,height: Single)
"""
@staticmethod
def Add(sz1,sz2):
"""
Add(sz1: SizeF,sz2: SizeF) -> SizeF
Adds the width and heigh... |
ba1d3f5e441b667310bd2de8e076ce7a96a6fcf3 | MattStammers/ClinDev-algorithms | /09 palindrome/Simple_Palindrome_Checker.py | 634 | 4 | 4 | # simple:
def characters(x):
x = str(x)
return [str(y) for y in x]
def is_palindrome(x):
chars = characters(x)
for f, r in zip(chars,reversed(chars)):
if f != r:
return False
return True
# even simpler!:
def is_palindrome(string):
return str(string)[::-1] == str(string)
# or:
def is_... |
609d0a6ad31ec9de2d7cb8ec635873efe4d575cd | Gustaft86/trybe-exercises | /modulo4_ciencia/bloco_33/dia_1/exercicio_dia/bonus4.py | 1,024 | 3.890625 | 4 | # Exercício 4: Um posto está vendendo combustíveis com a
# seguinte tabela de descontos:
# Álcool:
# - Até 20 litros, desconto de 3% por litro;
# - Acima de 20 litros, desconto de 5% por litro.
# Gasolina:
# - Até 20 litros, desconto de 4% por litro;
# - Acima de 20 litros, desconto de 6% por litr... |
ce5c0ab2b61c25dbc157c62a000c0fa05d173ab9 | Isabellajones71/Mlhm | /IF-else in class.py | 367 | 3.953125 | 4 | class Student:
def __init__(self,name,age):
self.name = name
self.age = age
student1= Student('Jason',12)
student2= Student("Jeffrey",18)
print(student1.name,student1.age)
print(student2.name,student2.age)
if (student1.age)>(student2.age):
print("{} is older.".format(student1.name))
else:
... |
3e9b1d0736e6633d9258163f1e633a7ed956f12f | sungminoh/algorithms | /leetcode/solved/373_Find_K_Pairs_with_Smallest_Sums/solution.py | 2,253 | 3.984375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 sungminoh <smoh2044@gmail.com>
#
# Distributed under terms of the MIT license.
"""
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u,v) which consists of one element from th... |
13d5b48e0dab66c4f054b233c822c70ab50ecf61 | kaustubhhiware/hiPy | /think_python/flip-age.py | 1,479 | 4.125 | 4 | #question - http://www.cartalk.com/content/flipping-ages
def str_fill(i, len):
"""
return the integer (i) written as a string with at least
(len) digits
"""
return str(i).zfill(len)
def are_reversed(i, j):
"""
return True if the integers i and j, written as strings,
ar... |
683afe6c753c31a4bfa3ec537d39eafb6d866634 | MarinaFdezSues/PythonExercises | /diccionarios1.py | 626 | 3.78125 | 4 | def diccionarios1(lista):
print(lista)
dic={l[0] : l[1:] for l in lista}
return dic
def diccionarios1extra(l):
dic={}
print(l)
for x in l:
key=x[0]
values=list(x[1:])
dic[key]=values
return dic
def extraDicc1(l):
dic={}
k=l[0]
v=l[1]
for x in range(0,len(k)):
try:
d... |
ddceaab30555d2c59c3339e50893293403ded9aa | dharper998/CS110-Course-Work | /lab4.py | 3,960 | 4 | 4 | '''
Estimates pi using Monte Carlo simulation
Virtual Dartboard has area 2 X 2 to accommodate unit circle
Total area is 4
Therefore, since area of unit circle = pi * radius^2 (and radius of 1 squared
is 1), ratio of area of unit circle to area of board should be pi/4
Theoretically, if you fill the entire board wit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.