blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
69a7be99ad60506f74079b53569a104444bf151e | Amit006/Python-competitive | /practice/lamda_expration.py | 225 | 3.53125 | 4 | i= 5
def f(arg=i):
print(arg)
i=6
f()
f(i)
def fun(a,l=[]):
if(l is None):
l.append(a)
#return l
else:
print("hi there")
print(fun(1))
|
a334e372e34f6ba62aca0cf11224621d7fcb6ff3 | shauge91/is-206-final- | /ex45.py | 1,643 | 3.90625 | 4 | #imports
from sys import exit
from random import randint
from ex45maps import *
# Engine of the game
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
while True:
print "\n-------... |
80458c7b4e1f334631f94d1d2c7a5c8dd09d4fd2 | furkangulseren/game-of-life | /conways game of life.py | 2,891 | 3.578125 | 4 | import numpy as np
import matplotlib
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import random
N = 55
data = np.ones((N, N)) * 1
data.ravel()[np.random.choice(data.size, 3000, replace=True)] = np.nan # data.size = Number of elements in the array.
# random.choice() : Random sample from 1-D... |
ccb2f28dc9f035a1ecb5b7eb4cdd2bdba5d10660 | zahraaassaad/holbertonschool-python | /0x0B-python-inheritance/101-add_attribute.py | 424 | 3.65625 | 4 | #!/usr/bin/python3
"""
This is a module for add_attribute.
"""
def add_attribute(obj, key, value):
"""Add a new attribute to an object if its possible."""
if not hasattr(obj, "__slots__") and not hasattr(obj, "__dict__"):
raise TypeError("can't add new attribute")
if hasattr(obj, "__slots__") and... |
aceebd70590245f91f5ea3f5490910f7a048af53 | shaabhishek/stanford-tensorflow-tutorials | /examples/03_linreg_starter.py | 4,567 | 3.640625 | 4 | """ Starter code for simple linear regression example using placeholders
Created by Chip Huyen (huyenn@cs.stanford.edu)
CS20: "TensorFlow for Deep Learning Research"
cs20.stanford.edu
Lecture 03
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import time
import numpy as np
import matplotlib
matplotlib.use('TKAgg... |
f690b97287a3d0c5b2dced143712776ab288e387 | CaseyMcGuire/CodeEval | /MultiplicationTables/python/solution.py | 593 | 3.546875 | 4 | from __future__ import print_function
def get_multiplication_tables(num):
table = []
for i in range(num):
table.append([])
cur_num = i + 1
for j in range(num):
table[i].append(cur_num + j*cur_num)
return table
def _get_whitespace(num):
if num < 10:
return " ... |
65b4b2bff8e84479c47b6222c8d8fdbc755b413a | MikelSotomonte/mask-turret | /SpeachToText Example.py | 444 | 3.515625 | 4 | import speech_recognition as sr
r = sr.Recognizer()
''' Euskera --> "eu-ES" ---- English --> "en-US" ---- Castellano --> "es-ES" '''
print("Speak you CrackHead")
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
data = r.record(source, duration=3)
print("Analizando")
try:
... |
d217a754322b78e0a80bed0ff1893f6014c39ade | bssrdf/pyleet | /S/StudentAttendanceRecordII.py | 2,486 | 3.703125 | 4 | '''
-Hard-
*DP*
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
'A': Absent.
'L': Late.
'P': Present.
Any student is eligible for an attendance award... |
e19415fa0e4b475c00fa88199daf12543cbcdb4d | Tallys01/Faculdade-Exercicios | /Aula_1_sabado/Aula_Sabado_6.py | 844 | 3.9375 | 4 | def media_ponderada(nota_1, nota_2, nota_3):
if nota_1 > nota_2 and nota_1 > nota_3:
return ((nota_1*4) + (nota_2*3) + (nota_3*3)) / 10
elif nota_2 > nota_1 and nota_2 > nota_3:
return ((nota_2*4) + (nota_1*3) + (nota_3*3)) / 10
else:
return ((nota_3*4) + (nota_1*3) + (nota_2*3)) / 10
def aprovado_re... |
84de41c055fd5e5c561c375e97cefdff4e344d0a | justpuzey/python | /Code With Mosh/Python for Beginners/temp.py | 102 | 3.6875 | 4 | for number in range(1, 10):
if (number % 2) == 0:
print(number)
print(f"this is a test") |
83d1bbc7173793e861b1c2ffce2e85d32e3e9f6c | meretciel/backtesting_platform | /backtesting/strategy.py | 7,460 | 3.5625 | 4 |
"""
Script: strategy.py
In this script, we will define the Strategy class. It serves as a wrapper of all the information about a strategy.
"""
import heapq
import pandas as pd
import numpy as np
import random
import stoperator.GA as GA
import logging
logger = logging.getLogger('main.strategy')
logger.setLevel(log... |
9f8b1864e8c117082b80075e9fd12d1864f01004 | ahmadabudames/snakes-cafe | /test.py | 861 | 4.0625 | 4 | # list=[]
# list= input("enter a number >")
# print("Array is :",list)
# res = list[::-1] #reversing using list slicing
# # print("Resultant new reversed array:",res)
# def reverseArray(lst):
# new_lst=lst[::-1]
# return new_lst
# lst=input("please enter numbers >")
# print(reverseArray(lst))
def binary_... |
ad9b1b026d3de2ba8301040e53230e42d0c05028 | Alice-Avetisyan/Machine_Learning | /ML_individual_work/regression.py | 4,438 | 3.671875 | 4 | import pandas as pd
insurance_data = pd.read_csv('insurance.csv')
'''
Problem setting ->> Using data, check how much a person is charged for the insurance
'''
# Retrieving the data
insurance_data = pd.read_csv('insurance.csv')
# Checking the data - phase 1
print('-----Insurance data columns-----\n', in... |
d3bd4a956e5b04b1e819f7a060deb96cfe614293 | BKBetz/ML | /P3/test/neurontest.py | 3,183 | 3.703125 | 4 | import unittest
from P3.code.neuron import Neuron
from P3.code.neuronlayer import NeuronLayer
from P3.code.neuronnetwork import NeuronNetwork
"""
Hieronder zijn de tests met de juiste parameters voor een neuron
"""
class NeuronTest(unittest.TestCase):
def testNOT(self):
t1 = Neuron([-1], 0.5)
... |
e342ed1dcb622cb3aa18dc9ff03aa6f4bbe842f3 | reafreitas1/pythonApps | /Practice_idealWeight.py | 172 | 3.625 | 4 | #Entradas
altura = float(input("Informe sua altura: "))
#Processamento
peso_ideal = (72.7 * altura) - 58
#Saida
print("O seu peso ideal e {0:.2f}". format(peso_ideal)) |
d667741c997636a3a409cb4f56a599f8e95325a9 | Bharadwaja92/DataInterviewQuestions | /Questions/Q_078_LargestElementsInArray.py | 755 | 4.28125 | 4 | """""""""
Given an array with k distinct elements, write a function to return all elements that have at least two elements greater than themselves in the same array:
For example, given the following array:
array = [2,3,9,7,6]
Your function should return:
[2,3,6]
"""
import sys
method1 = "Sort the array. Return arr[:... |
97e49ed0257e6f87dd9dd55ccaa7034b2f50ca9f | foleymd/boring-stuff | /more_about_strings/advanced_str_syntax.py | 1,051 | 4.1875 | 4 | #escape characters
#quotation
print('I can\'t go to the store.')
print("That is Alice's cat.")
print('That isn\'t Alice\'s "cat."')
print("Hello, \"cat\".")
print('''Hello, you aren't a "cat."''')
#tab
print('Hello, \t cat.')
#newline
print('Hello, \n cat.')
print('Hello there!\nHow are you?\nI\'m fine!')
#backslas... |
faf4b2aad4c87353843c0e61f124a577a41633ec | pbarden/python-course | /Chapter 9/name_format.py | 347 | 3.96875 | 4 | full_name = input()
f_name = full_name.split(' ')
if len(f_name) == 3:
first_name = f_name[0]
middle_init = f_name[1][0]
last_name = f_name[2]
print('{2}, {0} {1}.'.format(first_name, middle_init, last_name))
else:
first_name = f_name[0]
last_name = f_name[1]
print('{1}, {0}'.for... |
67aaa6f1a472cd91db9a236286b365eb44476574 | Jaswanth-Devarinti/crypt-it | /OTP.py | 982 | 3.78125 | 4 | import PRG #we need to import the pseudo random number generator
msg=input("enter message: ") #Here is your msg that has to be encrypted
key=int(input("enter key: ")) # key
code=0
for i in msg:
code=code*1000+ord(i)
##CountBin counts the number of binary digits the msg conv into binary contains
def CountBin... |
f5ada322537d455d5894076bfa6956bb476e412d | hah-ak/algorithm-study | /programmers/jump.py | 340 | 3.546875 | 4 | def combination(n, k):
N, K = 1, 1
while k > 0:
N *= n
K *= k
n, k = n - 1, k - 1
return N // K
def solution(n):
answer = 0
k = 0
while n > 0:
answer += combination(n, k)
k += 1
n -= 1
return answer % 1234567... |
caee49f2df0101efa621993c7027a44244357fe8 | mustafraca/Python-Ornekler | /5-Modüller/HesapMakinesi1.py | 601 | 3.984375 | 4 | import math
print("""
Hesap Makinesi
İşlemler;
1- Yukarı Yuvarla
2- Aşağı Yuvarla
3- Faktoriyel
4- Karekök
5- Üs
Çıkmak için Q'ya basın!
""")
while True:
islem = input("İşlem Numarası: ")
sayi = float(input("Sayı:"))
if islem == "Q" or islem == "q":
break
elif islem == '1':
print(math.... |
555740ad6712712c0caf03df21cc1545280d92f7 | goelhardik/programming | /leetcode/construct_binary_tree_from_inorder_and_postorder_traversal/sol.py | 1,103 | 3.953125 | 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 buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
... |
c5d53f75514558dddf3b8a1f88b97f2a3dbee7df | sagynangare/Intermediate_python_examples | /args_kwargs.py | 235 | 3.6875 | 4 | import matplotlib.pyplot as plt
def graph_operation(x, y):
print('function that graphs {} and {}'.format(str(x),str(y)))
plt.plot(x, y)
plt.show()
x1 = [1, 2, 3]
y1 = [5, 3, 4]
graph_me = [x1, y1]
graph_operation(x1, y1)
|
0f8eaaa7c4ffa95b5100fc74a54bce5107b79617 | Sandoque/maratona-python-14dias | /challenge-02/main.py | 4,107 | 3.515625 | 4 |
## use este espaço de cima do código para
## declarar funções e escrever seu código
#####!! NÃO EDITE O CÓDIGO ABAIXO DESTA LINHA !!#####
tracking_codes = ["JN426598162BR", "JN426598255BR","JN426598247BR","JN426598145BR","JN426598057BR","JN426598074BR","JN426598233BR","JN426598220BR","JN426598278BR","JN426598281BR... |
98e80ebbd1a5996ca10dc54d009a9b11599109d8 | therealfortune/Nwawkwo-Fortune | /BasicPython.py | 4,345 | 3.921875 | 4 | # ages = []
# user_input = int(input('Enter class age , type -1 to quit :>'))
# while user_input > 0:
# ages.append(user_input)
# user_input = int(input("Enter next age :> "))
# print(f'There are {len(ages)} age(s) which are {ages}')
# class_names = []
# count = 0
# name = str(input('Enter name of... |
21865a9061d624fa47b2ce7cce26bb937ed3cc1c | xiaogengchen/di_ai_mu | /homework3/hw3_book_11-7.py | 709 | 4.125 | 4 | # !/usr/bin/env python
# -*-coding:utf-8-*-
'''
用 map() 进 行 函 数 式 编 程 。 给 定 一 对 同 一 大 小 的 列 表 , 如 [1 , 2 , 3] 和
['abc','def','ghi',....],将两个标归并为一个由每个列表元素组成的元组的单一的表,以使我
们的结果看起来像这样:{[(1, 'abc'), (2, 'def'), (3, 'ghi'), ...}.(虽然这问题在本质上和
第六章的一个问题相似,那时两个解没有直接的联系)然后创建用 zip 内建函数创建另一个解。
'''
def main():
list1 = [1, 2, 3]... |
cd58285ecf8fa5badb7f418ae30bc0c7b6af9fd3 | staffordc/PyGame | /lexicon/lexicon.py | 1,177 | 4.125 | 4 | stuff = input('> ')
def scan(words):
results = []
directions = {'north', 'east', 'west', 'south'}
verbs = {'go', '', 'eat'}
stops = {'the', 'in', 'of', 'from', 'at', 'it'}
nouns = {'door', 'bear', 'princess', 'cabinet'}
words = convert_lower(words)
splitwords = words.split()
# loops... |
247d8e1ce2ad2b84383a1e3d0bff0c158949e3a8 | rafaelperazzo/programacao-web | /moodledata/vpl_data/5/usersdata/112/1783/submittedfiles/atm.py | 198 | 3.8125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
valor=input('Digite quanto deseja sacar:')
a=20
b=10
c=5
d=2
e=1
f=0
j=(valor//a)
r=(valor%a)
if r == f:
print('a= %.2d'% j)
|
89efb2da880ee10490ebdf518cc985a3401dccde | stnorling/Rice-Programming | /poc/Week 3/stopwatch_game_testing_example.py | 1,377 | 4.125 | 4 | """
Example of testing, comparing a bug function to the correct function.
The test runs through all possible iterations and returns any mismatches.
For any returned errors, the given index should be used as a test case for the function.
"""
# Bad time format (erroneous method.. could be any erroneous method) below
d... |
fbc94e6220b1ff2e480c770c6cc3f2b2018cc153 | barsuk2/python_algos_gb | /Урок 7. Практическое задание сорт/Урок 7. Коды примеров/Алгоритм сортировки вставками.py | 938 | 3.78125 | 4 | """Сортировка вставками"""
import timeit
import random
def insertion_sort(lst_obj):
for i in range(len(lst_obj)):
v = lst_obj[i]
j = i
while (lst_obj[j-1] > v) and (j > 0):
lst_obj[j] = lst_obj[j-1]
j = j - 1
lst_obj[j] = v
return lst_obj
orig_list... |
0a6931d7772a2abc03d79070b6a6fc7dcf6b26a7 | nestauk/rhodonite | /rhodonite/utils/math.py | 1,101 | 3.609375 | 4 | import numpy as np
from scipy.sparse import csr_matrix, csc_matrix
def jaccard_similarity(A, B):
"""jaccard_similarity
Calculates the jaccard similarity between a vector a and all of the rows in
a matrix B.
Parameters
----------
A : :obj:`array-like`
A vector of length L.
... |
582a389432df37dfa2d65c32e27af24149ef3fe8 | ilan20-meet/meatyl1201819 | /lab2.py | 656 | 3.71875 | 4 | import random
# def first_last(list1):
# list2 = []
# list2.append(list1[0])
# list2.append(list1[-1])
# return(list2)
# print(first_last([1,2,3,4]))
# def under5(list1):
# list2=[]
# y=int(input("enter a number"))
# for x in list1:
# if x < y:
# list2.append(x)
# return(list2)
# print(under5([1,2,3,4,5... |
ae9ab4b597be94fb3f2a661c667756b245aa84c2 | yusupovbulat/eric-matthes-python-crash-course | /chapter_1_basics/part4/4-10.py | 378 | 4.28125 | 4 | pizzas = ['mozzarella', 'neapolitan', 'italy', 'diablo', 'four cheese']
print('The first three items in the list are:')
for pizza in pizzas[:3]:
print(pizza.title())
print('\nThree items from the middle of the list are:')
for pizza in pizzas[1:4]:
print(pizza.title())
print('\nThe last three items in the list... |
de7ee92e8a0662d80770506ac9d5d9ac2be8dcb1 | cgopalan/FileSizes | /filesizes.py | 1,380 | 4.03125 | 4 | """
Walks through the directory tree starting from a specified root
directory and lists files in decreasing order of size.
You can specify as a command-line argument how many number of
files you want displayed. If argument is omitted, it displays 10.
Works only on windows for now.
"""
import os, sys
from oper... |
c6e2b5df2c60d6caa3b0ad51598beee21e960120 | JiangFengJason/LeetCodePractice | /SolutionsPY/MultiplyStrings.py | 627 | 3.5625 | 4 | class multiplyStrings:
def multiply(self, num1, num2):
num1=num1[::-1]
num2=num2[::-1]
arr=[0 for i in range(len(num1)+len(num2))]
for i in range(len(num1)):
for j in range(len(num2)):
arr[i+j]+=int(num1[i])*int(num2[j])
ans=[]
for i in ran... |
9bb17c0a4450b9f92ca8bc6a4bd96ea1cc74f148 | kb0rg/hb_hw03 | /accounting.py | 3,015 | 3.734375 | 4 | """
cleaned up code/ made more human-readable
"""
"""
* count up the differerent types of melons that were sold.
"""
print "******************************************"
orders_by_type_file = open("orders_by_type.csv")
# create melon tally dictionary: melon type keys with count values set to zero
melon_tallies = {"Mu... |
ec64a65f6da20a98d8533e16f8b88247e1fe207f | gplatono/lexical_resources | /Noun Hierarchies/selecting_synsets_script.py | 2,909 | 3.546875 | 4 | from nltk.corpus import wordnet as wn
import io
'''
A script for viewing and selecting which senses of words to use in
tree seeding
Usage:
...
(1/200) angle -
angle.n.01: the space between two lines or planes that intersect; the inclination of one line to another; measured in degrees or radians
slant.n.01:... |
b00d45cd1f8d201031f1b7271cf22d17cb141da4 | Pavan-443/Python-Crash-course-Practice-Files | /chapter 8 Functions/album_8-7.py | 406 | 3.953125 | 4 | def make_album(artist_name, title, noof_songs=None):
"""returns info about music album in a dictionary"""
album = {}
album['artist name'] = artist_name.title()
album['song title'] = title.title()
if noof_songs:
album['no of songs'] = noof_songs
return album
print(make_album('dasari', 'h... |
1d6c3e0d8b832f28230b513f62434122d0eef33f | Yash-Gupta/coupon-proj | /item.py | 382 | 3.84375 | 4 | from balance import Category
class Item:
"""
An Item is part of the Store's database and represents an item's name, category and price.
"""
def __init__(self, name: str, category: Category, price: int) -> None:
self.name = name
self.category = category
self.price = price
def __repr__(self) -> st... |
e6a789338fdd6b4f7b7d889c5899a96746144507 | andriitugai/python-morsels | /leetcode/happy_number.py | 1,279 | 3.9375 | 4 | # https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3284/
# Write an algorithm to determine if a number n is "happy".
#
# A happy number is a number defined by the following process: Starting with any positive integer,
# replace the number by the sum of the squares of its digits, and r... |
bf07ef77769ccd71da25cc6d82e2e2fc18427bd9 | Dylane-SILVA/NLP_Vibe_Catcher | /VibeCatcher/Manual_Labelizer.py | 419 | 3.78125 | 4 | import pandas as pd
path = input("Enter the path of the CSV you want to labelize : ")
df = pd.read_csv(path, sep=',', header=0, encoding='latin-1')
label = []
for index, row in df.iterrows():
print(row["tweet"])
userlabel = input("0 = negative, 2 = neutral, 4 = positive : \n")
label.append(int(userlabel)... |
9ece3b87f519ad2de1c208b1e2de4b300adbe678 | laminsawo/python-365-days | /python-fundamentals/day-4-AdvancedLists/for-loops-for-adding-items.py | 264 | 4.125 | 4 | names = ['Lamin', 'John', 'Beth', 'Ash']
new_names = 'Sarah', 'Alison', 'Melissa'
print(new_names)
for name in new_names:
names.append(name)
print(name + ' has been added to the list')
print('These are the names in the list: \n \t', names)
|
0edd04c291de533fa6d629ef10513eedbf5e4430 | Ali-ismail-g/crowd_funding-app | /Functions/register.py | 2,417 | 3.8125 | 4 | import re
valid_inputs = {}
def signup():
print("*********Registeration*********")
first_name = input("please enter your first name: ")
if first_name.isalpha():
valid_inputs["first_name"] = first_name
else:
print("rewrite your name")
first_name = input("please enter your first... |
63715aba1093979b52fc6e9a46fd05029fa95a5c | j4wh3r/Py4e | /Ch08/Ex6.py | 724 | 4.21875 | 4 | # Exercise 6: Rewrite the program that prompts the user for a list of
# numbers and prints out the maximum and minimum of the numbers at
# 8.16. EXERCISES 107
# the end when the user enters “done”. Write the program to store the
# numbers the user enters in a list and use the max() and min() functions to
# compute... |
38684ebfc5ecc4e7e8b3ac3ca4e9c7f5e51d4280 | alchemizeur/good_shopkeeping | /most_recent/shopkeeper.py | 17,033 | 3.890625 | 4 | # !usr/bin/env python3
# shopkeeper.py
# introduces prompt script which askes your name, your preferred pronouns and your age.
import sys
import random
import shopkeeper_stats
import csv
from time import sleep
def get_player_data (shopkeeper_name, SHPKPR, color):
shopkeeper_names = ['Landriel', 'Kip'... |
c7a67c23b2aae88e039c045f3dae89fe6b372e5e | samarla/LearningPython | /factorial using function.py | 289 | 4.25 | 4 | number = int(input('enter any number: '))
def factorial(n):
if n == 1: # The termination condition
return 1 # The base case
else:
res = n * factorial(n-1) # The recursive call
return res
print('the factorial of given number is: ',factorial(number))
|
b09c5814654801bff7eb7b305822735466c48f1a | EthanOtholvinBrown/Let-Them-Be-Quizzed- | /Let Them Be Quizzed!/quiz_backendCURRENT.py | 6,571 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 11 20:43:40 2020
@author: cars_
"""
#Using Object Pool to store all objects
import os
from abc import ABC,abstractmethod
import requests
import json
#using factory and chain of responsibility pattern for quiz building
class Quiz_Factory():
def create(quiz... |
9ab10e71bd87592a82264a5a9842707709549185 | Taekyung2/Algo_collection | /BOJ/1000번대/1200/1259/q1259.py | 82 | 3.609375 | 4 | n = input()
while n != "0":
print(["no", "yes"][n == n[::-1]])
n = input() |
25e3d777994e97cc87718c9f94e1488394c4586a | jprajapat888/Python-Files | /Python Program to find the Square root for real and complex numbers.py | 188 | 3.9375 | 4 | #Find square root for real or complex numbers
#importing the complex math module
import cmath
num = 1+2j
#To take input from the user
#num = eval(input("Enter a number: "))
num_sqrt |
ab81e1b371b5cb529c85abb16630105e8a8e8413 | sharannyobasu/OpenCV-Pycharm- | /mouse_events_2.py | 1,350 | 3.6875 | 4 | #HOW TO DRAW CIRCLES IN OPENCV AND DRAW LINES BETWEEN EVERY CLICKED POINT
'''import numpy as np
import cv2
def click_event(event, x,y,flags,param):
if event==cv2.EVENT_LBUTTONDOWN:
cv2.circle(img, (x,y), 3
, (0,0,255), -1) #-1 thickness just fills the shape
points.append((x... |
9b41d382216ff06d42c72a067b514998182b48fa | javedmomin99/Pizza-Price-Calculator | /Pizza price calculator.py | 557 | 4.09375 | 4 | print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L \n")
if size == "S":
bill = 15
print("Small Pizza costs $15")
elif size == "M":
bill = 20
print("Medium Pizza costs $20")
else:
bill = 25
print("Large Pizza costs $25")
add_pepperoni = input("Do you want pepp... |
5c44ea6917586f3ebd261b16f09841f9073174ad | leedale1981/compsci | /binary_search/python/iterative_binary_search.py | 538 | 4.28125 | 4 | def binary_search(a_list, first, last, target):
"""Return the position where target is or should be inserted.
Assume 0 <= first < len(a_list) and last < len(a_list).
Assume a_list[first] <= a_list[first+1] <= ... <= a_list[last]
if first <= last.
"""
while first <= last:
middle =... |
9c97ac6347b4a5d21330bfacb0b5fe9823399a97 | tsung791027/Learning-path | /0427.py | 441 | 3.734375 | 4 | def dist(x1,y1,x2,y2):
def mysqrt(z):
return z** 0.5
dx = (x1 - x2) ** 2
dy = (y1 - y2) ** 2
return mysqrt(dx + dy)
print(dist(0,0,1,1))
#lambda funtion
#ch11_32
square = lambda x: x ** 2
print(square)
#lambda 使用時機
def mycar(cars,func):
for car in cars:
print(func(car))
dreamcars ... |
5998b59bf0965b207a2f12482376acae9a0fa6ab | JDavid121/Script-Curso-Cisco-Python | /207 errors failures.py | 228 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 19 09:59:36 2020
@author: David
"""
try:
x = int(input("Enter a number: "))
y = 1 / x
except:
print("Oh dear, something went wrong...")
print("THE END.") |
737193e8a7a6c718ceedd2e09f6b5aa6de447178 | GiangHoGoVap/python-learning | /FIFOqueue/FIFOqueue.py | 302 | 4.21875 | 4 | # Python program to print the FIFO queue
import queue
q = queue.Queue()
# Insert items at the end of the queue
y = int(input("Enter the queue: "))
for x in range(y):
q.put(str(x))
# Remove items from the head of the queue
while not q.empty():
print(q.get(), end = " ")
print()
|
bacd938ef52b7a22ee5482605288de7e6f5327fa | harrylee0810/TIL | /swexpert/python01/6247.py | 396 | 3.75 | 4 | # while문을 이용해 아래와 같이 별(*)을 표시하는 프로그램을 만드십시오.
# 출력:
# ******* => 7
# ***** => 5
# *** => 3
# * => 1
# n = int(input())
# for i in range((n+1)//2):
# star = '*'*(n-(i*2))
# blank =' '*i
# print(blank,star,sep='')
n = int(input())
for i in range((n+1)//2):
print(' '*i + ... |
61eb0a7486662baa6ec2acde8af38bc9eeb2e0c1 | Athilas-Silva/fpoo | /Aula19/fatorial/Fatorial.py | 158 | 3.75 | 4 | contador = 1
fatorial = 1
while contador <= 5:
fatorial = fatorial * contador
print('O fatorial de 5 é {}'.format(fatorial))
contador += 1 |
8772c80bd621ff045f8cd02cf8c2318d88fe4912 | pedroleon21/JogosEmPython | /main_gam.py | 360 | 3.75 | 4 | import adivinhacao
import forca
jogando = True
while jogando:
print('1. foca\n2. adivinhacao')
escolha = int(input('qual jogo: '))
if(escolha == 1):
forca.jogar()
if(escolha == 2):
adivinhacao.jogar()
if( input("deseja continar jogando? \n1.S\n2.N ").upper() == 'N'):
jogando ... |
53210f57f57abd6603bb1f0277e31c75ce1d8ab9 | elenghazaryan/test | /helpers.py | 4,820 | 3.5625 | 4 | import math
import random
from sympy.strategies.core import switch
def arithmetic(a, b, s):
if s == '+':
return '{a}+{b}={sum}'.format(a=a, b=b, sum=a + b)
elif s == '-':
return 'a-b={}'.format(a - b)
elif s == '/':
if b != 0:
return 'a/b={}'.format(a / b)
else... |
36fcc2ce80afab830a5539c7f58f65e3f096e8a3 | sid-sr/Shortest-Path-Genetic-Algorithm | /ShortestPathGA/graph.py | 1,066 | 3.9375 | 4 | #
# Genetic Algorithm for Shortest Path
# Create a graph to simulate the algorithm on
#
import random
import seaborn as sns
import matplotlib.pyplot as plt
# will be using adjacency matrix to represent the graph
# edge weights between 0 and 100 (exclusive) using a random distribution
class Graph(object):
''... |
d5e1eb9bed25f65d5d295f4b4324b5ca021c5e68 | aracthon/SPECT | /src/nn.py | 3,643 | 3.859375 | 4 | # Implementing a one-layer Neural Network
#---------------------------------------
#
# We will illustrate how to create a one hidden layer NN
#
# We will use the iris data for this exercise
#
# We will build a one-hidden layer neural network
# to predict the fourth attribute, Petal Width from
# the other three (Sepal... |
ce43e0facd3dce135955083842d91031f6ad2814 | annabechang/leetcode | /217_Contains_Duplicate.py | 1,981 | 4.03125 | 4 | """
217. Contains Duplicate
Easy
423
529
Favorite
Share
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Examp... |
97463196c171ea466c592eb412d92c996946e50e | z2z23n0/python_practice | /07_dictionary.py | 201 | 3.765625 | 4 |
dict1 = {'name':'高小一','age':18,'salary':30000}
dict2 = {'name':'高小二','age':19,'salary':20000}
dict3 = {'name':'高小五','age':20,'salary':10000}
list = [dict1,dict2,dict3]
print(list)
|
c24e38787754cb0ef365bb3fb6abb2d63d14a6c3 | LiuFang816/SALSTM_py_data | /python/eliben_deep-learning-samples/deep-learning-samples-master/cs231n/softmax.py | 2,192 | 4.09375 | 4 | # Softmax classifier loss function
import numpy as np
from random import shuffle
import linear_classifier
def softmax_loss_naive(W, X, y, reg):
"""Softmax loss function, naive implementation (with loops)
Important dimensions: K is number of classes we classify samples to. D is
the dimensionality of data... |
01e260df9e796602ef55939d01882ca270a263f1 | JeRusakow/epam_python_course | /homework7/task3/hw3.py | 2,150 | 4.3125 | 4 | """
Given a Tic-Tac-Toe 3x3 board (can be unfinished).
Write a function that checks if the are some winners.
If there is "x" winner, function should return "x wins!"
If there is "o" winner, function should return "o wins!"
If there is a draw, function should return "draw!"
If board is unfinished, function should return... |
b931dbb0843086e92bc312e5c4ade392b150132d | sadhanaauti93/pythonDemo | /loops.py | 558 | 3.71875 | 4 | greeting = "Good Morning"
a = 4
if a > 2:
print("condition matches")
print("second line")
else:
print("condation do not match")
print("if else conditation code is completed")
#for loop
obj = [2, 3, 5, 7, 9]
for i in obj:
print(i)
#sum of first natural number 1+2+3+4+5+=15
#range(i,j)-> i to j-... |
01b0c5702695ce0fa84fe0f9bfc72ec600c7295f | JoKerDii/BiasNets | /03_bspline_DL/utils.py | 4,596 | 3.5 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn.metrics as metrics
def sum_poisson_deviance(y_true, y_pred):
"""
y_pred & y_true: pandas data frame or series
"""
y_pred = y_pred.astype("float")
y_true = y_true.astype("float")
eps = 1e-99
sum_poisson_d... |
de22a99b7d56c52eaa46b51ad39d007680ac861c | parzipug/Final-Tech-iD-text-adventure-game | /FinalProject.py | 11,646 | 3.703125 | 4 | import time
import sys
#Basic player information and item information
lvl_select = input("Would you like to Experience This Game as the VietCong ")
player_username = input(" <<< Type Name To Start >>> ")
player_health = 8
player_backpack = ' '
bat_clb_dmg = ' '
Club = 7
Large_sword = 14
black_pills = 40
... |
4be32e81793228987fe3db431e148ba664917038 | evilpie/jsparagus | /jsparagus/lexer.py | 5,575 | 3.90625 | 4 | """ Lexical analysis is the breaking of a string into tokens. """
import re
class SyntaxError(__builtins__['SyntaxError']):
pass
class UnexpectedEndError(SyntaxError):
pass
class LexicalGrammar:
"""Quick and dirty lexer implementation.
In order to support multi-part lexing (multiple calls to .wr... |
59f24c38271b667edf68dbe515c92d87797c6d9a | angelacpd/PyAlpha | /main.py | 4,352 | 4.0625 | 4 | import re # regex
# Types
print("Aloha!")
print(5+6)
print("5"+"6")
print(2.73*3.14)
print(int("5")+int("7"))
print('She said: "I want that."')
print('She said: "Don\'t do that."')
print("This costs " + str(6+5) + " dollars.")
print("My name is " + "Hello:Angela:Nick".split(":")[1])
# string = str
# integer = int
# ... |
a6aff42071af88d4a14bedd8525689e7c8e17bc0 | vss-2/if672 | /Estruturas/BuscaBinariaIterativa.py | 2,785 | 4.09375 | 4 | from random import randint
# Busca binária implementada de forma iterativa
# Entrada: array (espera-se ordenado)
# Saída: índice do valor buscado (se estiver presente no array)
def buscaBinaria (entrada, tamanho, busca):
esq = 0
dir = tamanho - 1
while esq <= dir:
meio = int((esq + dir)/2)
... |
43453662cfb5ddca0f39f73d066cfdf58d1dd9ad | lucaslk122/Exercicios-python-estrutura-de-repeticao | /Exe40_acidentes_cidade.py | 1,053 | 3.828125 | 4 | maior = menor = count = soma_veiculos = soma_acidentes = soma_2k = 0
cid_maior = cid_menor = 0
for i in range(1,6):
codigo = int(input("Digite o código da cidade: "))
veiculos = int(input("Numero de veiculos de passeio: "))
acidentes = int(input("Numero de acidentes de transito com vitimas: "))
soma_v... |
46084387be945b29fc95d5b829c7e244050c3e7b | ssak32/Tutotrials | /Python/Udemy_PythonCoreAdvanced/encapsulation/student.py | 331 | 3.828125 | 4 | class Student:
def __init__(self):
#Private variables
self.__id = 123
self.__name = "Dan"
def display(self):
print(self.__id)
print(self.__name)
s = Student()
s.display()
#Name Mangling syntax- for accessing private fields of a class
print(s._Student__id)
print(s._Stu... |
f0849bd5ba43167e9526e239d26258e5ab4bda0e | Baobao211195/python-tutorial | /Clazz/classes.py | 562 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
start vs class in python
"""
class Shark():
"""
+ create class shark
+ self : reference to objects are created base on class
+ self : always first
"""
# define method
def swim(self):
print("the shark is swimming")
def be_awesome(self):
prin... |
b67551c33bfc07c35f1d931c48331a735fdac37b | kaladhar-mummadi/project-euler | /#12: Highly divisible triangular number.py | 1,087 | 3.5 | 4 | """
https://www.hackerrank.com/contests/projecteuler/challenges/euler012
"""
import math
def sieve(n):
#n = 50
arr = [True]*(n + 1)
res = 0
p = 2
while p < math.sqrt(n):
if arr[p]:
i = p*2
while i <= n:
arr[i] = False
i += p
p +... |
cf48687ece10bf563b6bebfcd9af3f84aa5d3a2a | FrogGreen/Python | /013. Comparable and Comparator/Class.py | 871 | 3.75 | 4 | class Dog(object):
def __init__(self, name, color, age):
self.__name = name
self.__color = color
self.__age = age
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name
@property
def age(self):
re... |
bfdb0ef399e0aa6cf40710235ebd4ecd45101bb1 | 0neir0s/ctci | /3-stacks-queues/basics.py | 986 | 3.921875 | 4 | class Node(object):
def __init__(self,data):
self.data = data
self.nxt = None
class Stack(object):
def __init__(self, top):
self.top = top
def pop(self):
if not self.top:
return None
output = self.top.data
self.top = self.top.next
return ... |
df39cd22e2f899aa6b439d4fff415fdabe688af3 | GoGiants1/swpp2021-design-pattern-practice | /problem2.py | 930 | 3.859375 | 4 | class A:
def build_floor(self):
raise NotImplementedError
def build_body(self):
raise NotImplementedError
def build_ceiling(self):
raise NotImplementedError
class House(A):
def build_floor(self):
print("Build House Floor")
def build_body(self):
print("Bui... |
e05ba94df3f7e3cf764ee7633df606e84cc05327 | yemao616/summer18 | /Top100/169. Majority Element.py | 866 | 3.703125 | 4 | # Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
# You may assume that the array is non-empty and the majority element always exist in the array.
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: L... |
533c98b0aab2aec8cf7c294000044b26d60983ba | peterkabai/python | /algorithm_problems/hackerrank_kattis/aliens.py | 2,749 | 3.640625 | 4 | #! /usr/bin/python3
import fileinput
import sys
def add_to_graph_values(from_node, to_node, graph=None):
if graph is None:
graph = {}
if from_node in graph:
if to_node not in graph[from_node]:
if to_node != from_node:
graph[from_node].append(to_node)
else:
... |
3ebb7360c1e5b60ab3bdeb3005d7cfd1781e4ad3 | piacontreras/MA3701 | /Método_Least_Square.py | 2,589 | 3.546875 | 4 | # -*- coding: utf-8 -*-
### importamos las librerías que usaremos ###
#Pía Contreras
#parte 1 a) ii)
import numpy as np
import matplotlib.pyplot as plt
import random
from scipy import *
from scipy.optimize import leastsq
# iniciamos la semilla para generar valores aleatorios
# recuerde cambiar '1' por s... |
2e33d5e686a1b3b3a85c539057fc5c2ff273b8a5 | Aasthaengg/IBMdataset | /Python_codes/p03424/s065609654.py | 163 | 3.625 | 4 | from collections import Counter
n = int(input())
s = list(input().split())
c = Counter(s)
if len(list(c.keys())) == 3:
print('Three')
else:
print('Four') |
8977b272860bb2312e7872872d269ccc3b2d4c51 | 15csmonk/computing_method | /计算方法_作业二/Gauss-Legendre.py | 467 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import math
def fun(x):
return 1/(1+x**2)
def main():
GauFive={0.9061798459:0.2369268851,0.5384693101:0.4786286705,0:0.5688888889}
GauSum=0.0
a=0.0
b=1.0
for key,value in GauFive.items():
GauSum+=fun(((b-a)*key+a+b)/2)*value ... |
01b78460c0ed6e9e4351d39fad566ee56220330a | ShiJingChao/Python- | /PythonStart/0722Python/0805Python/day18/demo08_全局解释锁.py | 1,360 | 3.59375 | 4 | """
全局解释锁:
进程中都有一把自己的独立的全局解释锁, 在cpu调度执行线程的时候,
执行哪个线程, 就给这个线程上一把全局解释锁, 在调度结束之后, 在释放这把锁;
计算密集型;
需要进行大量的计算, 消耗cpu的资源, 比如计算圆周率, 给视频进行高清的解码;
*可以多进程的方式, 由系统创建一个主进程, 在进程中又去创建了一个主线程, 主线程中执行的
IO密集型;
涉及到网络, 磁盘的IO操作;
"""
from threading import Thread
from multi... |
2f8143f40d875a211a05318fd6305b50a1197440 | zhanglianxin/pystudy | /oop_@property.py | 1,438 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @property 装饰器就是负责把一个方法变成属性调用的
class Student(object):
"""docstring for Student"""
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score mu... |
f8681499124adf09f335b842d95a248b42c1ab73 | TroyJeffrey/String-Manipulation | /StringManipulation.py | 706 | 4.21875 | 4 | #Troy Jeffrey Ameegashie
#STring Manipulation
print("Enter a list of words")
user_list = input(">")
print("The length of the string is :", len(user_list))
first_letter = user_list[0]
print(f"The first letter of the string is :", first_letter)
last_letter = user_list[-1]
print(f"The last letter of the string is :", ... |
2d8e00116b9d0eece003d7010ac2995326bda70b | 6ftClaud/Python-VU | /Test 1/2 uzd.py | 783 | 3.84375 | 4 | data_list = [
[1, 10, 34, 110, 400, 30, 20],
[-5, -10, 55, 120, 30],
[2, 67, 23, 78, 200],
]
"""
data_list = [
[-1, 45, 23, 32, 999],
[67, 99, 23],
[23],
]
"""
def Calc(a):
# Defining variables
max_value = 0
min_value = 0
sum_value = 0
average = 0
# Filtering the list
... |
d47759924a7a2122e3cb216d8a79f038aa11f262 | hoon0422/Text_to_Excel | /basic/file/files.py | 8,331 | 3.53125 | 4 | """ Classes for files such as normal file, text file, excel file (.xlsx) """
from typing import List
from basic.errors import *
from shutil import copyfile
import os
import xlwings as xw
class File(object):
"""Classes for normal file.
Attributes:
_name: file's name without a serial
_serial: s... |
c1877a5f92b98ffc7d0a24fd90592469368065db | yoy52012/python-practice | /dir_size.py | 1,255 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# Script Name : dir_size.py
# Author : chao yuan
# Created : 16th January 2017
# Last Modified : 17th January 2017
# Description :This will get the total size of a given folder (获取所给文件夹的总大小)
import os
import sys
def main():
'''
Call the main method
... |
483c5adb0e869dbd32e3d12fde958eee2cd4cb0e | icq6679166/Python | /BDPy/Py27Lab/demo18_format1.py | 506 | 3.515625 | 4 | import numpy
r = 4
a = r * r * numpy.pi
print '[1]radius=%f, area=%f' % (r, a)
print '[2]radius=%.3f, area=%.3f' % (r, a)
print '[3]radius=%(radius).3f, area=%(area).3f' % {'radius': r, 'area': a}
print '[4]radius=%(radius).3f, area=%(area).3f' % {'area': a, 'radius': r}
print '[5]radius={}, area={}'.format(r,... |
1f3331545eda9409d2d6bae4e0f9d90bec23a65f | zofiagrodecka/ASD | /Sortowania/CountingSort.py | 1,835 | 3.59375 | 4 | # Z WARTOWNIKIEM!!!
class Node:
def __init__(self):
self.val = 0
self.next = None
def add_end(head, x):
a = Node()
a.val = x
a.next = None
p = head
while p.next != None:
p = p.next
p.next = a
def add_begin(head, x):
a = Node()
a.val = x
a.next = None
... |
32af846351f631278122a4585de9f252221083a8 | mattwalo32/H2HonestReviews | /backend/app/database.py | 13,274 | 3.71875 | 4 | """Defines all the functions related to the database"""
from app import db
def fetch_waters() -> dict:
conn = db.connect()
query_results = conn.execute("Select * from Water;").fetchall()
conn.close()
water_list = []
for result in query_results:
item = {
"manufacturer_id": result... |
219ae9cce6d767a5793619593580a0f485fdfac1 | DBasoco/Daily-Interview-Pro | /2020-10-16.py | 3,088 | 3.90625 | 4 | # Today we have: Compare Version Numbers
#
# Version numbers are strings that are used to identify unique states of software products. A version number is in
# the format a.b.c.d and so on where a, b, etc. are numeric strings separated by dots. These generally represent a
# hierarchy from major to minor changes. Given ... |
cb5b4399b3ea6463a3e066f334a82e757ee043c7 | panhavad/python-bootcamp-2019 | /week01/ex/10_str_length.py | 128 | 4.3125 | 4 | input_str = input("Enter a string:\n")
if input_str is not "":
print(len(input_str))
else:
print("The string is empty.") |
5da8c1839a01d8ca7174448b83ff2d0be7351696 | zeal706/python_test | /zeal.py | 678 | 3.921875 | 4 | n = "李海灵"
print(n)
print("python")
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
def update_odometer(self, mileage):
"""新的里程数"""
def increment_odometer(self, miles):
... |
2453f54ba58027154cf7d5f58ad98eee47e9836a | kongchayang/myfirstpython | /madLibs.py | 459 | 3.703125 | 4 |
name = input('Please provide a name: ')
verb = input('Please provide a verb: ')
adjective = input('Please provide a adjective: ')
noun_2 = input('Please provide another noun: ')
# print('%s %s pass the %s %s' % (name, verb, adjective, noun_2))
def madlibs_func():
sentence_one = print('%s %s pass the %s %s' ... |
cad8fcd54e99f92e1bb567b23fdabd3aeb09b9c6 | jorgeaninoc/PythonDataStructures | /Recursion/TowersOfHanoi.py | 313 | 3.71875 | 4 | def towers_of_hanoi(numberOfDisks,startPeg=1,endPeg=3):
if numberOfDisks:
towers_of_hanoi(numberOfDisks-1,startPeg,6-startPeg-endPeg)
print("Moving %d from peg %d to peg %d" %(numberOfDisks,startPeg,endPeg))
towers_of_hanoi(numberOfDisks-1,6-startPeg-endPeg,endPeg)
towers_of_hanoi(6) |
f47c17658d22bc1f90ac11eb6ce5e07b740e2d87 | yekingyan/leetcode | /700.二叉搜索树中的搜索.py | 1,014 | 3.625 | 4 | #
# @lc app=leetcode.cn id=700 lang=python3
#
# [700] 二叉搜索树中的搜索
#
# 给定二叉搜索树:
#
# 4
# / \
# 2 7
# / \
# 1 3
#
# 和值: 2
# 你应该返回如下子树:
#
# 2
# / \
# 1 3
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# ... |
2aa0bd725ec163d36d811a992e1fc42bd98ffdab | JarHMJ/leetcode | /剑指offer/py_solution/面试题12. 矩阵中的路径.py | 947 | 3.65625 | 4 | from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
self.x = len(board)
self.y = len(board[0])
for i in range(self.x):
for j in range(self.y):
if self.dfs(board, word, i, j):
return True
... |
ead9e983e8c3ef7da74ccadee0393160eb2623a9 | brett-dun/UMN-Grade-Data-Project | /src/find_min_max.py | 1,482 | 3.75 | 4 |
import sys
import math
import pandas as pd
import numpy as np
def main():
df = pd.read_csv(sys.argv[1])
df2 = df.nsmallest(10, 'GPA')
#print('Courses with the lowest GPA:')
#print(df2)
print('<table>')
print('\t<tr>\n\t\t<th>Subject</th>\n\t\t<th>Course Number</th>\n\t\t<th>Average GPA</th>\n\t</tr>')
for i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.