blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d28681bb317c851e317e53654ad1ac2422d6aaf9 | marcoisgood/Leetcode | /0252.Meeting-Rooms.py | 861 | 3.828125 | 4 | """
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.
Example 1:
Input: [[0,30],[5,10],[15,20]]
Output: false
Example 2:
Input: [[7,10],[2,4]]
Output: true
"""
class Solution:
def canAttendMeetings(self, i... |
80d48560918be79ba76cda8bd8cb43aa05366d14 | marcoisgood/Leetcode | /0125.Valid-Palindrome.py | 589 | 4.28125 | 4 | """
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
"""
class... |
0681096fc27021a2c31bb1ff52b22bb182670506 | andres-aguilar/PyGame | /1_introduction/rectangles.py | 761 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import pygame
pygame.init()
width = 400
height = 500
surface = pygame.display.set_mode( (width, height) )
pygame.display.set_caption('Colors')
# RBG
red = pygame.Color(115, 38, 80)
white = pygame.Color(255, 255, 255)
green = pygame.Color(0, 200, 0)
rect ... |
ac0627dca644517741645b611a1183c6cee81e8e | BartoszSlesar/Python_Morsles_Exercises | /format_ranges/format_ranges.py | 1,795 | 3.796875 | 4 | from collections import Counter
def format_ranges(numbers):
# first, *rest = numbers
continuous = continuous_numbers(numbers)
# for val in continuous:
result = ','.join(f'{val[0]}-{val[-1]}' if len(val) > 1 else f'{val[0]}' for val in continuous)
# end = 0
# check = first
# result = ''
... |
5602e7268e2673635b16be4315fdff3a202a136d | harishaa-it19/dashboard | /file1.py | 117 | 3.6875 | 4 | a=int(input())
b=int(input())
def myfun(a,b):
c=a+b
d=a-b
e=a*b
return c,d,e
f= myfun(a,b)
print(f) |
783e1f4260739fec7d10f2b6e6de9e4b6bde6075 | bwerth/discrete_final_project | /nn.py | 1,847 | 3.828125 | 4 | """An implementation of Nearest-Neighbor path sorting."""
from tsp import (
Node,
Graph,
SvgGraph,
NaiveSvgGraph,
dist,
)
import random
def nearest_neighbor_sort(graph: Graph) -> Node:
def follow_path(n: Node):
if len(n.edges) > 1:
raise ValueError('Start {!r} has more tha... |
4c70226c467e2ebd422f93cfd0daf9c15377b163 | yeri918/personal_project | /nodes_and_edges.py | 3,708 | 3.984375 | 4 | node={} #Global variable with key as node ID (an integer), value as name of the node.
edge={} #Global variable with key as the node ID (an integer), value as a set of neighbor node ID(s)
def InsertNode(id,name):
count=0
if id not in node:
node[id]=name
else:
count+=1
if count>0:
... |
1fddc797dc1ad68da0fdc694e43a931a840ce0af | Poojajanwalkar/python-learning | /in place operator.py | 107 | 4 | 4 | x = 2
print("x= " + str(x))
x += 3
print("x+=3 : " + str(x))
x = "spam"
print(x)
x += " eggs3"
print(x) |
7323e55c5f44e804e2ab25a3de81f298a5c83c91 | Poojajanwalkar/python-learning | /My Day 1 exercise.py | 795 | 4.03125 | 4 | print(1 + 2)
print(3.4 + 11)
print(8 + 4.0)
print("7-5=" + str(7-5))
print("-6.0 + 11.78 = " + str(-6.0 + 11.78))
#calculate and print age
print("\n calculate your age")
#print("My age: " + input("What is your age?"))
x=input("enter year: ")
print("your age: " + str(int(2020) - int(x)))
#print(2020 - 1986)
#calculat... |
48c521561061cbcd4db0c1d3e346694ab43d1fcc | oychao/python-ml | /matplot_demo/knn.py | 4,658 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
this Python script is for displaying k nearest neighbors algorithm
"""
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
class Knn:
"""
knn class
"""
def __init__(self):
pass
@staticmethod
def generate_points(group_... |
5935eaf01a88c3fe63f815eb3e8d7057bf128e1f | Aunik97/Iteration | /spotchek 3.py | 398 | 3.6875 | 4 | #Aunik Hussain
#Iteration Spotcheck Q3
import random
number = random.randint(1,100)
NoTurn = 0
guess = int(input("enter your guess for the number"))
while guess == False:
NoTurn = NoTurn + 1
if guess == number:
number == True
print("well done youve guesssed correct")
elif gues... |
6505693ed1dcc9f10d9e9c9131fb5b53c54bcdc2 | Aunik97/Iteration | /iteration spotcheck 2.py | 245 | 4.03125 | 4 | #Aunik Hussain
#Iteration Spotcheck Q2
count = 0
for count in range(1,12):
count = count + 1
number = int(input("Please enter an integer"))
answer = count * number
print("{0:<2} * {1:<2} is {2:<2} ".format(count, number, answer))
|
81079fb0b228f9119f0ad52678fbd0bc7889aedf | nasraaden/coding-challenges | /intro/findEmailDomain.py | 599 | 4 | 4 | '''
An email address such as "John.Smith@example.com" is made up of a local part ("John.Smith"), an "@" symbol, then a domain part ("example.com").
The domain name part of an email address may only consist of letters, digits, hyphens and dots. The local part, however, also allows a lot of different special characters.... |
0191043fc2f72fe4de2f57dbfe610bd1314310c6 | nasraaden/coding-challenges | /intro/deleteDigit.py | 329 | 3.765625 | 4 | '''
Given some integer, find the maximal number you can obtain by deleting exactly one digit of the given number.
'''
def deleteDigit(n):
n = list(str(n))
max_arr = []
for i in range(len(n)):
copy_arr = n.copy()
copy_arr.pop(i)
max_arr.append(int(''.join(copy_arr)))
return max(... |
9dac22316714d60acc703a88a2e219c9589792ce | nasraaden/coding-challenges | /intro/differentSquares.py | 407 | 3.765625 | 4 | '''
Given a rectangular matrix containing only digits, calculate the number of different 2 × 2 squares in it.
'''
def differentSquares(matrix):
nums_set = set()
for i in range(len(matrix)-1):
for j in range(len(matrix[i])-1):
nums_set.add((matrix[i][j], matrix[i+1][j],
... |
4dc54e70e8616d8e3bdd9f30aa85dc05e6bd8e94 | nasraaden/coding-challenges | /intro/isMAC48Address.py | 905 | 4.5 | 4 | '''
A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment.
The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens... |
4d101f5cc0084c7bc953ef90d7f70ed2ac87299a | nasraaden/coding-challenges | /intro/depositProfit.py | 476 | 3.953125 | 4 | '''
You have deposited a specific amount of money into your bank account. Each year your balance increases at the same growth rate. With the assumption that you don't make any additional deposits, find out how long it would take for your balance to pass a specific threshold.
'''
def depositProfit(deposit, rate, thres... |
545cb664d1626b557a2e5c1d2179a891196dd8fc | nasraaden/coding-challenges | /intro/firstDigit.py | 173 | 4.03125 | 4 | '''
Find the leftmost digit that occurs in a given string.
'''
def firstDigit(inputString):
for i in inputString:
if i.isdigit() == True:
return i
|
87770ea600f766640428a72f1949e8bfc934bad6 | STHSF/stock_industry_sentiment_analysis | /sentiment_intensity/STP/test_tree/tree.py | 1,347 | 3.703125 | 4 | #!/usr/bin/env python
# encoding: utf-8
# -------------------------------------------
# 功能:
# Author: zx
# Software: PyCharm Community Edition
# File: tree.py
# Time: 16-12-22 下午2:43
# -------------------------------------------
import nltk.tree as tree
# 递归遍历
def test(t):
if isinstance(t, str):
print t... |
74dd31f2923fbb991f350fc9358b037c2f7112f3 | cverburgh/PythonScale | /GenericPinConfig.py | 885 | 3.546875 | 4 | import RPi.GPIO as GPIO
class Pin():
""" any old pin """
def __init__(self, pinNumber, gpioMode, initialpinValue = GPIO.LOW):
self.pin = pinNumber
self.mode = gpioMode
if (gpioMode == GPIO.OUT): self.pinValue = initialpinValue
@property
def pin(self): return self.__pin
@... |
2a955cf4a67910c454bcc71f0d2a6b9f5d549ac6 | s-xync/ml-and-dl | /Sixth Semester ML/MultiLayerPerceptronLearning/Conversions.py | 1,657 | 3.6875 | 4 | """
** Author : SaiKumar Immadi
** MultiLayer Perceptron Learning
"""
# Uses Python 2
# python Init.py TrainingData.txt TrainingTarget.txt TestingData.txt TestingTarget.txt
# optimal inputs for the given dataset 0.001, 10000, 1, 8
import numpy as np
def convertListsToArrs(listoflists):
vectorlength=len(listoflis... |
34b46f7160d05590e4a87e78d5899d323af9c363 | OctavianusAvg/Donny | /4.py | 701 | 3.5625 | 4 | '''
Створіть масив з п'яти прізвищ і виведіть на екран ті з них, які
починаються з певної букви, яка вводиться з клавіатури.
Виконав : Канюка Р. 122В
'''
import numpy as np
while True:
X = list()
#Ініціалізація масиву
for i in range(5):
X.append(input(f'Введіть {i+1} прізвище : '))
keyword = inp... |
b58b3c057bfd07c9cb7501109829092304e3e82a | OctavianusAvg/Donny | /25.py | 957 | 3.734375 | 4 | '''
25. Знайти добуток елементів лінійного масиву цілих чисел, які кратні 5.
Розмірність масиву - 10. Заповнення масиву здійснити випадковими числами від 10 до
100.
Виконав : Канюка Р. 122В
'''
import random
import numpy as np
while True:
#Ініціалізація масиву
X = np.zeros(10)
for i in range(len(X)):
... |
1cdf23bb6b15c4b54dbc49d1da045dffd30d50d1 | OctavianusAvg/Donny | /19.py | 1,090 | 4.09375 | 4 | '''
Знайти суму всіх елементів масиву цілих чисел що задовольняють умові:
остача від ділення на 2 дорівнює 3. Розмірність масиву - 20. Заповнення масиву
здійснити випадковими числами від 200 до 300.
Виконав : Канюка Р. 122В
'''
import random
import numpy as np
while True:
#Ініціалізація масиву
X = np.zeros(20)
... |
f255d85bcf80f444e0ccb90d7b4b75f4822703c0 | OctavianusAvg/Donny | /18.py | 1,094 | 3.515625 | 4 | '''
Знайти добуток всіх елементів масиву цілих чисел, менших 0. Розмірність
масиву - 10. Заповнення масиву здійснити за допомогою клавіатури.
Виконав : Канюка Р. 122В
'''
import random
import numpy as np
while True:
#Ініціалізація масиву
X = np.zeros(10)
while True:
try:
for i in range(... |
2f39f985a32811eb96899e91e84a14c4adc886c2 | ThomasMBury/ews_seasonal | /models_ricker/ricker_std/bifurcation/gen_pynamical.py | 1,341 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 17:46:28 2018
Generate a bifurcation diagram of a discrete system.
Model: Seasonal Ricker model
@author: Thomas Bury
"""
from pynamical import bifurcation_plot, simulate
import numpy as np
from numba import jit
# Fixed model params
alpha... |
c517370ffd392cf986757dc9b749174f54622fe8 | ThomasMBury/ews_seasonal | /models_logistic/logistic_std/bifurcation/generate_bif.py | 883 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 17:46:28 2018
Generate a bifurcation diagram of a discrete system.
Model: : Discrete logistic model
@author: Thomas Bury
"""
from pynamical import bifurcation_plot, simulate
import numpy as np
from numba import jit
# Model parameters (from ... |
24e0c30ae6a21457ccd52ce5584f798fda4cc48b | TheGigacorn/MSTMoCities | /prims.py | 10,252 | 3.75 | 4 | import math
import sys
from collections import defaultdict
import heapq
import time
######### MinHeap Class ##########
class Heap():
def __init__(self):
self.array = []
self.size = 0
self.pos = []
def newMinHeapNode(self, v, dist):
minHeapNode = [v... |
1dc7525d87e7a3d0da28848b08993b816a3a23ea | mlassoff/PFAB_2_2014 | /Homework2B.python | 234 | 3.921875 | 4 | #!/usr/bin/python
price = input("What is the cost of the item? ")
taxRate = input("What is the sales tax rate (Expressed as 0.XX) ")
taxes = price * taxRate
fullCost = price + taxes
print "The full price of the item is $", fullCost
|
eaa7d1dc1b67a50179332195b9a2690b2168a6dc | amannayyar1/PasswordGenerator | /PasswordGen.py | 982 | 4.28125 | 4 | '''
Random Password Generator using Python
Author: Aman Nayyar
'''
# import the necessary modules!
import random
import string
print('hello, Welcome to Password generator!') # greet the user
# input the length of password
length = int(input('\nEnter the length of password: '))
... |
f99f19f687910ead01eccb958bf1fe2bc6e7dd05 | qiuzhuangshandian/ProjectLIbs | /graduate/EMA/ema.py | 4,256 | 3.515625 | 4 | # -*- coding: utf-8 -*-
'''
Exponential smooth(指数平滑)的手工实现(无第三方库)
Author : Kabuto_hui
Date : 2018.04.19
'''
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter #设置科学计数
from color import cnames
#指数平滑算法
def exponential_smoothing(alpha, s):
'''
一次指数平滑
... |
7b63dcf5adda10210135fdef7e8ca4e8a0ea05ea | cristiano-xw/python | /python/乘法表.py | 123 | 3.640625 | 4 | for i in range(1,10):
for j in range(1,10):
result=i*j
print("%d*%d=%-3d"%(i,j,result))
print("\n") |
2773537cfc0df1a8c2256a3072fffea8401d7460 | cristiano-xw/python | /python/循环练习1.py | 449 | 3.609375 | 4 | b = ["剪刀", "石头", "布"]
a = 123456 #后面需要转换数据类型
while True:
name = input("请输入您的用户名")
if name in b:
break
else:
print('您输入的用户名不存在,请重新输入')
continue
while True:
password = input('请输入您的密码:')
if str(a) == password: #将a转换为字符串
print('进入系统')
break
else:
print('您输入的密码不正确,请重新输入')
continue
|
ba2f4dd61582eec67ae36b244aa62d5852699e2d | laubonghaudoi/Cantonese | /src/register_vm.py | 22,174 | 3.609375 | 4 | """
Cantonese语言寄存器式虚拟机
Created at 2021/7/18 7:58
"""
# 施工中... 请戴好安全帽
from enum import Enum, unique
from typing import Dict
from collections import namedtuple
@unique
class CanType(Enum):
NONE = -1
NULL = 0
BOOLEAN = 1
L_USER_DATA = 2
NUMBER = 3
STRING = 4
FUNCTION = 5
USER_DATA ... |
ebf90fcff9f92be352226f9f885a2ff843c003fe | GigotH/python | /section 2/zip_function.py | 356 | 3.75 | 4 | # zip combines two lists where each element of the new list is a tuple of elements.
friends = ["Tim", "Sasa", "casey", "Craig", "gigot"]
time_since_seen = [3, 7, 5, 20, 12]
new_list = dict(zip(friends, time_since_seen))
print(new_list)
"""
long_timers = {
friends[i]: time_since_seen[i]
for i in range(len(f... |
6e8f619af33b95c1033d0087fded37b42d2f302a | GigotH/python | /section 2/enumerate.py | 729 | 4.5 | 4 | friends = ["Tim", "Sasa", "casey", "Craig", "gigot"]
"""
# without enumerator
counter = 0
for friend in friends:
print(counter)
print(friend)
counter = counter + 1
"""
# using enumerator:
for counter, friend in enumerate(friends):
print(counter)
print(friends)
print(list(enumerate(friends)))... |
bd6826b3567b1bb773db4a12cb01a248c26fcda4 | GigotH/python | /section 2/list_comprehension.py | 911 | 4.4375 | 4 | # create a new list succinctly
# create a new list that is the numbers in the original list multiplied by 2
numbers = [0, 1, 2, 3, 4]
# one way...
"""
doubled_numbers = []
for number in numbers:
doubled_numbers.append(number * 2)
print(doubled_numbers)
"""
# better way, using list comprehension...
doubled... |
a1c9cde221c52a4c8d7742ca755a1e608c86e8e9 | Fergoth/Euler_Proj | /9. Special pythagorean triplet.py | 368 | 4 | 4 | # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
#
# For example, 32 + 42 = 9 + 16 = 25 = 52.
#
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
for i in range(1000):
for j in range(i,1000):
k = 1000-i-j
... |
c2c51361890d41ceac492e3e5d60b940bc7b281e | Kollaider/CheckiO | /checkio/elementary/first_word.py | 611 | 4.1875 | 4 | """First word.
URL: https://py.checkio.org/en/mission/first-word-simplified/
DESCRIPTION:
You are given a string and you have to find its first word.
The input string consists of only English letters and spaces.
There aren’t any spaces at the beginning and the end of the string.
INPUT/OUTPUT EXAMPLE:
f... |
dae1865c250bbc066c593a89c48fd893db472284 | Kollaider/CheckiO | /checkio/elementary/remove_all_before.py | 1,156 | 4.3125 | 4 | """Remove All Before.
URL: https://py.checkio.org/en/mission/remove-all-before/
DESCRIPTION:
For the illustration we have a list [1, 2, 3, 4, 5] and we need to remove
all elements that go before 3 - which is 1 and 2.
We have two edge cases here:
(1) if a cutting element cannot be found,
then the li... |
3a9662c71bc6673d72d40f0745aef4de2bd6948f | Kollaider/CheckiO | /tests/checkio/home/test_count_digits.py | 643 | 3.75 | 4 | from unittest import TestCase
from checkio.home.count_digits import count_digits
class SplitListTestCase(TestCase):
def test__count_digits_equal_result(self):
self.assertEqual(0, count_digits('hi'))
self.assertEqual(1, count_digits('who is 1st here'))
self.assertEqual(1, count_digits('my... |
828c6f4681047709180f5200af8fcb20165235cd | Kollaider/CheckiO | /checkio/elementary/end_zeros.py | 483 | 4.40625 | 4 | """End Zeros.
URL: https://py.checkio.org/en/mission/end-zeros/
DESCRIPTION:
Try to find out how many zeros a given number has at the end.
INPUT/OUTPUT EXAMPLE:
end_zeros(0) == 1
end_zeros(1) == 0
end_zeros(10) == 1
end_zeros(101) == 0
"""
from itertools import takewhile
def end_zeros(number: int... |
a628067276e766f907a081413bfdeac8d468a65e | ashutoshrvu/GuessingGame | /main.py | 379 | 3.96875 | 4 | # Guessing Game Of Wizard
# Defining variables
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input("I am the wizard. Guess the number, puny mortal: "))
guess_count += 1
if guess == secret_number:
print("You won. I am impressed!")
break
else:
... |
fb3c64309c73d43412ba683072fcda8d6db2169a | yulifromchina/python-exercise | /DesignMode/SimpleFactory.py | 628 | 3.8125 | 4 | # -*- coding:utf-8 -*-
#用静态方法实现简单工厂模式
import random
class BasicCourse(object):
def get_lab(self):
return 'basic_course:labs'
class ProjectCourse(object):
def get_lab(self):
return 'project_course:labs'
class SimpleCourseFactory(object):
@staticmethod
def create_c... |
84415ef6a7574375fc4f1266a0bcf06d5459d2f8 | yulifromchina/python-exercise | /python3_basic/lesson2/TestHundred.py | 179 | 4.3125 | 4 | #!/usr/bin/env python3
number = int(input("Enter an integer:"))
if(number <= 100):
print("Your number is smaller or equal to 100")
else:
print("Your number is bigger than 100")
|
333713414d586e22095b4c8383d4b2d09b6f8327 | yulifromchina/python-exercise | /python3_basic/lesson10/Property.py | 651 | 3.703125 | 4 | #!/usr/bin/env python3
# @property : make a function become an attrbute
class Account(object):
"""
account class
"""
def __init__(self, rate):
self._amount = 0
self.rate = rate
@property
def amount(self):
return self._amount
@property
def renmingbi(self):
return self._amount * self.rate
@amount.se... |
02b3f444f13fa10c2c25ce0bef09b596cef749af | fr4n3k/lightweight-erp-python-erp_transformers | /common.py | 1,942 | 3.640625 | 4 | """ Common module
implement commonly used functions here
"""
import random
import main
import ui
def generate_random(table):
"""
Generates random and unique string. Used for id/key generation:
- at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letter
- it mu... |
6f720ba9f808a6efdc4a9d83e3e72fb8cb17a32c | laohixdxm/LT_OJ | /leetcode_python/ITER_SymmetricTree.py | 2,912 | 3.8125 | 4 | #symmetric tree, iterative
#bug record "node.left" mistaken as "node.right":
#if(node.left!=None): fifo.append(node.right)
#=> if(node.right!=None): fifo.append(node.right)
#bug record, without None node processing after fifo.pop(0)
#if(node==None): continue
class TreeNode(object):
def __init__(self, x):
... |
1150fb6025fe14d985fa57057b5a84a0e0eb6cb7 | laohixdxm/LT_OJ | /leetcode_bash/validPhoneNumbers.py | 1,243 | 3.609375 | 4 | def format1(phone):
if(len(phone)!=12):
return False
for i in range(len(phone)):
char_status = False
if((i==3) or (i==7)):
if(phone[i] != '-'):
return False
else:
for j in range(10):
#print(phone[i], j)
if(int(phone[i]) == j):
char_status = True
break
if(char_status... |
7e1cdb54e3e27727f1407fa3c56277b23cd9af3d | laohixdxm/LT_OJ | /leetcode_python/IsomorphicStr.py | 412 | 3.875 | 4 | #leetcode IsoMorphic String
def IsoMorphic(s1, s2):
dict1, dict2 = {}, {}
for k,v in zip(s1,s2):
if(k not in dict1):
dict1[k] = v
if(v not in dict2):
dict2[v] = k
if(dict1[k] != v) or (dict2[v] != k):
return False
return True
print(IsoMorphic("eg... |
a180deb716e3f678d80c2e3089f1a3af01eb3257 | laohixdxm/LT_OJ | /leetcode_python/SingleNumIII.py | 404 | 3.53125 | 4 | #leetcode SingleNumIII, cannt solve,
def SingleNumIII(nums):
xor = nums[0]
for i in range(1,len(nums)):
xor ^= nums[i]
print(xor)
lowest = xor & (-xor)
pair = [0,0]
for i in range(len(nums)):
if(nums[i] & lowest):
pair[0] ^= nums[i]
else:
pair[... |
ab753664994b1c36af3320633c343c932bf0dadc | laohixdxm/LT_OJ | /leetcode_python/MergeTwoSorted.py | 1,513 | 4.03125 | 4 | #leetcode, Merge Two Sorted Lists,
#too tricky, give up temporarily
#hold cur(current node), next1, next2 pointer, done
import pdb
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def mergeTwoLists(l1, l2):
next1, next2, cur =... |
f0975b6de4444f67c69eb3ecffffcf876b87547c | laohixdxm/LT_OJ | /leetcode_bash/validPhoneNumbers2.py | 1,727 | 3.75 | 4 | import pdb
def validNumber(phone_number):
if len(phone_number) != 12:
return False
for i in range(12):
if i in [3,7]:
if phone_number[i] != '-':
return False
elif not phone_number[i].isdigit():
return False
return True
def validNumber2(phone_number):
for (i,c) in enumerate(phone_number):
if i... |
dae7ef9ccbe7e0e430d6d992c5a35ef681958c29 | mooseman/pdeditor | /pdeditor.py | 20,275 | 3.625 | 4 |
# pdeditor.py
# A small and simple text editor.
# This code is released to the public domain.
import sys, math, curses, curses.ascii, traceback, string, os
# A class to handle keystrokes
class keyhandler:
def __init__(self, scr):
self.scr = scr
# Dictionary t... |
a4cdc6978b16c81113c6245890e58fb445ef4402 | iNoSec2/skf-labs | /python/SessionPuzzle/createtable.py | 617 | 3.734375 | 4 | import sqlite3
conn = sqlite3.connect('database.db')
print('Opened database successfully')
conn.execute('''CREATE TABLE emptbl
(ID INT PRIMARY KEY NOT NULL,
USERNAME TEXT NOT NULL,
PASSWORD TEXT NOT NULL);''')
print('Table created successfully')
conn.execute("INSE... |
f0c7658385e9974362fa458340b092427ad69148 | iNoSec2/skf-labs | /python/user-registration-process/db/users.py | 1,614 | 3.84375 | 4 | import sqlite3
def seed_users():
users = [('Michael', '07RYbe$!9y11'),
('Adam', '07RYbe$!9y12'),
('Andrew', '07RYbe$!9y13'),
]
con = sqlite3.connect("db.db")
cur = con.cursor()
cur.execute('''
CREATE TABLE IF NOT EXISTS users
(id... |
63e50955402789b91fe4c4551af0590b5fd9a272 | faille/repo1 | /git5.py | 291 | 3.5 | 4 | from microbit import *
x = 0
while True:
if button_b.was_pressed() and x < 5:
for y in range(5):
display.set_pixel(x, y, 9)
x += 1
elif button_a.was_pressed() and x > 0:
for y in range(5):
display.set_pixel(x -1, y, 0)
x -= 1
|
810183d30d62b1efbb61657a7c66dc2751708135 | faille/repo1 | /git22bisopenfile.py | 256 | 3.671875 | 4 | fichier = open("file_3.txt", "a")
mot = ""
for i in range(6):
lettre = input("Donner une lettre : ")
while lettre[1:] != "":
lettre = input("Donner 1 lettre pas + : ")
mot += lettre
fichier.write(lettre)
print(mot)
fichier.close() |
dae509a5655a1c132c50ba663ba176433d3e46f6 | SofiaM1031/PG_SMe | /personality_SM.py | 331 | 4 | 4 | name = "Sofia"
state = "Vermont"
city = "Bogota"
book = "The Apothecary"
sport = "Hockey"
team = "Rangers"
print("Hello " name + " How are you")
print("What's your favorite subject")
subject = input ()
if subject == "Math":
print("That's my favorite too")
else:
print("That's alright to... |
24db5c92f7b300f6cd6a18a91c7978a748886344 | SofiaM1031/PG_SMe | /pg.quiz.SM_MP._..py | 1,799 | 3.703125 | 4 | import pyautogui as pg
import time
points = 0
#Question 1
answer = pg.prompt(
"""
How would you describe yourself?
a)I an angel
b)I am demon spawn
c)meh
"""
)
#Give points
if answer == "a":
points +=1
elif answer == "b"
points +=2
elif answer == "c"
points +=3
#Questio... |
aae4137f10193749e9497b252abba6a0b60dbec0 | ericsu378/Miller_Python_DS_Alg | /Chapter2/ch2_3_selfcheck.py | 1,811 | 4.0625 | 4 | __author__ = 'ESU'
####################################
# To-Do
# clean up variable names
# figure out why pyplot doesnt work w/in a function
####################################
# Problem Solving with Algorithms and Data Structures [Online]
# http://interactivepython.org/
# Brad Miller, David Ranum
# 2.3. Big-O No... |
8a9ee1ac0acfa21492d42a795b92d7692ee1715f | ericsu378/Miller_Python_DS_Alg | /Chapter1/ch1.7.py | 6,615 | 3.796875 | 4 | __author__ = 'ESU'
# Problem Solving with Algorithms and Data Structures [Online]
# http://interactivepython.org/
# Brad Miller, David Ranum
# 1.7 Programming Exercises
# 1. Implement the simple methods get_num and get_den that will return the numerator
# and denominator of a fraction.
# 2. In many ways it would be... |
39351de971228fd0f15f38cf9abaa6db9f4ce8a6 | ericsu378/Miller_Python_DS_Alg | /Chapter1/ch1_17_SudokuSolver.py | 8,563 | 4.09375 | 4 | __author__ = 'ESU'
# Problem Solving with Algorithms and Data Structures [Online]
# http://interactivepython.org/
# Brad Miller, David Ranum
# 1.17 Programming Exercises
# 15. Find a Sudoku puzzle in the local newspaper. Write a program to solve the puzzle.
# Ref: http://norvig.com/sudoku.html
# Definitions:
# A Su... |
a14ee261506e2a00e27b704122c89aad650cfbc7 | ericsu378/Miller_Python_DS_Alg | /Chapter1/Analysis_SelfCheck.py | 7,577 | 3.9375 | 4 | __author__ = 'ESU'
# Problem Solving with Algorithms and Data Structures
# Brad Miller, David Ranum
# http://interactivepython.org/runestone/static/pythonds/index.html
# Self Check
# Write two Python functions to find the minimum number in a list.
# The first function should compare each number to every other number ... |
7635a0477d2d7dfd592cf2b4f9de84ac83b8d9b9 | ECCIUCRLQ/sensores-k-o-f | /Codigo/Protocolo/sensor_interpreter.py | 447 | 3.65625 | 4 | def interpret(identifier):
if identifier == 1:
return "Movimiento"
elif identifier == 2:
return "Sonido (Big Sound)"
elif identifier == 3:
return "Luz"
elif identifier == 4:
return "Shock"
elif identifier == 5:
return "Touch"
elif identifier == 6:
return "Humedad"
elif identifier == 7:
return "Big ... |
918d3a3463f0928be328c705b5e4715249732e5c | qangdev/functional-programming | /python/chapter_1.py | 5,316 | 4.03125 | 4 | #
# C H A P T E R 1
# ------------------------
# F L O W C O N T R O L
#
if __name__ == '__main__':
# I. Pure function: Does not change the input and return new output
def pure(alist):
'''This function dose not change the input list but return a new list '''
newlist = []
for i in al... |
06c8a5439ede3eb2dbe1c1c25485bec7970e5354 | PleasingFungus/hex | /astar.py | 1,802 | 3.875 | 4 | ''' A* pathfinding. '''
from queue import PriorityQueue
def a_star_search(cells, start, goal, passable_metric):
''' Find the fastest path from the start to the goal in the given area.
A slightly modified version of http://www.redblobgames.com/pathfinding/a-star/implementation.html .
Args:
cells (... |
3ebcc112bdf89c5e962056977b6a5c9aa25d72d1 | jdhouti/Dame | /src/graph.py | 2,106 | 3.640625 | 4 | # graph.py - This files contains the Graph object
# Author: Julien Dhouti
# Graph : class - contains all of the attribute to the graph object
# Python 3.6.1
import data_object as do
class Graph(do.DataObject):
"""Contains a data object that is a graph.
Attributes:
type: a string specifying the type o... |
c4f71dc0b60743a7b4b1cdba50e2797bc39e16e0 | SantiagoRomeroPineda/analisis-de-algoritmos | /funciones_basicas_recursivas.py | 385 | 3.5 | 4 | def factorial(n):
return (1 if (n<=1) else (n*factorial(n-1)))
print (factorial(4))
def fibo(n):
return (n if (n<=1) else (fibo(n-1)+fibo(n-2)))
print (fibo(6))
def sumaLista(lista):
return (0 if not lista else (lista[0] + sumaLista(lista[1:])) )
print(sumaLista((1,2,3,4,5)))
def par_impar(n):
retu... |
050a2fdb387cc377726c8bae019bbef276c07adb | SantiagoRomeroPineda/analisis-de-algoritmos | /sumar_multiplicar_arreglo.py | 1,468 | 3.546875 | 4 |
"""
Realizado por:
Santiago Romero
Davis Steven Lopez Tobar
"""
import time
start_time = time.time()
print(time.ctime( start_time) )
# arreglos con n digitos Todos los digitos son 9
arr10= [9 for i in range(10)]
arr100=[9 for i in range(100)]
arr1000=[9 for i in range(1000)]
arr2000=[9 for i in range... |
4ffbae0da5326b0f37e9bbdd144e8d10fc855558 | SantiagoRomeroPineda/analisis-de-algoritmos | /taller3/mochila4.py | 803 | 3.578125 | 4 | import time
def mochila(peso, valor, pesoMaximo):
filas= len(peso)+1
columnas=pesoMaximo+1
matriz= [[0 for i in range(columnas)] for j in range(filas)]
for i in range(1,filas):
for j in range(1,columnas):
if peso[i-1] <= j:
matriz[i][j]=max(valor[i-1]+ matriz[i-1][j-p... |
f0ebcc3758bd943a8a8bbd73e1bce996fc8c091f | SantiagoRomeroPineda/analisis-de-algoritmos | /fibonacci_mejorado.py | 704 | 3.6875 | 4 | def fibo(n,mapa = {0: 0, 1: 1}):
if n not in mapa:
mapa[n] = fibo(n-1, mapa) + fibo(n-2, mapa)
return mapa[n]
#print(fibo(7))
def fibon(n,arreglo = [0,1]):
if len(arreglo)<n:
arreglo.append(fibon(n-1, arreglo) + arreglo[n-2])
return arreglo[n-1]
#print(fibon(5))
def fib (n, lista=[0,1]... |
6ce34a61a4c75437bc57ceca2c94db2f64e2d7be | BallinLikeStalin/rosebotics2 | /src/leeem.py | 912 | 3.953125 | 4 | """
Capstone Project. Code written by Eric Lee.
Fall term, 2018-2019.
"""
import rosebotics_new as rb
import time
def main():
""" Runs YOUR specific part of the project """
# run_test_wait_until_pressed()
# run_test_wait_until_released()
#run_test_drive_until_color()
run_test_beeping()
def r... |
2c641f0f18b4a492dfd0021ed1b36d431a840345 | LuckyDogg/LeetCodePython | /LeetCode204.py | 441 | 3.75 | 4 | class Solution:
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
count = 1
for num in range(3, n):
for i in range(2, int(num/2)):
i = 2
if num % i == 0:
break
count += 1
... |
f54409eaad55e9f692ed4567b55f52ecd6be2975 | AdamHerman69/PythonLabs | /06/palindrome.py | 97 | 3.765625 | 4 | def is_palindrome(string):
if (string == string[::-1]):
return True
return False
|
b726a50c5337fc9499a8dde73930ba1c64ff4545 | jazyrcp/Python | /assign_1/assign_9.py | 83 | 3.921875 | 4 | num = int(input("Enter the Number:"))
c=1
for i in range(num,0,-1):
c=c*i
print(c) |
64f8aa18e89071003a1ed9cbc21fbb5d70a188f9 | jazyrcp/Python | /tut24_marklist.py | 1,311 | 4.03125 | 4 | class Student:
"""Student name, marks in 3 subjects, total"""
def __init__(self,name):
self.name = name
def marks(self):
self.maths = int(input("Enter your mark in maths:"))
self.physics = int(input("Enter your mark in physics:"))
self.chemistry = int(input("Enter your mark in chemistry:"))
self.total = ... |
acff6706a97bbca7307bcf692b7d72d456fa5945 | jazyrcp/Python | /assign_1/assign_14.py | 91 | 4 | 4 | num = int(input("Enter the number: "))
c=0
for i in range(1,num+1):
c+=i
print("Sum =",c)
|
d9124334567ecbd34e831fc5409e79e1b6efffc8 | jazyrcp/Python | /tut38_iterclass.py | 251 | 3.6875 | 4 | class Iterate:
def __init__(self,n):
self.i=0
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.i >= self.n:
raise StopIteration()
else:
i=self.i
self.i += 1
return i
for x in Iterate(10):
print(x) |
370d70ca0de7df687ada399c2612b80d608249db | jazyrcp/Python | /tut11_linearSearch.py | 349 | 3.828125 | 4 | list1=range(450,0,-1)
print(list1)
n=int(input("Enter the number to be searched:"))
def search(list1,n):
c=0
j=0
l=len(list1)
for i in range(0,l):
if list1[i]==n:
# if n in list1:
c+=1
j=i
if c>0:
print("%d found in at %d position in list"%(n,j))
else:
print("Not Found")
search(list1,n)
t=[x for... |
d8433c981b59ad109155a2c7f85b7fa62bf4d94c | jazyrcp/Python | /assign_2/assign_5.py | 342 | 4.25 | 4 | size=int(input("Enter the size:"))
dic2={}
dic1={1:34,3:56,56:3434}
dic3={"name":"jasir","age":23,"place":"knr"}
for i in range(0,size):
key=input("Enter the key:")
value=input("Enter the value:")
dic2[key]=value
print(dic1)
print(dic2)
print(dic3)
dic1.update(dic3)
print(dic1)
print(dic1.items())
print(dic1.keys()... |
a21cd416b25fa2efb2745723275465a91010e6b0 | jazyrcp/Python | /assign_1/assign_6.py | 287 | 4 | 4 | #list1 = [6,5,4,3,2,1]
#list2 = [1,2,3,4,5,5,4,3,2,1]
for i in range(6,0,-1):
for j in range(0,i):
print("* ",end ="")
print()
for i in range(0,6):
for j in range(0,i):
print("* ",end ="")
print()
for i in range(6,0,-1):
for j in range(0,i):
print("* ",end ="")
print() |
7253a7df05b60a82f4f4efebff31c6bc72614e46 | jazyrcp/Python | /assign_3/assign_1.py | 170 | 4.15625 | 4 | num=int(input("Enter the Number to be Checked:"))
def check(num):
if num%2==0:
print("%d is an even number"%num)
else:
print("%d is an odd number"%num)
check(num) |
1a82c7fb814770c79eb9387e7e0c0ee8fbf5972f | jazyrcp/Python | /assign_2/assign_21.py | 105 | 3.890625 | 4 | dic1={"Dog":"Willie","Cat":"Tom","Rat":"Jerry"}
for i in dic1.keys():
print("%s is a %s" %(dic1[i],i)) |
c5d971b4e25dff56301e53fecea00abbbdb001a3 | jazyrcp/Python | /assign_3/assign_7.py | 185 | 3.515625 | 4 | lis1=[5,4,31,22,1]
lis2=['a','b','c','d','e']
def dictmaker(lis1,lis2):
dict1={}
for i in range(0,len(lis1)):
dict1[lis1[i]]=lis2[i]
return(dict1)
x=dictmaker(lis1,lis2)
print(x) |
3d71ef051269954187a5ec8b0fb7c6300c9f6663 | DenisProkopenko/Random-Python-Work | /Click.py | 723 | 3.875 | 4 | # This is just a fun game, try clicking the button and see what happens :)
from tkinter import *
from random import *
def do_event(event):
print("{},{}".format(event.x,event.y))
def jump(event):
app.button.place(relx=random(),rely=random())
class App:
def __init__(self,master):
frame = Frame(mas... |
f2562ae81b55dde9ab211c1893df60fdd5bcde33 | mxsw/sixteen | /scripts/pomo_generators.py | 791 | 3.5625 | 4 | #!/usr/bin/python3
import random
import math
'''
sumg
name lenght
'''
num_cases = 300
# def name_gen():
# ans = 'a'
# cur_char = 'a'
# while True:
# yield ans
# if(ans[-1] == 'z'):
# ans += 'a'
# ans[-1] += 1
def name_gen():
num = 0
while True:
yield... |
e2c035c2f9e7059865599b566e499157ff838382 | DrJeffKnisley/OperationsResearch | /Module1MainExample/1-MainExampleTools.py | 7,467 | 3.84375 | 4 |
from functools import partial
def add_method(obj, func):
'Bind a function and store it in an object'
setattr(obj, func.__name__, partial(func, obj))
def plotfill(ax, x, y, *args, **kwargs):
"""plotfill(axes, x, y, *args, kwargs) -> plot curve and fill region (see below)
x = list-like (iter... |
50fb8a87f35a35ea3d4ff0a21ab3d964f9f0a02a | JZSang/algorithms | /DailyProblem/day10.py | 2,272 | 4.25 | 4 | """
This problem was asked by Apple.
Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
"""
import threading
from time import time
class Scheduler:
def __init__(self):
self.fns = [] # tuple of (fn, time)
# The lock prevents 2 threads from ... |
46b875b6f47af61695c90f1cffc0cba35260f139 | deepakmhr/tensorflow | /linear-regression/linearRegression.py | 1,519 | 4.21875 | 4 | # Import the necessary libraries
import matplotlib.pyplot as plot
import numpy
import pandas
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# Import the dataset
def show():
# Import the dataset
dataset = pandas.read_csv('salaryData.csv')
x = dataset.... |
fe6f842b38db178a402e62d43a68ff93ebbb1b73 | Shulun/target_offer_solutions | /section3/print_list_reverse.py | 407 | 3.65625 | 4 | from utils import construct_linklist, ListNode
def print_list_reverse(head: ListNode) -> list:
stack, h = [], head
while h:
stack.append(h.val)
h = h.next
return stack[::-1]
l1 = (1, 2, 3, 4, 5)
print(l1)
l1 = construct_linklist(l1)
lst1 = print_list_reverse(l1)
print(lst1)
l2 = [3, 4, 8,... |
a12192a0ce835143f89fc42daf5cd05d0f21431f | wind0/min-python-profiler | /timer.py | 4,395 | 3.5 | 4 | import time
import sys
import inspect
import functools
import logging
class TimerError(Exception):
"""Custom Timer Error used to report Timer failures"""
class Timer:
def __init__(self, timing_func = time.perf_counter):
self._timing_func = timing_func
self.aggregated_timers = dict()
... |
90617f05e5ebddf55c560cd6d79df23508159808 | jxy01/Deep-Learning---Group-19---Final-Project | /3.1/Model1.0/ShowPic.py | 746 | 3.5 | 4 | import matplotlib.pyplot as plt
import numpy as np
import cv2
def showpic2(images,i):
# translate into numpy array
flatNumpyArray = np.array(images[0])
# Convert the array to make a 200*200 grayscale image(灰度图像)
grayImage = flatNumpyArray.reshape(200, 200)
# show gray image
cv2.imshow('GrayImag... |
54df58177c178e2da35e35bcf6d5e3bf306c9587 | KanardHeure/RPG | /RPG_combat.py | 1,372 | 3.90625 | 4 | # -*- coding:Utf-8 -*-
####----####----####----####----####
###############IMPORT###############
####----####----####----####----####
def Combat(joueur, monstre):
speed_joueur = joueur.speed
speed_monstre = monstre.speed
while True:
while speed_joueur < 100 or speed_monstre < 100:
... |
0c6f382d0127b3741ba6342ac0ca154703f53f14 | maxfilter/project-rosalind | /Bioinformatics_Stronghold/IEV/iev.py | 873 | 3.71875 | 4 | '''
Calculating Expected Offspring
2019.02.27
Given: Six nonnegative integers, each of which does not exceed 20,000.
The integers correspond to the number of couples in a population possessing each
genotype pairing for a given factor. In order, the six given integers represent
the number of couples having the followin... |
6852757a1145c2d2da16833f884be4a938519548 | wangying2016/Packet_Simulator | /socket c & s/Server1.py | 969 | 3.8125 | 4 | """
Server side
Author: Wang Ying
Last modified: May 21 2019
"""
from socket import socket, AF_INET, SOCK_STREAM
# Create socket
tcpSerSocket = socket(AF_INET, SOCK_STREAM)
# Bind ip & port
address = ('127.0.0.1', 9999)
tcpSerSocket.bind(address)
# Begin listen
tcpSerSocket.listen(5)
while True:
# Receive clien... |
b1f0cc21b2e5934acc93ce74a946570a8884208f | filipeferreira86/python | /.gitignore/listas/lista1.py | 461 | 4.125 | 4 | #Listas 1
lista = [1, 2, 3, 5, 7, 10, 3.4]
print(lista)
print(type(lista))
num = int(input('Digite o numero da lista: '))
print(lista[num])
#Outro jeito
lis1 = list(('Filipe Ferreira de Jesus', 'ola', 88))
print(lis1)
#Para declarar ua lista com parenteses é necessário informar uma virgula no final
lis2... |
9999ee59cf4bae59853becb58fb3a209e140cdef | filipeferreira86/python | /.gitignore/lacos/range.py | 399 | 3.953125 | 4 | #Range tem um sintaxe complicada, sendo inicio e fim, sendo fim não incluido
#O ultimo numero é a quantidade a ser adicionada a cada passada
#Neste caso ele inicia no zero, nossa lista fica com 0, 2, 4, 6, 8
#Isto pq o 10 não entra na lista pois é o ultimo
# neste caso então temos 0, (0+2) 2, (2+2) 4, (4+2) 6, (6+2... |
8aff573135893126d1397df3420a7d5d7c9abe4c | filipeferreira86/python | /.gitignore/lacos/continue.py | 335 | 4 | 4 | #finaliza o ciclo e reinicia do proximo ponto
num = int(input('Digite o numero para pular'))
for i in range(1,11,1):
if(i==num):
continue
print(i)
else:
print('escrevi de 1 a 10 pulando %d'%(num))
t=0
while(t<11):
t+=1
if(t%2==0):
continue
print('Somente impares')
... |
96b9b188418477c3d74180708bbb411faf54873b | filipeferreira86/python | /.gitignore/operadores/aulalog.py | 1,449 | 4.1875 | 4 | login = input('Login: ')
senha = input('Senha: ')
print('Seu login é: {}'.format(login))
# Operadores aritimeticos
# Soma
rsum = 5+2
#subtração
rsub = 5-2
#divisão
rdiv = 5/2
#divisão inteira
rdivi = 5//2
#Resto da divisão
rrest = 5%2
#multiplicação
rmult = 5*2
#potencia
rpot = 5**2
#raiz
rraiz = 5... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.