blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
8165feb1cf2ff8de8f80ca6d2aa289c848364481 | buildtesters/buildtest | /buildtest/utils/timer.py | 818 | 4.09375 | 4 | import time
class TimerError(Exception):
"""A custom exception used to report errors in use of Timer class"""
class Timer:
def __init__(self):
self._start_time = None
self._duration = 0
def start(self):
"""Start a new timer"""
if self._start_time is not None:
... |
d8508b1c364c2e9a2da7a50ac32a85bcb4bbc0a1 | searfmat/CLRS-Algos | /heapsort.py | 930 | 3.828125 | 4 | import math
def left(i):
return (i << 1) + 1
def right(i):
return (i << 1) + 2
def maxHeapify(arr, i, heapsize):
l = left(i)
r = right(i)
if l <= heapsize and arr[l] > arr[i]:
largest = l
else:
largest = i
if r <= heapsize and arr[r] > arr[largest]:
largest = r
... |
60e768f72e64ce0952b5baa1199848861301e999 | mahalakshmiraja/learn-python | /anti_vowel.py | 318 | 4.03125 | 4 | def anti_vowel(text):
lst = []
text = text.lower()
length = len(text)
for i in range(length):
if text[i]!="a" and text[i]!="e" and text[i]!="i" and text[i]!="o" and text[i]!="u":
lst.append(text[i])
print ("".join(map(str,lst)))
anti_vowel("welcome DAY") |
d57c2dfcc21a8a6a2c7aecc1ab70b75b1ce3c9b5 | alvinwang922/Data-Structures-and-Algorithms | /Trees/House-Robber-Three.py | 1,274 | 3.921875 | 4 | """
The thief has found himself a new place for his thievery again.
There is only one entrance to this area, called the "root."
Besides the root, each house has one and only one parent house.
After a tour, the smart thief realized that "all houses in this
place forms a binary tree". It will automatically contact th... |
b236a94f8b28348347ead209b98a7e0b996f9671 | FrosT2k5/LucifeR | /lucifer.py | 4,060 | 3.53125 | 4 |
import sys
import os
def clr():
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
def banner ():
ban = """
_ _ __ _____
| | (_)/ _| | __ \
| | _ _ ___ _| |_ ___| |__) |
| | | | | |/ __| | _/ _ \ _ /
... |
ca9f3c0c2336fe605b241d25e6b380496f733eaa | Jelowpat/Patryk-Jelowicki | /projects_from_infoshare_course/funtests/funtests.py | 5,677 | 3.625 | 4 | #a function for creating a new funtest
def nowy_test(nazwa=""):
licznik = 0
if nazwa == "":
nazwa = input("podaj nazwe testu(pliku)")+".txt"
plik = open(nazwa, "a", encoding="utf-8")
while True:
a = 0
pytanie_nowe = input("wpisz tekst swojego pytania, 'k' by zakonczyc")
i... |
2b74bc9a8dd5a098fa983cf352cb4222103c1068 | ywkpl/DataStructuresAndAlgorithms | /tree/test.py | 294 | 3.515625 | 4 | from datetime import datetime, timedelta
if __name__=="__main__":
begin = datetime(2018, 11, 1)
end = datetime(2019, 6, 18)
times=end-begin
print('天数:')
print(times.days)
print('月数余天数:')
print(str(times.days//30)+'月'+str(times.days%30)+'天')
|
d62313fc1a9dd396bfbb3e09defa940bdc2ef88c | jgarza9788/HackerRankCode | /Python/MergeTheTools!.py | 709 | 3.765625 | 4 | #Merge the Tools!
#https://www.hackerrank.com/challenges/merge-the-tools/forum
def merge_the_tools0(string, k):
i = 0
while i < len(string):
s = string[i:][:k]
fs = ''
for l in s:
if l in fs:
pass
else:
fs = fs+l
print(f... |
a40b78c6a113961e0a4eced2938e3da6c59c7af4 | developeryuldashev/python-core | /python core/Lesson_9/list_53.py | 158 | 3.796875 | 4 | a=[3,5,9,6,1]
b=[2,5,7,4,9]
c=[]
for i in range(len(a)):
if a[i]>=b[i]:
c.append(a[i])
else:
c.append(b[i])
print(a)
print(b)
print(c) |
9b42a10f3f7729255de50021347b3b93eb7db675 | Zasaz/Python-Practise | /Conditional.py | 165 | 3.875 | 4 | age = 18
if age >= 18:
print("You can vote")
print("Mature")
elif age < 18:
print("Not mature")
else:
print("Ok bye")
print("Ok i am done")
|
934c54e6dfab43180cb50c67dca9296ee1638e2f | danlaratta/rock-paper-scissors | /Rock_Paper_Scissors.py | 3,745 | 3.96875 | 4 | import tkinter as tk
import random
# sets up window, window's size, window's title, and window's background color
window = tk.Tk()
window.geometry("350x300")
window.title("Rock, Paper, Scissors")
window.configure(background='#66e0ff')
# game title
game_title = tk.Label(text="Rock, Paper, Scissors", bg="#66e0ff")
gam... |
155be1715b0e48b444fb66f8ac858ee3432bfd73 | shohoku3/Python30 | /demo9.py | 844 | 4.25 | 4 | # 结构化数据 字典
# 比较字典与列表
spam =['cats','dogs','mosses']
bacon=['dogs','cats','mosses']
if spam == bacon:
print('两个 list相同')
else:
print('两个list 不同')
eggs={'name':'zomap','age':'8'}
ham={'age':'8','name':'zomap'}
if eggs==ham:
print('两个字典相同')
else:
print('两个字典不同')
# values() keys() items()
for v in eggs.values():
pr... |
574d23e153afbdaf9b044b5296a12a9ef7c868e3 | gyang274/leetcode | /src/0500-0599/0542.matrix.distance.py | 1,046 | 3.609375 | 4 | from typing import List
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
"""bfs
"""
n = len(matrix)
if n == 0:
return []
m = len(matrix[0])
if m == 0:
return [[]]
queue = []
for i in range(n):
for j in range(m):
if matrix[i]... |
fe13512203237ee2d6dd3ba89e56840a611e315f | nsyzrantsev/algorithms_2 | /BinarySearchTree/BinarySearchTree.py | 5,239 | 3.609375 | 4 | # https://skillsmart.ru/algo/15-121-cm/bcd63523a1.html
class BSTNode:
def __init__(self, key, val, parent):
self.NodeKey = key
self.NodeValue = val
self.Parent = parent
self.LeftChild = None
self.RightChild = None
class BSTFind:
def __init__(self):
self.Node = N... |
4c177efc84ae9b4b127ba9560fef79962a48f7fe | sandeephalder/AlgoPractice | /Python/DP_Tushar/MinimumCostpath.py | 917 | 3.78125 | 4 | class MinimumCostPath():
weights = [[1,3,5,8],[4,2,1,7],[4,3,2,3]]
knapsack = [[0 for i in range(4)] for j in range(3)]
def print(self):
for i in range(3):
print()
for j in range(4):
print('-->',self.knapsack[i][j],end='-->')
def compute(self):
s... |
887eb20cba1cf61d838a65665d8b354cd0db50d0 | desmondlee/python | /while.py | 122 | 3.75 | 4 | # -*- coding: utf-8 -*-
L = ['Bart', 'Lisa', 'Adam']
n = len(L)
while n > 0 :
print("Hello, %s" % L[n-1])
n = n-1 |
dc48c9fc6d4326b999b17b65620514e0cfb3b58b | dombroks/Daily-Coding-Problems | /Microsoft_Problems/Microsoft_Problem_02.py | 1,370 | 3.734375 | 4 | """
This problem was asked by Microsoft.
You have an N by N board. Write a function that, given N, returns the number of possible arrangements of the board where N queens can be placed on the board without threatening each other, i.e. no two queens share the same row, column, or diagonal.
"""
N = 4
#NxN matrix with a... |
a515377a5c40ad22a74ea8a739af760ab9228d57 | testtatto/project_euler | /problem5.py | 583 | 4.0625 | 4 | """
2520 は 1 から 10 の数字の全ての整数で割り切れる数字であり, そのような数字の中では最小の値である.
では, 1 から 20 までの整数全てで割り切れる数字の中で最小の正の数はいくらになるか.
"""
import math
# 最小公倍数を求める関数
def lcm(a, b):
return a * b // math.gcd(a, b)
if __name__ == '__main__':
current_lcm = 1
# 最小公倍数を再帰的に更新していく
for i in range(1, 21):
current_lcm = lcm(curre... |
2ab678ffac70087c9374212c2451f1be19f27526 | neelabhpant/Intermediate_Python_For_Data_Science | /Using_Pandas.py | 948 | 4.03125 | 4 | import pandas as pd
names = ['United States', 'Australia', 'Japan', 'India', 'Russia', 'Morocco', 'Egypt'] # The country names for which data is available.
dr = [True, False, False, False, True, True, True] # A list with booleans that tells whether people drive left or right in the corresponding country.
cpc = [809, ... |
0d9a60aa6fb66af8c29c1c2fe0e0368f62410772 | ehhglen/Temperature-Conversion-Table | /TempConvertor.py | 960 | 4.03125 | 4 |
# Variables
Celsius = 0
list_of_celsius = [
0,
10,
20,
30,
40,
50,
60,
70,
80,
90,
100
]
# Function to convert Celsius to Fahrenheit
def convToFahrenheit(Celsius):
listOfFahrenheits = []
while (Celsius != 110):
fahrenheit = (Celsius * 9/5) + 32
Cels... |
44e1a16a97bfc253815c17d6abe79e441d035da3 | 18801308557/versusGame20210401 | /positionFunc.py | 305 | 3.84375 | 4 | import math
#计算两点之间距离是否小于r
def distanceInR(cx,cy,r,x,y):
dist=math.sqrt((math.pow(x-cx,2)+math.pow(y-cy,2)))
if dist<r:
return True
else:
return False
def distanceCal(cx,cy,x,y):
dist=math.sqrt((math.pow(x-cx,2)+math.pow(y-cy,2)))
return dist
|
16a873eb730d19c2d438a3369d599df0fdef55bf | szabgab/slides | /python/examples/dictionary/count_words_speed.py | 1,841 | 3.84375 | 4 | from collections import defaultdict
from collections import Counter
import timeit
def generate_list_of_words(number, repeat):
#words = ['Wombat', 'Rhino', 'Sloth', 'Tarantula', 'Sloth', 'Rhino', 'Sloth']
words = []
for ix in range(number):
for _ in range(repeat):
words.append(str(ix))
... |
34fcab54149e7ba78af0cdc80470629c5ec53d43 | BettiouiFarid/SHA-1 | /sha256.py | 1,078 | 3.640625 | 4 | # import the library module
import hashlib
def sha256 (text):
# encode the string
encoded_str = text.encode()
# create a sha1 hash object initialized with the encoded string
hash_obj = hashlib.sha256(encoded_str)
# convert the hash object to a hexadecimal value
hexa_value = hash_obj.hexdigest... |
81b2618645cdbe98598fd21e66f78c38bb005b7c | sanjoycode97/python-programming-beginners | /python tutorial/arithmatic progression/print the sum of n/python programming practice/count number of odd and even number in the list.py | 150 | 3.984375 | 4 | My_list=[1,2,3,4,5,6,7,8]
even=0
odd=0
for x in My_list:
if x%2==0:
even=even+1
else:
odd=odd+1
print(" ",even)
print(" ",odd) |
bac9041c8fd2278a20219b5af95cf6533f005971 | corineru/show_sword_to_offer | /print_binaryTree_after_lines.py | 799 | 3.578125 | 4 | # 2018-04-29
# xinru
# file: 把二叉树打印成多行
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
# write code here
if not pRoot:
return []
node_list = [pRoo... |
6c6279f8b6d10384c37708f51cc435d2ce0bce75 | GayatriMhetre21/python10aug21 | /Assignment2.que1/Area/oval/aoval.py | 144 | 3.890625 | 4 | # area of oval i.e area of an ellipse
PI = 3.14
def areaofoval(a, b):
result = PI * a * b
print("Area of oval : ", result, "units") |
7e9e962f2885f0129f27ab3d47ff8a70ab5b4850 | madduxc/Think_Python | /Chapter_5.py | 4,866 | 4.28125 | 4 | #Author: Charles D. Maddux
#Date: 12/28/2020
#Description: Think Python Chapter 5 exercises
import time
import turtle
def exercise_1(current_time):
"""
times the current time and converts to days, hours, minutes, seconds since the epoch
"""
#declare variables
unit_min = 60 ... |
bc3029b6ae717e192d185775694849c348cc48d7 | DanWro/Python | /Pythons/TicetForSpeed.py | 247 | 3.5 | 4 |
a=float(input("podaj limit: "))
b=float(input("podaj predkosc: "))
x=list(range(1,10))
m=(b-a<=10)
M=(b-a>10)
m1=(b-a)*5
M1=((10*5)+(b-(a+10))*15)
if m:
print(m1, "zl")
if M:
print(M1, "zl")
|
6e05b539a961ba4a5eae8b6ab07ac1b94e221246 | WuIFan/LeetCode | /Solutions/Roman_to_Integer.py | 527 | 3.578125 | 4 | class Solution:
table = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
def romanToInt(self, s: str) -> int:
ans = 0
last = 0
for c in reversed(s):
num = self.tabl... |
57367bee7da71ff6af5f18f68296240fda53b7d1 | gkimetto/PyProjects | /GeneralPractice/ListComprehension.py | 415 | 4.21875 | 4 |
x = [i for i in range(10)]
print(x)
squares = []
squares = [i**2 for i in range(10)]
print(squares)
inlist = [lambda i:i%3==0 for i in range(5)]
print(inlist)
# a list comprehension
cubes = [i**3 for i in range(5)]
print(cubes)
# A list comprehension can also contain an if statement to enforce
# a condition on... |
93df2fe9045a1d3c8f928ab64313371f3c0ce803 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4159/codes/1637_869.py | 270 | 3.640625 | 4 | # Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Use as mensagens de erro para corrigir seu código.
total = float(input("valor: "))
if(total>=200):
print(round(total-total/20, 2))
else:
print(round(total, 2)) |
0500420871411c5dd37882d145898a3cdb80abac | ericksalas11/python-exercise | /par-impar.py | 225 | 3.875 | 4 | print("Los numeros son: 4, 12, 15, 51, 563, 10 ")
numbers = [4, 12, 15, 51, 563, 10]
for numero in numbers:
if numero % 2 == 0:
print("Es par")
else:
print("Es impar")
print("Respectivamente") |
b4cbe92376ecb0f65fb64f6a08ea3e4f7699ddd9 | 3deep0019/python | /Input And Output Statements/evil.py | 336 | 4.375 | 4 | # eval():
# ---> eval Function take a String and evaluate the Result.
x = eval('10+20+30')
print(x)
# eval() can evaluate the Input to list, tuple, set, etc based the provided Input.
# Eg: Write a Program to accept list from the keynboard on the display
l = eval(input('Enter List'))
print (typ... |
1166b2e3a1366c98da23bad5485e3d7887bdb61a | 17313/GeorgeGriffindor | /SQL.py | 293 | 3.796875 | 4 | import sqlite3
with sqlite3.connect("BubbleLin.db") as connection:
c = connection.cursor()
sql = "SELECT * FROM Bubble_tea"
c.execute(sql)
results = c.fetchall()
for result in results:
print("BubbleLin: {0:15} Price: ${1:0}" .format(result[1], result[2]))
|
2b6df80e733ccd30a087ca80deb45f48e5463ae4 | EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions | /Chapter4/4.2.py | 787 | 4.09375 | 4 | #Minimal Tree: Given a sorted (increasing order) array with unique integer elements,
#write an algorithm to create a binary search tree with minimal height.
class Node():
def __init__(self,item):
self.right = None
self.left = None
self.value = item
def __str__(self):
return '('+... |
7b615b039df019a0a278a298f56cacc5cf492c02 | Ana-Vi/Homework | /Pythons/futebol.py | 609 | 3.71875 | 4 | '''vitoria= 3
empate= 1
derrota= 0
pontos= 0
total=int(input("digite o numero total de jogos: "))
for aux in range(total):
gol_a_favor= int(input("a favor: "))
gol_contra= int(input("contra: "))
if gol_a_favor>gol_contra:
pontos= pontos+3
elif gol_a_favor== gol_contra:
pontos= pontos+1
... |
88429dbeb7a1b60116168f2701f01060c8f48791 | tsakallioglu/Google-Foobar | /KillKthBit.py | 757 | 3.8125 | 4 | #In order to stop the Mad Coder evil genius you need to decipher the encrypted message he sent to his minions.
#The message contains several numbers that, when typed into a supercomputer, will launch a missile into the sky blocking out the sun,
#and making all the people on Earth grumpy and sad.
#You figured out tha... |
6758b82cdbf70f4169672e441197ed86a51476b6 | thewinterKnight/Python | /dsa/Trees/6.py | 9,452 | 4 | 4 | # Implement a threaded binary tree.
import random
import copy
class LinkedListNode:
def __init__(self, tree_node=None, next=None):
self.tree_node = tree_node
self.next = next
def get_tree_node(self):
return self.tree_node
def get_next(self):
return self.next
def set_next(self, new_tree_node):
self.... |
5dbdbfa40c733af412d18ae87904f8acd2d13031 | tmtiuca/ECE406 | /assignment2.py | 2,693 | 4.4375 | 4 | #!/usr/bin/env python3
"""
Username : tmtiuca
Student # : 20521385
"""
"""
Assignment 2 Python file
Copy-and-paste your extended_euclid and modexp functions
from assignment 1
"""
import random
import math
import sys
# part (i) for modular exponentiation -- fill in the code below
def modexp(x, y, N):
"""
... |
9cd9f47d758a85f49a57141979e5fee50f6e1e38 | kielejocain/AM_2015_06_15 | /StudentWork/orionbuyukas/madlib.py | 914 | 3.625 | 4 | # -*- coding: utf -8 -*-
article = "Here, roughly, is what we know so far about today's middle-class "
print article
response = raw_input("Enter plural noun.")
article += response + ": They seldom walk or "
print article
response = raw_input("Enter a verb.")
article += response + " to school, as generations did be... |
4283466430a9a7dffbb88aa4af824f4bce959fae | DavidBitner/Aprendizado-Python | /Curso/Challenges/URI/1038Snack.py | 256 | 3.53125 | 4 | A, B = input().split(" ")
x, y = int(A), int(B)
total = float(0)
if x == 1:
total = y * 4
elif x == 2:
total = y * 4.50
elif x == 3:
total = y * 5
elif x == 4:
total = y * 2
elif x == 5:
total = y * 1.50
print(f"Total: R$ {total:.2f}")
|
3017307ef8e6405fe8490003d68647543cdd4ef2 | bphillab/Five_Thirty_Eight_Riddler | /Riddler_18_08_03/Riddler_Express.py | 355 | 3.59375 | 4 | def calculate_non_water_weight(total_weight, percent):
return (1-percent)*total_weight
def calculate_new_weight(non_water_weight, percent):
return non_water_weight/(1-percent)
if __name__ == "__main__":
non_water_weight = calculate_non_water_weight(1000,.99)
new_weight = calculate_new_weight(non_wate... |
1b240091623b7f7cb1544456dbf1c98927f5ca0e | Kashif1Naqvi/Python-Algorithums-the-Basics | /quick_sort.py | 1,387 | 3.984375 | 4 | # implement a quicksort
items = [20,6,8,53,56,23,87,41,49,19]
def quickSort(dataset,first,last):
if first < last:
# calculate the split point
pivotIdx = partition(dataset,first,last)
# now sort the two partitions
quickSort(dataset,first,pivotIdx-1)
quickSort(dataset,pivotIdx+1,last)
def part... |
3cec8eaf6f68590519155613b2667106672eb034 | soraef/nlp100 | /1/8.py | 330 | 3.75 | 4 | import re
def convert(match):
return chr(219 - ord(match.group()))
def cipher(text):
return re.sub(r"[a-z]", convert, text)
# p21 名前に情報を追加する
plain_text = "ABCdefg1234あいうえおに"
encrypted_text = cipher(plain_text)
print(encrypted_text)
plain_text = cipher(encrypted_text)
print(plain_text) |
61e436b47dd905c70193100bcadbe146e17ccff4 | BeatrizOliveiraFerreira/DesafiosPython | /exercicio50.py | 250 | 3.90625 | 4 | soma = 0
count = 0
for i in range(1, 7):
valor = int(input('Digite um valor: '))
if i % 2 == 0:
soma = soma + valor
count = count + 1
print('A soma de todos os {} números PARES é igual a {}'.format(count, soma))
|
b9e9c1adc40e953a9d4a7bd757dfb9da9302f7a4 | Jason8Ni/MarkovianMusic | /src/parseMIDI.py | 3,442 | 3.515625 | 4 | #!/usr/bin/python3
# This class will parse the MIDI file and build a basic Markov chain from it
import hashlib
import mido
import argparse
from markovChain import MarkovChain
class ParseMIDI:
def __init__(self, filename):
"""
This is the constructor for a Serializer. This will serialize
... |
962d6503975d869f920e8d21700eb767555b4c52 | lpvera22/Study | /Lista_Ejercicios_3/Ejercicio_9.py | 678 | 3.765625 | 4 | # *-* encoding:UTF-8 *-*
'''Dado um conjunto S com n elementos, elabore um algoritmo que imprima todos os subconjuntos de S.'''
def Subconjuntos(conjunto):
subconjuntos = []
set_size = len(conjunto)
if set_size > 1:
subconjuntos += Subconjuntos(conjunto[1:])
elemento = [conjunto[0]]
... |
a4d113eb0c28e0fce8bf4f2ed33391dac90e5353 | RooL1024/-offer | /Python/平衡二叉树.py | 668 | 3.65625 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
if self.getDepth(pRoot) == -1:
return False
return True
... |
b1ccb52ff1fe2024ca8a19a8756d57ccd0d83910 | simonpatrick/interview-collections | /python/basic/file_io/randome_access_line.py | 382 | 3.71875 | 4 | # -*- coding: utf-8 -*-
# will not read file into memory
print(__file__)
sum=0
# generator
with open('sample_text.txt','r') as f:
for line in f:
sum+=1
print(line)
print(sum)
sum=0
# read line
big_file = open('sample_text.txt','rt')
line = big_file.readline()
while line:
line=big_file.readline... |
46afc3dcc0468761c9c6403d18abd2aeba46196d | royliu317/Code-of-Learn-Python-THW | /ex33_4.py | 802 | 4.09375 | 4 | # The rule of variable scopes: L(Local) –> E(Enclosing) –> G(Global) –>B(Built-in)
x1 = int(1) # Bulit-in
x2 = 2 # global
def outer():
x3 = 3 # Enclosing
def inner():
x4 = 4 # Local
print(x1, x2, x3, x4)
inner()
outer()
# Keywords: global, nonlocal
numbers = []
i = 0
de... |
a82ddbc979e8a6f1338d77ccc78f123609dd7e91 | OokGIT/pythonproj | /stochastic/random_walk.py | 4,849 | 4.03125 | 4 | import random
random.seed(0)
class Location(object):
def __init__(self, x, y):
'''
x and y are floats
'''
self.x = x
self.y = y
def move(self, deltaX, deltaY):
'''
deltaX and deltaY are floats
'''
return Location(self.x + deltaX, self.y +... |
dc1f13f80a6eaa3463531ccd1a6a1b83135d7696 | sharifahmeeed/AlgorithmandDataStructurePython | /array_python_list.py | 577 | 4.0625 | 4 | numbers = [10, 20, 30, 40, 50]
numbers[1] = "Adam"
print('Standard')
for num in numbers:
print(num)
print('\n \nNot standard')
for i in range(len(numbers)):
print(numbers[i])
print('first 2 items item: ', numbers[0:2])
print('without last one item: ', numbers[:-1])
print('without last two item: ', numbers[... |
adad9d91bd8ffd3498bed2dd18e23177aa1382a2 | nekozing/playground | /raw_algorithms/diff/edit_distance_dag.py | 497 | 3.53125 | 4 | def diff(a, b, i, j):
return 1 if a[i] != b[j] else 0
def edit_distance(a, b):
m = len(a)
n = len(b)
mn = [[0 for x in xrange(n+1)] for x in xrange(m+1)]
for i in range(m + 1):
mn[i][0] = i
for j in range(n + 1):
mn[0][j] = j
for j in range(1, n + 1):
for i in range(1, m + 1):
mn[i][j] = min(mn[i-1][j]... |
873db0cb7c9efe8914c7eaf6a9b0026fab2c3464 | wansook0316/problem_solving | /210701_백준_최단경로.py | 945 | 3.625 | 4 | import sys
import heapq
input = sys.stdin.readline
def dijkstra(start):
q = []
heapq.heappush(q, [0, start])
distance[start] = 0
while q:
now_cost, now_node = heapq.heappop(q)
if now_cost > distance[now_node]:
continue
for next_node, weight in graph[now_node]:
... |
eeda1ad3fb7941a5f496f70312e0d3a4c9b9b282 | hiSh1n/learning_Python3 | /py_project04.py | 245 | 4.25 | 4 | #To find out the greatest number from any two numbers.
first_no = int(input("enter first no. "))
second_no = int(input("enter second no. "))
if first_no >= second_no:
print(first_no, "is greater.")
else:
print(second_no, "is greater.")
|
6f9704f5bec83a4bde79caab50e62cbe14de6330 | darsovit/AdventOfCode2017 | /Day16/Day16.75.py | 5,419 | 3.5625 | 4 | #!python
def shift_programs( programs, shift_value ):
assert( shift_value > 0 )
return programs[-shift_value:] + programs[:-shift_value]
def exchange_slots( programs, slots ):
assert( len( slots ) == 2 )
tmp = programs[slots[1]]
programs[slots[1]] = programs[slots[0]]
programs[slots[0]] =... |
28d1a70bc75fb4d2a6ec551ab1380b3c95f85824 | experimentAccount0/lancet | /tests/test_shell_command.py | 2,441 | 3.515625 | 4 |
from collections import OrderedDict
from unittest import TestCase, main
from lancet import ShellCommand
class TestShellCommand(TestCase):
def test_kwargs_are_passed_correctly_ordered(self):
"""
Test ShellCommand works correctly with an OrderedDict
"""
# Given
sc = ShellC... |
4815d4e85ce17aee78cdbc4a065b3b20e06da5de | yevaaaa/homeworkk | /hw8_Yeva.py | 2,396 | 4.0625 | 4 | """
Problem 1
Create 3 dictionaries for your favourite top 3 cars. Dict should contain information like brand, model, year, and color.
Add all those dicts in one dict and print items.
"""
d1 = {
"brand": "Mercedes",
"model": "amg gt",
"year": "2021",
"color": "black"
}
d2 = {
"brand": "porsche",
... |
51566b71081c89cb4bf35dfba2e3c7da2da803a9 | deepcpatel/data_structures_and_algorithms | /Trees/children_sum_parent.py | 2,173 | 4.25 | 4 | # Link: https://www.geeksforgeeks.org/check-for-children-sum-property-in-a-binary-tree/
'''
Given a Binary Tree. Check whether all of its nodes have the value equal to the sum of their child nodes.
Example 1:
Input:
10
/
10
Output: 1
Explanation: Here, every node is sum of
its left and right child.
Exam... |
48f54e2587d11c80f5c79df3e79abbb92d8bd9d0 | SebastianOsinski/AdventOfCode2017 | /Day 2/day2.py | 882 | 3.640625 | 4 | import functools
file = open("day2_input", "r")
lines = file.readlines()
def numbers_from_line( line ):
return [int(str) for str in line.split("\t")]
matrix = [numbers_from_line(line) for line in lines]
def sum(list):
sum = 0
for number in list:
sum += number
return sum
# Part 1
max_min_p... |
1c523aa8ce307224cf4001a49fdcaf3e1ae3928b | Rujabhatta22/program1 | /program2.py | 134 | 4.03125 | 4 | base=int(input('enter any number'))
height=int(input('enter any number'))
area= (base*height)/2
print(f'area of triangle is{area}')3
|
b1413be8aff2d5885b7372d05fd4a2b4d91f9d7c | meliezer124/SheCodes | /Lecture8/ex1_Q7.py | 973 | 4.15625 | 4 | # solving common recursion mistakes
def sum_every_other_number(n):
"""Return the sum of every other natural number
up to n, inclusive.
>>> sum_every_other_number(8)
20
>>> sum_every_other_number(9)
25
"""
if n <= 0:
return 0
else:
return n + sum_every_other_number(n ... |
0788bd8ccc154ee86fd9bf4e4b6bb4db3cafbf9e | ednacao/conway_game | /game_of_life.py | 1,848 | 3.734375 | 4 | """Conway's Game of Life
Rules:
1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
2. Any live cell with two or three live neighbours lives on to the next generation.
3. Any live cell with more than three live neighbours dies, as if by overcrowding.
4. Any dead cell with exact... |
0150569cfa4c141cdcac58fad58f5611aca2ef6f | lilbex/algorithm | /anagram.py | 1,007 | 3.96875 | 4 | def anagram(s1,s2):
#remove spaces and lowecase letters
s1 = s1.replace(' ','').lower()
s2 = s2.replace(' ','').lower()
#return boolean for sorted match.
if sorted(s1) == sorted(s2):
return True
print(anagram('dog', 'god'))
def anagrams(s1,s2):
#remove spaces and lowecase letters
s1 = s... |
ca720249983d762ef10677c3af659a9324ca9a43 | wuranxu/leetcode | /101to150/105. 从前序与中序遍历序列构造二叉树.py | 1,397 | 3.890625 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
mp = {x: i for i, x in enumerate(inord... |
307300e73a370760d1a677b0b4c6c55e790a16fe | RafinaAfreen/Python | /PartTwo/RegularExpression.py | 940 | 3.6875 | 4 | import re
#patterns = ['term1','term2']
text = 'this is a strimg with term1, not the other!'
#for pattern in patterns:
# print("I'm Searching for: "+pattern)
# if re.search(pattern,text):
# print("MATCH!")
# else:
# print("no Match!")
match = re.search('term1',text)
print(match.start())
s... |
4d3cf89a4445429382a44a1adc3fc9014d8528cc | DaftGeologist/Simple-Python-Projects | /Assg_7_Bubble_Sort.py | 1,307 | 3.828125 | 4 | from random import randint
def displayList(PList):
for i in range(0,10):
print(PList[i])
print(" ")
def loadList(PList):
for i in range(1,11):
PList.append(randint(1,10))
def sortList(PList,PDirection):
sorted=False
cmp=0
swap=0
i=9
while not sorted and... |
b9fdb4b34f6a8daafed9e9be5516099ea68ae9cf | ceccs18c36/Course-Codes | /django4e/SimpleWebBrowserPy/swb.py | 1,592 | 4.125 | 4 | import socket
# sockets are built into python.
# this lib is used to connect to the server,send data and to recieve data from the server
mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# socket.socket is used to make something to make the connections
# just like a phone in a telephone communication
myso... |
d82b67d3e41716669b7c874689e1c3355bc8846f | kylemarienthal/python_april_2018 | /loops.py | 4,471 | 3.75 | 4 | arr = [1,2,3,4,4,5,6,6]
# JAVASCRIPT
# for (start, stop, step) {
# ...
# }
# for (var i = 0; i < ...; i++) {
#
# }
for i in range(len(arr)):
print 'i: {}'.format(i)
print 'arr[' + str(i) + ']', arr[i]
print 'arr[{}] - {}'.format(i, arr[i])
print '*'*20
for i in arr:
print i
# if (arr.length > 5 &&... |
4231ba30d8cfa77e97b9f7a73caac8030b6e8811 | GaoZWei/Python_Study | /code/high_level/fun5.py | 144 | 3.65625 | 4 | # map 映射
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
def squre(x):
return x*x
for x in list_x:
squre(x)
r=map(squre,list_x)
print(list(r)) |
8417ecba88fcdf11b361d551739317be308d6ba5 | Pyloons/MyPractices | /算法与数据结构/排序/经典算法/选择排序/select_sort.py | 647 | 4.125 | 4 | def find_smallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def select_sort(arr):
new_arr = []
for _ in range(len(arr)):
smallest = find_smalles... |
5c8a49fb2ed72ec4a6dcc1fae1a96e6c009e9f08 | maykim51/ctci-alg-ds | /PastProblems/word_ladder.py | 4,028 | 3.875 | 4 | '''
[MS SDE] Word-ladder
https://leetcode.com/problems/word-ladder but with a complex description. Same idea, and process.
SOLUTION
1) Use bfs in graph, but key is intermediate_word!!!!!! like d*g, *og!
traverse 할때는 내가 만들 수 있는 intermediate_word를 기반으로 딕셔너리를 탐색!
2) Bidirecition BFS
'''
import unittest
##... |
447be83d74195e09cabfe328ba5841cc01e683ae | Symbii/python_Oj | /yield.py | 661 | 3.8125 | 4 | def fab(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
#Fab是一个迭代类
class Fab(object):
def __init__(self, max):
self.max = max
self.n = 0
self.a = 0
self.b = 1
def __iter__(self):
return self
def __next__(self... |
4de49b82e4e01524f927a321bf90f28d0dd3b1f5 | MysteriousSonOfGod/LeetCode | /Q003/longest-substring-without-repeating-characters.py | 1,019 | 3.75 | 4 | """
* longest-substring-without-repeating-characters.py
*
* @param {string} s
*
* @return {int}
"""
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
last_repeating = -1
longest_substring = 0
positions = {}... |
33cb46b3099c9142b8f380e7c83732df936776ef | ArunkumarRamanan/CLRS-1 | /StanfordAlgorithmDesignAnalysis/week5DjikstrShortestPath.py | 1,882 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 10 13:56:21 2016
@author: Rahul Patni
"""
# Djistra's shortest path algorithm
import sys
def loadGraph():
graph = dict()
filename = "dijkstraData.txt"
#filename = "Graph5Dijkstra.txt"
fptr = open(filename)
for line in fptr:
line = line.rstri... |
e886c821f918f02af401fc1571ee4bf5e089b5f8 | colin-bethea/leetcode | /python/problemset/217.py | 523 | 3.71875 | 4 | # https://leetcode.com/problems/contains-duplicate/
class Solution(object):
'''
Solution #1 - Set
---
Use a set to retrieve unique elements in input array. Compare the length of the set to the length of input array.
If they are the same, there is no duplicate. If they differ, there is a duplicate.... |
805289d59ed33112d18ecdb0e04568d377e3cbdb | Pranav-Khurana/Competitive-Coding | /HackerRank-Algorithms/Bon_appetit.py | 661 | 3.640625 | 4 | #https://hackerrank-challenge-pdfs.s3.amazonaws.com/24060-bon-appetit-English?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1562406181&Signature=wP3fYOaEe4enS72PgBmN5HrbjbY%3D&response-content-disposition=inline%3B%20filename%3Dbon-appetit-English.pdf&response-content-type=application%2Fpdf
# Enter your code here. Read i... |
672a366814df3b813aad582a0ed82926fce694f5 | qnguyen3010/Leetcode-Python | /q206.py | 863 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 19 15:28:10 2017
@author: AaronNguyen
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseList(self, head):
"""
... |
f7a494c32516f1ba060e7e345d38b5d700a209f4 | samidavies/Project-Euler | /euler_1-13-18.py | 942 | 3.578125 | 4 | def isPrime(n):
if n == 1:
return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def euler_sum(n):
if n == 1:
return 0
if n == 0:
return 1
total = 0
for k in range(1,n+1):
if isPrime(k):
total += k... |
83dec5b600e336696269ef6bae4ec9b89935efd8 | kailash-manasarovar/A-Level-CS-code | /challenges/yes-no-tree.py | 990 | 4.03125 | 4 | class Node:
def __init__(self, question, answer):
self.left = None
self.right = None
self.question = question
self.answer = answer
def insert(self, question, answer):
# Compare the new value with the parent node
if self.question:
if answer == "Y":
... |
52eb78599f30346f8bd59c1d0128921fe2be80f4 | saipoojavr/saipoojacodekata | /alphanum.py | 254 | 3.6875 | 4 | string=str(input())
count=0
count1=0
for iter in range(0,len(string)):
if(string[iter].isalpha()==True):
count=count+1
elif(string[iter].isdigit()==True):
count1=count1+1
else:
continue
if(count>0 and count1>0):
print("Yes")
else:
print("No")
|
d874c9c0074a6e012ed2ba5d7e849f6ff4fd29c7 | proformatique/algo | /tp9/Eleve.py | 6,510 | 3.84375 | 4 | class eleve:
'''Classe représentant un élève.
Example
-------
>>> e1 = eleve('1,salmi,said,15.25,14.0,15.5')
>>> e1
'1,salmi,said,15.25,14.0,15.5'
'''
def __init__(self, texte):
'''Constructeur pour créer des élèves.
Parameters
----------
tex... |
9e7260f13846f5e35cea372ed909e768270d440d | aashishd/code_jam_2020_python3 | /NestingDepth/nesting_depth.py | 901 | 3.9375 | 4 | class NestingDepth:
def __init__(self):
raw_input = input()
self.values = [int(raw_input[i]) for i in range(len(raw_input))]
self.result = ""
self.nested_string()
def nested_string(self):
# creates the string with nesting
prev_num = 0
for current_value in... |
212490fe5275ff731a4d7ba1eabc79f98a841fa4 | zita9999/Clean-Code-Z | /How To Send Emails, Using Python (2021).py | 1,531 | 3.984375 | 4 |
#---How To Send Emails, Using Python (2021)---
##################################### -Importing Necessary Libraries- #############################################
import smtplib, ssl
from email.mime.text import MIMEText
##################################### -Sender, Reciever, Body of Email- ############... |
efaef2a6ced638f68eadfe13e2b5c00a40ca666d | Dragon20C/TicTacToe | /main.py | 2,070 | 3.71875 | 4 | import random
board = {"top-L": "", "top-M": "", "top-R": "", "mid-L": "", "mid-M": "", "mid-R": "", "low-L": "", "low-M": "",
"low-R": ""}
def draw():
print(board["top-L"] + " ┃ " + board["top-M"] + " ┃ " + board["top-R"])
print("------")
print(board["mid-L"] + " ┃ " + board["mid-M"] +... |
575838876475c5329ddf730414b6e8d7ea34608d | blue-alexa/ML_models | /dual_perceptron.py | 2,858 | 3.6875 | 4 | """
Dual Perceptron
1. Start with zero counts (alpha)
2. Pick up training instances one by one
3. Try to classify xn,
y = argmax(Sigma ai,y K(xi,xn)) bias?
4. If correct, no change!
5. If wrong: lower count of wrong class (for this instance), raise count of right class (for this instance)
ay,n = ay,n-1
ay*,n = ay*,n+1
... |
5f571d6b22cf4e568f526f9b6a87f6f687845d5b | serek2298/Embeded-Sys | /main.py | 499 | 3.875 | 4 |
''' Program wyznaczający pierwiastki
trójmianu dla przypadków rzeczywistych
'''
import math
a = float(input('a=')) # Wczytaj a
b = float(input('b='))
c = float(input('c='))
delta = b**2 - 4*a*c
if delta > 0:
x1 = (-1*b + math.sqrt(delta))/(2*a)
x2 = (-1*b - math.sqrt(delta))/(2*a)
print('Dwa pierwiastk... |
a2aa28e58475505e10bef33ff94d672e1e02e3d2 | Delictum/python_algorithms_and_data_structures | /old/db_and_oop/manager.py | 1,500 | 4 | 4 | from person import Person
class Manager(Person):
'''
Версия класса Person, адаптированная в соответствии
со специальными требованиями
'''
def __init__(self, name, pay):
Person.__init__(self, name, 'manager', pay)
def give_raise(self, percent, bonus=.10):
Person.give_raise(self... |
93eb293cc634d8b8efc7f305a7ffe16d9da20279 | audiodude/advent2019 | /3a.py | 999 | 3.609375 | 4 | import fileinput
paths = fileinput.input()
a_path = paths[0].strip().split(',')
b_path = paths[1].strip().split(',')
def path_to_coords(path):
cur = (0, 0)
coords = set()
coords.add(cur)
for move in path:
num = int(move[1:])
if move[0] == 'U':
for _ in range(num):
cur = (cur[0], cur[1] +... |
fc4294f4cb9bf3865f843bb5b36eabc1d4846e44 | qiujiandeng/- | /day18-oopday2/a.py | 1,021 | 3.8125 | 4 | class A:
def __init__(self,name):
self.name = name
def __repr__(self): #重写__repr__方法
#返回的是B('jerry','0001')
return "B('%s','%s')" % (self.name,self.id)
# def __str__(self): #重写__str__函数
# return "name = %s" %self.name
class B(A):
def __init__(self,name,id):
s... |
02853d08436261b19d28d03c4c07d67e140c297f | daxiangpanda/lintCode | /128.py | 1,450 | 4 | 4 | # 描述
# 在数据结构中,哈希函数是用来将一个字符串(或任何其他类型)转化为小于哈希表大小且大于等于零的整数。一个好的哈希函数可以尽可能少地产生冲突。一种广泛使用的哈希函数算法是使用数值33,假设任何字符串都是基于33的一个大整数,比如:
# hashcode("abcd") = (ascii(a) * 333 + ascii(b) * 332 + ascii(c) *33 + ascii(d)) % HASH_SIZE
# = (97* 333 + 98 * 332 + 99 * 33 +100) % HASH_SIZE
# ... |
9807d113d594235b6cc5470be0ec757125cd5b61 | Jamesgarrett279/TicTacToe | /JamesGarrettProject2.py | 5,951 | 3.921875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
# Author: James Carter Garrett
# Creates a blank game board
def create_board():
board = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
return board
# Display the game board
def display_board(gameboard):
counter = 0
... |
ca7bdb2f3ff170e59265deca1e3d4e094adcfd10 | computingForSocialScience/cfss-homework-KTCO | /Assignment5/fetchArtist.py | 1,025 | 3.78125 | 4 | import sys
import requests
import csv
def fetchArtistId(name):
"""Using the Spotify API search method, take a string that is the artist's name,
and return a Spotify artist ID.
"""
url = "https://api.spotify.com/v1/search?q="+name+"&type=artist"
src = requests.get(url)
id_data = src.json()
... |
2537ab826a6fba1c6a89ecc846ef7047d068236e | Padmabala/Leetcode_MonthlyChallenges | /Leetcode_JuneChallenge/12_InsertDeleteGetRandom.py | 156 | 3.625 | 4 | h={}
j=['a','b','c','d','a']
s=[]
for i in range(len(j)):
if j[i] not in h:
h[i]=j[i]
s.append(i)
print(h)
print(s)
a=[*h.keys()]x
print(a) |
ac83bb61b90b1feae8cf9e228e929c2ce1222f65 | mertlsarac/Numeric-Analysis | /Graphic.py | 1,177 | 4.21875 | 4 | print("---Graphical Method---")
def calculateEq(l, x):
res = 0
degree = len(l) - 1
for i in l:
res += pow(x, degree) * i
degree -= 1
return res
#inputs
coefficients = [float(input("Enter the coefficient of the %d. degree of the equation(x^%d): " % (i, i))) for i in range(int(input("Ent... |
a472eb4b8e5c724db0aff398a1003197200e5605 | thejosmeister/Advent-of-code-2019 | /Day14pt2.py | 6,330 | 3.625 | 4 | # Day 14 pt2
# Did this after about 3 days of thinking. Eventually went with finding the average amount of ore required for 1000 fuel.
# Once you find the average you can find the remaing ore from the trillion and run the make_ingredient alg until it has been used up.
# The initial fuel made will require more ore ... |
bbf0d8537680ed4cb6701c36f66989a73ea0f085 | HenryHo6688/Python | /cu2l.py | 134 | 3.96875 | 4 | #!/usr/bin/python3.6
u = input("Enter an uppercase letter:")
du=ord(u)
print ("The lower case letter you entered is:",chr(du + 32)) |
5e0dba0d39f0b30b095817b8ebed695f6152d9ba | ednayssell7/bedu_14_nov_1stsession | /e03_ciclo_for.py | 65 | 3.734375 | 4 | list = [1, 2, 3, 4]
for element in list:
print(element)
|
36522d898632827853a798e0bb53584d0981595b | gitter-badger/Printing-Pattern-Programs | /Python Pattern Programs/Symbol Patterns/Pattern 78.py | 251 | 4.15625 | 4 | for row in range(0, 6):
for col in range(0, 7):
if (row == 0 and col % 3 != 0) or (row == 1 and col % 3 == 0) or (row - col == 2)or(row + col == 8):
print("*",end=" ")
else:
print(" ",end=" ")
print(" ") |
da40f7972c1b9a4086e6aa405aa61f35b5098558 | mumana98/CS-313E-Elements-Of-Software-Design | /Boxes.py | 3,567 | 3.796875 | 4 | # File: Boxes.py
# Description: given the dimensions (length width and height) of 20 boxes,
# find the largest combination of boxes that can fit inside of each other
# Student Name: Matthew Umana
# Student UT EID: msu245
# Course Name: CS 313E
# Unique Number: 50300
# Date Created: 03/07/20
# Date Las... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.