blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
30e575db5970382f5eeb8a80cc4efc1e402f359e | Jiezhi/myleetcode | /src/1608-SpecialArrayWithXElementsGreaterThanOrEqualX.py | 978 | 3.6875 | 4 | #!/usr/bin/env python
"""
CREATED AT: 2022/4/12
Des:
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Easy
Tag:
See:
"""
from typing import List
class Solution:
def specialArray(self, nums: List[int]) -> int:
... |
c500b1809c1ba7f8dd7c38e9df26a2d44c950df1 | Striderserge/devops_ac06 | /com/ope/conta_corrente.py | 571 | 3.96875 | 4 | """programa conta corrente"""
class Contacorrente:
"""cria classe conta corrente"""
def __init__(self, numero, nomecorrentista, saldo=0.0):
"""recebe parametro"""
self.numero = numero
self.alterarnome(nomecorrentista)
self.saldo = saldo
def alterarnome(self, nomecorrentist... |
72d4d843caa2b7cbf043f06efeecc6da467e0c2a | FengFengHan/LeetCode | /Clone Graph_wrong.py | 943 | 3.703125 | 4 | # Definition for a undirected graph node
class UndirectedGraphNode(object):
def __init__(self, x):
self.label = x
self.neighbors = []
class Solution(object):
def cloneGraph(self, node):
"""
:type node: UndirectedGraphNode
:rtype: UndirectedGraphNode
"""
i... |
3373c6b68b7887de499f20e5a838456db4315623 | Thainahelena/python3-cursoEmVideo | /Mundo I/ex037.py | 746 | 4.125 | 4 | print('Bem-Vindo ao Conversor de Número!\nDigite um número inteiro para fazer a conversão.')
print('-=-' * 15)
numero = int(input('Digite o número para ser convertido: '))
print(' [ 1 ] para conversão em base binária\n [ 2 ] para conversão em base octagonal\n [ 3 ] para conversão em base hexadecimal')
base = int... |
bcd680da9b4616548ae1cd269b22630c2d86d870 | timekeeper13/python_scripts | /conditions_and_loops/leap_year.py | 252 | 4.0625 | 4 |
n = int(input("enter the year to check : "))
if n % 4 == 0:
if n % 100 ==0:
if n % 400 == 0 :
print(f"{n} is a leap year")
else:
print(f"{n} is not a leap year")
else:
print(f"{n} is a leap year")
else:
print(f"{n} is not a leap year") |
efd8f838bcef76084e07939525ef109bc7226870 | konjakuc/python | /python-basic/经典算法案例/排序/Select_sort.py | 344 | 3.859375 | 4 | def select_sort(list1):
for i in range(len(list1)-1):
min_index=i
for j in range(i+1,len(list1)):
if list1[j]<list1[min_index]:
min_index=j
list1[i],list1[min_index]=list1[min_index],list1[i]
print(list1)
testList=[2,43,453,-32,5465,432,23,13,4345,233,435,765... |
8a5f731f465777bc7283df90b86b461edfbf466f | rifatmondol/Python-Exercises | /133 - [Strings] Substituir Por Estrela.py | 568 | 4.03125 | 4 | #133 - Dado uma string `s`, retornar uma string onde
# todas as ocorrências de seu primeiro caractere
# seja alterado para '*', exceto o primeiro caracter. Exemplo:
#
# babble ---> ba**le
#
# Presuma que o tamanho da string seja 1 ou mais.
# Dica: s.replace (strA, strB) retorna uma versão da string s.
def subst(s):
... |
8f9fe3424a4402bccfc22e66c9a6db45172622ed | damodardikonda/matplotlib | /seaborn/sea_boxplot.py | 372 | 3.65625 | 4 | #The major advantage of using Seaborn for many developers in Python world is
# because it can take pandas DataFrame object as parameter.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('iris')
sb.boxplot(data = df, orient = "h")
plt.show()
df1 = sb.load_dataset('iri... |
97656fa7b479bf17dfbf36c1c9215cfed207e0b6 | w5802021/leet_niuke | /niuke/33..py | 673 | 3.5 | 4 | class Solution:
def VerifySquenceOfBST(self, sequence):
'''
二叉搜索树的后序遍历序列
:param sequence:
:return:
'''
length = len(sequence)
if length == 0:
return False
if length == 1:
return True
# 后序遍历根节点
root = sequence[-1]... |
f4a5437eaa6225a6e3f049e759003c8f69ab8a13 | tngo0508/practice_coding | /number_of_stairs_iter.py | 234 | 3.828125 | 4 | def staircase(n):
# Fill this in.
arr = [0] * (n+1)
arr[0] = arr[1] = 1
i = 2
while i <= n:
arr[i] = arr[i - 1] + arr[i - 2]
i += 1
return arr[n]
print staircase(4)
# 5
print staircase(5)
# 8
|
d3857e2707b7c839533d738082ed58681f36e24b | BStarcheus/algorithms | /graphs/depthFirstSearch.py | 2,345 | 3.53125 | 4 | try:
from .graph import *
except:
# Running file as __main__
from graph import *
def depthFirstSearch(graph, startNode, endNode, visual=False, visited=None):
"""
Search the graph until you find the endNode using depth first search.
:param graph: Graph object to be searched for a path
:p... |
123ae57abda7e0e37c73c6a86ef85b8b6866f2a6 | jagdishrenuke/Project_python | /ex14.py | 683 | 3.703125 | 4 |
from sys import argv
script,user_name ,game= argv
prompt = '-->'
print "hii %s , I am the %s script ." %(user_name,script)
print "I'd like to ask you a few questions ."
print "Do you like me %s ." % user_name
likes = raw_input(prompt)
print "Where do you live ?"
lives = raw_input(prompt)
print "What kind of com... |
b5b6fbd209cf3989c91118f3e9ba5e8ba8a9f7a0 | meadewaking/Hello-World | /MyPython/MyPython/DrawColorSnake.py | 1,405 | 3.609375 | 4 | import turtle
import time
def drawsnack(rad, angle, len, neckrad): #(半径,角度,长度,脖子部分半径)
colors = ["red", "yellow", "purple", "blue", "pink"]
for i in range(len):
'''
if i != 0:
if i == 1:
turtle.pencolor("red")
elif i == 2:
turtle.pencol... |
15e6a631c00842f7f228e2b2c88a0fac066a8bb4 | 606keng/weeds_study | /suanfa/动态规划/爬楼梯.py | 1,263 | 4.03125 | 4 | #!usr/bin/env python
#-*- coding:utf-8 -*-
"""
@author:DOULIHANG
@file: 爬楼梯.py
@time: 2020/11/24
"""
"""
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶... |
00208a0618c85aa5ea26c70c2b5477ce600a5416 | kirnie/Bank-Account | /bank_account.py | 1,552 | 4.15625 | 4 | #!/usr/bin/python3
class BankAccount():
def __init__(self, name, balance):
self.name = name
self.balance = balance
#introduce bank account
def __repr__(self):
return "{}'s account".format(self.name)
#show current balance on bank account
def show_balance(self):
prin... |
0b3f716f9c759d1dc9b3ae427c028e26daa0b48e | aldotele/the_python_workbook | /lists/ex127.py | 491 | 3.90625 | 4 | # exercise 127: Is a List Already in Sorted Order?
n = input('enter a number: ')
t = []
while n != '':
t.append(int(n))
n = input('enter a number (blank to quit): ')
def isSorted(li):
return li == sorted(li)
print(isSorted(t))
""" DIFFERENCE between sorted() and .sort()
- sorted() takes a list as para... |
1c023fa3be4bef93d6a01fcc949a708080c2b694 | sumerac/Python_Assignment | /Python HW1_Activity 1.py | 958 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 23 13:25:49 2018
@author: sumerac
"""
# SOURCE: https://stackoverflow.com/questions/41886219/conversion-of-kilometers
# -to-miles
import tkinter
Conversion_box = tkinter.Tk()
top_frame = tkinter.Frame(Conversion_box)
bottom_frame = tkinter.Frame(Conversion_box)
tkinter... |
4babad88ada7bb12e5f265ba855366d44447ebbe | Bagginz/pythonlab | /input.py | 439 | 4.375 | 4 | #Input FirstName MiddleName and LastName
first_name = str(input("Please Enter Your First Name: "))
middle_name = str(input("Please Enter Your Middle Name: "))
last_name = str(input("Please Enter Your Last Name: "))
first_name = first_name.capitalize()
middle_name = middle_name.capitalize()
last_name = last_name.capita... |
f99ed8b4ff385edba43ac233c42beb462477212b | jessapp/coding-challenges | /sortingalgorithms.py | 1,369 | 3.859375 | 4 | # Bubble sort
def bubble_sort(nums):
for i in rage(len(nums) - 1):
made_swap = False
for j in range(len(nums) - 1 - i):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
made_swap = True
if not made_swap:
break... |
d9888003182c7116df25bf1d39318d1a3aa01c3d | jztech101/Kenni | /modules/wiki.py | 805 | 3.71875 | 4 | #!/usr/bin/env python3
import re
import web
import tools
import wikipedia
def wiki(kenni, input):
query = input.group(2)
if not query:
kenni.say("Please enter a query")
else:
results = wikipedia.search(query)
if not results:
kenni.say("No results found")
else:
... |
fa817240624027f041bd7517ba864f78e7cb6930 | ksayee/programming_assignments | /python/CodingExercises/CombinationList.py | 758 | 3.578125 | 4 | # Permutations of a list lst=['us','uk','in']
import collections
def CombinationList(ary):
dict=collections.Counter(ary)
lst=[]
cnt=[]
for key,val in dict.items():
lst.append(key)
cnt.append(val)
res=[]
fnl_lst=[]
CombinationList_recur(lst,cnt,res,len(ary),fnl_lst)
re... |
4fc77294c36ad1f026c78802f10d48867b0fe588 | brandr/Roguelike_Python | /screenmanager.py | 4,744 | 3.6875 | 4 | """ A manager for various screens that can be displayed.
"""
from guiscreen import *
from targetcontrols import TargetControls
class ScreenManager:
""" ScreenManager (...) -> ScreenManager
The screenmanager conveys information between a GuiScreen object, a control manager,
and a pygame master screen.
Attributes... |
564ece79c6deb536a9ed8a1f55e00c948225f3f0 | raphaeldeonova/Pong | /Ball.py | 2,291 | 3.734375 | 4 | import math
import pygame
import random
from GameObject import GameObject
class Ball(GameObject):
#EFFECTS: makes a ball with its x, y, radius, speed, angle, and associated pygame.Surface
def __init__(self,x,y,r,speed,a, gameDisplay):
super().__init__(gameDisplay)
self.x = int(x)
self.... |
0ab5b3eb3355582e67871d6958b6c4a8b3d443d4 | Solaxun/aoc2016 | /AoC13.py | 1,973 | 3.515625 | 4 | from copy import deepcopy
DOWN,UP,LEFT,RIGHT = MOVES = [(1,0),(-1,0),(0,-1),(0,1)]
def fillspace(x,y,favnum):
part1 = x*x + 3*x + 2*x*y + y + y*y
space = sum(map(int,filter(lambda x: x == '1',get_binary(part1 + favnum))))
return '.' if space % 2 == 0 else '#'
def get_binary(num):
return bin(num)[2:]
def gen_gri... |
34286b304d721f8f0240048754f399ec953e6b32 | menarik-hmm/machine_learning | /knn_classification/run.py | 3,404 | 3.796875 | 4 | # IMPORT LIBRARY
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# FUNCTIONS
def jarak(x_1, x_2, metode="euclidean"):
"""
Fungsi untuk menghitung jarak antara 2 titik observasi x_1 dan x_2
Input:
x_1 (n-vektor) : vektor observasi 1
x_2 (n-vektor) : vektor ... |
8a795ef8940d095fbb3dc331531ead41c6f2bd61 | siva237/python_classes | /date_time.py | 523 | 4.0625 | 4 | # str() vs repr() in Python
# str() and repr() both are used to get a string representation of object.
import datetime
today = datetime.datetime.now()
# Prints readable format for date-time object
print(str(today))
# prints the official format of date-time object
print(repr(today))
s = 'Hello, Geeks.'
print (str(s))
... |
ab3681de6e71eab73a575a93cc5dfe077838fd95 | sahilbasera/Smart-Power-Prediction-And-Monitoring | /main.py | 908 | 3.90625 | 4 | import function as f
"""
This contains the main page for the Smart Power Prediction and Monitoring
"""
print("-"*80)
print("-"*80)
print("Welcome to the Main Page of Smart Power Prediction and Monitoring \n")
print("Smart Power Prediction And Monitoring is a power consumpton monitoring \nand prediction sof... |
67b36f3e7cf768269735d31aa87adb96b611e755 | zardain/python101-1 | /2.0-funciones/ejercicios_alumnos/Zardain, Javier/Ejercicios/Ej14.py | 482 | 3.828125 | 4 | '''
Created on 8/9/2016
@author: javier_zardain
Dadas 2 listas con la misma cantidad de elementos intercalarlos.
'''
def cruzarListas(lista1, lista2, nuevaLista, indice=0):
x = int(len(nuevaLista)/2)
nuevaLista.append(lista1[indice])
nuevaLista.append(lista2[indice])
if x != len(lista1)-1:
cr... |
f69e0abb1c1e802d4ce1d65140fa51a1bbf27571 | shikhaghosh/python-assigenment1 | /assignment4/question3.py | 273 | 4.03125 | 4 | num1=int(input("enter a number:"))
num2=int(input("enter a number:"))
if num1>num2:
smaller=num2
else:
smaller=num1
for i in range(1,smaller+1):
if((num1%i==0)and(num2%i==0)):
hcf=i
print("the h.c.f.of",num1,"and",num2,"is",hcf) |
6855f10ef90c9f98699985f4faece56791e24ee2 | csusb-005411285/CodeBreakersCode | /longest-increasing-path-in-a-matrix.py | 1,143 | 3.546875 | 4 | class Solution:
def __init__(self):
self.longest_path = 1
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
cache = [[1 for _ in range(len(matrix[0]))] for _ in range(len(matrix))]
visited = set()
for row in range(len(matrix)):
for col in range(len... |
0c83b1f8577fbba50a71f5bf01fa8d95994ed2ba | Lindseyj79/python-interfaces | /building-interfaces/03 - tk_message.py | 598 | 4.40625 | 4 | # Python 3 - Message tkinter program
# Author: J.Smith
# Import tkinter library
from tkinter import *
import tkinter.messagebox as box
# Create a window
window = Tk()
window.title('Message Box Example')
# Function to display various message boxes
def dialog():
var = box.askyesno('Message Box', 'Proceed?')
i... |
b7ffad8cce11c1f4d40b9a3937f2eee7d5b811ae | PQCuongCA18A1A/Ph-m-Qu-c-C-ng_CA18A1A | /PhamQuocCuong_44728_CH05/Exercise/page_145_exercise_04.py | 268 | 4.21875 | 4 | """
Author: Phạm Quốc Cường
Date: 8/10/2021
Problem:
Write a loop that accumulates the sum of the numbers in a list named data.
Solution:
"""
def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 2, 3, 0, 7))) |
e5bac127c14c8ec190894fce0fa07a2409e66466 | GonzMG/03MAIR-Algoritmos-de-Optimizacion-2019 | /Seminario/seminario_aux.py | 830 | 3.609375 | 4 | import random
from itertools import permutations
N = ["1","2","3","4","5","6","7","8","9"]
O = ["+","-","*","/"]
class Nodo:
def __init__(self, nums, padre):
self.nums = nums
self.cost = self.cost()
self.padre = padre
def algoritmo_a(val):
a = eval(N[0])
print(a)
return a
de... |
a04f74b2fc4efa064b1fbdbfc846d6d0cedb3058 | jessiebak/ExercicesPython | /Chapitre 2/Série A/C2A2.py | 357 | 3.875 | 4 | # Maintenant que vous savez faire un while tentez ceci :
# Ecrivez un bout de code qui écrit "Au revoir" 998 fois. Devant chaque "Au revoir", le numéro de l'itération est écrite.
# Cela devra donner quelque chose comme :
# 1) Au revoir
# 2) Au revoir
# 3) Au revoir
# ...
# 998) Au revoir
i=0
while (i<998):
print(... |
32e98ffcfcfb0f0db4e342da5d6c216b2557510f | jananee009/DataStructures_And_Algorithms | /Linked_Lists/LinkedListPalindrome.py | 973 | 4.4375 | 4 | # Implement a function to check if a linked list is a palindrome.
# Approach : Access the linked list in reverse and compare it with the linked list. If it is the same, then we have a palindrome.
import SinglyLinkedList as sll
def checkPalindrome(list):
curr = list.head
tempList = []
while(curr.getNext() != N... |
5fc56d9d02475b497d20988fbe8a244faec680e9 | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Basics/2_simple_calculations/Projects_Creation.py | 762 | 4.3125 | 4 | """
Simple Operations and Calculations - Lab
05. Creation Projects
Check: https://judge.softuni.bg/Contests/Compete/Index/1011#2
Write a program that calculates how many hours it will take an architect to design several
construction sites. The preparation of a project takes approximately three hours.
Entrance
2 lines a... |
496a1d7e30f847ceea2703912da2e068cbb6d730 | adityasunny1189/100DaysOfPython | /random/crc.py | 194 | 4.0625 | 4 | divident = input('Enter a input: ')
divisor = input('Enter a divisor: ')
len_of_divisor = len(divisor)
for i in range(len_of_divisor - 1):
divident += '0'
len_of_divident = len(divident)
|
85cb5b165a4e67d3020c946edd5a7ab75a94b5e8 | welsny/solutions | /797.All_Paths_From_Source_to_Target.py | 1,001 | 3.59375 | 4 | class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""
First approach that removes edges once we've traversed them:
"""
res = []
def dfs(path, g):
curr = path[-1]
if curr == len(graph)-1:
res.app... |
bc767ff04edf7dc8fa5230d22be8ef1f2446dc3d | vijaysawant/Python | /MaxMinFromList.py | 269 | 3.8125 | 4 |
def MaxMin(list):
max = list[0]
min = list[0]
i = 0
while i < len(list):
if(list[i] > max):
max = list[i]
if(list[i] < min):
min = list[i]
i += 1
return max,min
list = input("Enter list : ")
res1,res2 = MaxMin(list)
print res1,res2 |
76977ea8ed90f015959cd7c8160e36f6274ee369 | ksrikanthcnc/practise | /python/stack.py | 740 | 4.09375 | 4 | class Stack:
def __init__(self):
self.stack=[]
def isEmpty(self):
return self.stack==[]
def push(self,data):
self.stack.append(data)
def pop(self):
if self.isEmpty==True:
print("Stack Empty")
return
data=self.stack[-1]
del self.stack[-1]
return data
def peek(self):
if self.isEmpty==True:
p... |
1ee21b0f028421d9a59e2a0e2083fdb33a6bd584 | pbhereandnow/schoolpracticals | /Class 12/q13/q13.py | 375 | 3.53125 | 4 | """
Dhruv Jain
XII-D
Question 13
"""
f1 = open("file1.txt", "r")
f2 = open("file2.txt", "w+")
def isvowel():
for i in f1.readlines():
for j in i.split():
if j[0] not in "aeiouAEIOU":
f2.write(j+" ")
isvowel()
f1.seek(0)
f2.seek(0)
print("Original file:",f1.read()... |
d832784aac8803513c36eac3dbe356010c2da926 | Savirman/Lesson05 | /Example02.py | 776 | 4.28125 | 4 | """
Создать текстовый файл (не программно), сохранить в нем несколько строк,
выполнить подсчет количества строк, количества слов в каждой строке.
"""
# Программа подсчета количеств строк в файле и слов в каждой строке
with open('Example02.txt') as my_file:
content = my_file.readlines()
scount = len(c... |
8d380d9687140ee6681bfae7f8865e94b43438e6 | oc0de/pyEPI | /16/5.py | 775 | 3.578125 | 4 | def is_pattern_contained_in_grid(grid, pattern):
def helper(x, y, offset):
if offset == len(pattern): return True
if (0 <= x < len(grid) and 0 <= y < len(grid[0]) and
grid[x][y] == pattern[offset] and (x,y, offset) not in previous_attempts and
any(helper(x+a,y+b,... |
1b5cc8d471f2272e2de93fc9cf4939654ebeb0fa | EchoWho/StochasticGradientBoosting | /db/textmenu.py | 1,099 | 3.640625 | 4 | # Presents a numbered text menu for a series of items or from a GLOB string
#
# Output looks like the below where header = Select a dataset:
# ----- Select a dataset: -----
#
# 0: Exit
# 1: helicopter_data
# 2: mg_10
# 3: normalized_take_off_data
# 4: projected_mocap_data
#
# Select a menu item: 1
#
# Arun Venkatraman... |
e9df6a17dacca25487a793d11909a0253b733a38 | mlsmall/Python-scripts | /Sudoku.py | 3,142 | 3.75 | 4 | # Sudoku
# This function checks whether 9 lists of numbers consitute a Sudoku board
'''row1 = list(input("Enter first row: "))
row2 = list(input("Enter second row: "))
row3 = list(input("Enter third row: "))
row4 = list(input("Enter fourth row: "))
row5 = list(input("Enter fifth row: "))
row6 = list(input("Enter six r... |
5e532cfe9e147e90d9020819cc15c567f7e0e6d9 | IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-JAOC1930 | /Clase6/EjemploSwitch/EjemplosSwitch/MajeosSwitch/Ejemplo02.py | 544 | 3.90625 | 4 | numeroDia= int(input("Ingrese el numero del dia de la semana "))
if numeroDia == 1:
print("Dia %d es Lunes"%(numeroDia))
elif numeroDia == 2:
print("Dia %d es Martes"%(numeroDia))
elif numeroDia == 3:
print("Dia %d es Miercoles"%(numeroDia))
elif numeroDia == 4:
print("Dia %d es Jueves"%(numeroDia))
eli... |
e1d0f00bc8dccdb56a6389b28b0c77859027f013 | dwillia2/pythonStuff | /proj2.py | 1,207 | 4.03125 | 4 | import random
import math
def every_other_character(input_str):
output = ''
for i in range(0, len(input_str)):
if(i % 2 == 0):
output += input_str[i]
return output
def reverse_string(input_str):
output = ''
for i in range(len(input_str) - 1, -1, -1):
output += str(input_str[i])
return output
def is_p... |
294bcc77ffa280b0515bab46a23b7a8c28da6302 | Bennyg95/BrainyGames | /PingPong/Pong.py | 5,083 | 4 | 4 | import pygame
######################################################################################
class Player():
######################################################################################
def __init__(self):
self.x, self.y = 16, SCREENHEIGHT/2 #initial position of player
self.speed = 3 #spee... |
4dce5cdec99d9fc8eedfc41d9a309d347e5be57c | dansackett/ratingslist | /api/__init__.py | 1,245 | 3.6875 | 4 | import os
class Client:
"""Client is the main entrypoint for all API interactions.
Backends can be called through dot notation to make API calls. For
example, if you want to find movies then you can call:
import api
client = api.get_client()
matches = client.movie.search('The Roo... |
28362b087858d5f0af34c034a0202ceda03f4f72 | Methodologist/PythonIntroductions | /SmallFactory.py | 469 | 3.5 | 4 | BaseClass = type("BaseClass",(object,),{})
@classmethod
def Check1(self,myStr):
return myStr == "ham"
@classmethod
def Check2(self,myStr):
return myStr == "sandwhich"
C1 = type("C1",(BaseClass,),{"x":1, "Check":Check1})
C2 = type("C2",(BaseClass,),{"x":30, "Check":Check2})
def MyFactory(myStr):
for cls ... |
4f73983e34782bccdfbe44a8fe8dfd5f952d6842 | Dhruv282008/Flask | /app.py | 2,086 | 4.03125 | 4 | from flask import Flask, jsonify, request
app = Flask(__name__)
tasks = [{
"ID": 1,
"title": "Buy Groceries",
"description": "Milk, Pizza",
"done": False,
}, {
"ID": 2,
"title": "Learn Python",
"description": "Learn - Flask",
"done": False
}]
@app.route("/")
def hellow... |
bf8ed33f690dce73b023bcf4a75e055df348b997 | DanPsousa/Python | /Q12_Condicional.py | 278 | 4.03125 | 4 | def Multiplo(x):
if x % 7 == 0:
return "O número é múltiplo de 7"
else:
return "O número não é múltiplo de 7"
try:
x = int(input("Forneça um valor inteiro: "))
print(Multiplo(x))
except:
print("Não foi fornecido um valor inteiro.")
|
9dac1223b5c85ca97103a504cd547717841caa9f | gychoi0916/Algorithm | /Programmers/Python/Programmers_Kit/Level2/가장큰수/가장큰수.py | 226 | 3.78125 | 4 | def solution(numbers):
answer = ''
for i in range(len(numbers)):
numbers[i] = str(numbers[i])
numbers.sort(key = lambda x: x* 3, reverse=True)
answer = str(int("".join(numbers)))
return answer |
b0705ebbda4d6007ba876d5603d06e3b21a3127b | FlyAndNotDown/LeetCode | /Python/70.py | 296 | 3.65625 | 4 | """
@no 70
@name Climbing Stairs
"""
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
l = [1]
for i in range(1, n + 1):
if i == 1: l.append(1)
else: l.append(l[-1] + l[-2])
return l[-1]
|
47cb71fa758b17f1885c2bca49127695cd3506a9 | eechooo/letcode | /5.longest-palindromic-substring.161647676.ac.py | 1,118 | 3.765625 | 4 | #
# [5] Longest Palindromic Substring
#
# https://leetcode.com/problems/longest-palindromic-substring/description/
#
# algorithms
# Medium (25.39%)
# Total Accepted: 317.8K
# Total Submissions: 1.3M
# Testcase Example: '"babad"'
#
# Given a string s, find the longest palindromic substring in s. You may assume
# tha... |
db26e0dfcac321091a7b07ecc8875f9257af2382 | Bit64L/LeetCode-Python- | /LINKED_LIST_CYCLE.py | 623 | 3.71875 | 4 |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head):
if not head:
return False
fast = head
slow = head
step = 0
while fast and fast.next:
step = step+1
fast = f... |
c4dade5ea6a9aeaeaa121e82ee617d5684d67d2b | zimengrao/PythonLearn | /learn2020_03/script/db_migrate_s/ooo.py | 574 | 3.5625 | 4 |
"""
@Name: ooo.py
@Version:
@Project: PyCharm
@Author: wangmin
@Data: 2018/12/3
"""
class Parent(object):
a = 0
b = 1
def __init__(self):
self.a = 2
self.b = 3
def p_test(self):
pass
class Child(Parent):
a = 4
b = 5
def __init__(self):
super(Child, se... |
a7abf12ab31c6f5eaf322c1111f6e9a40c9a68f2 | pdotchen/python | /CSE20/Assignment_5/5.2.py | 1,829 | 3.640625 | 4 | # from 5.1
numbers = input()
numbers = numbers.split(',') # becomes list of numbers
numbers = [int(i) for i in numbers]
ord_nums = numbers
ord_nums.sort()
mode_ord = []
for i in ord_nums:
mode_ord.append(i // 10) # makes all numbers in list mode_ord % 10
mode_dict = {} # dictionary of elements and all occurren... |
1a2a3de207701d161a3959d4e4565e5080bf715c | motionlife/ChowLiuBoosting | /ChowLiu.py | 6,559 | 3.53125 | 4 | """
The implementation of Chow-Liu Tree algorithm for Categorical distribution
"""
from collections import defaultdict
import networkx as nx
import numpy as Num
import random
import copy
class ChowLiuTree:
def __init__(self, data, label, weight):
self.X = data
self.label = label
self.weig... |
ff4b7a936a36f944ae037b11c8200c0956695b0b | Ph0en1xGSeek/ACM | /LeetCode/107.py | 822 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
c470565cb0457fc3b65c0d4259cfabfff9e9e85b | leilalu/algorithm | /剑指offer/第一遍/tree/42.对称的二叉树.py | 2,487 | 3.828125 | 4 | """
题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
"""
class Solution1:
def isSymmetrical(self, pRoot):
""""
【递归法】
"""
return self.isSymmetricalCore(pRoot, pRoot)
def isSymmetricalCore(self, pRoot1, pRoot2):
if not pRoot1 and not pRoot2:
re... |
cc62b7eb50e95236c880758c7edcbc7e8a046211 | reichlj/PythonBsp | /Schulung/py04_regular/r09_caseignore.py | 135 | 3.6875 | 4 | import re
str = "Mayer ist nicht gleich Meier"
x = re.search(r"m..er",str)
print(x)
x = re.search(r"m..er",str,re.IGNORECASE)
print(x)
|
483c240b40157d34b21f729c218cac61e2fa9ba1 | ArthurJacquin/WormsPython | /Worms/Scripts/Vector2.py | 389 | 3.828125 | 4 | class Vector2:
def __init__(self, x=0., y=0.):
self.x = x
self.y = y
def __add__(self, vec):
vec2 = Vector2(self.x + vec.x, self.y + vec.y)
return vec2
def __sub__(self, vec):
vec2 = Vector2(self.x - vec.x, self.y - vec.y)
return vec2
def __mul__(self,a... |
f03ebc1a0f34d8656bbeeae02b537bb91d543a53 | guanjie/erictools | /0.old/py_hello/current python euler/p20_factorial_digit_sum.py | 535 | 3.796875 | 4 | '''
name: p20_factorial_digit_sum
author: Eric He
date: Feb, 4st, 2013
result: 648
hint: make the long a string and add back up the digits
'''
def factorial(n):
if n == 1:
return 1
elif n < 1:
print 'error!'
return
else:
return n*factorial(n-1)
def main():
num = 100
... |
5fc241d327d03a25d9c5065547bf772aaef95a9d | tanya-agarwal06/functions | /friday, 22/06.py | 480 | 3.5625 | 4 | '''class Complex():
def __init__(self,real,imag):
self.r=real
self.i=imag
c=Complex(2,3)
print(c.i)
print(c.r)'''
class Apollo():
destination = "Moon"
def __init__(self):
print("ready to launch")
def flying(self):
print("spaceship is flying")
def getdestination(self... |
9b81df4d670273a0a734461cead5795b5fd6c4ab | ohquai/LeetCode | /day12/quick_sort.py | 1,229 | 3.5 | 4 | # -*-coding:utf-8 -*-
"""
快速排序
"""
import time
import sys
import random
class Solution(object):
def quick_sort(self, s):
"""
:type s: list
:rtype: list
"""
if len(s) == 1:
return s
else:
h = s[-1]
i = -1
for j in range... |
93a1b065661badf22f7ab23188c35806d4ebe4f5 | mrb5960/Machine-Learning-techniques-implementation | /K-means clustering.py | 11,735 | 3.75 | 4 | import csv
import numpy as np
import random
import copy
import matplotlib.pyplot as plt
import math
from mpl_toolkits.mplot3d import axes3d
class Clusters:
'''
Class that stores the properties of a cluster such as
cluster_id, the members (guest_id) in that cluster and center of mass
or th... |
e9d4d7ae0061149aef54f3ec936fdfbadb6fffe2 | chensandian/Coursera_Data_structure_and_algorithms | /Algorithms on Graphs/week5_spanning_trees/1_connecting_points.py | 950 | 3.765625 | 4 | #Uses python3
import sys
import math
def minimum_distance(x, y):
result = 0.
connected = set()
cost_list = [float('inf')] * n
cost_list[0] = 0
line = 0
while line < n:
min_cost = float('inf')
curr_point = -1
for index, cost in enumerate(cost_list):
if cost ... |
d0c21838f76bd662e29869cb84f6cbb0eaf15d7d | ddryden/legendary-octo-engine | /randomXKCDPassword.py | 1,224 | 3.625 | 4 | #!/usr/bin/env python
"""
See https://xkcd.com/936/ for why you might want to generate these
passphrases.
Does require /usr/share/dict/words to be a file with words on
multiple lines. On Debian derived OS like Ubuntu install wbritish-insane
package and `sudo select-default-wordlist` to set it as th... |
22e64e9fa0192105222839860db3a64b6c346830 | RajatSharma11/Lab-Codes | /BoggleQ20.py | 1,609 | 3.625 | 4 | # Python 3.6
# Board Size 4 X 4
t = int(input())
def isWord(s,a):
#print(s,end = " ")
if(s in a):
return True
else:
return False
def findWordUtil(l,string,i,j,a):
visited[i][j] = True
#print(visited)
string += l[i][j]
#print(string)
if(isWord(string,a)):
... |
7471d72742c9f6e38e3d2017036f3bdfb6d813b0 | LachlanD/bio | /ex1.py | 334 | 3.609375 | 4 | s = 'ACTGTACGATGATGTGTGTCAAAG'
w = 'TGT'
def Count(string, word):
count = 0
start = 0
found = True
while found:
index = string.find(word, start)
if index > 0:
start = index + 1
count += 1
else:
found = False
return count
pri... |
ae4e86f4b54c313dd952da0bcb103589ce6c9068 | Skylar030801/plot | /scatterg.py | 993 | 3.578125 | 4 | '''
import matplotlib.pyplot as plt
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
plt.scatter(x, y)
plt.show()
import matplotlib.pyplot as plt
a=[1.3, 3.4, 2.3, 9.8]
b=[3.5, 4.9, 1.3, 2.2]
c=[9.7, 1.5, 4.3, 0.9, 11.2]
data1=[a,b,c]
plt.boxplot(data1)
plt.xlabel("Colleges")
plt.yl... |
b4773f33ce6f1d74442e1195291e76dfb5f6f8aa | aashaanX/Pycodes | /fiboonnaci_recursion.py | 167 | 4.09375 | 4 | n=int(input())
def fibonacci(n):
if n==0:
return 0
elif n==1:
return 1
elif n==2:
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)
print(fibonacci(n))
|
b034a6b7e9d13a7e229de870a136c81663f3a9ba | albihasani94/PH526x | /week1/Homework/Exercise_2.py | 460 | 3.53125 | 4 | import random, math
random.seed(1)
def in_circle(x, origin=[0] * 2):
return x[0] - origin[0] < 1 and x[1] - origin[1] < 1
R = 10000
x = []
inside = []
for i in range(R):
point = [random.uniform(-2,2), random.uniform(-2,2)]
x.append(point)
if in_circle(point, origin=(0, 0)):
inside.append(Tr... |
cd0212a0494ff90e876c0bb67a9ce82ac0ccc66d | Iseke/BFDjango | /week1/Informatics/Loop/FORloop/J.py | 85 | 3.703125 | 4 | count = 0;
for x in range(1, 101):
num = int(input())
count+=num
print(count) |
70da66daf44690518028d77c8b2ac11e6f2d9fa8 | Isonzo/100-day-python-challenge | /Day 25/main.py | 1,198 | 3.875 | 4 | # import csv
#
# with open("weather_data.csv") as data_file:
# data = csv.reader(data_file)
# temperature = []
# for row in data:
# print(row)
# if row[1] != "temp":
# temperature.append(int(row[1]))
# print(temperature)
import pandas
# data = pandas.read_csv("weather_data.csv"... |
6efb4f2811f020b32eced5999b06d17aed38f80f | Cliffcoding/python-the-hard-way | /ex7.py | 686 | 4.03125 | 4 | # will print the sting the number of times specified. String must my multiplied and can not be added
# You can do the math seperatly then multiply that by the string.
print('This is a string {}'.format('i'))
print('hello' * 10)
print('yowdy ' * (3 * 9 + 4))
# Takes a single letter and concats it to form a sentence.
# U... |
36034447aaa29729f8d18b773447eb0ba9eb572e | Jeremy277/exercise | /pytnon-month02/exercise/sort_对比.py | 690 | 3.625 | 4 | #1.
l = [4,5,7,1,2,9,6,8]
def mysort(list):
count = 0
#len(list)-1 最后一个数据 后面没有值了 不需要再比较
for r in range(len(list)-1):
#从当前数据的位置+1(下一个数据)开始 一直比到最后
for c in range(r+1,len(list)):
count += 1
#如果当前数据比后面的数据大 交换位置
if list[r] > list[c]:
#a,b = b,a
... |
3cf51024343631cd1a19cd6a0d924c843602b61e | minhye-lee/AlgorithmStudy | /algorithm_basic/data_structure/bracket/bracket.py | 561 | 4 | 4 | def check_bracket(_bracket):
_cnt_left_bracket = 0
_cnt_right_bracket = 0
for element in _bracket:
if element == '(':
_cnt_left_bracket += 1
elif element == ')':
_cnt_right_bracket += 1
if _cnt_left_bracket < _cnt_right_bracket:
return ... |
aead9f16b10bd77d64544043dd7518668bc90169 | tberhanu/elts-of-coding | /Recursion/hanoi_tower.py | 2,478 | 4.0625 | 4 | # Star Question
def solve_hanoi_tower_puzzle(N, A, B, C):
"""
Question: Assume you have N Rings pilled on Tower A like ring1, ring2, ring3, ... ringN where the largest ringN
will be placed at the very bottom of the Tower, followed by the next largest ringN-1, ringN-2 until
ring1 that... |
b4245df76af18326f6f54149b20d4df7af55ebd8 | StevenYangSX/Python-Course | /notes.py | 1,223 | 3.796875 | 4 | ##### Binary Search ########
def binarySearch(L, secret=73):
'''
L must be sorted.
'''
left = 0
right = len(L) -1
while left <= right:
mid = (left+right)/2
if L[mid] == secret:
return mid
elif L[mid] < secret:
left = mid + 1
else:
... |
f045465820be27b357be5a94de0c68d671884fbd | khadijakhaldi/Project-Gutenberg | /sentence completion.py | 2,671 | 3.953125 | 4 | '''
We want to create a simple autocomplete-like feature where we can input one or more words, and be returned a list of all sentences that can start with our input.
'''
from collections import defaultdict
class TrieNode:
# Trie node class
def __init__(self):
self.children = defaultdict()
# is... |
48fe277d93f101a7492a4ec2a01c161b909c72b1 | mikaelbeat/Modern_Python3_Bootcamp | /Modern_Python3_Bootcamp/Loops/Exercise2.py | 264 | 3.828125 | 4 |
from random import randint
number = 0
rounds = 0
while number != 5:
number = randint(1,10)
rounds += 1
print("Round: " +str(rounds) + " random number is " + str(number))
print("Randon number is 5 in round " + str(rounds))
|
154cbbbd2f7e0e9d0adb56c65199b133b3216825 | liuweilin17/algorithm | /leetcode/677.py | 1,428 | 3.546875 | 4 | ###########################################
# Let's Have Some Fun
# File Name: 677.py
# Author: Weilin Liu
# Mail: liuweilin17@qq.com
# Created Time: Tue Feb 19 21:04:27 2019
###########################################
#coding=utf-8
#!/usr/bin/python
#677. Map Sum Pairs
class TrieNode:
def __init__(self):
... |
b64763fed91c52fc36cefd2d0ca1c36b58825580 | Freeha-S/problemset | /datetime1.py | 1,285 | 4.375 | 4 | #this programme outputs today’s date and time in the format
# ”Monday, January 10th 2019 at 1:15pm”.
# @ Freha
import datetime # import datetime module
d = datetime.datetime.today() # get todays date in variable d
st=[1,21,31]
da= int(d.day) # as day is string in daytime object so need to cast it to integer to use ... |
fdad4b8b0faff7c96783c7cd4decb342f692f2bb | giovane-aG/exercicios-curso-em-video-python | /high_tech_tabuada.py | 143 | 4 | 4 | number = int(input('Digite um número: '))
print('Tabuada do número', number)
for i in range(1, 10):
print(number, 'x', i, '=', number * i)
|
3ee76e53d3ba05a914e13ec59105d650ce7f1d61 | greenkey/sales_taxes_test | /print_receipt.py | 736 | 3.53125 | 4 | import fileinput
import re
from decimal import Decimal
import math
from sales_taxes import get_rate, Item
def main():
items = [i for i in get_items_from_file(fileinput.input())]
print(produce_final_output(items))
def get_items_from_file(file_handler):
for line in file_handler:
item = Item()
... |
48c15e0d3f7ec42bd39ea53a6a35daf2263a7de0 | Dominic-Harvey/CS50 | /pset6/dna/dna.py | 2,027 | 3.953125 | 4 | import csv
from sys import argv, exit
import re
def main(argv):
if len(argv) != 3: #makes sure 2 args have been given
print("Usage: python dna.py data.csv sequence.txt")
exit(0)
STR_id, STR_pairs = count_STR(argv[1], argv[2])
check_database(argv[1], STR_id)
def count_STR(database, string)... |
41281e1c1d6b8b374adce8102ed370211689eef3 | MultiBug/python | /5_exceptions_and_files/Lesson_45/Lesson_45.py | 490 | 3.578125 | 4 | ####################################
# 45.1 Вызов исключений
print(1)
raise ValueError
print(2)
####################################
####################################
# 45.2 Вызов исключений
name = "123"
raise NameError("Invalid name!")
####################################
####################################
# 45.3... |
fe6098ddd80645d0077d0db6243667d0650e93d7 | leehsueh/djangoapps | /bible_tidbits/data/setup/read_bible.py | 4,634 | 4.09375 | 4 | # script to parse the plain text kjv Bible ('bible13.txt')
# bible13.txt downloaded from Project Gutenburg
import string
import re
def strip_header(file, starttext):
temp = file.readline()
while temp.find(starttext) == -1:
temp = file.readline()
return file
def read_kjv(filename):
"""Parse KJV... |
d9be2f30356610366393e47d26a449ac7666526b | sahilshah1610/LeetCode | /MediumLevel/MergeIntervals.py | 695 | 3.625 | 4 | class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
intervals.sort(key=lambda x:x[0])
i = 1
while(i<len(intervals)):
if intervals[i][0] <= intervals[i-1][1]:
starting ... |
788866b9fb16bc153d6994ffab4b45a315ffdf4c | MtKuma/Python_Basic_Ex | /02 - Boucles/Ex_boucle_11-20.py | 2,523 | 3.703125 | 4 | # Exercice 19
# Créer un programme qui demande un mot à l'utilisateur et qui lui retourne le nombre de voyelles qu'il y a dans le mot entré.
"""
mot = input("Entrez un mot :\n")
compteurVoyelle = 0
for lettre in mot :
if lettre in "aeiouyAEIOUY":
compteurVoyelle += 1
#print(lettre)
print("\nLe nombr... |
7a0d12b7f7558cf69c87215f0e9dba17baecd366 | livelifeyiyi/myleetcode | /94. Binary Tree Inorder Traversal.py | 703 | 3.765625 | 4 | import binaryTree
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stack = [root]
res = []
while stack:
node = stack.pop()
if isinstance(node, int):
res.append(node)
continue
if node:
if node.right:
stack.append(node.right)... |
85943bd8dd12d43b5cad7d63c7b6021bcf768721 | libra202ma/cc150Python | /chap18 Hard/18_10.py | 302 | 3.75 | 4 | """
Given two words of equal length taht are in a dictionary, write a
method to transform one word into another word by change only one
letter at a time. The new word you get in each step must be in the
dictionary.
EXAMPLE
Input: DAMP, LIKE
Output: DAMP->LAMP->LIMP->LIME-LIKE
Recursion.
"""
# TODO
|
3236887df489809913ad9e89df1fcad093cb9aa6 | MiLk/adventofcode | /2019/day11/__init__.py | 2,192 | 3.546875 | 4 | from collections import defaultdict
from typing import Dict, Tuple
from intcode import Computer
from utils import int_list_lines
parse_input = int_list_lines(',')
directions: Dict[int, Tuple[int, int]] = {
0: (0, 1), # UP
1: (1, 0), # RIGHT
2: (0, -1), # DOWN
3: (-1, 0), # LEFT
}
def p1(lines... |
54eb56a42f06c588bc522df536fd5a9ec0121866 | dctongsheng/my-python | /练习题.py | 2,324 | 3.859375 | 4 | # _*_ coding:utf-8 _*_
'''
把乘法表打印出来%d"*"%d"="%d%(j,i,j*i)
'''
# for i in range(1,10):
# for j in range(1,i+1):
# print("%d*%d=%d"%(j,i,j*i),end=" ")#格式化输出应该引号中
# print("\n")
# i = 1
# while i<10:
# j = 1
# while j<=i:
# print("%d*%d=%d"%(j,i,i*j),end = " ")
# j+=1
... |
2139b78402908739cbdacaa09e0fe7bc279d95f0 | Samia-00/Python_Basic | /Data Structure/basicFunction.py | 323 | 3.734375 | 4 | class Robot:
def introduce_self(self):
print("My name is " + self.name)
print("My color is " + self.color)
print (self.weight)
r1=Robot()
r1.name = "tom"
r1.color = "red"
r1.weight = 30
r2=Robot()
r2.name="jerry"
r2.color="blue"
r2.weight = 40
r1.introduce_self()
r2.introduce_self... |
8f2a41722059d7c35adc9b97b0f0d05d23c29800 | meliezer124/SheCodes | /Notes/Strings.py | 1,802 | 4.53125 | 5 | ## Formatting
#Usual way :
variable = "string"
print("{}".format(variable))
#Using fstring:
print(f"{variable}") # the fstring allows you to remove the .format() and insert variables directly into their spot
#To look at what actions you can take with a type, use help(TYPE). For example:
help(str)
#Can access fields f... |
44f34244dbf7b8246e98fb967593951c6240b814 | tinkle1129/Leetcode_Solution | /DynamicProgramming/650. 2 Keys Keyboard.py | 1,284 | 3.75 | 4 | # - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: 2 Keys Keyboard.py
# Creation Time: 2018/1/5
###########################################
'''
Initially on a notepad only one character 'A' is present. You can perform two operations on this... |
1099ae504f18ab6ede2d92892eed8046c6728cc5 | Abjcodes/ML-DL-implementation | /MLlib/utils/misc_utils.py | 5,284 | 3.828125 | 4 | import numpy as np
import pickle
def read_data(file):
"""
Read the training data from a file in the specified directory.
Parameters
==========
file:
data type : str
Name of the file to be read with extension.
Example
=======
If the training data is stored in "dataset... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.