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 |
|---|---|---|---|---|---|---|
32aa978e7c03150b287dc9335236b2904dcfda76 | AbdelazizMohamedB/python-plotly-dash | /heatmaps/Ex8-Heatmap.py | 762 | 3.59375 | 4 | #######
# Objective: Using the "flights" dataset available
# from the data folder as flights.csv
# create a heatmap with the following parameters:
# x-axis="year"
# y-axis="month"
# z-axis(color)="passengers"
######
# Perform imports here:
import plotly.offline as pyo
import plotly.graph_objs as go
import pandas as p... |
d2883c07b0016bd95688a26d45d48925b958ddeb | AiramL/Comp-II-2018.1 | /aula01/Exercicio01.py | 618 | 3.5625 | 4 | def montarGradeCurricular(gradeCurricular, codigo, nome, numRequisitos, requisitos):
if gradeCurricular != []:
for cont in range(len(gradeCurricular)):
dicionario = gradeCurricular[cont]
dicionario.values
if codigo in dict.values(dicionario):
print "... |
c1e3827548ec7a2629faa8914513d30125d7e6ff | rishavhack/Data-Structure-in-Python | /Control Flow/Generators.py | 216 | 3.765625 | 4 | def simpleGenerator():
yield 1
yield 2
yield 3
for value in simpleGenerator():
print value
def nextSquare():
i =1;
while True:
yield i*i
i += 1
for num in nextSquare():
if num>100:
break;
print num |
07dae140d5f44e0e5c4dfd997f09bfd09c6c4fd0 | zhlinh/leetcode | /0058.Length of Last Word/test.py | 156 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from solution import Solution
s = "Hello World "
sol = Solution()
res = sol.lengthOfLastWord(s)
print(res)
|
7e5271dc2dd332be83abbf815d0772eb1bd316e3 | gaopenghigh/algorithm | /lc/union_find/lc_990_satisfiability-of-equality-equations.py | 1,770 | 3.84375 | 4 | # 990. 等式方程的可满足性
# 给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或 "a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。
# 只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false。
# 使用并查集,a==b 表示 a 和 b 连通, a!=b 表示 a 和 b 不连通。
class Solution:
def equationsPossible(self, equations: list[str]) -> bool:
d... |
dce9e09a728f4fe780216c4277a355a5ece9e898 | MiguelDelCastillo/university | /Estructura de datos y su procesamiento/Actividad2-Edad.py | 1,562 | 3.796875 | 4 | '''
Codificar un script de Python que solicite la fecha de nacimiento de una persona
y nos regrese su edad aproximada mediante restar el año actual al año de nacimiento reportado
'''
import datetime
SEPARADOR = ("*" * 20)
# Preguntar al usuario fecha de nacimiento
fechaNacimiento = input("Ingrese su fecha ... |
fe3d6065ec7923fcd50837b81a709146d29bce6e | balaramhub1/Python_Test | /While/while_02.py | 504 | 3.921875 | 4 | '''
Created on Jul 24, 2014
@author: HOME
'''
def sum_n():
x=0
total=0
y=input("Enter the Number : ")
print(y.isdigit())
y=int(y)
while(x<=y):
total+=x
print("Value of x is : ",x)
print("Value of Sum is : ",total)
x=x+1
print("Thank you..!!")
... |
5aebecbba1ee15a503c9206f85d9c4af9b5ba086 | tanzi10/dsi_workshop | /capstone_preliminary_tz.py | 2,996 | 3.5 | 4 | __author__ = 'tanzinazaman'
import pandas as pd
import numpy as np
#Loading dataset given at Kaggle compitition
import random
filename = 'expedia_train.csv'
n = sum(1 for line in open(filename))-1 #number of records in file (excludes header)
percent = 1
s = n*percent/100 #desired sample size
skip = sorted(random.sa... |
bb24a9346cb25ce4a20a6cab22b3f7fa1f1d912f | BabyCakes13/Python-Treasure | /Laboratory 7/util.py | 282 | 4.28125 | 4 | def pretty_print(iterable):
"""
Pretty prints the elements of a collection.
The elements of the given collection are printed ont he same line, separated by space.
:param iterable: a collection.
"""
for element in iterable:
print(element, end=' ')
|
68230b9744ea163d38600a2fd0946e7edb2f0c66 | bennyyoav/hello-word | /untitled/tree.py | 601 | 4.125 | 4 | class Node:
def __init__(self, item, left=None, right=None):
"""(Node, object, Node, Node) -> NoneType
Initialize this node to store item and have children left and right.
"""
self.item = item
self.left = left
self.right = right
def depth(Node):
if Node==None:
... |
2fda7364c7836fded2896d41003f9aabe0f017bd | cicada-ZIQI/red-wine-classification-tree | /Grow_tree+PEP.py | 10,959 | 3.828125 | 4 | """divide the data into left branch or right branch according to the split number"""
def split_data_set_left(data_set, axis, mean_value):
# All the data in the left brach have a smaller value of the feature than the split number.
# All the value of that feature are deleted
new_data_set_left = []
f... |
8834f88487c6d2cde74d1b574a898e38e781c133 | sindhu819/Greedy-5 | /Problem-160.py | 1,300 | 3.640625 | 4 | '''
Leetcode- 44. Wildcard Matching
time complexity - O(N)
space complexity - O(1)
Approach - two pointers approach
1) when two chars are equal we move sp and pp pointer
2) when there is "*", we consider or we don't consider it
a) when we won't consider "*" we keep track of str_inde... |
f675a26895696833e7e8bea6bddb72b10190333c | meat9/Algoritms | /Спринт 15 Деревья/K. Числовые пути.py | 935 | 3.765625 | 4 | # Ребята решили поиграть в игру.
# Дано дерево, в узлах которого записаны цифры от 0 до 9.
# Таким образом, каждый путь от корня до листа содержит число,
# получившееся конкатенацией цифр пути.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.right = r... |
0e2d136a2daa312fa7febfe219ea2724e0142e84 | debbycosoi/Activities_Intro_to_Python | /Activity6-MarielCosoi.py | 868 | 4.34375 | 4 | car = {
"Year":1964,
"Brand":"Ford" ,
"Model":"Mustang"
}
print(car)
year = car.get("Year")
brand = car.get("Brand")
model = car.get("Model")
print("This dictionary should describe the following object:")
print(year)
print(brand)
print(model)
print("Access the dictionary to print the value of... |
0704bbe86d5d64b0cbf7eaa2e8956fb90cd8e18f | yurimalheiros/IP-2019-2 | /lista4/joaovitor/questao3.py | 270 | 3.984375 | 4 | entrada = int(input("Digite um número: "))
lista = []
while entrada != 0:
lista.append(entrada)
entrada = int(input("Digite outro: "))
lista.sort()
maior = len(lista)-1
print("O menor valor é", lista[0], "e o maior é", lista[maior])
|
dc235c271d53500fa896f2e185c0a0579e3c5c50 | barnwalp/python_syntax | /basic_python/24. reading_files.py | 404 | 3.6875 | 4 |
# modes are 'r', 'w', 'a', 'r+'
employee_file = open("employee.txt", "r")
# print(employee_file.read())
# print("-------------------------")
# print(employee_file.readline())
# print(employee_file.readline())
# print("-------------------------")
# print(employee_file.readlines())
# print("-------------------------")
f... |
fc72641f8e225dbdba5fddbe9e422c577dd4503b | Jeffrey1202/comp9021 | /Sample questions/sample_1.py | 816 | 3.96875 | 4 |
def remove_consecutive_duplicates(word):
'''
>>> remove_consecutive_duplicates('')
''
>>> remove_consecutive_duplicates('a')
'a'
>>> remove_consecutive_duplicates('ab')
'ab'
>>> remove_consecutive_duplicates('aba')
'aba'
>>> remove_consecutive_duplicates('aaabbbbbaaa')
'aba'... |
edb5075decfbb6d1215715100be72794cc96d018 | gauravnewar/Python | /decimaltobinary.py | 215 | 3.9375 | 4 | def Conversion(decimal):
bit = []
counter = 0
while counter != 8 :
remainder = decimal%2
bit.append(remainder)
decimal = decimal//2
counter += 1
return bit
|
647ee6960b3d2473089ba25ebf603486ecd9baf0 | jeremietd/Assessment | /QuestionAnswer.py | 767 | 3.515625 | 4 | import json
from random import randint
def load_json():
with open('./sample.json') as f:
data = json.load(f)
return data
def generator(data):
question_num = len(data)
no = randint(0, question_num - 1)
# Indexing
q = list(data.keys())[no]
answer = data[q][0]['answer']
opt... |
8144f3a3e22297b097154158b0f97813e2029872 | benbendaisy/CommunicationCodes | /python_module/examples/1318_Minimum_Flips_to_Make_a_OR_b_Equal_to_c.py | 990 | 3.9375 | 4 | class Solution:
"""
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).
Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
Example 1:
Input: a ... |
7c28ee45e6f6cbe09065e36638816c2c0fd682fc | ibrahiimmohd/Python-Project | /group_3_display_gauge_2.py | 2,146 | 3.90625 | 4 | from tkinter import Tk, Canvas, Frame, BOTH, W
import tkinter as tk
class Example(Frame):
entryValue = "0"
recHeight = 230
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title('Lab 9/10 Temperature')
self.pack(fill=BOTH, ex... |
dd24c5f7bce469cabc1ca30387187a4532e64a35 | candlewill/Algorithms | /13.ordered_matrix_lookup.py | 754 | 3.9375 | 4 | # 在一个m行n列二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
# 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
def lookup(m, nb):
nb_row, nb_col = len(m), len(m[0])
print("nb_row, nb_col=%s, %s" %(nb_row, nb_col))
# start point
i, j = 0, nb_col-1
print("start point: ", i,j)
while(i<nb_row and j>=0):
pri... |
c608b1b9692d85bc5b6a377063d221a0baa6c778 | Do-code-ing/Python_Built-ins | /Functions/zip.py | 1,720 | 4.40625 | 4 | # zip(*iterables)
# 각 iterable의 elements를 모으는 iterator를 만들어 반환한다.
# arguments가 없다면, 빈 iterator를 반환한다.
# arguments가 하나 이상이라면, 모든 iterable의 elements를 포함하는 각 tuple이 있는 tuples iterator를 반환한다.
# 사용해보자
# 출처 https://www.programiz.com/python-programming/methods/built-in/zip
# list를 만들고
number_list = [1, 2, 3]
str_list = ['on... |
1b0d04a0b3f9ab9a67debb02d9018acf767feaa6 | nata27junior/Curso-de-Python | /Mundo 2/ex044.py | 1,349 | 3.84375 | 4 | print('{:=^40}'.format(' Casas Cabia ')) # ^centralizado entre 40 espaços
print('''Exercício Python 044: Elabore um programa que calcule o valor a ser pago por um produto,
considerando o seu preço normal e condição de pagamento:
- à vista dinheiro/cheque: 10% de desconto
- à vista no cartão: 5% de desconto
- em até 2x... |
2c59021df653fb0235e7d64d20281d6be4d5f5ef | Yoav6/Final-Version-Perfected-implementation-in-Python | /final_version_perfected.py | 2,387 | 3.53125 | 4 | # inspired by
# https://www.lesswrong.com/posts/xfcKYznQ6B9yuxB28/final-version-perfected-an-underused-execution-algorithm
import json
to_do_list = []
def startup():
while True:
user_input = input("""What would you like to do?
1: add item
2. prioritize items
""")
if user_input == '... |
aef4cf22ded08923e89a300de5ab4a96ff1081a2 | Raghav-Hebbar/Employee-Management-System-with-OOPs | /EMS/EmployeeManagement.py | 846 | 3.6875 | 4 | class PerformanceManager():
def track(self, employees, hours):
print("Tracking Employee Performance")
print("=============================")
for employee in employees:
#employee.work(hours)
status = employee.work(hours)
print(f"{employee.name} : {status}"... |
81d8b2be4cfbf835a6c216d6fa2e42ddf1738d85 | 097475/AI2018 | /AI/AI2018/verifier.py | 2,151 | 4.0625 | 4 | '''
Created on 11 ott 2018
@author: Utente_
This script verifies a previously found solution step by step
'''
from board import Board
import main
import sys
helpstr = '''
commands :
step - move ahead by 1
jump n - move ahead by n
exec - executes all moves
help - show this help dialog
exit - close ... |
2c016b5bd9851de30a64609a2972140029ff6484 | vgiabao/door-to-door_project | /Node.py | 329 | 3.703125 | 4 | from math import sqrt
class Node:
def __init__(self, city, x, y):
self.city = city
self.x = x
self.y = y
def __str__(self):
return '{}, {}, {}'.format(self.city, self.x , self.y)
def get_distance(self, other):
return sqrt((self.x - other.x) ** 2 + (self.y - other.... |
bd87c318ae411b28ef20ef554e83cade0d6b4a41 | Mykola-Prshesmytskyi/IK-31-Prshesmytskyi | /lab2a/__main__.py | 1,436 | 3.890625 | 4 | print("Lab2", False)
print("Lab2", True)
print("Lab2", None)
a=2
print(abs(-12.5), f"є рівним {abs(12.5)}")
print(abs(a), f"+ {abs(a)}", "= 4")
print(abs(a), f"+ {abs(a)}", f"={abs(a*2)}")
documents = ["Лапи", "вуса","хвіст"]
for oficer in documents:
if ofice... |
edc50b649bec57a801282f498a4c0cf0271cf0ab | srishtishukla-20/function | /Q26(3 largest).py | 542 | 4.21875 | 4 | def threeLargest(list):
i=0
largest1=0
largest2=0
largest3=0
while i<len(list):
if list[i]>largest1:
largest1=list[i]
j=0
while j<len((list)):
if (largest1>list[j] and largest2<list[j]):
largest2=list[j]
e=0
while e<len(list):
if largest2>list[e] and largest3<list[e]:
lar... |
1550b0b457b789a2a3b1f9621ab9163d7d8b49a2 | siem2siem/IS211_Assignment3 | /IS211_Assignment3.py | 4,455 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""IS211 Assignment3 - csv and re module. Tested in Python 2.7"""
import argparse
import urllib2
import csv
import datetime
import operator
import re
def main():
"""This is the main function where the assignment3 will use
the following url as data.
http://s3.... |
f9cebb503a2f736e2a7a631a4ed88db67c4621c9 | AnkitAvi11/100-Days-of-Code | /Day 11 to 20/Queue.py | 505 | 4.03125 | 4 | # Python program for queue
class Queue :
# constructor for the class
def __init__(self) :
self.arr = list()
def hasElements(self) :
if self.arr :
return True
return False
# inserting an element
def insert(self, sk) :
self.arr.append(sk)
... |
a537fccef746c407d0007ba5c203f212ad76832a | AkiYama-Ryou/easyPyMySQL | /easyPyMySQL/TableField.py | 5,335 | 3.609375 | 4 | """
一个TableField对象代表数据表中的某列
添加持久化支持
"""
class TableField(object):
"""
返回一个对象代表一行数据
"""
def __init__(self, table_name, field_name, s = ["",[]]):
self.table_name = table_name
self.field_name = field_name
self.sql = s
def SQL(self):
SQL = self.sql[0]
... |
bf8af980732acd572bd2dc0498d59b87f80e51ca | tskpcp/pythondome | /pandasDome/dataframe.py | 2,967 | 3.796875 | 4 | import numpy as np
import pandas as pd
from pandas import Series,DataFrame
def dataFrameDome():
print('用字典生成DataFrame,key为列的名称')
data={'state':['Ohio','Ohio','Ohio','Nevada','Nevada'],
'year':[2000,2001,2002,2001,2002],
'pop':[1.5,1.7,3.6,2.4,2.9]}
print(data)
print('/---------------... |
f123fe68d4191e94492a427d5ee893ebcf1bc6c1 | gaussalgo/MLP_2017_workshop | /phase_1_data_preparation/sql_utils.py | 4,050 | 3.921875 | 4 | import re
def generate_pivot_table_sql(id_column, key_column, value_column, key_values, prefix_of_new_columns,
table_name=None, table_sql=None):
"""
Generates an SQL query of pivot table.
It takes a table and for each id in the id_column returns one record,
key_values will... |
4d111ceb598ca1e3b51d999debbab203c4495205 | naufan250/lolxd | /trabajo#6.py | 181 | 3.953125 | 4 | "juan esteban triviño"
m=input("escoja un numero")
p=input("escoja otro numero")
while p<=m:
p=input('elija otro numero')
print("el primer numero fue ",m)
print("el segundo numero fue",p)
|
c88ae9bd740e91aaef8fe1bd22df8079f19afc32 | wfeng1991/learnpy | /py/leetcode/107.py | 989 | 3.828125 | 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]]
"""
if n... |
18ab2b7b8dad91e5bfe1c7cac1427c9783698387 | VictoriaGuXY/MCO-Menu-Checker-Online | /Learning/python_algorithms7.py | 1,400 | 4.25 | 4 | # This program is about Merging Sort using Divide and Conquer algorithm.
# Combine small sorted lists to get a large sorted list.
# Version 2
def merge(lfrom, lto, low, mid, high):
# compare two lists which need to be combined
# small in lto and lfrom index+1
# get new element and do comparison again
... |
b22256f1ba6f25103272f0277f28a7d4f94457b8 | rafaelperazzo/programacao-web | /moodledata/vpl_data/67/usersdata/172/31561/submittedfiles/imc.py | 160 | 3.5 | 4 | # -*- coding: utf-8 -*-
a=float(input('Digite o peso em kg: '))
b=float(input('Digite o a altura em metros: '))
imc=(a)/(b**2)
if imc<20:
print('abaixo')
|
fbe6d3059ea7b06d7b264ad676c7753de2571abb | billaanil3/PRACTICE | /perfectNum.py | 162 | 3.828125 | 4 | num=int(input("Enter a number:"))
sum=0
for i in range(1,num):
if num%i==0:
sum=sum+i
if sum==num:
print "Perfect Number"
else:
print "Not a perfect Number"
|
13865ef1dcab1f81b7d8e701306256c2208193c3 | Ladeiraalexandre/Python | /Redes/geradorSenhas/geradorsenha.py | 752 | 4 | 4 | import random, string
tamanho = int(input('Digite o tamanho de senha que você deseja: ')) #senha com 16 caracteres
#metodo que envolve uper e lower case, gerando letras maiusculas e minusculas na seha,
#depois adicionamos digitos e caracteres especiais para poder formar uma senha forte
chars = string.ascii_letters + ... |
081d1a79134796f00f33966f23ec82c783a7cd45 | davidglo/TMCS-2018-freshStart | /game_projects/harry-game/source/colourlist.py | 912 | 4.0625 | 4 | # dictionary of colours and associated RGB values
"""Colourlist is a module containing a dictionary of colours and their RGB values.
It also contains a function to print all the colours in the dictionary."""
colours = {} # declare a color dictionary
colours['yellow'] = [1.0, 1.0, 0.0] # fill each entry of the color... |
abed77a7562a9087afa4e74b620738779f5dfbad | ianjosephjones/Python-Pc-Professor | /8_18_21_Python_Classs/craps_homework.py | 1,348 | 4.25 | 4 | import random
"""
Create a two six-sided dice that changes
every roll. If you get a 7 or 11 on the first
roll you win! If you get a 2, 3, or 12
on the first roll then you lose.
Otherwise, what ever you roll becomes
your "point". You'll keep rolling the dice
until you roll either a 7 or your point.
If you roll a 7, yo... |
977ce48c32f0ae964715f4c739ed422262372406 | pauldavid23/TurtleDifferentShapes | /main.py | 2,334 | 4 | 4 | from turtle import Turtle, Screen
the_turtle = Turtle()
the_screen = Screen()
the_turtle.shape("turtle")
the_turtle.color("green")
def forward_right():
the_turtle.forward(150)
the_turtle.right(90)
the_turtle.forward(150)
def turn_right():
the_turtle.right(90)
def create_square():
forward_right(... |
97cf36e5d96dc9662128208c6f4cff099dff5e6e | Helga-Helga/ADS | /ADS_lab5/main.py | 1,063 | 3.765625 | 4 | import datetime
from tree import Node
from file import search, delete
tree = Node('')
with open('input.txt') as f:
for line in f:
tree.insert(line)
print("1. Print tree\n2. Search node\n3. Delete node\n4. Exit")
ans = True
while ans:
ans = raw_input("What would you like to do? ")
if ans == "1":
... |
877650d3ed67bd301dbb4a5f1eca91206aa1b552 | imalihaider/HacktoberFest2021-Python | /Speech to Text/speechToText.py | 508 | 3.71875 | 4 | # import the module for speech recognition
import speech_recognition as sr
# create the recognizer
u = sr.Recognizer()
# define the microphone
mic = sr.Microphone(device_index=0)
# record your speech
with mic as source:
audio = u.listen(source)
# speech recognition
result = u.recognize_google(audio)
# ... |
ea38be25b8bf31d88563554a17a87062d1531cfe | farmrwthshotgun/Project-97 | /guessingGame.py | 392 | 4 | 4 | import random
randomNumber = random.randint(1,10)
guesses = 0
while guesses < 5:
number = int(input("Guess the number :"))
if randomNumber == number:
print("you win")
break
elif number < randomNumber:
print("Your guess was low")
else:
print("Your guess was too ... |
6d2eb33b3f6bea6c1c025bd7282f3b106c5d47e5 | William-Zhan-bot/2021_Python_Class | /6.4 練習題 參考解答/6.4 OJ練習第二題 參考解答.py | 554 | 3.78125 | 4 | # 雙重輸出
# 此題的要點在於將兩個輸入項目轉換為整數同時,也必須保留原本字串的資料型態
# 小提示: input()函式內建的資料型態為字串
a = input() # 建立輸入變數a
b = input() # 建立輸入變數b
int_a = int(a) # 創造新的變數 並將a轉換為整數型態存入其中
int_b = int(b) # b如同a一樣操作
# 依題目要求的將結果打印出來
print(int_a+int_b) # a+b
print(int_a*int_b) # a*b
print(int_a%int_b) # a%b
print(a*int_b) # a輸出b次
print(b*in... |
b25ef5e7238d86cf2d2d50fb46c0db85e9bbe0ea | mannhuynh/Python-Codes | /python_codecademy/hacking_the_fender/hacking_the_fender.py | 4,487 | 4.34375 | 4 | """
The Fender, a notorious computer hacker and general villain of the people, has compromised several top-secret passwords including your own. Your mission, should you choose to accept it, is threefold. You must acquire access to The Fender‘s systems, you must update his "passwords.txt" file to scramble the secret dat... |
ffc24a31ef05d9fd54350d9c859feb882d776160 | kamlesh910/codewars | /programs/codewars/shortesyword.py | 108 | 3.734375 | 4 | def find_short(s):
return min([len(word) for word in s.split()])
return l # l: shortest word length
|
d8671fabc5ff2916a268497c8a007301855b2cd6 | kdkchy/praxis-academy | /novice/01-04/latihan/latihan1-06.py | 390 | 3.6875 | 4 | # super()
class A:
print("A")
def truth(self):
return 'Angka Genap'
class B(A):
print("B")
pass
class C(A):
print("C")
def truth(self):
return 'Angka Ganjil'
class D(B,C):
def truth(self,num):
if num%2 == 0:
return A.truth(self)
else:
... |
f8db4a47964bb8a188f5c67ab17eac191c4be80d | yanismiraoui/PoP_student_submissions | /exercise_06/exercise_6_YanisMiraoui/nonlinear_solvers/solvers.py | 3,626 | 4.03125 | 4 | """A module providing numerical solvers for nonlinear equations."""
class ConvergenceError(Exception):
"""Exception raised if a solver fails to converge."""
pass
def newton_raphson(f, df, x_0, eps=1.0e-5, max_its=20):
"""Solve a nonlinear equation using Newton-Raphson iteration.
Solve f==0 using N... |
41f8546a554f5cffce803e3913ef7d896935c7ef | zhulei2017/Python-Offer | /sword-to-offer/28.1.py | 553 | 3.921875 | 4 | from itertools import permutations
def my_permutation(s):
str_set = []
ret = [] # final result
def permutation(string):
for i in string:
str_tem = string.replace(i, '')
str_set.append(i)
if len(str_tem) > 0:
permutation(str_tem)
e... |
dde7b88424a937c4e41b4db86928baee972b0f76 | riteshgcoder/birthday-remainder-mini-project-python | /birthday rem.py | 1,329 | 4.28125 | 4 | dict={}
while True:
print('@@@@@Birthday ramainder app@@@@@@')
print('1. Show birthday')
print('2. Add to birthday list')
print('3. Exit')
choice=int(input('Enter the choice'))
if choice==1:
if len(dict.keys())==0:
print('Nothing to show')
else:
... |
99c50eeb381299f897d3618d8a99a690e2588ca3 | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/shnhua002/question1.py | 520 | 3.8125 | 4 | """QUESTION 1, Assignment 7
Charlie Shang
SHNHUA002"""
string = ''
print('Enter strings (end with DONE):')
wordlist = []
while not string.upper() =='DONE':# repeat input while the user is not done.
string = input()
if string not in wordlist: #f the input isnt already in the list, then append
... |
3ef8589aca6fe9d41427072d1cfcf702fb5fbfc6 | 1715509415/ALPHA-ZERO-SharedMem | /SharedMemLogic.py | 7,382 | 3.78125 | 4 | class Board():
# list of all 8 directions on the board, as (x,y) offsets
__directions = [(1,1),(1,0),(1,-1),(0,-1),(-1,-1),(-1,0),(-1,1),(0,1),(0,0)]
__oldBoard = []
def __init__(self, n):
"Set up initial board configuration."
self.n = n
# self.oldBoard = {}
# self.oldB... |
2d909616c87ae117559ad88c38b563d4b7dd5721 | yanshengjia/algorithm | /leetcode/Tree & Recursion/270. Closest Binary Search Tree Value.py | 3,110 | 3.953125 | 4 | """
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the target.
Example:
Input: root = [4,2,5,1,3], target = 3.714286
4
... |
3b49b8fe287935488da4d2f3369f644011b851cc | poulomikhaiitm/Shinichi-Kudo | /minutes & seconds.py | 221 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 17 13:54:03 2019
@author: shinichikudo
"""
N = int(input('Enter the value of Minutes = '))
P = int(input('Enter the value of seconds = '))
S = (N*60) + P
print(S) |
9d2ada0df72768eefc18784637ddd912f5e0075c | Leoleopardboy12/Tasks-for-Programming | /Task 49.py | 1,139 | 3.515625 | 4 | Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import random
>>> arrs = [random.randint(-10,20) for iter in range(20)]
>>> print(arrs)
[16, -8, 9, 17, 16, -5, 14, 14, -5, -2, -2, 9, 11, 6, 1... |
cb156f1bed49400f7edb7a63edab8747796864fb | pamtabak/LeetCode | /25_reverse_nodes_k_group.py | 2,280 | 3.6875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
# this is a simple solution that solves the problem, but using lots of extra memory space (since we create 2 lists of ints and a new ListNode too)
def ... |
da554e7c2297ea24fb957bc06a8a820308120bc4 | ThanhTungHoang/Codeforces | /watermelon.py | 146 | 3.828125 | 4 | i = int(input())
if i >= 1 and i <=100:
if i % 2 == 0 and i > 2:
print("YES")
else:
print("NO")
else:
print("") |
8a489eb93a3c367302ee3e9f879a5d766a33e237 | angus-101/monte-carlo | /Ex3 Python.py | 25,132 | 3.53125 | 4 |
"""
Created on Thu Feb 20 12:09:54 2020
@author: angus
"""
import numpy as np
import matplotlib.pyplot as plt
import time
from mpl_toolkits.mplot3d import Axes3D
import statistics as st
detector1 = 0.55
detector2 = 0.6
detector3 = 0.85
detector4 = 0.5
def sinAnal():
"""
This fun... |
10ae2ed10c81eda0e085e336c1aed143c25e6767 | Santiago-2209/Python-CEC-EPN-SantiagoC | /pandas/practica_big_data.py | 776 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 24 19:42:08 2020
@author: CEC
"""
import pandas as pd
titulos=pd.read_csv("data/titles.csv")
print(titulos.head(100))
print("\n"*2)
elenco=pd.read_csv("data/cast.csv", encoding="utf-8")
print(elenco.head(10))
print (len(titulos))
print(titulos.sort_values('... |
1cb0fb88486caaf71cf6bc11544e907ce990217c | thiagoaslima/LP1 | /exercicios/01/e01.py | 688 | 3.890625 | 4 | # -*- coding: utf-8 -*-
n1 = input("digite o primeiro número: ")
n2 = input("digite o segundo número: ")
if (n1 == n2):
print("Você escolheu o número " + str(n1) + " duas vezes.")
else:
maior = n1 if n1 > n2 else n2
menor = n1 if n1 < n2 else n2
print("Você escolheu os números " + str(menor) + " e ... |
55c629a933c67c59f3a0b362e99e9a1645348089 | Ippo343/SpeechAgent | /vectorUtils.py | 816 | 3.5 | 4 | #!/usr/bin/env python
# This module contains some utilities to simplify the computation of the angles between vectors.
import math
from numpy import *
# Versors of the axes
ux = array([1, 0, 0])
uy = array([0, 1, 0])
uz = array([0, 0, 1])
# Returns the angle between two vectors,
# by inverting the formula of the ... |
f1d8f300ed968594c4c5957606d97e4cadf11bf7 | rickylovebaby/PythonTutorial | /Fibonacci.py | 240 | 3.828125 | 4 | def fib(n):
a,b=0,1
while a < n:
print(a,end=' ')
a,b= b,a+b
print()
def fib2(n):
result = []
a,b=0,1
while a < n:
result.append(a)
a,b = b,a+b
return result
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
|
ec17bfa965f1984cd0e2f6a872255f4a27e8c961 | aryabartar/learning | /interview/sort/insertion_sort.py | 394 | 4.25 | 4 | def insertion_sort(array):
for i in range(1, len(array)):
biggest__index = 0
for j in range(0, len(array) - i + 1):
if array[j] > array[biggest__index]:
biggest__index = j
array[len(array) - i], array[biggest__index] = array[biggest__index], array[len(array) -... |
6249d7f0c2d7e73ee56f4855ebdd2e862d359729 | daao/swarm-intelligence | /src/ants.py | 4,818 | 3.515625 | 4 | from ant import Ant
import Params
import numpy as np
class Ants:
def __init__(self, distances, flows, nb_ants, nb_cities):
self.distances = np.array(distances).copy()
self.flows = np.array(flows).copy()
self.nb_cities = nb_cities
self.nb_ants = nb_ants
self.colony = []
... |
660a4c1dbab68722b2f17a9922db77dc9b7449d4 | nnopp/NLP-100-Python | /Chapter_1/03.py | 636 | 3.546875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
# 03. 円周率
# "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.
input_string = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mecha... |
738d96e2106164e40c21082b770176ee7a12dc57 | Puhalenthi/-MyPythonBasics | /Python/DSA/Chapter 6/PolynomialADT.py | 1,129 | 3.5 | 4 | class Poly():
def __init__(self, coef, var, pow):
self.coef = coef
self.var = var
self.pow = pow
def returnterm(self):
return '{}{}\u00b{}'.format(self.coef, self.var, self.pow)
def add(self, other):
if self.var == other.var and self.pow == other.pow:
... |
65030f89ce9182b5747bc7bd71b696e814b6f7e6 | rafaiy/simple-programs | /codechef/triangle.py | 699 | 3.515625 | 4 | testcases=int(input())
array=[]
max1=0
for _ in range(testcases):
trilength=int(input())
array2 = [[0 for row in range(trilength)] for col in range(trilength)]
for x in range(trilength):
line=input()
for y in range(x):
array.append(y)
array = line.split()
for z in... |
81a4b7dca093a1831db69b144eabbbe6cf582aed | AverageNormalSchoolBoy/Final-Project | /tutorial.py | 2,321 | 3.53125 | 4 | error = " "
from ggame import Sprite, TextAsset
slideNumber = 1
def tutorial1():
global error
st = input('{0} Welcome to Survival. You are the grey sprite, everyone else is trying to kill you. 4 hits and you die. WASD move you, with W always moving you in the direction of the arrow. Press the "w" key when you u... |
91a374d399cd264b2661e34c51f2dcfb446470d4 | amdel2020/Algorithms | /Huffman.py | 1,251 | 3.859375 | 4 | from collections import defaultdict
from queue import PriorityQueue
class Node:
def __init__(self, char, frequency, left=None, right=None):
self.char = char
self.frequency = frequency
self.left = left
self.right = right
class HuffmanEncoding:
def encode(self, root, string, huf... |
5484eaa2350116455179ffaadb17f01ab2cddb8a | saran1211/rev-num | /avg.py | 148 | 3.96875 | 4 | n=int(input('enter the no of elements'))
l=[]
for i in range(1,n+1):
a=int(input('enter the elements'))
l.append(a)
avg=len(l)//2
print (avg)
|
953c1f0343943b562617c159e0e858fbb1d4f014 | Nobode7/Assignment_1 | /compute_Total_Time.py | 1,109 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[21]:
def compute_Total_Hrs(Hours,Total_Hrs):
Total_Hrs = Total_Hrs + float(Hours)
return Total_Hrs
def compute_Avg_Hrs(Total_Hrs):
Avg_Hrs = round(Total_Hrs/3,2)
return Avg_Hrs
def get_Weekly_Hrs():
Week = ["Week1","Week2","Week3","Week4"]
Tasks = ... |
d5fcd58abadd116d208e149e27e7e803a493752a | tangmessi/pycharm_git_practice | /tkinter_4_2.py | 2,229 | 4.0625 | 4 | '''
from tkinter import *
root = Tk()
group1 = LabelFrame(root,text = '作品',padx = 5,pady = 5)
group1.pack(padx = 5,pady = 5)
group2 = LabelFrame(root,text = '作品',padx = 5,pady = 5)
group2.pack(padx = 5,pady = 5)
enter1 = Entry(group1)
enter1.insert(0, "请输入姓名")
enter2 = Entry(group2)
enter2.insert(0, "请输入学号")
button1 = ... |
8e4657a768560ddc7301037cfc005200174f4136 | 16861/MIT-open-course-problem-set-solutions | /ps1a.py | 796 | 3.875 | 4 | # pylint: disable=invalid-name
DOWN_PAYMENT_PERCENT = 0.25
RETURN_RATE = 0.04
def ask():
"""
docstring
"""
a_s = int(input("Enter your annual salary: "))
per = float(input("Enter the percent of your salary to save, as a decimal: "))
cost_ = float(input("Enter the cost of your dream home: "))... |
0dd6f85b5fdc522ed80930e069cbf14effe7179f | Payalkumari25/GUI | /frame.py | 366 | 3.5 | 4 | from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title("Frame")
#Create frame
frame = LabelFrame(root,padx=50,pady=50)
#Display frame
frame.pack(padx=10,pady=10)
# Create button
b1 = Button(frame, text="Click Here")
b2 = Button(frame, text="Don't Click Here")
# Display button
b1.grid(row=0,colum... |
54655ca01096516336f2b05570e0a39b12415b27 | anjali0503/python-codes | /ex2.py | 999 | 4.125 | 4 | # Exercise 2: Given a range of the first 10 numbers, Iterate from the start number to the end number, and
# In each iteration print the sum of the current number and previous number
def sum_Num(num):
previous_Num = 0
for i in range(num):
sum = previous_Num + i
print("Current Number", i, "Previou... |
8aa2436a013b9458480f0fe29a3f14a18fce798b | raulhernandez1991/Codewars-HackerRank-LeetCode-CoderBite-freeCodeCamp | /Codewars/Python/8 kyu/N-th Power.py | 208 | 3.765625 | 4 | def index(array, n):
return array[n]**n if len(array)-1>=n else -1
def index_up(array, n):
try: return array[n]**n
except: return -1
print(index([1, 2, 3, 4],10))
print(index_up([1, 2, 3, 4],2)) |
7be463810917c621d4cd343e6f16927168b40ecd | cccccccccccccc/Myleetcode | /979/distributecoinsinbinarytree.py | 865 | 3.859375 | 4 | # Definition for a binary tree node.
"""
timecomplexity = O(n) spacecomplexity = O(n)
root make children balance
balance(root) = val-1+balance(l)+balance(r)
flow(l) = abs(balance(left))
flow(r) = abs(balance(right))
ans += flow(l)+flow(r)
"""
class TreeNode:
def __init__(self, x):
self.val = x
sel... |
32adb99186ced366c6cde29e0508b850c2219822 | JiajunSong629/advent-of-code | /advent2020/day07.py | 3,125 | 3.53125 | 4 | from typing import NamedTuple, Dict, List
from collections import defaultdict
import re
RAW = """light red bags contain 1 bright white bag, 2 muted yellow bags.
dark orange bags contain 3 bright white bags, 4 muted yellow bags.
bright white bags contain 1 shiny gold bag.
muted yellow bags contain 2 shiny gold bags, 9 ... |
cba16e96ff90549d0c9f314351dc451b50c09064 | pkndiritu/python-basics | /strings.py | 951 | 3.5625 | 4 | # strings are enclonsed in speech marks either double or single, this is to tell pyton to take that value literally
# name = "Paul Kirira + Ndiritu"
# print(name)
# marks = '45+45+56+45'
# marks2 = 45+45+56+45
# print(marks)
# print(marks2)
#
# phone_number = "0710923458"
# print(type(phone_number))
# typecastings
#... |
9809862c2246650006ba3260519f4350f2d4ade5 | emtmm/Python_fundamentals | /exercises5.py | 1,786 | 3.609375 | 4 | import math
def mystery(s):
i = 0
result = ''
while not s[i].isdigit():
result = result + s[i]
i = i + 1
return result
def example(L):
''' (list) -> list
'''
i = 0
result = []
while i < len(L):
result.append(L[i])
i = i + 3
return result
def co... |
2c1b659497232ba250617f87fec0a9df841ed85b | smith-sanchez/trabajo03 | /Calculadora 9.py | 535 | 3.6875 | 4 | #Calculadora 9
#Esta calculadora realizara el calculo de diferencia de potencial
diferencia_de_potencial=0.0
intensidad_de_corriente=0.0
resistencia_electrica=0.0
#Asignacion de valores
intensidad_de_corriente=5
resistencia_electrica=11
#calculo
diferencia_de_potencial=(intensidad_de_corriente*resistencia_... |
c631d0d460da0197b6ceb86bdeb6152963b62542 | dianafisher/CodeJam | /2015/standing_ovation/standing_ovation.py | 1,171 | 3.5625 | 4 | # shyness level S
# Each audience member has shyness level of Si.
# An audience member will wait until at least Si other people are standing
# If Si == 0, audience member always stands and clpas immediately regardless of what anyone else does.
# What is the minimum number of friends you need to invite?
# T = number o... |
f396b36b4b9a8d1f8a6d1540c3021a7ae6ccd76c | 22Rahul22/Hackerrank | /Super Reduced String.py | 357 | 3.734375 | 4 | def reduce_s(s):
res = ''
i = 0
while i < len(s):
if i + 1 == len(s) or s[i + 1] != s[i]:
res += s[i]
else:
i += 1
i += 1
return res
def superReducedString(origin):
res = reduce_s(origin)
while res != origin:
res, origin = reduce_s(res), ... |
3e27223025234c5881533bdc41e7e026771ae209 | barbara-lisboa/mat-esp-python-intro-2015 | /bubble-sort.py | 3,077 | 4.125 | 4 | import matplotlib.pyplot as plt
N = 20 #numero de variaveis
lista = [11,18,3,1,16,12,6,19,5,0,14,4,17,9,13,7,10,15,2,8] #lista de variaveis entre colchetes
#gráfico figura final (lista desorganizada)
plt.figure() #cria figura
plt.plot(range(0, N),lista,'ok') #propriedades do grafico: alcance, variavel utilizada, graf... |
e8b05552adbff0311817ba901f3adb089785422c | e56485766/280201109 | /lab10/example1.py | 82 | 3.625 | 4 | def f(n):
if n == 0:
return 0
else:
return f(n-1) + 3
print(f(10))
|
057bf9213adfac5e470b5e2cb1c553c47290f9bf | ShawnStephens517/Python_Learning | /learn_python_hard_way/questions.py | 569 | 3.96875 | 4 |
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
height = input()
print("How much do you weigh?", end=' ')
weight = input()
print(f"So, you are {age} old, {height} tall and {weight} heavy.")
print("What is the number?", end= ' ')
x = int(input())
print("Do some adding", end= ' ')
... |
4fd3dd0094ed694453460017137cb97128103033 | Susanne-n/Twitch-Project-Analyze-and-Visualize-Data-SQL-Python | /script_part_two.py | 1,991 | 3.953125 | 4 | import codecademylib3_seaborn
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
# in this part of the project you will be taking your findings from the SQL queries and visualize them using Python and Matplotlib
# Bar Graph: Top 10 Most Popular Games
games = ["LoL", "Dota 2", "CS:GO", "DayZ"... |
6a6663b6fa4804f204acf4913ddd5cbbf0fd9553 | Jianglinhe/LinearRegression | /test_reg.py | 599 | 3.546875 | 4 | import reg
# 1.读数据文件,并对数据预处理(txt的数据的第一列都是1)
data = reg.input_data('ex0.txt')
X = data[:,0:2]
y = data[:,2:3]
print(X.shape)
print(y.shape)
# 2.绘制数据的散点图,并进行观察,确定目标函数为线性回归目标函数y = theta0 + theta1 * x
reg.my_scatter(data)
# 3.初始化参数(theta值,学习效率step,以及使用梯度下降法的训练次数)
theta_init = [1,3]
step = 0.5
n = 100
# 4.得到训练的结果
theta... |
48e7693b2872cf44825147a3a78d516bd9363c68 | FengZhe-ZYH/CS61A_2020Summer | /4.2 Implicit Sequences.py | 3,200 | 4.21875 | 4 | # lazy computation describes any program that delays the computation of a value until that value is needed.
# The iterator abstraction has two components: a mechanism for retrieving the next element in the sequence being
# processed and a mechanism for signaling that the end of the sequence has been reached and no fur... |
5c0d0e42e56d889763422e034785a99017c76695 | daniel99s/proyecto1 | /05.py | 1,188 | 3.953125 | 4 |
elijePc = ""
print("1)Cielito lindo ")
print("2) Salio el sol")
print("3)Botella tras botella")
opcion = int(input("Que elijes: "))
if opcion == 1:
elijeUsuario = "Cielito lindo"
elif opcion == 2:
elijeUsuario = "Salio el sol"
elif opcion == 3:
elijeUsuario = "Botella tras botella "
pri... |
8b2aa285c0ee9b542e8158d78f020236a07965a1 | zparnold/cs7641 | /assignment2/eightqueens.py | 7,250 | 3.515625 | 4 | import six
import sys
sys.modules['sklearn.externals.six'] = six
import mlrose
import numpy as np
import math
import matplotlib.pyplot as plt
# Define alternative N-Queens fitness function for maximization problem
def queens_max(state):
# Initialize counter
fitness = 0
# For all pairs of queens
for ... |
87fa0758c437c845663509806e914a541bdc1551 | TanaySinghal/Ibava | /IbavaSource/run.py | 13,316 | 4 | 4 | # Token types
#
# EOF (end-of-file) token is used to indicate that
# there is no more input left for lexical analysis
EOF, NULL, INTEGER = 'EOF', 'NULL', 'INTEGER'
VARIABLE, CODE = 'VARIABLE', 'CODE'
PLUS, MINUS, TIMES, DIVIDE, EXP, MOD = 'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'EXP', 'MOD'
endProgram = False
line_number ... |
c0fe7acf847c335f0ca823121b586830bca5f8bd | NikethBoReddy/Trace-Genomics | /bunny.py | 3,004 | 3.84375 | 4 | def get_center_cells(grid):
"""
:param grid: The garden matrix
:return: A list of the middle cells of the given grid
"""
rows = len(grid)
cols = len(grid[0])
row_mid, col_mid, mid_cells = [], [], []
# An even number of rows/cols adds in an extra middle cell
if rows % 2 == 0:
... |
2b8e8c40c8954599e5a481d7a00e2753263fc3cc | prathyusha1231/Contact-Book | /Contact Book.py | 2,490 | 4.46875 | 4 | print("Welcome to the phone book!")
# An empty dictionary to store our entries in
book = {}
# Repeat this loop until they exit
while True:
# Print the menu options
print("What would you like to do?")
print(" 1 - Add an entry")
print(" 2 - Lookup an entry")
print(" 3 - Delete an... |
188b5a9e4a0c49621d01d6fab2fec7f8ed8de934 | mulhod/suicide_lyrics | /project3/bin/ngrams_3.py | 26,595 | 3.78125 | 4 | #!/usr/bin/python -tt
from __future__ import print_function
import nltk
import sys
# For unigrams: Given a text file (say, a file of all an artist's lyrics), returns a
# list of unigrams.
def unigram_list(filename):
f = open(filename, 'rU')
text = f.read() # Stores the entire text as a string
text = text.lower() # ... |
1bc87d9258d4c69af1b3732f9c27f9786ccfb196 | tormantor/Roppers_ATBSWP | /project11/temp.py | 350 | 4.03125 | 4 | import random as r
guess=''
while guess not in (1,0):
print('Guess the coin toss! Enter heads or tails: ')
guess=int(input())
toss=r.randint(0,1)
if toss==guess:
print('You got it!')
else:
print('Nope! Guess again!')
guess=int(input())
if toss==guess:
print('You got it')
else:
print('Nope. You are ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.