blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4629c3a610a362fe28b0233587491fad10d13beb | kzd0039/leetcode_problems | /7.py | 448 | 3.859375 | 4 | def reverse(x):
start=str(x)
l=len(start)
result=''
if start[0]=='-':
result='-'
for i in range(1,l):
result=result+start[l-i]
else:
for i in range(l):
result=result+start[l-i-1]
result=int(result)
if result<-2**31 or result>(2**31-1... |
2715456f2e6e64a95cdc920156f7159553c62508 | kzd0039/leetcode_problems | /456.py | 393 | 3.796875 | 4 | def find132pattern(nums):
k=float('-inf')
st=[]
for nm in nums[::-1]: #traversing nums in reverse order
if nm<k:
return True
while st and st[-1]<nm:
k=st.pop()
st.append(nm)
return False
def main():
nums = [3, 1, 4, 2]
ans = ... |
0bbd21a4cd6caaaec69385e1634bfcd8f5e2ca38 | park81/pythonworkspace | /gui_basic/13_scrollbar.py | 666 | 3.515625 | 4 | from tkinter import *
root = Tk()
root.title("Nado GUI")
root.geometry("640x480")
#스크롤 바는 스크롤바와 스크롤바 위젯이 되는것을 하나의 Frame에 넣는것이 관리편하다.
frame = Frame(root)
frame.pack()
scrollbar = Scrollbar(frame)
scrollbar.pack(side="right",fill ="y")
# set이 없으면 스크롤을 내려도 다시 올라옴
listbox = Listbox(frame, selectmode="extended", heigh... |
aaf7dfd1431d14977ec732590a824d3284ccd857 | sundael/python_learning | /chapter1-11/chapter4(操作列表).py | 987 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 9 17:32:00 2019
@author: 13225
"""
magicians=['alice','david','carolina']
for magician in magicians:
print(magician)
#创建数字列表
numbers=list(range(1,6))
print(numbers)
squares=[]
for square in range(1,11):
square=square**2
squares.append(square)
print(square... |
852592bb79d6229c30072d25d600cc3f605e6d79 | myt2000/python-yield-practice | /collections_abc_verified/collections_veified.py | 758 | 3.75 | 4 | # -*- coding: utf-8 -*-
from collections.abc import Set
class ListBasedSet(Set):
''' Alternate set implementation favoring space over speed
and not requiring the set elements to be hashable. '''
def __init__(self, iterable):
self.elements = lst = []
for value in iterable:
... |
a9b9b75dcc9f127823ad1ac639a4bf1d578938ed | myt2000/python-yield-practice | /iter_test/chain_test.py | 270 | 4.0625 | 4 | # from itertools import chain
def chain(*iterables):
# chain('ABC', 'DEF') --> A B C D E F
for it in iterables:
for element in it:
yield element
if __name__ == '__main__':
a = 'ABC'
b = 'DEF'
print(list(chain(a,b))) |
c9c45811c7fcc02213e0a9aa207c29e46ed20aed | tejamarneni/Project-Euler-Problems | /n_prime_pe10.py | 381 | 3.875 | 4 | prime_list = []
def primelist(num):
i = 0
j = 3
while i <= num:
d = 0
for k in range(3,int(j**0.5)+1,2):
if j % k == 0:
d += 1
if d == 0:
prime_list.append(j)
i += 1
j += 2
return prime_list
# prin... |
fdab3c22686662aee7b1c400a19505abd0054abb | RayRayYSR/BU-CS542-MachineLearning | /ps1/rock_paper_scissors.py | 415 | 3.6875 | 4 | '''
After playing with the program online, I realize that the computer can learn my play pattern,
so I use the simplest theory to beat AI. The amazing Random. If the computer would like to
learn my pattern. There is no pattern for it to learn. Let's leave the result to God.
1 represents Rock
2 represents Paper
3... |
2e17aa33413fb859deeee6d1336fb59714cc6bf6 | Rostik-101/Al-mova-python | /pr1/34.py | 494 | 3.78125 | 4 | year = int(input('Введіть рік: '))
if year % 400 == 0:
print("%d Високосний" %year)
elif year % 100 == 0:
print("%d НЕ високосний" %year)
elif year % 4 == 0:
print("%d високосний" %year)
else:
print("%d НЕ високосный" %year)
name = "Козачков Ростислав"
import datetime
print('Автор програми: ' + name)
... |
fc934698fde4019f8ef2d51a32ba670ff6844c98 | Rostik-101/Al-mova-python | /pr1/до завдання 9.py | 498 | 3.921875 | 4 | R = 8.314
P = float(input('Введіть тиск у паскалях: '))
V = float(input('Введіть обєм: '))
T = float(input('Введіть температуру у Цельсіях: '))
K = T + 273.15
n = (P * V) / (K * R)
print('Молярна маса газу: {:.2f}'.format(n))
name = "Козачков Ростислав"
import datetime
print('Автор програми: ' + name)
a = datetime.dat... |
b0351f6408815f469bee7dffdd9f2df0e5213da8 | oolsson/oo_eclipse | /Practise_stuff/numbers/round.py | 173 | 3.65625 | 4 | '''
Created on Dec 28, 2012
@author: oo
'''
A=1.00333
C='NaN'
if type(A)==float:
print round(A,3)
print type(A)
print type(C)
D=[1,2,3]
print max(D)
|
e75c26347ef77834fb955797c69d5595f931b570 | oolsson/oo_eclipse | /Practise_stuff/pandas/df/4.groupings.py | 640 | 3.578125 | 4 | import numpy as np
randn = np.random.randn
import pandas as pd
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : randn(8), 'D'... |
a97da64ceb1d3d2648262cf640723edb781d470c | oolsson/oo_eclipse | /Practise_stuff/nympy_commands/numpy_randomwalk.py | 550 | 3.640625 | 4 | import random
import matplotlib.pyplot as plt
import numpy as np
position = 0
walk = [position]
steps = 100
for i in xrange(steps):
step = 1 if random.randint(0, 1) else -1
position += step
walk.append(position)
print walk
#or
nsteps = 100
draws = np.random.randint(0, 2, size=nsteps)
steps... |
bab58f3bc30716453ae863a1088dfda674b6cc70 | oolsson/oo_eclipse | /Practise_stuff/object/object.py | 412 | 3.9375 | 4 | '''
Created on Jan 29, 2012
@author: oo
'''
#class is the blueprint for objects
class exampleClass():
def __init__(self):
eyes='blue'
self.age=27
print'p'
def m1(self,x):
return x+' is king'
#you need to create an object to acces values in a class
a=exampleClass(... |
bed293350b11d17b76715cdcaf4b3cc014d6b207 | oolsson/oo_eclipse | /Practise_stuff/pandas/df/1.4_np_rows_columns_and_some_arithmetics.py | 1,115 | 3.796875 | 4 | import numpy as np
randn = np.random.randn
#from pandas import *
import pandas as pd
index = pd.date_range('1/1/2000', periods=12)
df = pd.DataFrame(randn(12, 3), index=index,columns=['A', 'B', 'C'])
'''
print '------------print and print transpose'
print df
print df.T
print df.T.to_string()
'''
'''
... |
bd93725de7c6467e82d280d93b6ccf25d6d7af00 | oolsson/oo_eclipse | /Practise_stuff/Unit_test/asserts.py | 1,532 | 3.515625 | 4 | https://docs.python.org/2/library/unittest.html
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertIs(a, b) a is b 2.7
assertIsNot(a, b) a is not b 2.7
assertIsNone(x) x is None 2.7
assertIs... |
b114348958e00351ed47369554824930e47d3484 | oolsson/oo_eclipse | /Practise_stuff/dictionaries/o_d3.py | 220 | 3.59375 | 4 | '''
Created on Jun 7, 2012
@author: oo
'''
A={}
A['test']=[11,22,33,44]
print A['test'][2]
from collections import defaultdict
if 'test' in A:
print "yes"
else:
print 'pp'
print len(A['test']) |
4165561625209f42ef6cf9b1ec9059ec0a262fe5 | BrieannaBenson/csf | /Lab3.py | 1,286 | 4.375 | 4 | # Brieanna Benson
# Lab 3
# Computer Science Foundations
# October 20th, 2013
# assign variables for 'if' check
n = 25
series = 'myon'
# steps to execute if the string is 'fibonacci'
if series == 'fibonacci':
print 'Fibonacci numbers, the ' + str(n) + 'th fibonacci number'
# create space for the ints to ... |
0aab68a1fb29e9632625f8cee9c061415a18f7c8 | unnimannel/Algos | /BinarySearch.py | 708 | 3.96875 | 4 | #find an element in a sorted array using Binary Search
class BinarySearch:
def __init__(self):
pass
def main(self):
inp = [1,23,41,55,67,68,74,85,88,89,92,93,94,99]
num = 92
print("Input List: ",inp," Input Number to search: ",num)
indexx = self.binarysearching(inp,num)
if indexx >= 0:
print(num," fou... |
1dd143534c531f44d965860566c170140667a27c | vanmathi1998/set1 | /3p.py | 103 | 4 | 4 | a=int(input("enter the value:"))
b=int(input("enter the value:"))
for i in range(0,1):
n=a**b
print(n)
|
eefb7ca6c3b18cf8f4f84105648b0b3733bd4485 | newbieeashish/DataStructure_Udacity | /balanced Parantheses.py | 1,200 | 4.5 | 4 | '''
We will be using stacks to make sure the
parentheses are balanced in mathematical expressions such as:
((32+8)∗(5/2))/(2+6). In real life you can see this extend to
many things such as text editor plugins and interactive development
environments for all sorts of bracket completion checks.
Take a string... |
a03801f667ee1a287af4d94e9bd9d62df25b4062 | methermeneus/google_foo_bar | /level_3/save_beta_rabbit/solution.py | 2,371 | 3.75 | 4 | def answer (food, grid):
"""
And this version gives me a memory error instead of a time error. How the
hell do I pare this down?
Notes:
Rabbit can only move left or down, and grid is top-to-bottom,
left-to-right. First element will always be 0 because rabbit starts in
top-left ro... |
e902e5f686883cfbaa323a9620f3fd6ddc8c5bcc | alfredo-svh/DailyCodingProblem | /231.py | 705 | 3.921875 | 4 | '''
Given a string with repeated characters, rearrange the string so that no two adjacent characters are the same.
If this is not possible, return None.
For example, given "aaabbc", you could return "ababac". Given "aaab", return None.
'''
import collections
def rearr(s):
res = ""
c = collections.Counter(s... |
8b087097d5c7ff8c074ecf0a2d1f492eda936091 | alfredo-svh/DailyCodingProblem | /438.py | 1,144 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 22:47:20 2021
@author: Alfredo
"""
# Daily Coding Problem #438
# Problem:
# Implement a stack API using only a heap. A stack implements the following methods:
# - push(item), which adds an element to the stack
# - pop(), which removes and returns the most recently a... |
eb9736f922ec5034ef94798f83a6056dbfe0468b | alfredo-svh/DailyCodingProblem | /254.py | 1,768 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 10 13:23:44 2020
@author: Alfredo
"""
# Daily Coding Problem: Problem #254
# Problem: Recall that a full binary tree is one in which each node
# is either a leaf node, or has two children. Given a binary tree,
# convert it to a full one by removing nodes with only one ... |
f46c8ccfdc78a57f53b6b030a990f5f47ebfb9e5 | alfredo-svh/DailyCodingProblem | /269.py | 1,917 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 25 17:25:38 2020
@author: Alfredo
"""
# Daily Coding Problem #269
# Problem:
# You are given an string representing the initial conditions of some
# dominoes. Each element can take one of three values:
# - 'L', meaning the domino has just been pushed to the left,
# - '... |
171eb5b791ab9d186e84f6b3b16502016934824f | alfredo-svh/DailyCodingProblem | /416.py | 928 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 11:34:26 2020
@author: Alfredo
"""
# Daily Coding Problem #416
# Problem:
# You are in an infinite 2D grid where you can move in any of the 8 directions.
# You are given a sequence of points and the order in which you need to cover
# the points. Give the minimum numbe... |
591b89c2cdb093dbb0db7e3c20a5cd897e8122e1 | alfredo-svh/DailyCodingProblem | /810.py | 1,661 | 4.1875 | 4 | # Daily Coding Problem # 810
# Problem:
# In Ancient Greece, it was common to write text with the first line going left to right, the second line going right to left, and continuing to go back and forth. This style was called "boustrophedon".
# Given a binary tree, write an algorithm to print the nodes in boustrophedo... |
bc2b1f203314c30aa5467078ee21b10f3209953c | alfredo-svh/DailyCodingProblem | /435.py | 2,008 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 17:44:21 2021
@author: Alfredo
"""
# Daily Coding Problem #435
# Problem:
# Given pre-order and in-order traversals of a binary tree, write
# a function to reconstruct the tree.
def helper(po, io):
# the first value in preorder will be our next node
newNo... |
af0088973b1ef016c7ced1a70d59fc132419fd0d | carmensalas14/python-challenge-23012020 | /challenge.py | 484 | 3.640625 | 4 | import math
class Vec:
def __init__(self, x, y):
self.x = x
self.y = y
self.length = math.sqrt(self.x**2 + self.y**y)
def plus(self, newVec):
vec = Vec(self.x + newVec.x, self.y + newVec.y)
return vec
def minus(self, newVec):
vec = Vec(self.x... |
6f20af77d80b18e6dd88de0a2c87156c9fb34903 | WeiS49/Python-Crash-Course | /python_work/ch5/practice/5-4 alien_color2.py | 239 | 3.5625 | 4 |
alien_color = 'yellow'
alien_color2 = 'green'
if alien_color == 'green':
print("True, 5 scores.")
else:
print("False, 10 scores.")
if alien_color2 == 'green':
print("True, 5 scores.")
else:
print("False, 10 scores.")
|
2316110c81471485e3bf137ff8d3cddff1e19640 | WeiS49/Python-Crash-Course | /python_work/ch7/7.3.1 confirmed_users.py | 552 | 3.671875 | 4 |
# 7.3.1
# 在列表之间移动元素
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users: # 当该列表还有数据’‘
current_user = unconfirmed_users.pop()
print(f"Verifying user:{current_user.title()}")
confirmed_users.append(current_user)
# 显示所有已验证的用户
print("\nThe following users have ... |
1d992e66adeb8fac9526adc22433cf676e8e1fbb | WeiS49/Python-Crash-Course | /python_work/ch5/practice/5-6 stages_in_life.py | 217 | 3.859375 | 4 |
age = 18
if age < 2:
print("baby")
elif age < 4:
print("tutor")
elif age < 13:
print("child")
elif age < 20:
print("teenager")
elif age < 65:
print("adult")
else:
print("old people")
|
13b74e54760c8c4123b5c52508012aa29bc5891b | WeiS49/Python-Crash-Course | /python_work/ch10/practice/10-5 investigation.py | 391 | 3.703125 | 4 |
filename = 'python_work/ch10/practice/programming.txt'
reasons = []
reason = ''
while reason != 'quit':
reason = input("Why do you like programming? ")
if reason == 'quit':
break
reasons.append(reason)
with open(filename, 'w') as file:
file.write("Here are reasons why people love programming... |
9d47c7f5e57a71ff5993efb7dcdf5eb6e63e8ed5 | WeiS49/Python-Crash-Course | /python_work/ch4/practice/4-7 three.py | 63 | 3.671875 | 4 |
listx = list(range(3, 31, 3))
for i in listx:
print(i)
|
a0c9dbfa94759370153dfb62266e7ca31c90f829 | WeiS49/Python-Crash-Course | /python_work/ch6/practice/6-4 vocabulary2.py | 309 | 3.546875 | 4 |
vocabulary = {
'test': 'practice',
'python': 'snake',
'C++': 'hard to learn',
'list': 'can save any type of data',
'dictionary': 'json',
'test1': 1,
'test2': 2,
'test3': 3,
'test4': 4,
'test5': 5,
}
for k, v in vocabulary.items():
print(f"{k.title()} : {v}")
|
d348920a498b608ec246a7840244e8a2ecdb95cc | WeiS49/Python-Crash-Course | /python_work/ch6/practice/6-5 rivers.py | 360 | 4.25 | 4 |
rivers = {
'Yellow River': 'China',
'Seine': 'France',
'nile': 'egypt',
}
for river, country in rivers.items():
print(f"The {river.title()} runs through {country.title()}")
print()
for river in rivers.keys():
print(f"Here is {river.upper()}.")
print()
for country in rivers.values():
print(... |
cdae64f027460f3527dad16c292a6f131295c045 | WeiS49/Python-Crash-Course | /python_work/ch6/practice/6-1 people.py | 252 | 3.78125 | 4 |
someone = {
'first_name': 'John',
'last_name': 'Smith',
'age': '24',
'city': 'New York',
}
for i in someone.items(): # items内部元素的存储方式是元组
print(i, type(i))
print(someone.items(), type(someone.items()))
|
ea2ddf67569ac480b523f483062db336bc7e9f4d | WeiS49/Python-Crash-Course | /python_work/ch6/practice/6-9 favorite_place.py | 299 | 3.6875 | 4 |
favorite_places = {
'john': ['Shanghai'],
'mike': ['Beijing', 'Tianjin', 'Shenzhen'],
'cassie': ['Canton', 'Changsha'],
}
for name, place in favorite_places.items():
print(f"{name.title()}'s favorite place are: '")
for location in place:
print(f'\t{location}')
|
a26264b0642731b86583fff935446a207954bae3 | WeiS49/Python-Crash-Course | /python_work/ch7/7.1 age.py | 283 | 3.90625 | 4 |
age = input("How old are you? ") # 这里的结果是字符串类型
print(age, type(age)) # 字符串类型不可以用于数值比较
# 将输入类型转换成整型
# 如果输入的内容非数字, 则报错
age2 = int(input("How old are you? "))
print(age2, type(age2))
|
d9ee8df3aefafe769be8c2eb0846a1ec0da80efd | WeiS49/Python-Crash-Course | /python_work/ch9/9.3.3 electric_car.py | 2,110 | 4.46875 | 4 |
class Car:
""" Initialize property of cars. """
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 直接在初始化函数中创建变量
def get_description_name(self):
""" Return a clean descriptive information. """
... |
62bf07c3f2708fb7c17755eef43e8deaa6868f6c | WeiS49/Python-Crash-Course | /python_work/ch9/practice/9-9 upgrade_battery.py | 3,038 | 4.5 | 4 |
class Car:
""" Initialize property of cars. """
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 直接在初始化函数中创建变量
def get_description_name(self):
""" Return a clean descriptive information. """
... |
7d10895153aafd5c33f47a3d31d5bec11e010243 | WeiS49/Python-Crash-Course | /python_work/ch8/practice/8-8 user_album.py | 939 | 4.15625 | 4 |
def make_album(singer, title, number = None):
""" Print album information and number of songs(optional). """
music_album = {'singer': singer, 'title': title}
if number:
music_album['song_number'] = number
return music_album
while True:
print("\nTell me about album you like")
pri... |
1b0910f83efc8d0a718658e01c61e829eeb1d08d | WeiS49/Python-Crash-Course | /python_work/ch10/practice/calc.py | 418 | 4.03125 | 4 |
def test():
print('hello')
while True:
print("\nPlease enter two numbers. ")
a = input("\nPlease enter the first number. ")
if a == 'q':
break
b = input("Please enter the second number. ")
if b == 'q':
break
try:
a = int(a)
b = int(b)
except Value... |
1e6bae823d509b3d5c8eb26558068cf292a0f68e | spvisal/python_sandbox | /while-loops/Ex-GrowingStrength.py | 458 | 4.09375 | 4 | # The player's power starts out at 5
power = 5
# Player's initial strength
print("The player's intial strength is %d. " % power)
# The player is allowed to keep playing as long as their power is over 10
while power < 10:
print("You are still playing, because your power is %d " %power)
power = power + 1
... |
37b0ad6ca4137683398b693ba8ac4809a5ea9fda | StefankinaO/LeetCode | /1768.py | 377 | 3.578125 | 4 | class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
ans = ''
n = min(len(word1), len(word2))
for i in range(n):
ans += word1[i] +word2[i]
if len(word1) > len(word2):
ans += word1[len(word2):]
if len(word1) < len(word2):
... |
fe8fe9904e22c1df6cd7fd4d4cf67836f236d67e | Ciwonie/Python_Days_of_Code | /4_ai_art_replicate_hirst_and_random_walk/main.py | 1,084 | 4.09375 | 4 | import turtle as t
from turtle import Screen
import random
t.colormode(255)
tut = t.Turtle()
tut.shape("turtle")
turtle_colors = ["CornFlowerBlue", "DarkOrchid", "IndianRed", "DeepSkyBlue", "LightSeaGreen", "wheat", "SlateGray",
"SeaGreen"]
directions = [0, 90, 180, 270]
tut.pensize(15)
tut.speed("f... |
f0c8bb3b990aa6725f0e75784980856efde2490b | benedictpennyinskip/Iteration | /Class Exercises - Selection Statements - Strech Task 3.py | 363 | 3.875 | 4 | #Class Exercises - Selection Statements - Strech Task 3
#Ben penny Inskip
#01/11/2014
binaryNumber = str(input("Please enter an 8bit binary number"))
add = 128
denaryNumber = 0
for counter in range(8):
print(counter)
number = binaryNumber[counter]
if number == "1":
denaryNumber = denar... |
45eb8f38b5149e198e64f404e772e624023c75aa | ucefizi/CodeForcesPython | /PB6a.py | 360 | 4.03125 | 4 | # Problem statement: http://www.codeforces.com/problemset/problem/6/A
x = [int(i) for i in input().split()]
x.sort()
if x[3] < x[2]+x[1] or x[3] < x[2]+x[0] or x[3] < x[1]+x[0] or x[2] < x[1]+x[0]:
print("TRIANGLE")
elif x[3] == x[2]+x[1] or x[3] == x[2]+x[0] or x[3] == x[1]+x[0] or x[2] == x[1]+x[0]:
print("... |
5a66a25695151aec3bd33284ebfa5f12b94a5883 | ucefizi/CodeForcesPython | /PB672a.py | 193 | 3.5 | 4 | # Problem statement: http://www.codeforces.com/problemset/problem/672/A
n = int(input())
if n < 10:
print(n)
else:
strg = ""
for i in range(n+1):
strg += str(i)
print(strg[n])
|
c3a35acd0ca125f76eb58653dd39f17692d5d1fd | Eugene-Arefyev/Lesson2_1 | /lesson2_1improve.py | 1,787 | 3.796875 | 4 | def create_recipe_line(name, quantity, measure):
return {'ingredients_name': name, 'quantity': int(quantity), 'measure': measure}
def get_cookbook_from_file(filename):
cook_book = dict()
with open(filename, "r", encoding="utf-8") as f:
for recipe in f.read().split("\n\n"):
name, count,... |
537d229a19a754f7d4b7afe029335fee6fc95561 | linitachi/LeetCode_Practice | /medium/2.两数相加.py | 1,714 | 3.8125 | 4 | #
# @lc app=leetcode.cn id=2 lang=python3
#
# [2] 两数相加
#
# https://leetcode-cn.com/problems/add-two-numbers/description/
#
# algorithms
# Medium (36.56%)
# Likes: 3876
# Dislikes: 0
# Total Accepted: 319.7K
# Total Submissions: 874.3K
# Testcase Example: '[2,4,3]\n[5,6,4]'
#
# 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按... |
f82601e8262887769c36eb17e2accb5361648654 | linitachi/LeetCode_Practice | /medium/17.电话号码的字母组合.py | 4,027 | 3.53125 | 4 | #
# @lc app=leetcode.cn id=17 lang=python3
#
# [17] 电话号码的字母组合
#
# https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/description/
#
# algorithms
# Medium (52.34%)
# Likes: 586
# Dislikes: 0
# Total Accepted: 79.3K
# Total Submissions: 150.9K
# Testcase Example: '"23"'
#
# 给定一个仅包含数字 2-9 的字符串,返... |
ae657631ecf290d0d488909d8d556f4597abd348 | linitachi/LeetCode_Practice | /hard/25.k-个一组翻转链表.py | 2,252 | 3.8125 | 4 | #
# @lc app=leetcode.cn id=25 lang=python3
#
# [25] K 个一组翻转链表
#
# https://leetcode-cn.com/problems/reverse-nodes-in-k-group/description/
#
# algorithms
# Hard (63.13%)
# Likes: 756
# Dislikes: 0
# Total Accepted: 105.5K
# Total Submissions: 167K
# Testcase Example: '[1,2,3,4,5]\n2'
#
# 给你一个链表,每 k 个节点一组进行翻转,请你返回翻... |
213f2814a2da4800af57884a34bd70a93a376897 | linitachi/LeetCode_Practice | /easy/136.只出现一次的数字.py | 1,197 | 3.5 | 4 | #
# @lc app=leetcode.cn id=136 lang=python3
#
# [136] 只出现一次的数字
#
# https://leetcode-cn.com/problems/single-number/description/
#
# algorithms
# Easy (70.15%)
# Likes: 1587
# Dislikes: 0
# Total Accepted: 297K
# Total Submissions: 422.4K
# Testcase Example: '[2,2,1]'
#
# 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只... |
50ea700b484d706257ab265fe4418341b76a4adf | linitachi/LeetCode_Practice | /medium/162.寻找峰值.py | 1,799 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=162 lang=python3
#
# [162] 寻找峰值
#
# https://leetcode-cn.com/problems/find-peak-element/description/
#
# algorithms
# Medium (47.75%)
# Likes: 322
# Dislikes: 0
# Total Accepted: 63.7K
# Total Submissions: 133.3K
# Testcase Example: '[1,2,3,1]'
#
# 峰值元素是指其值大于左右相邻值的元素。
#
# 给定一个输入数组 nums,... |
a246274eb2fca893ea286382767cf239cd22a1fe | twtrubiks/python-notes | /what_is_the_abstractmethod/demo2.py | 365 | 3.859375 | 4 | import abc
# class A(metaclass=abc.ABCMeta):
class A(abc.ABC):
@abc.abstractmethod
def action1(self):
pass
@abc.abstractmethod
def action2(self):
pass
class B(A):
pass
# 有使用 abstractmethod 一定要實作 action1, action2
b = B()
# TypeError: Can't instantiate abstract class B with abstr... |
615740c9ebc048d0a99315c2b4dc3e4474820725 | twtrubiks/python-notes | /asyico_tutorial/demo8_asyncio.py | 376 | 3.578125 | 4 | # https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for
import asyncio
async def eternity():
# Sleep for one hour
await asyncio.sleep(3600)
print('yay!')
async def main():
# Wait for at most 1 second
try:
await asyncio.wait_for(eternity(), timeout=1)
except asyncio.Time... |
f30375537a363fc34809a671099a1a6e49d1ec4e | twtrubiks/python-notes | /asyico_tutorial/demo1_async_2.py | 806 | 3.859375 | 4 | """
https://docs.python.org/3/library/asyncio.html
asyncio is often a perfect fit for IO-bound and high-level structured network code.
"""
import asyncio
import time
# def 前面加上 async 就會變成 coroutine function (有非同步的功能)
async def something(num):
print('第 {} 任務,第一步'.format(num))
# time.sleep is blocking call.
... |
26f6b8e8e35c2b499e6c255e0ef12c3e2bf3a9ec | twtrubiks/python-notes | /what_is_the_abstractmethod/demo2_fix.py | 384 | 3.71875 | 4 | import abc
# class A(metaclass=abc.ABCMeta):
class A(abc.ABC):
@abc.abstractmethod
def action1(self):
pass
@abc.abstractmethod
def action2(self):
pass
class B(A):
def action1(self):
print('hello action1')
def action2(self):
pass
# 有使用 abstractmethod 一定要實作 a... |
64eb7cf52cc0854fa92219c9316076a82fc6ca3e | twtrubiks/python-notes | /re_tutorial.py | 7,480 | 3.75 | 4 | import re
'''
ref.
https://docs.python.org/3/library/re.html
http://www.runoob.com/python/python-reg-expressions.html
https://goo.gl/cPmofe
使用 re module 之前,先思考一下你的問題是否可以用其他方法解決,
像是 replace , split , translate
'''
if __name__ == "__main__":
'''
re.sub(pattern, repl, string, count=0, flags=0)
'''
... |
44de00867a1ed6a588a741930a7425e1414574ae | twtrubiks/python-notes | /__getattr__tutorial.py | 682 | 3.75 | 4 | """
ref
https://docs.python.org/3/reference/datamodel.html#object.__getattr__
Called when the default attribute access fails with an AttributeError.
Note that if the attribute is found through the normal mechanism,
__getattr__() is not called.
"""
class A:
def __init__(self, name: str):
self.name = name... |
1032f88d725c35c32ef1548aebab7d93152d0245 | twtrubiks/python-notes | /__new__tutorial.py | 602 | 3.515625 | 4 | class A:
def __new__(cls, *args, **kwargs):
print("__new__")
instance = super().__new__(cls, *args, **kwargs)
return instance
def __init__(self):
print("__init__")
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
... |
32b617a4c37567e54cdf50618f227433cedaeeec | twtrubiks/python-notes | /reduce.py | 490 | 4.25 | 4 | # Reduce is a really useful function for performing some computation on a list
# and returning the result. For example, if you wanted to compute the product of a list of integers.
if __name__ == "__main__":
f = lambda a, b: a if (a > b) else b # but PEP-8 recommend use def
f_result = reduce(f, [47, 11, 42, 1... |
0424c57f023ccf6517a423d310db92f52220dd6c | twtrubiks/python-notes | /fibonacci_numbers_tutorial/demo4.py | 242 | 3.75 | 4 | def fib_tail_recursion(num, result, temp):
print('call')
if num == 0:
return result
else:
return fib_tail_recursion(num - 1, temp, result + temp)
if __name__ == '__main__':
print(fib_tail_recursion(5, 0, 1))
|
b4d023831d2ff74764a5211d7d4f42785c0dcbcb | twtrubiks/python-notes | /filter.py | 858 | 4.28125 | 4 | def fn(x):
return x if x > 3 else None
if __name__ == "__main__":
# the filter() method filters the given iterable with the help of
# a function that tests each element in the iterable to be true or not.
# filter(function, iterable)
seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = filter(fn, seq)
... |
4360aec0316747b3f4b0b9eb514e286b52e16a45 | twtrubiks/python-notes | /operator_mul_tutorial.py | 164 | 3.578125 | 4 | from operator import mul
'''
operator.mul(a, b)
Return a * b
'''
# example_1
a, b = 2, 5
print(mul(a, b))
# example_2
print(list(map(mul, [1, 2, 3], [4, 5, 6])))
|
70ef31cf29e8a9e173037c53e40dcedda7021eb2 | twtrubiks/python-notes | /queue_tutorial.py | 1,815 | 3.546875 | 4 | from queue import Queue
# Queue is thread-safe.
# if the operation cannot successfully complete because the queue is either empty (cant get) or full ( cant put).
# The default behavior is to block or idly wait until the Queue object has data or room available to
# complete the operation.
# You can have it raise excep... |
9f149234f70e0bc357909db31691c75e10379f69 | matyasfodor/advent-of-code-solutions | /day_11/task2.py | 1,844 | 3.90625 | 4 | from string import ascii_lowercase
from input_data import input_data
ALPHABET_LENGTH = len(ascii_lowercase)
def string_to_int_list(password):
return [ord(character) - ord('a') for character in password]
def int_list_to_string(password):
return ''.join([chr(number + ord('a')) for number in password])
def ... |
b6ace04bccd23c6726674c7b795292d4cc1bc773 | CvanderStoep/AlgorithmicToolbox | /Dynamic Programming/Maximum Value of an Arithmetic Expression/arithmetic_expression.py | 1,850 | 3.625 | 4 | # python3
import math
def Digits_and_Operators(dataset):
#only positive single digits
#only + - * operators
digits = list(map(int, dataset[::2]))
operators = list(dataset[1::2])
return digits, operators
def doMath(operator, digit1, digit2):
if operator == "*" or operator == "x":
retur... |
af969646e9fb609cda93bad35c12792144c54d95 | lamthuylt/daily-coding-problem | /solutions/3_serialize-deserialize-binary-tree.py | 1,681 | 4.28125 | 4 | """
This problem was asked by Google.
Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
For example, given the following Node class
class Node:
def __init__(self, val, left=None, right=None):
... |
90170cc7086a0f3e596039133894136387d98e97 | RavenDuffy/BeginningVectors | /AsteroidsMechanics.py | 5,691 | 3.75 | 4 | import pygame
import math
import random
class AsteroidsMechanics:
pygame.init()
def __init__(self):
self.WHITE = (255, 255, 255)
self.BLACK = (0, 0, 0)
self.clock = pygame.time.Clock()
self.font = pygame.font.SysFont("monospace", 32)
self.size = self.wid... |
ceaf4a5084a0b3d47776f71c999a3c0dc7dda741 | heleensev/TextGraver | /Textminer/textgraver/regex_genes.py | 3,431 | 3.53125 | 4 | #Funtion to find genes in abstracts with regex additional to the genes from the Uniprot CBB API
import simplejson as json
import re
def get_regex_genes(articles_doc):
#Loading the articles from the json file for gene analysis
articles_doc = json.loads(articles_doc)
articles_doc = articles_doc
#splittin... |
90f033e0abfa58780ca324914b33b114eb09d775 | hughy603/Python_Util | /log_config.py | 6,071 | 3.5 | 4 | """ This modules gives an easy to use logging configuration
class. The goal is to give a logging API like
LogSetup.init_log()
LogSetup.initLog(log_file='myapp.log')
LogSetup.initLog(log_dir='path/to/myapp/', log_file='myapp.log')
Inheritance can add log settings to the default configuration
A custom file handle is u... |
da99815407874adadd28ca4677fbd313f0ee1082 | uuzaix/Practice | /FizzBuzz.py | 247 | 3.96875 | 4 | def print_fizzbuzz_for(i):
if i%3 == 0 and i%5 == 0:
print "FizzBuzz"
elif i%3 == 0:
print "Fizz"
elif i%5 == 0:
print "Buzz"
else:
print i
def fizzbuzz(n):
for i in range(1,n+1):
print_fizzbuzz_for(i)
fizzbuzz(100)
|
11ef5d58dda5cfd5d0af32d4d3e0c7aaee0bbe71 | Keerthana215/Project | /largest.py | 145 | 3.875 | 4 | x, y, z = input().split()
if (x > y) and (x > z):
largest = x
elif (y > x) and (y > z):
largest = y
else:
largest = z
print(largest)
|
b075789647b04d4519cffe67241930c6141c084e | Cleoparra/portfolio | /python/Project05/Project5c.py | 1,673 | 3.75 | 4 | #Cleo Parra CIS 122
#Project5c.py Read the romeo_and_juliet.txt into a word_count dictionary with word to look up.
#http://www.cs.uoregon.edu/Classes/15W/cis122/data/romeo_and_juliet.txt
import urllib.request
def make_word_list(line):
line = line.strip(' ').lower()
clean_line = ""
for letter in line:
... |
1e925085b8dff06947ba41fc952fd804b7407b30 | sirisha143/python-programming | /largest num.py | 209 | 4.15625 | 4 | num1=10
num2=12
num3=24
if(num1>=num2) and (num1>=num3):
largest=num1
elif(num2>=num1) and (num2>=num3):
largest=num2
else:
largest=num3
print("the largest number between num1,num2 and num3 is",largest)
|
ac04d809fb52bbae929ffb0cf60d7b679caa78dd | sirisha143/python-programming | /sum53.py | 100 | 3.53125 | 4 | e=int(input(" "))
total=0
while(e>0):
dig=e%10
total=total+dig
e=e//10
print(" ",total)
|
5f1e5589adf0058baead3a4b21666576fa1463e5 | iOS-CSPT7/Data-Structures | /singly_linked_list/singly_linked_list.py | 1,309 | 3.890625 | 4 | class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
class LinkedList:
def __init__(self):
s... |
671befe93ca815ef45a12bd5f8e5b59ec303bdbb | itsatrap1/Analog-clock- | /Ceas.py | 2,002 | 3.53125 | 4 | import turtle
import time
from time import strftime
screen = turtle.Screen()
screen.setup(600, 600)
screen.tracer(0)
screen.bgcolor("black")
# Clock features
clock = turtle.Turtle()
clock.speed(0)
clock.pensize(4)
clock.pencolor("green")
def mid_dot(circle):
circle.goto(0, 0)
circle.dot(... |
33b7aec2a2e39ef5f5ab7b7bf41ad5d4bb477abb | tryko/learning-python | /codewars/ky6_missing_letter.py | 219 | 3.890625 | 4 | # ["a","b","c","d","f"] -> "e"
# ["O","Q","R","S"] -> "P"
def find_missing_letter(chars):
for x in range(1, len(chars)):
if ord(chars[x]) - ord(chars[x - 1]) != 1:
return chr(ord(chars[x]) - 1) |
fe6cbf427da000a4b9c494d25c54a584a2cc6689 | tryko/learning-python | /codewars/ky7_str_compare.py | 327 | 3.890625 | 4 | def solution(string, ending):
sub_str = string[len(string) - len(ending):]
return sub_str == ending
# def solution(string, ending):
# return string.endswith(ending)
# solution = str.endswith
print(solution('abcde', 'cde')) # true
print(solution('abcde', '')) # true
# 'sensei', 'i'
print(solution('sensei'... |
49220ec3cec285302b0b098214be47558fb27c92 | Goddess-Coder/Selection-Sort | /12a.Selection Sort.py | 724 | 4.09375 | 4 | def selectSort(this_arr):
arrLength = range(0, len(this_arr)-1)
print("given array is ", this_arr)
for a in arrLength:
lowestNum = a
for x in range (a+1, len(this_arr)):
if (this_arr[x] < this_arr[lowestNum]):
# print("index value is ", lowestNum, " before ... |
50b9a950048930d40a094f3c688cffdab6776b1c | will-jac/sskm | /data/sphere.py | 1,618 | 3.5625 | 4 | import numpy as np
import util
# generates two classes for binary classification
# the classes are overlapping circles
rng = np.random.default_rng()
#Get a random point on a unit hypersphere of dimension n
def random_hypersphere_point(d, n, r=1, m=0, sd=1):
# fill a list of n normal random values
points = rn... |
bac5310ef527750c0b25467343c294cbe1ea0d7a | Mistborn/connect4 | /connect4.py | 13,264 | 3.953125 | 4 | #! /usr/bin/python3
"""A program to play connect4. Yay!"""
import time
import random
import re
import sys
from random import choice
class Board(list):
"""A board for playing connect4."""
def __init__(self):
# Initialize empty board
for row in range(6):
self.append([' ', ' ', ' ', ' ', ' ', ' ', ' '])
... |
9ee5103b7dc29c169bef41be524b87ff7ebf2150 | dileepuday/task1_mycaption | /area.py | 150 | 4.25 | 4 | n=int(input('Input the radius of the circle: '))
pi=float(3.14159265)
area=(pi*(n**2))
print('The area of the circle with radius', n ,'is :', area)
|
7245305b6d33236f1dd28be52f7eddd01bfe96aa | alfredgamulo/google-code-jam | /python/jams/util/string.py | 443 | 3.9375 | 4 | def is_palindrome(s):
return str(s) == str(s)[::-1]
'''
>>> "blue,red,green".split(',')
['blue', 'red', 'green']
for c in "string":
#do something with c
>>> for i, c in enumerate('test'):
... print i, c
...
0 t
1 e
2 s
3 t
>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r',... |
de0388559dcbe38a79895447d220f185d61c8753 | 3ximus/project-euler | /problems/p085.py | 451 | 3.78125 | 4 | def how_many_fit(small_side, big_side):
# how many small sides fit on one big size
return big_side - small_side + 1
def how_many_squares(w, h):
c = 0
for i in range(1, w+1):
for j in range(1, h+1):
c += how_many_fit(i, w) * how_many_fit(j, h)
return c
erro = 100
for i in range(100):
for j in range(100):
... |
072944998972ef06a98b3083dcdc116b14f07713 | 3ximus/project-euler | /problems/p039.py | 408 | 3.609375 | 4 | """TODO Should be optimised"""
p_max = 1000
def get_solutions(number):
solutions = 0
for i in range(1, int(number/3)):
for j in range(i, i + int(number/3)):
if (number - i - j)**2 == i**2 + j**2:
solutions += 1
return solutions
max_solutions = 0
number = 0
for i in range(p_max, 1, -1):
s = get_solution... |
f161bcdad897ba00cc17aad992a6853aa032df77 | misssoft/Fan.Python | /src/exceptional.py | 184 | 3.65625 | 4 | """A module for demonstrating exceptions"""
import sys
def convert(s):
'''convert to a integer'''
try:
return int(s)
except (ValueError, TypeError):
raise |
42e0d1e605ca4741307d55cb486989017e49d090 | Kaushik8511/Competitive-Programming | /Trees/rightViewOfTree.py | 1,052 | 4.09375 | 4 | class Node:
def __init__(self,key=None,left=None,right=None):
self.key = key
self.left = left
self.right = right
#using level order traversal
#idea is to make level order traversal and print node if its a last node of level
def rightView(root):
if ... |
1f136e9c4ad62ae63a28a0f1f82357333b167b02 | Kaushik8511/Competitive-Programming | /Codevita/Compiler design.py | 1,431 | 3.609375 | 4 | def solve(s):
error = "Compilation Errors"
noError = "No Compilation Errors"
if len(s)<2:return error
if s[0]!='{' or s[-1]!='}':return error
main = 0
ismain = False
isfun = False
st = []
stm = 0
# {, }, (, ), <, >
for i in range(len(s)):
if s[i]==" ":co... |
9d11bf0733962adffdfa9a18d2134f8559a1cccc | Kaushik8511/Competitive-Programming | /Bit Manipulation/convert A to B.py | 278 | 3.78125 | 4 | # A or X==B find how many X's are there which satisfy the condition
a = 10
b = 11
def fun(a,b):
count=1
while a or b:
if a&1:
if b&1:count*=2
else:return 0
a=a>>1
b=b>>1
return count
print(fun(a,b))
|
d532bf49808fefd2b999a2292df7c2ee841ba5b6 | Kaushik8511/Competitive-Programming | /Trees/levelOrderTraversal.py | 711 | 3.859375 | 4 | class Node:
def __init__(self,key=None,left=None,right=None):
self.key = key
self.left = left
self.right = right
def LevelOrder(root):
if root is None:
return
queue = [root]
while queue:
curr = queu... |
dd30a35d6f525d4e7606e4998990271c1b10eaba | Kaushik8511/Competitive-Programming | /Trees/levelOrderTraversal(Reverse).py | 780 | 3.6875 | 4 | class Node:
def __init__(self,key=None,left=None,right=None):
self.key = key
self.left = left
self.right = right
def RLevelOrder(root):
if root is None:
return
q = [root]
s = []
while q:
... |
3a8bb3bd7e84cacbc609b28e71ac39b3cde1fa9b | Kaushik8511/Competitive-Programming | /Codevita/Prime fibonacci.py | 1,161 | 3.546875 | 4 | prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
def find_prime(left,right):
start,end = 0,len(prime)-1
while start<=end and prime[start]<left:start+=1
while end>=start and prime[end]>right:end-=1
return prime[start:end+1]
def isPrime(n):
... |
f65e3f3e1febdad08afc1bb24a6a4bca7cd16a81 | Kaushik8511/Competitive-Programming | /Graph algos/Topological sort.py | 860 | 3.625 | 4 | def visit(source,pre,visited,result):
visited[source-1]=True
if source in pre:
for i in pre[source]:
if not visited[i-1]:
visit(i,pre,visited,result)
result.append(source)
n = int(input("enter number of vertices :... |
cfc347ccdd53418afdb9ff6534307e4d7f2045ed | Kaushik8511/Competitive-Programming | /String/string matching-1(Trie DS).py | 1,033 | 3.859375 | 4 | #return if s is substring of t or not
s = "wehngsdndsuhrouabfden"
t = "fefuafidajigffjakiogteiajndangfoitjwehngsdndsuhrouabfdenjfauhfuweyhujafsdnfabfded"
class TrieNode:
def __init__(self):
self.end = False
self.child = [None for i in range(26)]
class Trie:
def __init__(self):
... |
826f4a11dc10ef10dbda2fed5da036af80b17fbf | Kaushik8511/Competitive-Programming | /Trie/Trie implementation.py | 1,421 | 3.984375 | 4 | class TrieNode:
def __init__(self):
self.count=1
self.end=0
self.child = [None for i in range(26)]
class Trie:
def __init__(self):
self.root=TrieNode()
def insert(self,s):
ptr = self.root
for char in s:
ind=ord(char)-ord('a')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.