blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c8d9acb81ae074a09b5bba7f60d7cb919bfd6a0b | bingzhong-project/leetcode | /algorithms/path-sum-iii/src/Solution.py | 1,052 | 3.65625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def pathSum(self, root: 'TreeNode', sum: 'int') -> 'int':
def func(node, res):
if node.val == sum:
res[0] += 1... |
f05c2c875d5ce33ef7c9d706f086bcdee5205e03 | soufuru/Python_textbook_summary | /chapter3/chapter3-1.py | 1,437 | 4.15625 | 4 | # chapter3-1
########################
###---リストについて---###
########################
#あるクラスの平均点を求めるプログラム
points = [88, 76, 52, 90, 62]
sum_v = 0
for i in points:
sum_v += i #
print("平均点は", sum_v / len(points) )
#リストの値を一気に合計するsum()関数
sum_v = sum(points)
print("合計点は", sum_v)
#リストに入るのは数値だけではない
fruits = ["Apple","B... |
cff15c82fbff49aa47986d3182beea726910fbd6 | chandlersupple/Area-of-a-Triangle | /main.py | 927 | 3.765625 | 4 | import math
class triangle_area():
def __init__(self):
print("Choose the proper method for your given knowns. Enter 'object.help_' for options")
def help_(self):
print("object.method")
print("object.SSA_scalene - two sides and one angle opposite a given side are given")
... |
cbeed23ff289ab34a5e2919e0b58932c44a1cb5b | ramonvaleriano/python- | /Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 3/Exemplo 3a/Algoritmo83_InversoAbsoluto.py | 248 | 3.890625 | 4 | # Program: Algoritmo83_InversoAbsoluto.py
# Author: Ramon R. Valeriano
# Description:
# Developed: 23/03/2020 - 16:59
# Updated:
number = float(input("Enter with a number:"))
if number >= 0:
result = 1/number
else:
result = number*(-1)
print(result)
|
4871d9018ffebb749b6745c7d134e617af9ea6fe | team31153/test-repo | /Ryan/RyanChapter5HW/7barChart.py | 2,158 | 4.15625 | 4 | #!/usr/bin/env python3
import turtle
def draw_bar(t, height):
""" Get turtle t to draw one bar, of height. """
if height >= 200:
t.color("blue", "red")
t.begin_fill() # Added this line
t.left(90)
t.forward(height)
t.write(" "+ str(height))
t.right(90... |
68491fceb645c5d510d75a8fbe23881c96784b6f | muazniwas/leetcodeanswers | /Two Sum/bruteforce.py | 381 | 3.515625 | 4 | class Solution(object):
def twoSum(self,nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(0, len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i]+nums[j] == target:
... |
846cffdfa10479491b6f5c8c0f1edcb0fdcee83d | d-ssilva/CursoEmVideo-Python3 | /CursoEmVideo/Mundo 3/1 - Tuplas/DESAFIO 077 - Contador de vogais.py | 380 | 4.03125 | 4 | """ Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar,
para cada palavra, quais são as suas vogais."""
palavra = ('Agatha', 'Graciele', 'Danilo', 'Daniele')
for p in palavra:
print(f'\nNa palavra {p} temos ', end='')
for letra in p:
if let... |
32571406804517b6b7451ea31392738f698355df | zhangyuejoslin/algorithms | /algorithm_homework/Tim_sort.py | 6,254 | 3.71875 | 4 | import random
import time
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator
import numpy as np
def insertion_sort(array, left=0, right=None):
if right is None:
right = len(array) - 1
for i in range(left + 1, right + 1):
key_item = array[i]
j = i - 1
... |
5f7e2090cd463cd9d62074197aafd3fab15e1c73 | FutureInfinity/Darkness | /darkness-engine/tools/codegen/HistoryIterator.py | 4,304 | 3.546875 | 4 |
class HistoryIterException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class HistoryIter(object):
def __init__(self, *args):
self._it = iter(*args)
self.history = []
self.history_ptr = 0
self.history_length = 0
self.count = 0
def __iter__(sel... |
a1ffc8a35a97515b595072931c341f710f43a9bf | Mikhail-QA/IU | /Web_services/Subject_page/Сheck_all_elements_on_the_subject_page/test_пользователь_не_авторизован_проверка_Body.py | 7,738 | 3.546875 | 4 | """
Проверить наличия элементов на странице Алгебра 8 класс в Body
Пользователь не авторизован И проверка наличия инфоблока в Предмете Литература 8класс
URL: https://web-dev01.interneturok.ru/algebra/8-klass"
На странице отображаются: http://joxi.ru/vAWbBDLHkK1YM2
"""
import allure
from selenium.webdriver.common.by im... |
47f9c629a106d88dd0ecf2fa1628bd241990ca50 | TY-Jeong/numerical-recipes | /Machine Learning/neural_network.py | 2,848 | 3.609375 | 4 | # Simple fully connected neural network Following the text book "Make Your Own Neural Network" by Tariq Rashid
import numpy as np
def tanh(x):
return np.tanh(x)
def tanh_deriv(x):
return 1.0 - np.tanh(x)**2
class NeuralNetwork:
def __init__(self, structure, learning_rate):
... |
edf18a0e46f26d171451e38163c235a39a49818a | nehapokharel/pythonPractice | /question6.py | 178 | 3.6875 | 4 | w = input('enter sentence: ')
if 'not' and 'poor' in w:
a = w.index('poor')
b = w.index('not')
c = w[b:a+len('poor')]
w = w.replace(c,'good')
print(w)
|
ca0c1f2a5e009558b7465ba5a0dc969ea25ece61 | murali-kotakonda/PythonProgs | /PythonBasics1/excel1/Ex2_5.py | 854 | 3.8125 | 4 | # print("A1 TO C1")
#read by ROW WISE
from openpyxl import load_workbook
from openpyxl import Workbook
# create workbook obj
workbook = load_workbook('response1.xlsx')
#get sheet obj
sheet = workbook.active
print("print multiple selected rows")
rows = sheet[1:3] # read rows from 1 to 3
print("**********print en... |
0361a9f9f33338046d4bf9bd04cdc95fd7cd90d7 | johnvanmeerten/TiCT-VIPROG-15 | /Les02/Perkovic 2.28.py | 169 | 3.609375 | 4 | lst = [1, 4, 6, 3, 2, 4, 7]
index = (int(len(lst)/2))
print(index)
print(lst[index])
lst.sort(reverse=True)
print(lst)
x = lst[0]
lst.pop(0)
lst.append(x)
print(lst) |
1de557866c28cda30ad3a7cb8729a8ebbbb2c47d | Bedoya1123/taller_clase | /Cristian+Bedoya.py | 645 | 3.75 | 4 |
# coding: utf-8
# In[3]:
print "Hola Mundo"
# $\sum_{p}li(x^p)-log(2)$
# In[ ]:
# # Hola mundo
# python
# In[9]:
2+4+5/6.0-3
# In[8]:
3/2
# In[10]:
3.0/2
# In[11]:
3+5j
# In[12]:
(3+5j)-(1-1j)
# In[13]:
abs(3+5j)
# In[14]:
5**3
# In[15]:
int(_13)
# In[16]:
float(_15)
# In[17]:
rou... |
0f332f4f410a2154f1d422dfce4c47afbd74a174 | AchrafONEBourajjai/PythonNetworking | /Json.py | 310 | 3.796875 | 4 | #how to code and decode json
import json
I = ['ali','ahmad','amine','achraf']
print(json.dumps(I))#dumps() converts objects to json string
s = json.dumps(I)
print(type(s)) #to know type of variable
s = '["ali","ahmad","amine","achraf"]'
print(json.loads(s)) #json object to list
print(json.loads(s)[3]) #prouve |
b5568225226eea3488b290601aa419acc6e98dcb | WindboyBase/Who_am_I | /simp_serv.py | 1,140 | 3.765625 | 4 | #此示例为服务器
import socket
address = ('0.0.0.0',9999)
#创建socket
server = socket.socket()
#绑定地址:bind()函数
server.bind(address)
#监听 listen(),10表示:如果服务器没有能力去接收的话,后面可以有多少个队列在此等候
server.listen(10)
print('服务器已启动',address)
#接收请求:accept()函数,接收服务器的请求,这个时候在这儿会形成阻塞,也叫阻塞函数。如果没有客户端连接,它会
#在这一直等,等到有客户端连接时,这个时候才会有返回值,
#sockfd是返回的新的套接字,... |
610fbe124aa7ca61ba709f29d4ff69d42a803b94 | SBolsec/SKRJ | /03/zadatak1.py | 2,597 | 3.859375 | 4 | import sys
def load_matrix(file):
matrix = {}
header = file.readline().strip()
if not header: # check if header exists
raise RuntimeError("Header does not exist!")
header = header.split(" ")
if len(header) != 2: # header must contain two values
raise RuntimeError("Header must co... |
74e0dae9cee6d043043dd799fc32c2f59a197147 | arrebole/Ink | /src/algorithm/solved_leetcode/31.next-permutation/solution.py | 1,252 | 3.640625 | 4 | #! /usr/bin/env python
from typing import List
class Solution(object):
def nextPermutation(self, nums):
return self.lexicographicPermute(nums)
def lexicographicPermute(self, array: List):
i = self.findMaxOrdered(array)
if i == -1:
array.sort()
return array
... |
05bb03f4033f9f2749627cedfae766e4df3ec7f5 | CodeForContribute/Algos-DataStructures | /Array/search_element_in_rotated_Array.py | 1,682 | 3.703125 | 4 | def pivotBinarySearch(arr, n, key):
pivot = findPivot(arr,0, n-1)
if pivot == -1:
return binarySearch(arr, 0, n, key)
if arr[pivot] == key:
return pivot
if arr[0] <= key:
return binarySearch(arr, 0, pivot-1, key)
return binarySearch(arr, pivot+1, n-1, key)
def findPivot(arr,... |
c801216940638daf8dd5028529e864a34bf42150 | esix/competitive-programming | /e-olymp/2xxx/2864/main.py | 196 | 3.9375 | 4 | #!/usr/bin/env python3
from math import sin
a, b, h = map(float, input().split(' '))
def f(x):
return 3 * sin(x)
x = a
while x <= b:
y = f(x)
print("%.3f %.3f" % (x, y))
x += h |
ec11bc66fa29c9951d621abfd87d39468889b578 | Richimetz/introprogramacion | /Practico_1/ejer_10.py | 285 | 3.609375 | 4 | def timeConv (v):
n = int(input("cantidad de tramos realizados: "))
for i in range(0,n):
v = print("duración de tramo: ")
n = v % 60
print(n)
r = (v - m)/60
print(r)
resultado = str(r) + ":" + str(n)
print(timeConv(266)) |
548cedc64e1f8e119e92f7a5d047fb62fe8b4ee1 | keli0215/Coding-Excercise | /stackSort.py | 623 | 4.1875 | 4 | class Solution(object):
def stacksort(self, stack):
if len(stack) != 0:
temp = stack.pop() #First pop all the elements from the stack and store poped element in variable 'temp'.
self.stacksort(stack)
self.stackinsert(stack, temp) #Now stack is empty and 'stackinsert' function is called and it inser... |
b1da60e212cd02e26276488725534145fcb87042 | hah-ak/algorithm-study | /programmers/biggstNum.py | 245 | 3.671875 | 4 | def solution(numbers):
numbers = list(map(str, numbers))
numbers.sort(key = lambda x: x*3, reverse = True)
if numbers[0] == 0:
return '0'
return ''.join(numbers)
print(solution([0,0,0,0,10,101,1000,111]))
|
adef0e89893e398718ebcfa658405379756a9ab0 | sanshitsharma/pySamples | /leetcode/zigzag_iterators.py | 1,743 | 3.6875 | 4 | #!/usr/bin/python
class ZigzagIterator(object):
def __init__(self, v1, v2):
"""
Initialize your data structure here.
:type v1: List[int]
:type v2: List[int]
"""
self.d = {0: v1, 1: v2}
self.currItr = 0
self.itrsIndx = []
if len(self.d[0]) > ... |
2dec7acc7b021b7894b7bba11d7b6c8d02b17499 | ShaneNelsonCodes/100Days_Python | /Day11_Blackjack.py | 2,474 | 3.796875 | 4 | from Day11_Blackjack_Art import logo
import random
import os
def clear():
os.system('cls')
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def deal_card():
rand_card = cards[random.randint(0, len(cards)-1)]
return rand_card
def calculate_score(player_list):
total = sum(player_list)
if 11 in... |
5def9383de1ab2ea5017caf654679136b11f03a8 | KennaNeitch/KennaNeitch.github.io | /python/Case_Study_Textual_Analysis.py | 3,649 | 3.703125 | 4 | from bs4 import BeautifulSoup
from urllib import request
url = "https://raw.githubusercontent.com/humanitiesprogramming/scraping-corpus/master/full-text.txt"
html = request.urlopen(url).read()
soup = BeautifulSoup(html, "lxml")
raw_text = soup.text
texts = eval(soup.text)
# print(len(raw_text))
# print(len(texts))
i... |
6bc4dbf7f77b486953ee2b4957670ee40a8309a2 | Jagdale-pooja/program | /reverse_arr.py.py | 117 | 3.859375 | 4 | array=[10,11,12,13,14,15]
print("array before reverse",array)
arr2=array[::-1]
print("array after reverse",arr2)
|
f62a6df9e077e6f6c79787a14d332369360fbc98 | kookkig11/Python_Language | /ex5-1.py | 554 | 3.9375 | 4 | i = 0
sum = 0
while True :
x = input()
# check non-input ?
if x == "" :
break
else :
num = float(x)
# loop start and set default value
if i == 0 :
max = num
min = num
# num is positive integer
if num >= 0 :
if num > ... |
7bef991e0b0cc4a0ccbb6365b1ad0fae7bce83cf | KristinCovert/Bootcamp | /PythonProjects/fibonacciCalc.py | 478 | 3.875 | 4 | __author__ = 'Kristin'
def range_top():
top_range = input('Up to what number would you like to calculate the Fibonacci: ')
return top_range
def fibonacci(rt):
i = 0
j = 1
fibonacci_list = []
for number in range(0, rt):
k = i + j
fibonacci_list.append(k)
i = j
... |
e587cc8e56ab08640d4091836b2d976c9b0af2ea | Tradingstrategie/Test-Projekt | /String-Permutation.py | 1,446 | 3.765625 | 4 | # Permutation:
# Eingabe:
zeichenkette = list(input('Bitte gib eine Zeichenkette ein: '))
# Funktion Fakultät:
def fakultät_r(n):
if n == 0:
return 1
else:
return (n * fakultät_r(n-1))
# Funktion Permutation:
def permutation(zeichenkette):
if len(zeichenkette) == 1:
... |
62798aaa0821639e7a3079c946c53c23ec9e32fa | Carolinacapote/holbertonschool-higher_level_programming | /0x02-python-import_modules/2-args.py | 541 | 3.859375 | 4 | #!/usr/bin/python3
if __name__ == "__main__":
from sys import argv
number_arguments = len(argv) - 1
if (number_arguments == 0):
print("{} arguments.".format(number_arguments))
elif (number_arguments == 1):
print("{} argument:".format(number_arguments))
print("{}: {}".format(numbe... |
6ccf7faf51030e55ad6304d48adf19eb2f860dc9 | jaeyson/py-scripts | /diff.py | 1,838 | 3.71875 | 4 | #####################################################
# how to use:
# python3 diff.py csv1 csv2 output
# where 1st column from csv1 not found in csv2
# should NOT go inside output file.
# contents from newcsv are the updated rows from csv1
#####################################################
import csv
import os
imp... |
3813e265f2aef2ac691dc7a28a0211918346d2d0 | msmccue/APCSP-P3 | /hangmanTestingV2.py | 246 | 3.796875 | 4 | theWord = "fair"
#if the user guesses letter "f",
# we would change the variable "theWord" to
# contain "air"
foundLetter = theWord.find("e")
if (foundLetter > -1):
theWord = theWord[:foundLetter] + theWord[foundLetter+1:]
print(theWord)
|
a0efd0079899d45676b286d3fbc5213757bd35a7 | JACKSUYON/TRABAJO5_PROGRAMACION_1_B | /boleta_7.py | 769 | 3.703125 | 4 | #boleta 7: clacular el area lateral del cilindro
#input
pi=3.1416
radio1=float(input("ingrese el radio:"))
generatriz1=int(input("ingrese la generatriz:"))
#processing
area_lateral_cilindro=(2*pi*radio1*generatriz1)
#verificador
verificador=(area_lateral_cilindro>=29)
#output
print("#################################... |
778d3c819a14048813f420a75ca9d9c27c2fd22b | shamayn/aoc2020 | /day5.py | 1,443 | 3.6875 | 4 | import math
def findSeat(seatcode):
rowcode = seatcode[0:7]
colcode = seatcode[7:10]
row = binarySearch(rowcode, 127)
col = binarySearch(colcode, 7)
print("seat:", row, col)
return (row, col)
def binarySearch(code, max):
start = 0
end = max
for i in range(len(code)):
if code[i] == "F" or code[i] == "L":
... |
61f098ba2c13663b0388db5115849dcbcfb4fdb4 | ToBeTree/cookbookDemo | /4-迭代器和生成器/4-3自定义迭代.py | 367 | 4.125 | 4 | # 实现一个自定义的模式
# 一个生成器的主要特征是只回应next的操作
# 一个函数有yield就可以是生成器了
def frange(star, stop, step):
n = star
while n < stop:
yield n
n += step
for i in frange(1, 3, 0.5):
print(i)
# 原生的range函数不支持浮点型step
# for i in range(1, 10, 0.5):
# print(i)
|
10ca6223125562a474e13280f8c2c4b8f9ca5867 | maryam98hasan/Computer-Graphics | /Draw spiral polygon.py | 385 | 4.28125 | 4 | # Python program to draw spiral polygon in turtle programming
import turtle
screen = turtle.Screen()
screen.bgcolor("black")
t = turtle.Turtle()
t.color("red")
t.speed(0)
numberOfSides = 9
lengthOfSide = 100
exteriorAngle = 360 / numberOfSides
for i in range(200):
t.forward(lengthOfSide)
t.right(ext... |
edcfabc6ef02b8edce79ecc967e2676d412fbab9 | saikrishna1103/first | /twelve.py | 132 | 3.546875 | 4 | b=int(input())
tem=b
re=0
while(b>0):
dig=b%10
re=re*10+dig
b=b//10
if(tem==re):
print("yes")
else:
print("no")
|
4c7009d21c5707bfdd97767a8c4d0339f8bbf8f6 | JeanGrijp/Algorithms | /Estruturas de Dados/arvore.py | 17,687 | 3.953125 | 4 | class No:
def __init__(self, key, value, left=None, right=None):
self.key = key
self.value = value
self.left = left
self.right = right
class Tree:
def __init__(self):
self.root = None
self.size = 0
def insert(self, key, value):
cont = ... |
648b5b0725f2df7bfe71ce059bb22fec6b22b691 | Grug16/CS112-Spring2012 | /hw05/nims.py | 861 | 3.921875 | 4 | #!/usr/bin/env python
"""nims.py
A simple competitive game where players take stones from stone piles.
"""
print "Welcome to Nims. Whoever takes the last stone loses."
stonecount = int(raw_input("Number of stones in the pile: "))
maxtake = int(raw_input("Max number of stones per turn: "))
player = 1
taken = 0
while... |
f04cc9fdae490629df8ee3f3ebd479df3b7c3819 | vip7265/ProgrammingStudy | /leetcode/problems/sjw_remove_the_nth_node_from_end_of_list.py | 1,222 | 3.515625 | 4 | """
Problem URL: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:... |
ad8d3c51d4fc20fe4c6f1585a6da27f7e1daf77a | marielymoon/Ejercicios-Python | /conv_funciones.py | 409 | 4.03125 | 4 | # -*- coding: utf-8 -*-
def cambiar(cantidad):
tipo_cambio= 18.81
return cantidad/tipo_cambio
def main():
print('Calculadora de Dolares')
print('')
cantidad = float (input('Ingresa la cantidad de pesos que quieres convertir: '))
result= cambiar(cantidad)
print('${} pesos mx ${}dolares (us)'... |
1fe9c086f48709dfe96a161654e6cf5ebaa41dc9 | bindu0999/py-assignment | /p10.py | 354 | 4.1875 | 4 | #Write a Python program to search a character in a given string using slicing
s = input("Enter string : ")
c = input("Enter a search character : ")
flag = 0
for i in range(0,len(s)-1):
if c == s[i]:
print("Given charcter found at the position index ",i," in String "+s)
flag = 1
if flag == 0:
... |
705ab23680aba538702f4335d825ec55d2173e6f | Alves-Bruno/Paradigmas_de_Programacao | /extras/HFYT/aux.py | 1,018 | 3.65625 | 4 | import curses
from random import randint
class Screen(object):
def __init__(self, MAX_X, MAX_Y, difficulty):
self.MAX_X = MAX_X
self.MAX_Y = MAX_Y
self.exit = 0
self.vidas = 3
self.difficulty = difficulty
class Lists(object):
def __init__(self, TAM_MA... |
9a3a7df8b0cb8bbc6e75870e2483db06e5bd4f23 | mykespb/edu | /tests/summapn.py | 2,173 | 4.09375 | 4 | #!/usr/bin/env python3
# программа ищет суммы положительных и отрицательных чисел в списке
# (C) М.Колодин, 2021-06-25, 2021-08-26 1.2
# -------------------------------------- подготовка
import random
ranger = range(10)
def makerand(size=10, low=-100, upp=100):
""" сделать список из size элементов,
минимал... |
24de8c41e123a3983e3471a711e7ce3369a44d01 | alisher13/CitronResearch | /match.py | 3,828 | 3.8125 | 4 | import csv
from datetime import datetime, timedelta
import os.path
def get_stock_prices(file_name):
# date (object, not string) will be the dictionary key, adjusted
# close will be the value something like {"2017-01-01": 200, ...}
data = {}
if not os.path.isfile(file_name):
print("ERROR: %s... |
7c29f58705bc7cba349a7502cc5fc9629d5b59de | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2/cuongd/submission.py | 2,200 | 3.890625 | 4 | #!/usr/local/bin/python
import sys
class RevengeOfPancakes(object):
"""
https://code.google.com/codejam/contest/6254486/dashboard#s=p1
"""
def __init__(self, filename):
""" Initialize with the given input file.
:param filename: input file path
:return:
"""
sel... |
d0ac1b137bffddcd809fb638ea71302e938f06d2 | young-geng/RatingAnalysis | /preprocess.py | 869 | 3.59375 | 4 | """
Preprocess the raw data to remove month seperation columns and filter out
unused columns.
Usage: python preprocess.py <input filename> <output filename>
"""
from __future__ import division
import numpy as np
import scipy
import pandas as pd
from sys import argv
if __name__ == '__main__':
assert len(argv) =... |
e3edf89d753427e43f81d956ecb7635ed4f5b870 | JoaoGabrielDamasceno/Estudo_Python | /coleção/order_dict.py | 357 | 3.796875 | 4 | """
Orderer Dict --> Dicionario em que a ordem de inserção dos elementos importa
"""
from collections import OrderedDict
d1 = {'a': 1, 'b': 5}
d2 = {'b': 5, 'a': 1}
if d1 == d2:
print(True)
else:
print(False)
dic1 = OrderedDict({'a': 1, 'b': 5})
dic2 = OrderedDict({'b': 5, 'a': 1})
if dic1 == dic2:
... |
5b48051a4f37257976f8d22b7ec5feda6cef1cf6 | hnko/uva-judge | /mix/13286.py | 3,297 | 3.609375 | 4 | # AC - topological sort + 01Knapsack
import sys
B = 0
did = {}
dishes = []
prestiges = []
costs = []
recipes_from = {}
opt = []
def topological_sort():
# los platos que tienen in_degree a 0, platos base, en este caso solo hay uno.
in_degree = {}
for x, neighbors in recipes_from.items():
in_degree.setdefault(x, ... |
aee8b29374b41e5574fd136f75de95e11086243a | themichaelyang/dynsys | /hw-1.5.py | 255 | 3.609375 | 4 | import math
def f(x):
return math.e**x - 2
def g(x):
return math.log(x + 2)
def main():
x = 0
for i in range(10):
x = f(x)
print(x)
print()
x = 0
for i in range(10):
x = g(x)
print(x)
main()
|
c80d8471849bc11eae1b406f9a7881cf80ee380f | Jas-Gomes/2021-software-general-homework | /lesson_3assignment3.py | 510 | 3.859375 | 4 | from typing import cast
x = 1
translation = {}
while x == 1:
ring = input("Please enter a word, or press enter to end: ")
if ring == "" :
print("bye, bye")
break
if " " in ring:
print("You cannot enter spaces")
print("bye, bye")
break
if ring in translation.keys... |
947d9b0a2389d0bb9b845b525c52ba2ccb67d456 | EvaChitul/python_national | /Own projects/rock_paper_scissors.py | 1,438 | 4.0625 | 4 | '''Make a two-player Rock-Paper-Scissors game.
Rock beats scissors
Scissors beats paper
Paper beats rock'''
def main_menu():
while True:
action = input ('Welcome to Rock Paper Scissors! Please choose an option. Type: \n'
'N for a new game \n'
'Q ... |
fa50b1b3acb1a22f531dafb7ef177a3efb7d78da | vunderkind/Intro-Python-II | /src/player.py | 531 | 3.71875 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, current_room=None):
self.name = name
self.current_room = current_room
def __str__(self):
output= ''
output += f'[{self.current_room}]'
if s... |
e03eda9aaedd7ba9dcbdd1a44270b22771e2d258 | HangZhongZH/LeetCodeAlgorithms | /130. 被围绕的区域.py | 1,223 | 3.515625 | 4 | class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
if not board:
return board
def dfs(i, j):
board[i][j] = 'B'
for x, y in [(1, 0... |
abf8cde53a6fd3a1cebe22413e035639ea1afe90 | gajjarjigar/HackerRank | /Python/Strings/python-string-formatting.py | 329 | 3.890625 | 4 | def print_formatted(number):
width = len(str(bin(number))[2:])
for i in range(1,number+1):
print('{} {} {} {}'.format(str(i).rjust(width), str(oct(i))[2:].rjust(width),str(hex(i))[2:].upper().rjust(width), str(bin(i))[2:].rjust(width)))
if __name__ == '__main__':
n = int(input())
print_form... |
463621215260e3d90d02c751bfa5f34b8414f44e | justin-tse/cs50 | /cs50x/pset1/mario/mario.py | 207 | 4.09375 | 4 | while True:
n = int(input("Height: "))
if 0 < n <= 8:
break
print("Input number between 1 and 8.")
for i in range(n):
print(" " * (n - i - 1) + "#" * (i + 1) + " " + "#" * (i + 1)) |
f872cb155bf270d217ea431f53b6053fc22d55fa | ManiNTR/python | /CheckDictionaryEmptyOrNot.py | 383 | 4.5 | 4 | #Python program to check a dictionary is empty or not
num={"one":1,"two":2,"three":3,"four":4,"five":5,"six":6}
print(num)
if not num.items():
print("The dictionary is empty")
else:
print("The dictionary is not empty")
dictionary={}
print(dictionary)
if not dictionary.items():
print("The dictionar... |
d7146ac279687399c78b2b33e88f4d00efc151c3 | CarloShadow/CodesByCJ | /Python/guppe/TESTE.py | 60 | 3.65625 | 4 | while True:
num = int(input('Digite um número: '))
|
466b3a60d9c62730129b00cc4b222a0b0f3b8375 | walterwsj/hogwarts_lg | /bicycle/bicycle.py | 583 | 3.75 | 4 | class Bicycle:
def run(self,km):
print(f"Total running {km} miles")
class E_Bicycle(Bicycle):
def __init__(self,valume):
self.valume=valume
def fill_charge(self,vol):
self.valume+=vol
print(f"Charged {vol}. Current volume is {self.valume}")
def run(self,km):
powe... |
afc44623763aee68bea5817c5d605835e24940af | Ankitahazra-1906/Rock-Paper-Scissors-Game | /rock paper scissors game.py | 1,075 | 4.1875 | 4 | import random
while True:
user_choice=input("Enter any of the 3 choices between( rock ,paper and scissors): ")
possible_choices=["rock","paper","scissors"]
comp_choice=random.choice(possible_choices)
print("\n You choose", user_choice ,"\n Comp choose", comp_choice,"\n")
if user_choice==comp_c... |
6137dbc5fc51b1b2df71980350d2eceb6847acf7 | SamanehGhafouri/MIT-problems-practice | /ObjectOrientedProgramming/practice1.py | 845 | 4.34375 | 4 | from abc import abstractmethod, ABC
class Animal(ABC): # Abstract class
@abstractmethod
def how_running(self):
pass
class Horse(Animal): # Class Horse is inherited from class Animal
def how_running(self):
print("with 4 legs")
class Human(Animal): ... |
8c215f22adad76c5db50beb6a1b560277e2f0e42 | astrosec/virtualagc-docker | /convert.py | 1,350 | 4.53125 | 5 | # TypeConversions from decimal and binary
# to their respective octal representations
# The choices present to the user
print("a. Hexadecimal to Octal ")
print("b. Decimal to Octal")
print("c. Binary to Octal")
# Function generates octal representation
# from it's binary from
def bin_to_oct():
print("Ente... |
b64e584569fec77fce64c81e460de556d9e880c5 | jmstudyacc/python_practice | /POP1-Recursion/recursion _sums.py | 910 | 4.125 | 4 | """
Implement a function my_sum(lst) that given a list lst of interger numbers, returns the sum of them.
In this exercise, do not use the standard sum function and no loop of any kind. Implement the function recursively using the following idea:
- If the list contains one element, the sum of the list is equal to this... |
baf2a2ff88c0af02af12d36e320065b306f91aa7 | MartinaLima/Python | /exercicios_python_brasil/estrutura_repeticao/24_media_varias_notas.py | 484 | 3.984375 | 4 | print('>>> Informe as notas:')
c = 0
soma = 0
continua = ''
while continua != 'N':
c += 1
nota = float(input(f'- NOTA {c}: '))
soma += nota
continua = str(input('Continuar? [S/N]: ').upper())
while continua not in 'S' and continua not in 'N':
continua = str(input('Continuar? [S/N]:... |
6bae5cc77931e2eed4acbf92795437f913691864 | judywu29/python_pj | /buble_sort.py | 371 | 3.890625 | 4 |
def bubble_sort(seq):
seq_len = len(seq)
for i in range(seq_len):
print(seq_len)
for j in range(seq_len-1, i, -1): # for j in range(i, seq_len-1)[::-1]:
if(seq[j] < seq[j-1]):
temp = seq[j]
seq[j] = seq[j-1]
seq[j-1] = temp
seq = ... |
047ef617837009070c75a48d1e0b0eb9948a8480 | BarisATAK/Python_Practise | /11_functions_examples.py | 1,092 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 20 01:24:34 2020
@author: atakb
"""
# Factorial Function.
def Factorial(number):
for i in range(1,number):
number *= i
return number
# Fibonacci Function.
def Fibonacci(number):
f1 = 0
f2 = 1
print(f1+f2)
for i in range(0,number):
... |
b6495f5833d953aec86eb570edf283711c691951 | rfsip/learnpython | /DATATYPE.py | 825 | 4.25 | 4 | #coding:utf-8
'''
pyton3有6种数据类型:Number、String、List、Tuple、Sets(集合)、Dictionary
Number: 支持 int、float、bool、complex。只有一种整数类型int,表示长整型。
bool类型只有True False。
String: 长度不可变,用单引号和双引号表示。a="abc",其中a为变量,"abc"才是字符串。a可变。
除法: python3 除法有两种 '/'为精确除,结果为浮点数 10/3=3.33333333 9/3=3.0
'//'为地板除,结果为整型 10/... |
d02d3fdf8c160798a9f6e8933a96fbd24a5e5d22 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/mrpgeo001/question2.py | 2,986 | 4.03125 | 4 | """Vending Machine (Change Calculator)
Geoff Murphy
MRPGEO001
13 April 2014"""
def Vend():
cost = eval(input("Enter the cost (in cents):\n")) #The total amount to be paid
pay = 0 #'pay' is amount of money deposited
dollar = 0 ... |
82e317794b839558392368c42b5f371668c6617b | RafaelTeixeiraMiguel/PythonUri | /br/com/rafael/teixeira/uri/beginner/uri_1045_triangle_types.py | 636 | 3.84375 | 4 | values = input().split()
a = float(values[0])
b = float(values[1])
c = float(values[2])
if(c > b):
aux = b
b = c
c = aux
if(b > a):
aux = a
a = b
b = aux
if(c > b):
aux = b
b = c
c = aux
if((a >= (b + c))):
print("NAO FORMA TRIANGULO")
else:
if(((a ** 2) == ((b ** 2)+ (c ** 2)))):
print("T... |
fea37ec9410bce6bdb1357a406b811a3564e24e7 | Introduction-to-Programming-OSOWSKI/2-8-hasl-BrooksOBrien22 | /main.py | 168 | 3.6875 | 4 | #WRITE YOUR CODE IN THIS FILE
def hasL(w):
for x in range(0, len(w)):
if (w[x]) == "l":
return True
return False
print(hasL("word")) |
22c7ebe71b0a58a0dd7531e30580b17c152b451a | ilhamdsofyan/exercism | /python/pangram/pangram.py | 172 | 3.875 | 4 | def is_pangram(sentence):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in sentence:
return False
return True
|
162f26140f4cceaf422c78f11247e5d9a2b02e8b | Computants/StringOperations | /py-23112019-DataTypes.ipynb | 4,942 | 3.9375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
import this
# In[3]:
5 + 8 # Operation
#Operators
# +, - ,/ ,*, %, **
# =, +=, -=, ?=, *=, %=
# ==, >, <, >=, <=
# 5, 8 Oprands
# In[4]:
#complex operation
#PEMDAS
5 + 7 - 8 * (2/2) + 200
# In[9]:
a = 8 #shallow co... |
20317fd4711a7332adada3f46ad876975e1fa51a | hanwenzhang123/python-note | /functional-python/9-currying.py | 845 | 4.71875 | 5 | Currying - technique is used to create alternate versions of a function based on the number of provided arguments
Currying may actually change the behavior of the function, not just its arguments.
you can call a func and that func if does not have enough argument
it will fill in as many argument as it can to itself an... |
f5ffa705f4016969ea5ca9d5777718f26c8e5d1c | ignifluous777/Exercises | /data_structures/stacks_and_queues/2_stack_insert/Solution/solution.py | 1,219 | 3.890625 | 4 | class Stack:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while temp:
print(f"{temp.value}")
temp = temp.next
def push(self, value):
new_head = Node(value)
new_head.next = self.head
self.head ... |
1537f1f629bc83af582bb930ad83628b13301830 | 17akitsvad/Programming-Portfolio | /madlib.py | 1,292 | 3.953125 | 4 | def main():
adjective1 = raw_input("Please enter an adjective: ")
adjective2 = raw_input("Please enter another adjective: ")
bird = raw_input("Please enter a type of bird: ")
room = raw_input("Please enter a room in a house: ")
verbPast = raw_input("Please enter a past tense verb: ")
verb = raw_input("Please ente... |
4cd018273fc3e3e6622b5fa4235af539e5820a08 | Tmizu0719/csv_convert | /souce/csv_convert.py | 1,913 | 3.84375 | 4 | """
January 4th 2020
Author T.Mizumoto
"""
#! python 3
# ver.01.10
# csv_convert.py - this program converts .csv file to matrix
import numpy as np
import sys
class CsvConvert:
delimiter = ","
def convert_np(self, path):
# header
with open(path, "r") as file:
lines = ... |
36b76d1c304ce7c89614b03abd858502668f0a8a | sakshigupta06/Breakfast_Bot | /breakfast_bot1.py | 2,302 | 4.3125 | 4 | # Before refactoring
# Here's our original code, before we did any refactoring:
import time
print("Hello! I am Bob, the Breakfast Bot.")
time.sleep(2)
print("Abra ka dabra gili gili chu!!🧙♂️")
print("Today we have two breakfasts available.")
time.sleep(2)
print("The first is waffles with strawberries and ... |
359e03ad7accf5955f822b39f28c3dbd37e133ac | dkaushik95/learn_python | /42.py | 215 | 4.125 | 4 | def reverse_a_string(given_string):
if len(given_string) <= 1:
return given_string
return reverse_a_string(given_string[1:]) + given_string[0]
print reverse_a_string('Hello')
print reverse_a_string('mississipi') |
c276866c0b6141c295209cc87c6452313e8cbab0 | Sergey0987/firstproject | /Алгоритмы/Решето Эрастофена - ГОТОВО.py | 556 | 3.765625 | 4 | N = int(input())
list_of_numbers = []
list_of_numbers2 = []
for i in range(2, N+1):
list_of_numbers.append(i)
p = list_of_numbers[0]
index = 0
while p**2 <= N:
for i in range(index+p, len(list_of_numbers), p):
list_of_numbers[i] = False
index = index + 1
while list_of_numbers[index] == Fa... |
171dcb91067aeb212ef365fbd0ca2df94a975087 | janice-cotcher/stick_man | /stick_figure_blank/stick_figure_blank.pyde | 693 | 3.546875 | 4 | # change each of the given functions so they accept parameters
def drawHead():
"""Circle head"""
ellipse(100, 35, 25, 25)
def drawBody():
"""Stick body"""
line(100, 50, 100, 80)
def drawArms():
"""Stick arms"""
line(100, 52, 70, 45)
line(100, 52, 130, 45)
def drawLeg... |
38aec61b8a09893303be94bcab4fb645659efa15 | janlee1020/Python | /Vacation.py | 409 | 3.8125 | 4 | #Vacation.py
#Janet Lee
#Lab 2 MW 2:15
#Plan a vacation
def main():
#Ask what activity you like to do
activity= input("What activity do you like to do?")
#Ask where you would like to visit
visit=input("Where would you like to visit?")
#Print the result
print("You just got to SU a... |
0cd88cef07b0b666eb2bef8cb2620d8ad5539e9f | uwhwan/python_study | /test/dayofyear.py | 742 | 4.4375 | 4 | #计算指定的年月是这一年的第几天
def is_leap_year(year):
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
def which_day(year,month,date):
'''计算传入的日期是这一年的第几天'''
days_of_month = [
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
]
#布尔值fals... |
89ff82227f6f7e5218eb59e217ba32f7b97aa027 | tianyuchen/project-Euler | /040-Champernowne's_constant.py | 1,164 | 3.796875 | 4 | # -*- coding: utf-8 -*-
'''
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression.
d1 ×... |
3d577367fb9152d1dfc728b5a2d090a39f90411e | LarisaFonareva/Various | /1.5_Caesars_cipher.py | 223 | 3.796875 | 4 | d=int(input())
for c in input():
if c.isalpha():
if c.islower():
print(chr((ord(c)+d-1072)%32+1072),end='')
else: print(chr((ord(c)+d-1040)%32+1040), end='')
else:
print(c,end='') |
82b5788e7f4ea01abdecd1b8a88b91bb079f9f88 | jthiruveedula/PythonProgramming | /OOP/Abstraction.py | 804 | 4.125 | 4 | #Abstraction:- Is the meachanisam of only declaring methods but not instantiated, declared methods are implemented in its child classes
from abc import ABC,abstractclassmethod
#initiating abstract and could be used in other child classes
class abstractClass(ABC):
@abstractclassmethod
def abstractMethod(self):... |
2692895ca051c582f0c1485517591f6cc75cff42 | tuxnani/pyrhmn | /Day21/reverse_even_list.py | 1,209 | 3.6875 | 4 | class Node:
def __init__(self, next = None, data = None):
self.next = next
self.data = data
def newNode(d):
newnode = Node()
newnode.data = d
newnode.next = None
return newnode
def reverse(head, prev):
if (head == None):
return None
temp = N... |
f7b549b4bed14ce634509699ea00eb2635db42f3 | Manuel-Python/Python-Maths | /main.py | 735 | 3.984375 | 4 | import math
from tkinter import *
# Based on Angela Yu's work
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
window = Tk()
window.title("Maths")
window.config(padx=200, pady=200, bg=GREEN)
pheta = 1 / (2 * math.sin(math.radians(18)))
print("18 - ", pheta)
pheta1 = 2 * m... |
7bff1ff2cccdbb4c8f43d5a504bc1d41c7d5545b | crazyyin/algorithm | /search.py | 720 | 3.6875 | 4 | # -*- coding: utf-8 -*-
number_list = [0, 1, 2, 3, 4, 5, 6, 7]
def linear_search(value, iterable):
for index, val in enumerate(iterable):
if val == value:
return index
return -1
assert linear_search(5, number_list) == 5
def linear_search_v2(predicate, iterable):
fo... |
f6100afa1fc937dca3428adb024e71932837c011 | phantomnat/python-learning | /leetcode/tree/111-minimum-depth-of-binary-tree.py | 1,022 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
depth = 0
if... |
307ba4f86661c52f438dda1ccdb1ee78ffdc46a9 | zheryulia/moon_map | /main.py | 681 | 3.625 | 4 | matrix = []
with open("matrix.txt") as file:
for line in file:
matrix.append([int(num) for num in line.strip()])
def calculate(moon_map):
k = 0
row = len(moon_map)
column = len(moon_map[0])
for i in range(row):
for j in range(column):
element = moon_map[i][j]
... |
6274c8a72fc65e2b1c7f44dd4668624f3c52145c | azupero/nlp100knocks | /ch01/nlp04.py | 894 | 3.515625 | 4 | # “Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.”
# という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し,
# 取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.
text = 'Hi He Lied Because Boron Could Not Oxidize Fluorine. N... |
070fccd3ac03fd351de02c7bd0d98a52b4e01d1e | piquesel/coding-math | /ep3.py | 1,476 | 3.75 | 4 | # Coding Math Episode 3
# Boucing ball
__author__ = "piquesel"
import pygame
import math
pygame.init()
RED = pygame.color.THECOLORS['red']
screen = pygame.display.set_mode((800, 600))
screen_rect = screen.get_rect()
centerx = screen_rect.width // 2
centery = screen_rect.height // 2
offset = screen_rect.height * 0.4... |
71f15e85a636b858a6e6c7c947c1645bff0586a6 | sushinpv/LabChat | /user.py | 579 | 3.71875 | 4 | name = raw_input("Enter your name: ")
if name != "":
while True:
msg = raw_input("Message : ")
if msg == "<<<":
newmsg = name + " : MultiLine Message \n========================================================================\n"
temp = raw_input("")
while temp != ">>>":
newmsg = newmsg + temp + "\n"
... |
ddd9018f61be4954247dc5739b26636936c6edfd | HeyIamJames/CodingInterviewPractice | /missing_element.py | 427 | 3.96875 | 4 | """
There is an array of non-negative integers.
A second array is formed by shuffling the elements of the first array and
deleting a random element.
Given these two arrays, find which element is missing in the second array.
http://www.ardendertat.com/2012/01/09/programming-interview-questions/
"""
def findMissingNumb... |
2cc7aca22e9af5346b130aee4bd16bee626d757b | guihehans/self_improvement | /code_pattern/subsets/duplicate_subsets.py | 1,356 | 3.5 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: guihehans
@file: duplicate_subsets.py
@time: 2020/12/23 9:53
@function:
"""
def find_subsets(nums):
subsets = [[]]
nums.sort()
last_generated_subsets = subsets
for num_idx in range(len(nums)):
if num_idx > 0 and nums[num_idx] == nums[num_i... |
437656422020878aa26cd24a65bc16ccda8a69c6 | smritibhati/Decision-Tree | /q-1-1.py | 5,515 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import pandas as pd
import numpy as np
import math
data=pd.read_csv('decision_Tree/train.csv')
# In[3]:
# Divide the data into training and validation. Drop all non categorical columns from the dataframe
# In[4]:
data,testdata= np.split(data,[int(0.80*len(data))... |
38ffeef91b0bd96b2ef593209e0895d514a2ed12 | etporter/Bomb-A-Mole | /bombamole_lib/high_score.py | 3,481 | 3.734375 | 4 | """
This is a program for displaying the user's high scores.
"""
import sys, pygame
pygame.init()
class hs(object):
def __init__(self):
pygame.display.set_caption('High Score')
# set the window size:
dimensions=[1200,650]
font = pygame.font.F... |
546271bd7d5f5ae3f6fdd8030de110dbf75dfbc2 | thanders/light_switch | /lightswitch/displayboard.py | 1,190 | 3.734375 | 4 | class displayboard:
# Initializes instance of the displayboard class
def __init__(self, start_row, finish_row, start_column, finish_column):
self.__grid = []
self.__start_row = start_row
self.__finish_row = finish_row
self.__start_column = start_column
self.__finish_column =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.