blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a286c9a7738692d108c4d0a67819d6223cfc7e47 | mia2628/Python | /Basic/Calculate.py | 534 | 4 | 4 | def plus(a, b):
if a !== int():
a = int(a);
if b !== int():
b = int(b);
return a + b;
a_plus = plus(2,3)
print(a_plus)
def minus(a, b):
return a - b;
a_minus = minus(2,3)
print(a_minus)
def time(a, b):
return a * b;
a_time = time(2,3)
print(a_time)
def division(a, b... |
f14a54399443304fe756678209508f0bd1f1927e | mia2628/Python | /Machine_Learning/1.Pythonic Code/List comprehension.py | 238 | 3.59375 | 4 | case_1 = ["A", "B", "C"]
case_2 = ["D", "E", "F"]
result = [a+b for a in case_1 for b in case_2]
print(result)
case_1 = ["A", "B", "C"]
case_2 = ["D", "E", "F"]
result = [[a+b for a in case_1] for b in case_2]
print(result)
|
25cf753adb357b7437e6aa510df9f065623874ab | RahulRwt125/Classwork | /Pangram.py | 332 | 3.8125 | 4 | x=[]
s=[chr(j) for j in range (97,123)]
s=set(s)
a=input("Enter a string : ")
a=a.lower()
a=set(a)
for i in a:
if i in s:
x.append(i)
if (len(x)==26):
print("\n\nThe string is a Pangram.")
else:
print("\n\nThe string is not a Pangram.")
t=input("\n\n\nPress any key to terminate the pr... |
9c9bbeeaa4e8f07aaa5c509239bb9729ee7aa205 | RahulRwt125/Classwork | /UPPERLOWER.py | 286 | 3.703125 | 4 | b=[]
c=[]
a=input("Enter a word : ")
for i in a:
if(i.isupper()):
b.append(i)
elif (i.islower()):
c.append(i)
print("\n\nNumber of uppercase letters: ",len(b))
print("\nNumber of lowercase letters: ",len(c))
o=input("\n\n\nPress any key to exit.") |
01ffbe46cab7dffc22271c784c6fe408624aaa98 | yiqiufeng/test | /python002.py | 554 | 3.8125 | 4 |
#华氏温度与摄氏温度转换
C=input("请输入摄氏温度(数字):")
f=((int(C)*9)/5)+32
F = str(f)+"F"
print("华氏温度:%s"%F)
#输入圆的半径计算周长和面积
r=int(input("请输入圆的半径(m):"))
L1=2*3.14*r
L=str(L1)+"m"
s=3.14*r**2
S=str(s)+"m²"
print("圆的周长为:%s"%L)
print("圆的面积为:%s"%S)
#判断年份是否为闰年
T=int(input("请输入年份(数字):"))
y=T%4
if y==0:
print("您输入的年... |
6be3ad884fe9e9b68a783038a5924bec24628c95 | mousemgr/EjerciciosProgramacion | /Programas Python/EjemploWhile3.py | 205 | 4.03125 | 4 |
while True:
linea = input(">>")
if linea == "fin":
break #rompe ciclo While
if linea[0] == "#":
continue #Salta a la siguiente iteracion
print(linea)
print("Terminado") |
35f99851174b5f6b60ef3f054a2a80c846977415 | Diogo1457/EncryptAndDecrypt | /encrypt/utils/utils.py | 3,707 | 3.625 | 4 | try:
from config.config import *
import os
except Exception as e:
print("[EXCEPTION] ", e)
exit()
class File():
def exits(filename):
"""
:param filename: filename
:return: bool
verify if the file exist
"""
try:
a = open(fi... |
24f0ce9a73c8405ecd98c46e46ef869729e6d373 | pcho1967/CUHK-GNBF5010 | /Python assignment/Fib/FibPython.py | 437 | 3.515625 | 4 | import Fib
#----------------------------------------------------------------------
if __name__ == "__main__":
import sys
print sys.argv
algorithim = sys.argv[1].lower()
valFib = int(sys.argv[2])
if algorithim == "si":
Fib.SimpleIteration(valFib)
elif algorithim == "sr":
print Si... |
5a8ff5865ad3a305ff2539aff244c5b590d1dc21 | Stting14/test02 | /dog.py | 3,345 | 3.796875 | 4 | #age=int(input("请输入你家狗狗的年龄:"))
#input("")
#if age<0:
# print("你是在逗我吗?")
#elif age==1:
# print("相当于11岁的人")
#elif age==2:
# print("相当于22岁的人,")
#elif age>2:
# human=11+(age-2)*11
# print("相当于人的年龄:",human)
#print("点击Enter建退出")
#程序演示==操作符
#print(5==6)
#使用变量
#x=5
#y=6
#print(x==y)
#n=100
#sum=0
#counter=... |
c842a2f8aa036a72e97234d0e32d35689ff251cb | Stting14/test02 | /test18.py | 496 | 3.828125 | 4 | # -*- coding: UTF-8 -*-
# Filename : test18.py
# author by : STT
#定义函数
def lcm(x,y):
#获取最大的数
if x>y:
greater=x
else:
greater=y
while True:
if ((greater%x==0)and (greater%y==0)):
lcm=greater
break
greater+=1
return lcm
#获取用户输入
num1=int(in... |
fbbb975fe1d6ee4b82b783023ef9bfb572c87dd8 | Stting14/test02 | /test37.py | 691 | 3.78125 | 4 | def factorial(n):
result=n
for i in range(1,n):
result *=i
return result
number=int(input('请输入一个数字:'))
result=factorial(number)
print('%d 的阶乘是: %d'% (number,result))
def factor(n):
if n==1:
return 1
else:
return factor(n-1)*n
number=int(input('请输入一个正整数:'))
re... |
81ce31771b9d92f38a70f839eaf9ea7a22381c7f | Yaphel/py_interview_code | /剑指OFFER/算法和数据操作/查找和排序/排序/桶排序.py | 456 | 3.71875 | 4 | def bucket_sort(arr,start,end,bucketnumber):
bucket=[]
for i in range(bucketnumber):
bucket.append([])
piece=(end-start)//bucketnumber
for i in arr:
point=(i-start)//piece
bucket[point].append(i)
rtn=concat_bucket(bucket,bucketnumber)
return rtn
def concat_bucket(bucket,bucketnumber):
rtn=[]... |
69364978465689d056bf2597b23106945bb8bef8 | Yaphel/py_interview_code | /剑指OFFER/二叉搜索树转双向链表.py | 2,416 | 3.84375 | 4 | #要求是不占用额外空间
#可记录重复数字的二叉排序树
class Tnode(object):
def __init__(self,data):
self.data=data
self.count=1
self.lc=None
self.rc=None
self.next=None
self.prev=None
def constructor(arr):
arr_len=len(arr)
root=Tnode(arr[0])
for i in range(1,arr_len):
constructor_slave(arr[i],root)
return ... |
18e21b0c204800069067b59ddad3cb5559c22d21 | Yaphel/py_interview_code | /剑指OFFER/算法和数据操作/查找和排序/查找/顺序查找.py | 396 | 3.578125 | 4 | #最简单的查找,On
def normal_find(arr,data):
arr_len=len(arr)
for i in range(arr_len):
if arr[i]==data:
return "found: "+str(data)+" in "+str(i)
return "not found "+ str(data)
import unittest
class MyTest(unittest.TestCase):
def test_01(self):
print(normal_find([1,2,3,4,5],3))
print(normal_fin... |
51c3a41f1eb4f105053fbf40cfe79e04ad26f899 | Yaphel/py_interview_code | /剑指OFFER/二叉搜索树的后序遍历序列(有点问题).py | 504 | 3.84375 | 4 | def check_is_sort_tree(arr):
if len(arr) is 1 and 0:
return False
a=len(arr)-1
flag=0
cut_point=a
for i in range(a-1):
if arr[i]>arr[a]:
flag=1
cut_point=i
elif flag is 1 and arr[i]<arr[a]:
return "error input"
elif arr[i] is arr[a]:
return "error input"
if cut_point ... |
d5048fe2e7f67275d0da6772d7e9a56668552762 | Yaphel/py_interview_code | /剑指OFFER/树/树的前序遍历(递归and非递归).py | 1,990 | 3.921875 | 4 | #链表实现树的前序遍历(非递归)
class Node(object):
def __init__(self,data,next = None):
self.data = data
self.next = next
self.flag = 0 #记录被访问的变量
def push(node):
self.next = node
class TNode(object):
def __init__(self,data,lc = None,rc = None):
self.data = data
self.lc = lc
self.rc = rc
#构造... |
b0533dbf145f6e03e60a275c10f8b769039404fe | Yaphel/py_interview_code | /剑指OFFER/算法和数据操作/查找和排序/排序/堆排序.py | 803 | 3.84375 | 4 | def heap_constructor(arr):
#解决树的序号和数组开头的问题。
arr_len=len(arr)-1
i=arr_len//2
while i>0:
arr=heap_constructor_slave(arr,i)
if i*2 <= arr_len//2:
arr=heap_constructor_slave(arr,i*2)
if i*2+1 <= arr_len//2:
arr=heap_constructor_slave(arr,i*2+1)
i-=1
return arr
def heap_construct... |
84766da96111660bef71f8da34654d67ea5b3b26 | Yaphel/py_interview_code | /剑指OFFER/字符串/替换空格.py | 364 | 3.734375 | 4 |
def repeat_number_divide(str1): #Onlogn O1
rtn=''
str_len=len(str1)
for i in range(str_len):
if str1[i]==' ':
rtn=rtn+'!!SPACE!!'
else:
rtn=rtn+str1[i]
return rtn
import unittest
class MyTest(unittest.TestCase):
def test_01(self):
print(repeat_number_divide('hello everyone'))
if... |
d491064d30f01ab55b30004c1accdf026235f5ad | DongOP/Automated-Testing | /Useful Previous/练习/insertionSorting.py | 420 | 3.765625 | 4 | #coding=utf-8
"""
Insertion Sorting
"""
l = [4,1,9,13,34,26,-10,7,-4]
def insert_sort(l):
for i in range(len(l)):
min_index = i
for j in range(i+1,len(l)):
if l[min_index] > l[j]:
min_index = j
tmp = l[i]
l[i] = l[min_index]
l[min_index] = tmp
... |
e497f53936d3e76c177269c211400f642130ddc6 | SQLSJX/Kaikeba-AI-Homework | /tetet.py | 3,129 | 3.65625 | 4 | '''
a = [1,2,3,4,5,6,7,8]
b = [3,5]
def Arr_split(a,b):
num_arr1 = []
num_arr2 = []
num_arr3 = []
for i in a:
num_arr1.append(i)
#print(num_arr1)
if num_arr1[-1] in b:
num_arr1.pop()
#b.pop(0)
num_arr2 += [num_arr1.copy()] # 可变对象赋... |
8e4a3b44c8b1f97cf0336292cfd4268f0764cd9f | rmaso/hokimi | /torneos/pyhparser/cleaner.py | 1,570 | 3.734375 | 4 | #This file contains all the functions that are used to parse the input file or text
import re
regexComment = r"\#.*?$"
regexCommentReplacement = ""
regexDuplicateWhitespace= r"([\r\t\f ])+"
regexDuplicateParagraphs= r"([\v\n])+"
regexWhitespaceLeftBracket = r"({)[\r\t\f ]*"
regexWhitespaceRightBracket = r"[\r\t\f ]*... |
163e4fa3eb9175f18dbf949f58e475bcb5b8bcfa | sagar8080/Algorithms | /DFS.py | 1,158 | 3.765625 | 4 | import re
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
return
def insert_elements(input_sequence, root, index):
length_of_sequence = len(input_sequence)
if index < length_of_sequence:
temp_root = Node(input_sequence[inde... |
2d94d167b8a2056b2b693c0b1fc3ae9ed2a26285 | sagar8080/Algorithms | /Sort/quick_sort.py | 1,002 | 4.375 | 4 | # Implement Quick Sort
def quicksort(input_sequence):
# If there are less than or 1 element in the list return the list as is
if len(input_sequence) <= 1:
return input_sequence
# Else fix pivot as the mid position
pivot = input_sequence[len(input_sequence) // 2]
# Sort elements to the left o... |
bb82660c60a1ac8bf2ae9f7dba5306b325f3dfa0 | sagar8080/Algorithms | /Search/Interpolation_Search.py | 774 | 4.03125 | 4 | # Implement interpolation search
def interpolation_search(input_sequence, key):
start = 0
end = len(input_sequence) - 1
while input_sequence[end] != input_sequence[start] and key >= input_sequence[start] and key <= input_sequence[end]:
mid = int(
start + ((key - input_sequence[start]) * ... |
702597683d63e56cf55669fcc47ef712bcae6c70 | sagar8080/Algorithms | /Trees/Breadth_first.py | 1,922 | 4.15625 | 4 | # Implement breadth first traversal in a graph
from collections import defaultdict, deque
# initialize graph class
class Graph:
def __init__(self, directed=False):
self.graph = defaultdict(list)
self.directed = directed
# function to add edge
def add_edge(self, source, dest):
self.graph[... |
0e1f21bd2e3a08a6e67d4a4d7cc6dbd130ef181e | sagar8080/Algorithms | /Trees/Fenwick_Tree.py | 1,423 | 3.875 | 4 | def update(index, value, array, fenwick_tree):
while index < len(array):
fenwick_tree[index] += value
index += index & -index
# function to calculate sum of elements from beginning to the index in the binary index tree
# return sum of elements from beginning till index
def get_sum(index, fenwick_tre... |
9785dd8356a56698f0511ec77fc7b8dc448cb470 | sagar8080/Algorithms | /Uncategorized/rain_terraces.py | 1,164 | 4.03125 | 4 | # implement rain terraces
def tap_water(input_sequence, length):
# initial water that is trapped
tapped = 0
# max bar length on left and right
left_bound = 0
right_bound = 0
# indices to traverse the array
left = 0
right = length - 1
while (left <= right):
if (input_sequence[... |
aae95d31b185b52a33474ed7918e79cec554ef6d | stringertheory/computer-art | /text/pang.py | 1,759 | 3.53125 | 4 | #!/usr/bin/env python
import sys
import math
import cairo
import pangocffi as pango
import pangocairocffi as pc
RADIUS = 150
N_WORDS = 10
FONT = "Serif 27"
def draw_text(cairo_ctx):
# Center coordinates on the middle of the region we are drawing
cairo_ctx.translate(RADIUS, RADIUS)
# Create a Pango Conte... |
6efc71a7f6aca4d3768506b4d03baf7dfcccacad | hoanhp/Codewar-funs | /RGB_to_HEX.py | 360 | 3.6875 | 4 | def rgb(r, g, b):
result = ''
for i in (r,g,b):
if i in range(0,256):
result += format(i,"02X")
else:
if abs(i-0) > abs(i-255):
result += "FF"
else:
result += "00"
return result
print rgb(255, 255, 255) # returns FFFFFF
print rgb(255, 255, 300) # returns FFFFFF
print rgb(0,0,0) # returns 000000... |
a017162129f3708feffbc0b3decb2b099ae520d3 | friosl/ST0247-032 | /laboratorios/lab03/codigo/Exercise1.py | 1,186 | 3.53125 | 4 | from sys import maxsize
def shortest(graph, initial, final):
minimum = [maxsize]
visiteds = dict()
shortestAux(graph, initial, final, minimum, visiteds )
return minimum[0]
def shortestAux(graph, actual, final, minimum, visiteds):
sucessors = graph.getSuccessors(actual)
visiteds[actual] = True
... |
ccb2f2dc4897f3c086852f17001e5d04469f397d | kaushikreddie/learning | /identity and membership operrator.py | 121 | 3.6875 | 4 | a='tv'
b='ac'
#identity operator
print(a is b)
print(a is not b)
#membership operator
print('t' in a)
print('a' not in b) |
eca4d574d4c2e2ab58d740613f553b9f42dbb573 | luciorgomes/py_the_santo | /backup_to_zip.py | 2,233 | 3.765625 | 4 | import os
import zipfile
import datetime
from tkinter import filedialog
def define_diretorio():
'''chama o filedialog do Tkinter para definir o diretório'''
folder = filedialog.askdirectory()
return folder
def executa_backup(folder):
'''Faz backup do conteúdo do 'folder' em um arquivo Zip.'''
# De... |
934213decd8d1432c799974471d017a67603f142 | TariniS/Python-TariniSrikanth | /practice if statements.py | 292 | 4 | 4 | print(" give me a number")
num1=input()
print ("give me another number")
num2= input ()
if (int(num1) > int(num2)):
print (num1 ," is greater than ", num2)
elif (num2 > num1):
print ( num2 , "is greater than ", num1)
else:
print (num1, "is equal to" ,num2)
|
c7147fee4551f1821daff149cf82ac7f3919b825 | marczalik/discrete-math | /gcd.py | 329 | 3.890625 | 4 | # Calculates the greatest common divisor of 2 integers
def gcd(a, b):
"""
a: positive integer
b: positive integer
Returns the greatest common divisor of a and b
"""
x = a
y = b
while y != 0:
r = x % y
x = y
y = r
return x
print(gcd(41... |
1ff4365b74521bd8a0a702b115e41657ba81a948 | Meet0037/PythonMiniProjects | /#10 Url shortener app using tkinter-python/Url_shortener(#10).py | 754 | 3.5 | 4 | from tkinter import *
import tkinter.ttk as ttk
from ttkthemes import ThemedTk
from tkinter import messagebox
import pyshorteners
import webbrowser
def logic():
s = pyshorteners.Shortener()
a = s.tinyurl.short('www.google.com')
messagebox.showinfo("This is your URL",a)
def callback():
url = "www.... |
e2d1a2be53fab0a8b71ab7179b12cc2c8e2ed79b | ashok1230/temp_con | /converter.py | 657 | 3.859375 | 4 | class converter:
def __init__(self):
change="Enter f for fahrenheit to celsius change or c to celsius to Fahrenheit"
ch=raw_input(change)
choice=ch.lower()
try:
if choice=='f':
for_heit=float(raw_input("enter fahrenheit temperature"))
con=(for_heit-32.00)/1.8
... |
7831b5f9ad08ce9ebabf0f1c16f697e86a934732 | tolumyckel/python_scripts | /gis_work/work1/PhoneUtils.py | 2,249 | 4.0625 | 4 | #-------------------------------------------------------------------------------
# Name: Module name
# Purpose: Brief desciption of what module does
# Usage: Module name and required/optional command-line parameters (if any)
# Author: Your name(s)
#
# Created: 21/10/2016
#---------------------... |
86fba686b2dea688d9cb50923f398dacac40f607 | tolumyckel/python_scripts | /sorting_alogirthm/bubblesort.py | 619 | 4.1875 | 4 | import random
def bubbleSort(my_list):
swapped = True
while swapped:
swapped = False
for i in range(len(my_list)-1):
if my_list[i] > my_list[i+1]:
my_list[i], my_list[i+1] = my_list[i+1], my_list[i]
print("Swapped: {} with {}".format(my_list[i], my_li... |
1e2ecca8879405e6dd70ec2be705b9a523db7400 | tolumyckel/python_scripts | /gis_work/work3/scripts/gis/FileUtils.py | 1,093 | 3.703125 | 4 | # -*- coding: UTF-8 -*-
# ------------------------------------------------------------------------------
# Name: exercise_template.py
#
# Purpose: Brief desciption of what module does
#
# Usage: Module name and required/optional command-line parameters (if any)
#
# Author: Your name(s)
#
# Created... |
34460ec60e5777683e1d7f03be98f6c089e91604 | FarzanehTh/Data-structures | /LL.py | 8,288 | 4.03125 | 4 | """ Node and LinkedList classes """
class LinkedListNode:
"""
Node to be used in linked list
=== Attributes ===
@param LinkedListNode next_: successor to this LinkedListNode
@param object value: data this LinkedListNode represents
"""
def __init__(self, value, next_=None):
"""
... |
573ffe583862a13e1f15ff1231abef4a4ee5b1a7 | Aryan810/HelloWorld | /strings2.py | 1,430 | 3.9375 | 4 | # 432109876543210
# 01234567890123
parrot = "Norwegian Blue"
print(parrot[0:8:2])
print(parrot[0:8:3])
print(parrot[0:8:4])
number = "7:999;555.666,333-222,111"
separators = (number[1::4])
print(separators)
values = "".join(char if char not in separators else " " for char in number).split()
print([i... |
ca960b06b0e6f9082e23e5ff3bbe00b0a8a16235 | JavierLeonAlcantara/Tarea-02 | /auto.py | 482 | 3.8125 | 4 | #encoding: UTF-8
# Autor: Javier León Alcántara , A01745532
# Descripcion: Calcula distancia y tiempo
velocidad = float(input("Escriba la velocidad en km/h"))
distancia_6 = (velocidad*6)
distancia_10 = (velocidad*10)
tiempo_500 = (500/velocidad)
print("La distancia en km. que recorre en 6 horas es : ",distancia_6, ... |
66725669030eb594931cb73949c818271cd3a84a | mchendil82/Python_progs | /call_magic_method_sample.py | 514 | 3.84375 | 4 | #Implementing the __call__ magic method in a class causes its instances to become callables -- in other words, those instances now behave like functions. You can use the built-in function callable to test if a particular object is a callable (callable returns True for functions, methods, and objects that have __call__)... |
11a368d4fecc89b4f0cf2130c329407050735df2 | mchendil82/Python_progs | /first_class_function_and_decorators/logging_example_for_decorator.py | 3,530 | 3.578125 | 4 | #This is use case of decorator to track how many function is called using decorator
#We call display function and decorator first_logger_func_decorator function calls and record how many time it is called by creating
#in the name of calling function... here it will create logs under "logs/display_info.log"
from functo... |
894f68d59177cf1cb2060b6eb2ec82b5b6f0a75f | riccardopizzi/clean_code | /src/utils/json_utils.py | 548 | 4.0625 | 4 | import json
def read_json(file):
"""
Wrapper function to read json file into a python dictionary
:param file: path to json file
:return: content of json file (type: dict)
"""
with open(file, encoding="utf-8") as f:
data = json.load(f)
return data
def save_json(dict_object, file)... |
f894782699e03aee5608539fbdc9baf901902d3c | sterbinsky/APSpyLecture5 | /lecture5_lib.py | 3,810 | 3.75 | 4 | '''
library of functions used in APS 2016 Python lecture 5
.. autosummary::
peak_position
center_of_mass
fwhm
'''
def _get_peak_index(y):
'''
report the index of the first point with maximum in y[i]
:param [float] y: array (list of float) of values
:return int: index of y
'''
... |
4f9c2ee1a290ca80a90778d3b5e6ea4f46c646a6 | leesen934/leetcode_practices | /20. 有效的括号.py | 1,635 | 3.671875 | 4 | # 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
#
# 有效字符串需满足:
#
# 左括号必须用相同类型的右括号闭合。
# 左括号必须以正确的顺序闭合。
# 注意空字符串可被认为是有效字符串。
#
# 示例 1:
#
# 输入: "()"
# 输出: true
# 示例 2:
#
# 输入: "()[]{}"
# 输出: true
# 示例 3:
#
# 输入: "(]"
# 输出: false
# 示例 4:
#
# 输入: "([)]"
# 输出: false
# 示例 5:
#
# 输入: "{[]}"
# 输出: true
class Solution:
def ... |
467e83be47ce56be8b703c2d96020732b4f7b029 | leesen934/leetcode_practices | /695. 岛屿的最大面积.py | 2,977 | 3.609375 | 4 | # 给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个
# 边缘都被水包围着。
#
# 找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)
#
# 示例 1:
#
# [[0,0,1,0,0,0,0,1,0,0,0,0,0],
# [0,0,0,0,0,0,0,1,1,1,0,0,0],
# [0,1,1,0,1,0,0,0,0,0,0,0,0],
# [0,1,0,0,1,1,0,0,1,0,1,0,0],
# [0,1,0,0,1,1,0,0,1,1,1,0,0],
# [0,0,0,0,0... |
74e529238c87d49663845d4b2b9c43459d816ead | leesen934/leetcode_practices | /590. N叉树的后序遍历.py | 1,817 | 3.9375 | 4 | # 给定一个N叉树,返回其节点值的后序遍历。
#
#
#
# 例如,给定一个3叉树:
# 1
# / | \
# 3 2 4
# / \
# 5 6
# 返回其后序遍历: [5, 6, 3, 2, 4, 1].
#
# 说明: 递归法很简单,你可以使用迭代法完成此题吗?
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
class Solution(object):
... |
9a7aab6ba9b2aad73dd46b322cb773e524e0ffd5 | leesen934/leetcode_practices | /167. 两数之和 II - 输入有序数组.py | 3,136 | 3.796875 | 4 | #
# 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
#
# 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
#
# 说明:
#
# 返回的下标值(index1 和 index2)不是从零开始的。
# 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
# 示例:
#
# 输入: numbers = [2, 7, 11, 15], target = 9
# 输出: [1,2]
# 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
class Solution:
def tw... |
bc24b5f23325eb0e7edb671231802a191ace89e7 | leesen934/leetcode_practices | /226. 翻转二叉树——第一颗树.py | 1,763 | 4.125 | 4 | # -*- coding: utf-8 -*-
# 翻转一棵二叉树。
#
# 示例:
#
# 输入:
#
# 4
# / \
# 2 7
# / \ / \
# 1 3 6 9
# 输出:
#
# 4
# / \
# 7 2
# / \ / \
# 9 6 3 1
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.ri... |
d9d5610ea78bee57aebd7c3e52cb9a03438c2f69 | luschetinger/Sample_2_files | /conditionals.py | 189 | 4.0625 | 4 | x = range(10)
for n in x:
age = input ("what is your age ? ")
if int(age) > 18:
print("you are an adult")
else:
print("you are a child or teen")
|
69e50a17a6efa8f490fc12fdac7b71547d110ef5 | rahulr2003/Python_Stuff | /Excercise6.py | 167 | 3.875 | 4 | """
program a function that takes a n digit number as input, reverses it and outputs the same.
test cases
>>> reverse(4323)
3234
>>> reverse(14054)
45041
"""
|
cb10726a4c8df7332bfd9a246fec579338313335 | ishalyminov/interviewbit | /regular_expression_match.py | 1,063 | 3.65625 | 4 | class Solution:
# @param s : string
# @param p : string
# @return an integer
def isMatch(self, s, p):
if not len(s) or not len(p):
return not len(s) and not len(p)
table = [False for _ in xrange(len(p) + 1)]
table_prev = [False for _ in xrange(len(p) + 1)]
tab... |
5281926cf6b7aac35ca364f26324e9ba68767f14 | codingyen/CodeAlone | /Python/0053_maximum_subarray.py | 485 | 3.796875 | 4 | # The way to solve this problen is tricky.
# Decide to add the next element or starting from the next element.
# Update the result.
#
# Time: O(n)
# Space: O(1)
class Solution:
def maxSubArray(self, nums):
result, curr = float("-inf"), float("-inf")
for i in nums:
curr = max(curr + i, ... |
bcb06b81efe525c9ef7f76b3a83681b0f3b2e991 | codingyen/CodeAlone | /Python/0167_two_sum_II.py | 532 | 3.703125 | 4 | # Two pointers vs Dic
# Time: O(n)
# Space: O(1)
class Solution:
def twoSum(self, numbers, target):
start = 0
end = len(numbers) - 1
while start != end:
sum = numbers[start] + numbers[end]
if sum < target:
start += 1
elif sum > target:
... |
87a22a7a2f562193f06e80cdaa1c62aaba895049 | codingyen/CodeAlone | /Python/0033_search_in_rotated_sorted_array.py | 944 | 3.953125 | 4 | # Time: O(logn)
# Space: O(1)
class Solution:
def search(self, nums: 'Lists[int]', target: 'int') -> 'int':
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif (nums[... |
73e60a7ac38dffd436ce36c97614a81dae84799d | codingyen/CodeAlone | /Python/0034_find_first_and_last_position.py | 865 | 3.5625 | 4 | # Binary search
# Time: O(logn)
# Space: O(1)
class Solution:
def searchRange(self, nums, target):
if not nums:
return [-1, -1]
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if... |
6260b98dcb6a782f55b90da6f3a6e72a11c5f337 | codingyen/CodeAlone | /Python/0205_isomorphic_strings.py | 468 | 3.59375 | 4 | class Solution:
def isIsomorphic(self, s, t):
if len(s) != len(t):
return False
s2t, t2s = {}, {}
for p, w in zip(s, t):
if p not in s2t and w not in t2s:
s2t[p] = w
t2s[w] = p
elif p not in s2t or s2t[p] != w:
... |
46aeb638ddb016a65db646c506930286f3862af6 | codingyen/CodeAlone | /Python/0024_swap_nodes_in_pairs.py | 720 | 3.59375 | 4 | class ListNode:
def __init__ (self, val, next = None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head):
dummy = ListNode(0)
curr = dummy
dummy.next = head
while curr.next and curr.next.next:
tmp = curr.next
tmp2 ... |
4ae7c4b8c78297a90dd8dec4860df04c3dd6c7e8 | codingyen/CodeAlone | /Python/0168_excel_column_title.py | 329 | 3.78125 | 4 | # Use ord() and chr()
class Solution:
def convertToTitle(self, n):
res = ""
dvd = n
while dvd:
res += chr(int((dvd - 1) % 26) + ord('A'))
dvd = (dvd - 1) // 26
return res[::-1]
if __name__ == "__main__":
n = 701
s = Solution()
print(s.convertTo... |
ab9a302917a4981feec305c9bdfac79a3684c80e | codingyen/CodeAlone | /Python/0070_climbing_stairs.py | 397 | 3.96875 | 4 | # It's fibonacci.
# Use dynamic programming.
# Use array to store each step.
class Solution:
def climbStairs(self, n):
dp = [0] * (n + 2)
dp[1] = 1
dp[2] = 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
if __na... |
7fc373afb86d995047bdb7569870a7107846be8b | codingyen/CodeAlone | /Python/0118_pascals_triangle.py | 475 | 3.515625 | 4 | # First, solve what res should be look like. Fill with [1]
# Locate the position and get the result from the previous array.
class Solution:
def generate(self, numRows):
res = [[1] * (i + 1) for i in range(numRows)]
for i in range(2, numRows):
for j in range(1, i):
res[i... |
041366d1c7e1ceac451623ce72e205c9a6efaf91 | codingyen/CodeAlone | /Python/0108_convert_sorted_array_to_binary_search_tree.py | 607 | 3.734375 | 4 | # DFS
# Find the logic and how to recursive.
class TreeNode:
def __init__(self, val = 0, left = None, right = None):
self.val = val
self.left = left
self.right = right
class Solution:
def sortedArrayToBST(self, nums):
if not nums:
return None
mid ... |
ff3915072eecf7e0359c92f4494cdd794616a44f | bozzlab/data-engineering-workshop | /python/example-5.py | 207 | 3.703125 | 4 | n = int(input())
for idx in range(1, n +1):
for sub_idx in range(1, idx +1):
print(sub_idx, , end = "")
print("")
## Ref : https://snakify.org/en/lessons/for_loop_range/problems/ladder/
|
dc1e3de90e5289c287efe767c45ad10649919cfd | SecretAardvark/Python | /pycrashcourse/ex7-3.py | 161 | 4.28125 | 4 | number = int(input("Enter a number: "))
if number % 10 ==0:
print('Your number is divisible by 10.')
else:
print('Your number is not divisible by 10.') |
905cce8e42b4c3c7e9c5e35be5a419925c15fdcc | SecretAardvark/Python | /pycrashcourse/DataViz/csv_convert.py | 639 | 3.703125 | 4 | import csv
import sys
import os
# Convert comma-delimited CSV files to pipe-delimited files
# Usage: Drag-and-drop CSV file over script to convert it.
inputPath = sys.argv[1]
outputPath = os.path.dirname(inputPath) + "death_valley_2014.csv"
# https://stackoverflow.com/a/27553098/3357935
print("Converting tab delimit... |
edfef61c3153e059976d6305c5838e7e6bf860b0 | SecretAardvark/Python | /pycrashcourse/ex7-4.py | 247 | 4.0625 | 4 | prompt = "\nEnter a topping for your Pizza: "
prompt += '\n Enter quit to end the program.'
while True:
topping = input(prompt)
if topping == 'quit':
break
else:
print("I'll add " + topping.title()+ ' to your pizza.') |
b1403db8bba9b3b3991423e65e5f4d1e19c04caf | SecretAardvark/Python | /531calc.py | 2,992 | 4.0625 | 4 | #TODO: Write a function to calculate 1RM and training max
def find_onerep(weight, reps):
onerepmax = int(weight) * int(reps) * .0333 + int(weight)
#training_max = onerepmax * .9
return onerepmax #training_max
#TODO: Use that function and user input to calculate user's 1rm weights.
lifts = ['ohp','squat'... |
356c78b74f024dfbfc02fa3051a79723075def96 | SecretAardvark/Python | /pycrashcourse/ex8-7.py | 392 | 3.546875 | 4 | def make_album(artist_name, album_name, number_of_tracks=''):
album = {'Artist' : artist_name , 'Album' : album_name,}
if number_of_tracks:
album['Tracks'] = number_of_tracks
return album
print(make_album('Led Zeppelin', 'In through the out door'))
print(make_album('The Beatles', 'The White Album',... |
68a7c020122f2a605f872461dc2602b69afe89f9 | SecretAardvark/Python | /pycrashcourse/ex8-12.py | 278 | 3.578125 | 4 | def make_sandwich(*ingredients):
print("Making a sandwich with: ")
for ingredient in ingredients:
print("-" + ingredient)
make_sandwich("bacon", "sourdough", "lettuce", "tomato")
make_sandwich("egg", "cheese", "turkey")
make_sandwich("peanut butter", "Jelly") |
7a26b5a914f63d30fe225554641a0426ea475f96 | SecretAardvark/Python | /pycrashcourse/favlang.py | 331 | 4 | 4 | languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby','phil': 'python',
}
poll = ['Chad', 'Sabrina', 'Wiley', 'jen', 'sarah', 'phil']
for name in poll:
if name in languages:
print(name + ", thanks for taking the poll.")
elif name not in languages:
print(name + ", please take the po... |
64439515f5c989fc9c4d18c0cd36466c4130b6d4 | SecretAardvark/Python | /weights.py | 291 | 3.5 | 4 | import matplotlib.pyplot as plt
def find_onerep(weight, reps):
onerepmax = weight * reps * .0333 + weight
return onerepmax
ohp = [125, 130, 140, 130, 135, 145]
for number in ohp:
ohpmax = number * 5
return
for max in ohp:
find_onerep(max, 5)
plt.plot(ohp)
plt.show() |
8a03fe6c60097de3aa9a9902e5ff3069cdb3524b | SecretAardvark/Python | /hardway/ex8.py | 452 | 4.03125 | 4 | formatter = "{} {} {} {}"
#Defines a variable with 4 {} to be formatted
print(formatter.format(1,2,3,4))
print(formatter.format("one","two","three","four"))
print(formatter.format(True, False, False, True))
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format(
"Try your",
"Own t... |
775a1bddf2d3db24fafda6b0138279633a08786e | SecretAardvark/Python | /pycrashcourse/ch15notes.py | 1,415 | 4.5 | 4 | #Notes on the Matplotlib module
import matplotlib as plt
#Simple line Graph
squares = [1,4,9,16,25]
plt.plot(squares) #plt.plot() : Tries to plot given numbers in a meaningful way.
plt.show() #plt.show(): Opens Matplotlibs viewer and displays the plot.
#formatting a plot
plt.plot(squares, linewidth=5) #'linewidth'... |
3da1db74e007cc7c9630eeccd511523cfc291091 | Andrew-Abishek-A/ScriptingLab | /Assignments/Assignment200919/Q2.py | 243 | 3.640625 | 4 | A = [12, 24, 35, 70, 88, 120, 155]
b = []
for i in A:
if i % 2 == 0:
b.append(i)
print(b)
for i in b:
if i % 5 == 0:
print(str(i), "is divisible by 5")
if i % 7 == 0:
print(str(i), "is divisible by 7")
|
0ff1ed0c4e9be340a01d5d5415fb809a988dd84a | Andrew-Abishek-A/ScriptingLab | /Python programs/Program4.py | 804 | 4.5 | 4 | #Demo: Classes in python
#Concept: Use of del function to delete attributes of an object and the object itself
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
p1 = Person("Anagha", 19)
print("\nName of the person 1 is:", p1.name)
print("\nAge of the person 1 is:", p1.age)
print("****... |
1acae932fa9e8fd0bec4c65666994d456bf33824 | andrea270872/machineLearningTasks | /lecture1/perceptron_v0.py | 599 | 3.875 | 4 | # 9 July 2013
# Andrea Valente www.create.aau.dk/av
# Lecture 1 Machine Learning lecture notes
#
# 1) load all 7 images, as 16x16 grayscale images
# 2) Alien, Bee, Female and Male should be accepted
# 3) train a perceptron to recognize the "good" images and reject the bad ones
# 4) see how well the trained perception p... |
4eec5dce0f0d9cfda0d54f2cc37eaa71f5096644 | Harshie/Python_Practice | /DSI_python/001_python_pandas_basics.py | 683 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 10 13:46:20 2020
@author: ehars
"""
# Importing pandas for grocery dataset
import pandas as pd
# Importing grocery data
sales_data2 = pd.read_csv("grocery_sales.csv")
# Filling the missing value
sales_data1 = sales_data
# Dropping null rows
sales_data1 = sales_data1... |
ee7da08d4464c255e1184104ee40b6ba2915c0d9 | 20wildmanj/AdventOfCode2020 | /part18.py | 3,138 | 3.53125 | 4 |
from collections import deque
number = "0123456789"
def process(opq,ops): #process the expression as is (infix), uses a stack and a queue
while (len(opq) > 0):
arg = opq.popleft()
if arg == "+":
x = ops.pop()
y = opq.popleft()
if (y == "("):
pro... |
88d556783e586db4fa8d4c223903c13e17391e16 | EMCain/friday_13 | /do_a_scare.py | 1,144 | 3.8125 | 4 | import random
GHOST = """
.-.
(o o) boo!
| O \\
\\ \\
`~~~'
"""
CAT = """
.-.
\\ \\
\\ \\
| |
| |
/\\---/\\ _,---._ | |
/^ ^ \\,' `. ;
( O ... |
9aef9aac20362278fe6b4cb7e13e14da36ba329e | vaibhav17082002/aimycaptain.pyt | /loopforif.py | 159 | 3.765625 | 4 | list1=[12,-7,5,64,-14]
list2=[12,14,-95,3]
for x in list1:
if x>0:
print("list1[",x,"]")
for x in list2:
if x>0:
print("list2[",x,"]")
|
31ff8786e0a1a12ea8fadd046d807c1650a3bd99 | Botany-Downs-Secondary-College/mathsquiz-PhoenixWG | /Sprint2_3Check_answers.py | 6,331 | 3.625 | 4 | from tkinter import*
from tkinter import ttk
from random import*
class MathQuiz:
def __init__(me,parent):
#Widget for the Welcome Frame
me.Welcome = Frame(parent)
me.Welcome.grid(row=0, column=0)
me.TitleLabel = Label(me.Welcome, text = "Welcome to Math Qu... |
6a19413df03417af18380b24fb11ec9fffbe3f09 | Orekisama/Python-scripts | /static_csv_file.py | 688 | 3.53125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import csv
# 计算总流量
band = []
band_group = []
csv_file = csv.reader(open('acs.csv', 'r'))
#print(csv_file)
for line in csv_file:
band.append(float(line[1]))
#print(sum(band)/1024/1024/1024, 'G')
print("total bandwidth is:", '{:.2f}'.format(sum(band)/1024/1024/1024) + 'G')
#... |
0718960801bfc53ab11ba82cd0aaa1dfd5ee3fe5 | Orekisama/Python-scripts | /excel_filter.py | 706 | 3.5 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 按照指定要求过滤excel文件,并将结果输出到新的excel中
import pandas as pd
from pandas import *
import sys
input_file = sys.argv[1]
output_file = sys.argv[2]
sheetName = 'SalesForce'
data_frame = pd.read_excel(input_file, sheetName, index_col=None)
# 每个data_frame即为一个列标题,'=='后代表此列需要过滤的条件,可以有多个条件
... |
f87cca2f6acc846417e4aafb3418e76974d83a48 | rsreenivas2001/LabMain | /Sem 4/ps b1/2.py | 198 | 3.65625 | 4 | x = []
inp = 1
while True:
inp = input("Enter website : ")
if inp == '0' or inp == '':
break
x.append(inp)
for ite in x:
arr = ite.split('.')
print(ite, " - ", arr[2])
|
d062ed9d3d86f334b19c66293e78de7125fc6480 | rsreenivas2001/LabMain | /Sem 4/ps b1/9.py | 150 | 3.546875 | 4 | print("Enter Arr : ")
x = []
while True:
inp = int(input())
if inp != -1:
x.append(inp)
else:
break
print(sum(x)/len(x)) |
cbb01d1732d0d583a4b8b297ba858a299fcfb529 | rsreenivas2001/LabMain | /Sem 4/ps/5.py | 712 | 3.9375 | 4 | alice_ratings = {"alonzo": 1, "bob": 3, "turing": 2}
bob_ratings = {"alice": 1, "alonzo": 2, "turing": 3}
alonzo_ratings = {"alice": 3, "bob": 2, "turing": 1}
turing_ratings = {"alice": 2, "alonzo": 1, "bob": 3}
friends = {"alice": alice_ratings, "bob": bob_ratings,"alonzo": alonzo_ratings, "turing": turing_ratings}
d... |
66e870af4edb9ab08228d69b518b0d67e38f16d1 | rsreenivas2001/LabMain | /Sem 4/ps2/10.py | 230 | 4.09375 | 4 | def number_of_digits(val):
cnt = 1
while True:
if val/10 >= 1:
cnt += 1
val /= 10
continue
break
print(cnt)
x = int(input("Enter a Number : "))
number_of_digits(x)
|
b18042370f3ccebda284d6e8e6ca58b4239e3965 | llpvqll/homework_from_course | /practissLessons/task_14.py | 144 | 3.78125 | 4 |
lst = ['m', 'b', 'a', 'd', 't', '', 'e', '', 'y', '']
for index, value in enumerate(lst):
if not value:
lst.pop(index)
print(lst) |
aa8ebaac145e12f63ca3916e027b86b074f17494 | llpvqll/homework_from_course | /practissLessons/task_5.py | 240 | 4.03125 | 4 |
first_lst = [1, 22, 33, 4, 55, 66, 34, 29, 32, 552]
second_lst = [2, 33, 55, 11, 5, 29, 552, 245, 231]
third_lst = []
for first_item in first_lst:
if first_item not in second_lst:
third_lst.append(first_item)
print(third_lst) |
f1fb0a5a69a1d65ddd66b131a73a7a8aa87f41b6 | llpvqll/homework_from_course | /practissLessons/task_11.py | 111 | 3.84375 | 4 |
lst = [1, 2, 3, 4, 5]
shift = 3
for item in range(shift):
tmp = lst.pop(0)
lst.append(tmp)
print(lst)
|
f6c7e30688286107246a62ce404d780ae104acf2 | llpvqll/homework_from_course | /sequencesProject/additionTask.py | 152 | 3.90625 | 4 |
filter_list = []
num = input(f"Enter some num: ")
for item in num:
filter_list.append(item)
filter_list = sorted(filter_list)
print(filter_list)
|
0ff0666fb7dac21fca07451a554c402d3465bd41 | Timehsw/PythonCouldbeEverything | /PythonModels2/learnBeautifulSoup4/basic04.py | 964 | 3.71875 | 4 | # -*- coding: utf-8 -*-
'''
Created by hushiwei on 2017/7/23.
'''
'''
遍历文档树
'''
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters;... |
73f0cbf3af1ebf113f738c509aab5a45930b4950 | Timehsw/PythonCouldbeEverything | /PythonModels/learnBasic/oop_option.py | 1,107 | 3.875 | 4 | # coding=utf8
__author__ = 'zenith'
class Person():
id=0
name=""
def __init__(self,_id,_name):
self.id=_id
self.name=_name
def say(self):
print("id:%s name:%s"%(self.id,self.name))
def pl(self):
print "ddddddddddd"
class Man():
man="default"
def __init__(se... |
d8d6d31ebed1b730d9083c541b8321ec4de89455 | praak/cloud_computing | /HW4/all the shit i did/passCrack_working8m.py | 1,731 | 4.1875 | 4 | # Password cracking - passCrack.py - Given a string of characters on the command line, find what string hashes to it. Passwords are sometimes stored in a hashed form, so if the database is breached, the passwords are not easily usable. For this assignment, assume we have a hash of a password in hex form. Given this h... |
2fb6ca90d9d88b9e50b03664d9487a4c9a8755dc | mekakil/Python_Exercises_3_Completed | /Tryme - Exercise 6.4 Pythoon Book - Programming Unit 4.py | 873 | 4.21875 | 4 | """
@Author:Victor Hugo de Barros
"""
import math
def divisible(a, b):
if int(a) and int(b) and a>0 and b>0:
if a%b == 0:
result1 = b**a
return int(result1)
else:
result2 = b**(a/b)
return int(result2)
else:
return "number is n... |
88e4adfa22603b041f6936da52adf2e8b71e5422 | salupsjr/cursoPythonGuanabara | /Desafios/desafio13Aula7.py | 191 | 3.765625 | 4 | salario = float(input('Qual o salário do funcionário? '))
salarioAtual = salario + (salario * 0.15)
print('O salário com 15% de aumento ficou no valor de R${:=.2f}'.format(salarioAtual)) |
7311f47d980ac9a31bbb806c4c152c9e762583e7 | salupsjr/cursoPythonGuanabara | /Exercicios/testeAula6.py | 182 | 3.78125 | 4 | #-*-coding:utf8;-*-
#qpy:console
n1 = int(input('Digite um número:' ))
n2 = int(input('Digite outro número: '))
s = n1 + n2
print ('A soma entre {} e {} é {}'.format(n1,n2,s)) |
a8451df45345a5bc4ba962e86cdf3b83c4d2a37a | salupsjr/cursoPythonGuanabara | /Exercicios/ex19Aula8.py | 722 | 3.875 | 4 | #-*-coding:utf8;-*-
#qpy:console
'''import random
a1 = str(input('Informe o nome do primeiro aluno(a): '))
a2 = str(input('Informe o nome do segundo aluno(a): '))
a3 = str(input('Informe o nome do terceiro aluno(a): '))
a4 = str(input('Informe o nome do quarto aluno(a): '))
lista = [a1, a2, a3, a4]
escolhido = rando... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.