blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
476b041ca6f300773a1342f16ba45511a00290b5 | piecesofreg09/DSA | /Course_1/W4/6_closest_points/closest.py | 4,374 | 3.5 | 4 | #Uses python3
import sys
import math
#import random
#import time
def minimum_distance_naive(x, y):
d_min = float('Inf')
for i in range(len(x)):
for j in range(i + 1, len(x)):
t = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j])
d_min = min(t, d_min)
return d_min... |
ec8462176e244bddfbf830a9d3af69940eb7f5ec | kaskrex/pythonexercises | /Python Files/dog.py | 99 | 3.65625 | 4 | def dogcal (age):
hum = age * 7
return hum
age = int(input("Dog age?"))
print(dogcal(age)) |
a9b00824405fbac7d0059a4a9bcc2fea6871340f | dimivas/tictactoe | /players/tictactoe_computer_naive.py | 7,105 | 3.703125 | 4 | """
The implementation of the Tic-Tac-Toe player component
using a naive version of Q-Learning
"""
from __future__ import print_function
import random
from .abstract_tictactoe_player import AbstractTicTacToePlayer
class TicTacToeComputerNaive(AbstractTicTacToePlayer):
"""
The implementation of the Tic-Tac-... |
897d10034ad4e41e4c183ca730d33144caeadb08 | AggarwalAnshul/Dynamic-Programming | /InterviewBit/Strings/add-binary-strings.py | 1,455 | 3.90625 | 4 | """
Given two binary strings, return their sum (also a binary string).
Example:
a = "100"
b = "11"
Return a + b = “111”.
[+]Temporal marker : Mon, 13:12 | Feb 17, 20
[+]Temporal marker untethered: Mon, 13:25 | Feb 17, 20
[+]Comments : EASY
[+]Space Complexity : O(N)
[+]Time Compl... |
3a11f2858cb592ee6905101eb150b4bb03a53564 | nmortha/HacktoberFest2019 | /src/sum/sum.py | 300 | 4.1875 | 4 | #!/usr/bin/env python
num1=(input('Enter number1 to calculated sum of two munmbers: '))
num2=(input('Enter number2 to calculated sum of two munmbers: '))
print ('Enterted Numbers are : '+ num1 + " ,"+ num2)
total=int(num1)+int(num2)
print('Sum of 2 numbers '+ num1+ ','+ num2 + ' is :', total)
|
6d972eb7fa93e7e5a34edf81ffdf6c1c19de9492 | f-fathurrahman/ffr-MetodeNumerik | /chapra_7th/ch04/chapra_example_4_4.py | 708 | 3.859375 | 4 | def f(x):
return -0.1*x**4 - 0.15*x**3 - 0.5*x**2 - 0.25*x + 1.25
def df(x):
return -0.4*x**3 - 0.45*x**2 - x - 0.25
x = 0.5
h = 0.5
#h = 0.25
true_val = df(x)
print("true_val = ", true_val)
print("h = ", h)
# Forward diff
approx_val = ( f(x+h) - f(x) )/h
print("Using forward diff: ", approx_val)
print("ε... |
86aa1aab9ba6df46ccdf85dc30c58c19e980ca25 | ThaiSonNguyenTl/NguyenThaiSon-Lab-c4e24 | /lab3/calculate.py | 272 | 3.78125 | 4 | a = int(input("Enter a:"))
b = int(input("Enter b:"))
from calc import evaluate
# print()
# if ptoan == "+":
# n = a + b
# elif ptoan == "-":
# n = a - b
# elif ptoan == "*":
# n =a*b
# else:
# n =a/b
pt = input("pt: ")
n = evaluate(a,b,pt )
print(n) |
6c6571d242844e89b80cabb238833b36a4161d8f | GingerLee11/ATBS_ed2_projects | /collatz_sequence.py | 793 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 19 12:21:15 2021
@author: Cleme
"""
#! python3
# collatz.py - Number is evaluated as odd or even and is then evaluated
# down to one
import sys
# Define the collatz sequence
def collatz(number):
if number % 2 == 0:
print(number // 2)
... |
643357c540c2ababe9acd4d6565269fbfcb19325 | yangke928/connect-four-gameboard | /project/point.py | 2,042 | 3.609375 | 4 | '''Ke Yang
cs5001
Project
April 1st
'''
class Point:
'''Class Point
Attributes: point_red, point_yellow
Methods: add_point_red, add_point_yellow, add_point_yellow
initialie_point_red, initialie_point_yellow
'''
def __init__(self):
'''
Constructor -- c... |
83539941e3d6b2ce784c660d28427fc278a7b91f | Zain1298/Python-Matplotlib | /Python-Matplotlib/Piechart.py | 306 | 3.578125 | 4 | from matplotlib import pyplot as plt
numbers = [15,35,25,12.5,12.5]
subjects = ['English','Maths','Physics','Chemistry','Urdu']
cols = ['r','g','b','m','c']
plt.pie (numbers, labels=subjects, colors=cols, startangle=90, shadow=True,explode=(0,0.1,0,0,0),autopct='%0.1f%%')
plt.title('Pie Plot')
plt.show() |
fadfd54e5684ffb9f2b545feea8fa8bc259f2c7b | greatjunekim/py | /조건 판정문 (만약에~라면)/WhatsMyGrade.py | 127 | 3.609375 | 4 | 점수 = eval(input("점수를 입력"))
if 점수 == 100:
print("A+")
if 점수 <= 90:
print("A")
elif:
print("")
|
1f4f63fbd57e2a865f75f48e28f60588bde674fa | spiroxide/COMP-17100 | /Flippers/Flippers.py | 407 | 3.640625 | 4 | from random import *
def coinFlip():
return randint(1, 2) == 1
def flipper1():
heads = 0
for i in range(100):
if coinFlip():
heads += 1
return heads
def flipper2():
flips = 0
heads = 0
while heads < 50:
flips += 1
if coinFlip():
heads +=... |
b25ef2140bd3725b44cca58d9769fa0a98909fcb | ravalrupalj/BrainTeasers | /Edabit/Day 1.4.py | 403 | 4.125 | 4 | #Find the Index (Part 1)
#Create a function that finds the index of a given item.
#search([1, 5, 3], 5) ➞ 1
#search([9, 8, 3], 3) ➞ 2
#search([1, 2, 3], 4) ➞ -1
#If the item is not present, return -1.
def search(lst, item):
if item in lst:
return lst.index(item)
else:
return -1
print(sear... |
804f12562d380abaea2d1af8611fa8b5fbfa9d76 | athitf56/CP3-Arthit-Sankok | /Lecture71_Arthit_S.py | 593 | 3.796875 | 4 | menulist = []
menuprice = []
def showBill():
Count = 0
print("---ThitShop---")
for number in range(len(menulist)):
print(menulist[number], menuprice[number])
Count += menuprice[number]
print("Total =", Count, "Bath")
while True :
menuName = input("กรุณาใส่ชื่อเมนู : ... |
1ba65e2ce177744d171d59335ad3bf84be476490 | gheorghecr/Course-Work-Programming-Algorithms-and-Data-Structures-Module | /CourseWork/Exercise1And2/binaryTree_test.py | 2,152 | 3.8125 | 4 | import unittest
import sys
from binaryTree import BinaryTree
#To complete the exercise I based my self on some tutorials and information such as:
"""Title: *args and **kwargs in python explained
Author: Yasoob
Date: 2013
Availability: https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/
... |
74c0406fc6b11c2ce4cfc144e71d688c9b73718f | infiniteoverflow/Student-Information-Analysis | /screens/tk.py | 291 | 3.78125 | 4 | from tkinter import *
root = Tk()
root.geometry("500x500+0+0")
startbutton = Button(root, text="Start",height=1,width=4)
startbutton.place(relx=0.5, rely=0.5, anchor=CENTER)
#Configure the row/col of our frame and root window to be resizable and fill all available space
root.mainloop()
|
a0a1035464453e65ab385229220183141c50a7c4 | Comvislab/Deep-Learning-Fundementals | /Simple Linear Regression/simplelinearregression.py | 2,451 | 3.921875 | 4 | #THIS CODE IS MODIFIED VERSION of
# My STUDENT ISMET EMIR DEMIR(180315070)
#
# Objective : Gold Price Prediction Using Simple Linear Regression
# CopyRight (C) : Ismet Emir Demir & Muhammed Cinsdikici
# Date : 30 March 2021, 13:20
# Code Repo : ComVIS Lab
# DataSet : https://evds2.tcmb.gov.tr/index.php?... |
8f6d1c31a07bdbf641125fa348da99a3777d473b | tamasdinh/data-structures | /Queue_stack.py | 1,638 | 4.3125 | 4 | # Implementing a Queue based on a stack structure
#%%
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def push(self, value):
self.items.append(value)
def pop(self):
i... |
b5ea944432c7721b0185261283eb633d56ab2e3c | davidsram/written-examination-questions | /balance.py | 224 | 3.84375 | 4 | balance=int(input('balance'))
payment=int(input('payment'))
i=0
while (balance-payment)>0:
i+=1
balance=balance-payment
print(i,balance,payment)
else:
i=i+1
payment=balance
print(i,balance,payment)
|
06c9137917c37dce85fd7cb6b4c8d8cfa287c260 | dhnesh12/codechef-solutions | /02-CodeChef-Easy/1119--Walk on the Axis.py | 95 | 3.640625 | 4 | for _ in range(int(input())):
N=int(input())
total=int(N+(N*(N+1))/2)
print(total) |
a24d6ac4c5b738538a9e9722220aff0723807179 | VittorioYan/Leetcode-Python | /306.py | 1,949 | 3.515625 | 4 | from typing import List
class Solution:
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
num1, num2 = num1[::-1], num2[::-1] # 将输入字符串逆序
len1, len2 = len(num1), len(num2) # 获得字符串长度
res = '' # 初始化结果变量
car... |
b705ce921720d4bfecf2453964620155832be5ad | rayramsay/skills-object-orientation | /assessment.py | 4,976 | 4.78125 | 5 | """
Part 1: Discussion
1. What are the three main design advantages that object orientation
can provide? Explain each concept.
* Encapsulation:
Data and its behaviors "live" close together, so it's easy to see what
data can do/how it can be acted upon.
* Abstraction:
Details can be ... |
49ee058afc3fd8c5c98cb7b641bbf2be032f3861 | AugustLONG/Code | /CC150Python/crackingTheCodingInterview-masterPython全/crackingTheCodingInterview/cha10/solution1001.py | 575 | 3.609375 | 4 | """
10.1 You have a basketball hoop and someone says that you can play
1 of 2 games.
Game #1: You get one shot to make the hoop.
Game #2: You get three shots and you have to make 2 of 3 shots.
If p is the probability of making a particular shot, for which
values of p should you pick one game or the ot... |
9db6647800be1649cda1f84a1d117bb3568e0f6b | Akhilvijayanponmudy/pythondjangoluminar | /oops/ingeritance.py | 198 | 3.75 | 4 | class Parent:
def phone(self):
print("i have nokia 5310")
class Child(Parent):
pass
c=Child()
c.phone()
#different types of inheritance
#parent->child
#suoer->sub
#base->derived |
6c2b2fa740be7d0f423e42017de413e609d5622d | austinschrader/Python-Game | /classexample.py | 653 | 3.90625 | 4 | class Room:
"""Making a room class for the game. Rooms has a width and height, doors, enemies, and chests.
These will all be other classes. """
def __init__(self, width, height, doors, enemies, chests, character):
self.width = width
self.height = height
self.doors = doors
self.enemies = e... |
8ad898ea5186ebaa41adba6f8916c7d31d72e048 | PedroGal1234/Unit4 | /functionDemo.py | 397 | 4 | 4 | #Pedro Gallino
#10/16/17
#functionDemo.py - learning fuctions
def hw():
print ('Hellow,world!')
def bigger(num1, num2): #prints which function is bigger
if num1>num2:
print(num1)
else:
print(num2)
def slope(x1, y1, x2, y2):
print((y2-y1)/(x2-x1))
#hw() #runs function
#bigger(13,... |
f4c6f6ac698877c51376925b1fe1d08b3ffefae4 | trampolo/project-euler-python | /eu-1.py | 499 | 4.28125 | 4 | # Multiples of 3 and 5
# Problem 1
# If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
multiples_3 = [x for x in range(3, 1000, 3)]
multiples_5 = [x for x in range(5, 1000, 5)]... |
c23de213208c1c3707c0136a80092bb439722ef7 | yeloblu/Python | /Basics/assign1.py | 434 | 4.25 | 4 | print("Assign 1 - Input Factorial");
#fact=1;
x=input ("Enter a number :");
if (x==0):
print("Factorial is : 1");
elif (x<0):
print("Invalid number!");
else while(i>0):
print(i*i-1);
i=i-1;
#elif(n>0):
# while(n>0):
# fact=fac... |
d95152e227ad0b8e0f28711a280606ceb2716daa | sureshn98/python-assignment-3 | /Q.6.py | 207 | 4.0625 | 4 | #new list with unique elements of current list
list=['1','1','2','a','s','a','3','d']
def newlist():
j=[]
for i in list:
if i not in j:
j.append(i)
return j
print(newlist())
|
6357aaab4df5c762d754a591a3688196f9ab1922 | charleyjohnston/python-scripts | /write_numbers_to_text_file.py | 8,029 | 3.96875 | 4 | #write_numbers_to_text_file.py
#Writes a range of numbers between and including two numbers inputted by the user to a text file, with one number per line.
#Author: Charley Johnston
#Date: December 3, 2018
#V2 - Added undo function
from Tkinter import *
import tempfile
import base64
import zlib
##########... |
452de579bbb9ce2c4beb3a744c34eed42cee9fda | JorgeMGuimaraes/uff-chronos | /src/chronos/Entidade.py | 1,470 | 4.03125 | 4 |
class Entidade():
"""
Guarda informacoes gerais sobre o aluno.
"""
def __init__(self, id: int):
'''
Guarda informacoes gerais sobre o aluno.
'''
self.id = id
self.nota_ponderada = 0
self.carga_horaria_total = 0
retur... |
2ef56889c27d4e1b8df3cc5e451ab42a8cc18434 | ototonari/Anna | /remove.py | 732 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# DIR内の、引数の文字列に一致したファイルを削除する
import sys, os, re, traceback
from time import sleep
from datetime import datetime, timedelta, time
def remove(filename, directory):
# target dir
DIR = directory or "./file/"
fileList = os.listdir(DIR)
pattern = re.comp... |
61e6dd6432050d2b5c7f2109481419497c169dde | JunnanZ/production-network | /stochastic_k.py | 5,287 | 3.5 | 4 | # Code for the paper "Equilibrium in a Model of Production Networks" by Meng
# Yu and Junnan Zhang
#
# File name: stochastic_k.py
#
# Compute the equilibrium prices as a fixed point of T specified in equation
# (3) and (6) in the paper. Two methods are used: one is successive
# evaluations of T and the other is Algorit... |
bb7cf0837caa179a8fcba045ca678cc662ff0fe9 | D1egoS4nchez/Ejercicios | /Ejercicios/ejercicio30.py | 384 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def suma_while():
x = 1
suma = 0
while x<=10:
valor = int(input("Ingrese el numero que va a sumar: \n"))
suma = suma + valor
x = x + 1
promedio = suma // 10
print("La suma de los 10 valores que ingreso es: \n", suma)
print("... |
124ac95e766e57766ac9123d36c5ef5433f6d44a | 1050669722/LeetCode-Answers | /Python/problem0461.py | 800 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 11 16:43:48 2019
@author: ASUS
"""
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
X, Y = [], []
while x:
tmp = x%2
X.append(tmp)
x //= 2
while y:
tmp = y%2
Y.append... |
9e1912941af02bfa1259bf1034f51c65b7622eef | gierulum/PYTHON_LESSONS | /FUN_IMP.py | 252 | 4.0625 | 4 | import sys
my_name = input("Whats u name?")
print ("My name is " + my_name)
my_list = [1,2,3,4,5,6]
for x in range(1,4):
print(x)
def print_list(list_name):
var_list_name = list_name
for a in var_list_name:
print (a)
print_list(my_list)
|
259b1dd8bbaccfdd292156e587bf6f532ec6acf8 | atheenaantonyt9689/Python-Problems | /DAY3/robot_simulator.py | 1,521 | 4.09375 | 4 | EAST = 1
NORTH = 2
WEST = 3
SOUTH = 4
class Robot:
def __init__ (self,direction=NORTH,x=0,y=0):
self.direction=direction
self.x=x
self.y=y
self.coordinates=(self.x,self.y)
def move(self,instructions):
for i in instructions:
if self.direction == "R":
... |
9a0d6a487f6483f3c3b637d29d3547fd743d2992 | mirszhao/python-base | /basefile/oop.py | 1,496 | 3.84375 | 4 | #coding:utf-8
__author__ = 'Administrator'
class Student(object):
def __init__(self,name,score):
self.name = name
self.score = score
def print_score(self):
print('%s %s'%(self.name,self.score))
def get_grade(self):
if self.score >= 90:
return 'A'
elif ... |
845a92a140b20540cd4bde8a52bd232a954cfa62 | Fitrah1812/Tugas3Kelompok | /Greedy/Tugas3-Maze-Greedy.py | 2,648 | 3.640625 | 4 | import math
from time import time
goal_x=5
goal_y=0
maze=[
['#','#','#','#','#','G','#','#'],
['#','#','#','#',' ',' ',' ','#'],
[' ',' ',' ',' ',' ','#',' ',' '],
[' ','#','#','#','#','#','#',' '],
[' ','S',' ',' ',' ',' ',' ',' ']
]
maze_width=8
maze_height=5
class Node:
... |
870e9fc73a49fff86281badf208e854e3fd966ab | z778107203/pengzihao1999.github.io | /python/pythonday1/python_07_if3.py | 171 | 3.53125 | 4 | holiday_name = "圣诞节"
if holiday_name == "情人节":
print("haha")
elif holiday_name == "圣诞节":
print("kaka")
else:
print("每天都是节日啊") |
19c16c440ceb8fdc79087ab3c925c5f5f3553bd3 | tomasmika/Computational-Science-course-UvA | /Assignment4/CA4.zip/plot.py | 2,995 | 3.71875 | 4 | # Name: Tomas Bosschieter en Sven de Ronde
# UvAnetID: 12195073 en 12409308
# Description: This program makes the plots from the data made by experiment.py
# How to run: python3 plot.py <code>
# - code : 0 plots the density experiment, 1 the p_den, 2
# the p_veg, both if omitted
#
... |
7aa67ca1b08c2e2a4a6df42c014c923f77c80aa1 | allenai/robustnav | /allenact_plugins/ithor_plugin/ithor_util.py | 975 | 3.53125 | 4 | import math
def vertical_to_horizontal_fov(
vertical_fov_in_degrees: float, height: float, width: float
):
assert 0 < vertical_fov_in_degrees < 180
aspect_ratio = width / height
vertical_fov_in_rads = (math.pi / 180) * vertical_fov_in_degrees
return (
(180 / math.pi)
* math.atan(ma... |
07397eadd2299bf5cbb38fde390fbe529db0343f | sooryaprakash31/ProgrammingBasics | /OOPS/Polymorphism/Python/method_overloading.py | 952 | 4.28125 | 4 | '''
Polymorphism:
- Polymorphism - Many forms
- It allows an entity such as a variable, a function, or an object to have more than one form.
Method Overloading:
- Performing different operations using the same method name.
- Python does not support method overloading as it does not uses arguments as ... |
3ade6966f7dcaab81d3b88d8acc35d693368a67c | campjake/algorithms | /Viterbi.py | 2,457 | 3.6875 | 4 | '''
The Viterbi algorithm is a dynamic programming algorithm for finding the most likely
sequence of hidden states (the Viterbi path) that results in a sequence of observed events.
INPUT
- The observation space O = {o_1, o_2, ..., o_N}
- the state space S = {s_1, s_2, ..., s_K}
- an array of initial probabilitie... |
9bbb39ffff1f92d4ac3530f0029a9bd995e6f859 | feiyanshiren/myAcm | /leetcode/t000766.py | 1,985 | 3.828125 | 4 | # 766. 托普利茨矩阵
# 如果一个矩阵的每一方向由左上到右下的对角线上具有相同元素,那么这个矩阵是托普利茨矩阵。
# 给定一个 M x N 的矩阵,当且仅当它是托普利茨矩阵时返回 True。
# 示例 1:
# 输入:
# matrix = [
# [1,2,3,4],
# [5,1,2,3],
# [9,5,1,2]
# ]
# 输出: True
# 解释:
# 在上述矩阵中, 其对角线为:
# "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]"。
# 各条对角线上的所有元素均相同, 因此答案是True... |
a4bd50b4ac26814d745411ca815aa8115c058d0c | bettymakes/python_the_hard_way | /exercise_03/ex3.py | 2,343 | 4.5 | 4 | # Prints the string below to terminal
print "I will now count my chickens:"
# Prints the string "Hens" followed by the number 30
# 30 = (30/6) + 25
print "Hens", 25 + 30 / 6
# Prints the string "Roosters" followed by the number 97
# 97 = ((25*3) % 4) - 100
# NOTE % is the modulus operator. This returns the remainder ... |
e3a7d0d86c46c6175e4a309b892c92a1845b7c5e | Kieran-W-97/Miscellaneous_Problems | /nonogram_solve_main.py | 400 | 3.515625 | 4 | """
AUTHOR: KIERAN WACHSMUTH, 30th Jun 2020
Main script for solving a Nonogram.
"""
import numpy as np
#import matplotlib.pyplot as plt
from useful_fns import load_obj
from permutator import permutate
#
x = load_obj('nonogram_x')
y = load_obj('nonogram_y')
dim_x = len(x)
dim_y = len(y)
# Generate all solutions for eac... |
c27415f61954fbb8f8a0ffa801ce8566f1394d1f | robinsharma1911/ATM | /ATM_code.py | 2,138 | 4.0625 | 4 |
#accounts dict contains:-
#keys as account no's of two persons and value[0] as pins and value[1] as balance
accounts = {822466:[1234,20000],822456:[2345,30000]}
#main function after authentication
def main_function(account_number, accounts):
while True:
amt = accounts[account_number][1] ... |
de8347a2d7fc26aa61f763d26a09ebb9edd6baa1 | KamalAres/Infytq | /Infytq/Day8/Exer-40.py | 230 | 3.84375 | 4 | #PF-Exer-40
#This verification is based on string match.
num1=20
num2=30
div = lambda num1,num2:num1+num2
if(div(num1,num2)%10)==0:
#write your logic here
print("Divisible by 10")
else:
print("Not Divisible by 10")
|
1cf3ef3ea86a74420d90dd94e6f1a1722052b8a0 | robgoyal/CodingChallenges | /HackerRank/Algorithms/Implementation/31-to-40/fairRations.py | 1,059 | 3.984375 | 4 | # Name: fairRations.py
# Author: Robin Goyal
# Last-Modified: December 5, 2017
# Purpose: Calculate the number of loaves to distribute so everyone has even loaves
def fairRations(N, B):
'''
N -> int: number of subjects in bread line
B -> list: number of loaves for each subject
return -> int: number o... |
e3ffdc9519620627b87f1742954e00653fa52578 | sudhir512kj/just-test | /find_fractions_bw_0_to_1.py | 1,018 | 3.84375 | 4 | # def printfractions(n):
# for i in range(1, n):
# for j in range(i + 1, n + 1):
# # If the numerator and
# # denominator are coprime
# if __gcd(i, j) == 1:
# a = str(i)
# b = str(j)
# print(a + '/' + b, end=", ")
# def ... |
bba8dfad6c31ed40c931bd39245eaeec7669302f | orazaro/udacity | /cs101/reachability.py | 1,087 | 4.15625 | 4 | #!/usr/bin/python
#Reachability
#Single Gold Star
#Define a procedure, reachable(graph, node), that takes as input a graph and a
#starting node, and returns a list of all the nodes in the graph that can be
#reached by following zero or more edges starting from node. The input graph is
#represented as a Dictionary wh... |
b116bfd419b2cac66b8e78ab0821b39f93ff9794 | paeoigner/Functional-Python-Programs | /SpeechRecognitionAsk.py | 500 | 3.5625 | 4 | def ask():
import speech_recognition as sr
r = sr.Recognizer()
count = 4
while count > 0:
print("Please speak now")
with sr.Microphone() as source:
audio = r.listen(source)
print("Processing audio")
try:
return r.recognize(audio) # recognize speech using Google Speech Recognition
except LookupError... |
81ae43652e02f95a4942224f4fe8c3d5c9f72084 | shao918516/spider | /docs/s12306/test/map_filter_reduce_test(1).py | 258 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Terry'
# filter
li = [1, 2, 3, 4, 5]
li_new = filter(lambda x: x%2 == 0, li)
print(list(li_new))
# li_new = []
# for i in li:
# if i % 2 ==0 :
# li_new.append(i)
#
# print(li_new) |
a1be4ab30ad76ea5a8d037a2096b73d4a77077cd | maddymb/PythonBasics | /basics/whileloop.py | 249 | 3.71875 | 4 | i = 0
# while(i< 45):
# print(i)
# i = i+1
# while(True):
# print(i)
# if (i==10):
# break
# i = i+1
while(True):
if i < 5:
i = i+1
continue
print(i)
if (i==10):
break
i = i+1
|
a3199ffdf27987fade5dbfd25e76951667063380 | zhanganxia/other_code | /笔记/selfstudy/04-函数/studentmangement3.py | 2,489 | 3.875 | 4 | #encoding=utf-8
#用来保存学生的所有信息
stuInfos = []
#获取一个学生的信息
#全局变量
newName = ""
newSex = ""
newPhone = ""
def getInfo():
global newName
global newSex
global newPhone
#3.1 提示并获取学生的姓名
newName = input("请输入新学生的名字:")
#3.2 提示并获取学生的性别
newSex = input("请输入新学生的性别:(男/女)")
#3.3 提示并获取学生的手机号码
ne... |
f06fe107a35f0c80c736ee7b889a04e59f267c24 | dayitachaudhuri/Basic_Python_Problems | /31_insertion sort.py | 258 | 3.65625 | 4 | fruits = ['red' ,'blue', 'pink', 'magenda', 'green','olive']
n=len(fruits)
for i in range(n):
j=i-1
key = fruits[i]
while j >=0 and fruits[j] > key:
fruits[j+1]=fruits[j]
j -= 1
else:
fruits[j+1]=key
print(fruits)
|
07a1bc601f91288255686d274e3a81c97d5d0557 | jegadeesh2001/Lab-Main | /Sem4/Python/Basics-1/2.py | 296 | 3.875 | 4 | website = ["www.zframez.com", "www.wikipedia.org", "www.asp.net", "www.abcd.in"]
# total = int(input('Enter the number of websites '))
#
# for i in range(0,total):
# str = input('Enter the website ')
#
# website.append(str)
for web in website:
str = web.split('.')
print(str[2]) |
22b17f36a01b5068a998ccd61ee8672400cf795d | andrestbr/html_engine | /create_html_element.py | 1,436 | 3.953125 | 4 | '''Creates an html element.
Args:
element (str): element name to be created, i.e. <div>
content_list (str): the content of the element <div>'content'</div>
attribute (str) (optional): for creating an element with an attribute <div style='text-align:right'>'content'</div>
attribute_value ... |
1fed2b362226b94a18b96e1fcd96ea3ad5ca7fe7 | rmitio/CursoEmVideo | /Desafio047.py | 234 | 3.890625 | 4 | #DESAFIO047 Crie um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50.
#for c in range(0, 51, 2):
# print(c)
for c in range(1, 51):
if c % 2 == 0:
print('{}'.format(c), end=' ') |
ad1f85c147cb84a4740a7de5179ad889cd30e4a8 | RownH/MyPy | /py_fluent/leetCode/257.py | 1,406 | 4.28125 | 4 | '''
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-paths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
# Definition for a binary tree node.
# class TreeNode(object)... |
922ca8ebaaa3d278e2a64732390208b1ff685361 | melvingiovanniperez/pythonprojects | /spiral.py | 196 | 3.703125 | 4 | from turtle import *
def spiral():
for x in range(10, 50):
forward(x)
left(90)
def spira(angle):
for x in range (10,50):
forward(x)
left(angle)
|
70e02d7de4981df52b7c895c6b1ed25d62d84c95 | EduMeurer999/Algoritmos-Seg- | /15.py | 131 | 3.703125 | 4 | tempF = float(input('Informe temperatura em °F: '))
tempC = ((tempF-32)*5)/9
print("Temperatura em °C: ", round(tempC, 4), "°C") |
c6e53cf87d7dec6b3b18378a64cf12ca175bf08e | jenerational/Python_NYU-CS-1114 | /Lab09/Lab09-1a-e.py | 1,133 | 3.671875 | 4 |
def main():
print("a. Count:")
lst = [0, 32, 'a', '0', '4', 15, 'q', '0']
item = '0'
print(count(lst, item))
print("b. Powers of 2:")
n = int(input("Please enter an integer."))
print(powersOfTwo(n))
print("c. Find Min Index:")
lst = [56, 24, 58, 10, 33, 95]
print(findMinIndex(l... |
350f49f6c2bfb455bb5a5e210c1e516ff66a2300 | rkdvnfma90/Algorithm | /Python/Shortest_path/02_min_heap.py | 942 | 3.6875 | 4 | """
개선된 다익스트라 알고리즘을 사용하기에 앞서 필요한 최소힙의 사용법을 알아본다.
파이썬같은 경우 heapq 라이브러리는 기본적으로 최소 힙으로 되어있다.
Java도 마찬가지로 최소 힙으로 되어있고, C++ 같은 경우는 최대 힙으로 되어 있다.
만약 파이썬에서 최대힙을 사용하고 싶다면 우선순위에 음수 부호를 붙여서 넣었다가 꺼낼때 다시 음수 부호를 붙여 원래의 수로 돌린다.
"""
import heapq
# 오름차순 힙정렬(Heap sort)
def heap_sort(iterable):
h = []
result = []
# 모든 원소를... |
118ba7903c6e50eb95a335c90e50b6f9d2999da3 | FlynnHillier/World-Population-Calculator | /Population Calculator V2.py | 2,174 | 3.984375 | 4 | print("Welcome to Kalanz's Population Calculator!\n")
#change base values here
baseyear = 2017
basepopulation = 7550262101
annualprcntchange = 1.2
print("Current Statistics set to the base year "+(str(baseyear))+", a base popualtion of "+(str(basepopulation))+", and an annual population percentage change of ... |
7528a9bc3626c7007745ab79add73a2f1cb139ea | martin-costa/incremental-cycle-detection | /Python Graphs/BFGT11.py | 3,912 | 3.640625 | 4 | from graphs import *
import math
# O(min{m^1/2, n^2/3} * m) algorithm from BFGT 2011, for sparse graphs
class BFGT11:
def __init__(self, n, m):
# stores the number of nodes and edges to be added
self.n, self.m = n, m
slef.delta = min(m**(1/2), n**(2/3))
# stores the level and in... |
2349a6c727fb538b776d67238099dfc1815b16d2 | Gary2018X/data_processing_primer | /E4-1.py | 371 | 3.609375 | 4 | # -*- coding: utf-8 -*-
# author:Gary
import numpy as np
storages = [24, 3, 4, 23, 10, 123]
print(storages)
# 1. 调用array方法生成ndarray
# np.array(list数据类型)
np_storages = np.array(storages)
print(np_storages, type(np_storages))
# 2. 调用arange方法生成ndarray
# np.arange(X)生成0至X-1个整数的一元数组
# np.arange(4) # 生成[0,1,2,3]
|
b3c21a31df07f42f3ebee513e6b9c4f77e2f4e70 | alejopijuan/Python-Projects | /Distance Conversion/smoots.py | 529 | 3.9375 | 4 | def conversion(data):
x = data
smoots = x / 5.583
return round(smoots,1)
def main():
while True:
y = float(input("please enter bridge lentgh in feet:"))
if y >= 0:
print(conversion(y))
elif y < 0:
print("error number must be ... |
7090d875ee568146727a3c60185c70325313569b | chymoltaji/Algorithms | /MoveZeros.py | 371 | 4.21875 | 4 | #Given an array nums, write a function to move all zeroes to the end of it
# while maintaining the relative order of the non-zero elements.
array1 = [0,1,0,3,12]
array2 = [1,7,0,0,8,0,10,12,0,4]
def move_zeros(array):
for i in array:
if i == 0:
array.remove(0)
array.append(0)
... |
3cb105cbe124891734a96d8c3e1683addecdd0b5 | Bruno-morozini/Aulas_DIO_Phyton | /Coursera_Phyton/LISTA_04/Exercicio_03 .py | 160 | 3.890625 | 4 | x = int(input("Digite um numero para descobrir se o numero é divisivel por 5 : "))
teste = x % 5
if teste == 0:
print("Buzz")
else:
print(x)
|
019eb14a799b2d3156ee235081dd7f13fb336466 | JonMer1198/developer | /secondorderdiff.py | 1,075 | 3.640625 | 4 | from math import *
def solver (a,b,c):
print("This is a solution to the second order homogenous differential equation ay'' + by' + cy = 0 where the answer has:")
#Case 1:
if b**2 - (4.0*a*c)==0:
print("repeated roots")
r1= (-b/(2.0*a))
r2= (-b/(2.0*a))
r1=str(r1)
r2=str(r2)
return([r1,r2])
... |
60c306aa373f8de0a8652a163a54a5c22d3bc79b | C4DLabOrg/ca-training | /elseif.py | 373 | 4.375 | 4 | '''
Introducing the if - else statements
'''
'''
a = 4
b = 5
if a == b:
#print 'the numbers match'
else:
#print 'the numbers do not match'
using elif statements in python
'''
marks = 45
marks2 = 45
if marks > marks2:
print 'marks is greater than marks2'
elif marks < marks2:
print 'marks is lesser than m... |
9d9b663881913e0e4754748748b304b59838937a | EthanDills/Sudoku-Verifier | /find_duplicate.py | 1,260 | 3.953125 | 4 | '''
for given array A of size n, determine whether there are any duplicate values in the array
'''
# Input array
A = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Compute ( determine existence of duplicate )
## could stop at any point
# let int k=0 s.t. A[k] is compared to every value in A[k+1...n-1],
# and when A[k] ... |
53dc36ab6468bd5ec9d593ce56a81e8c7a3e9188 | keer2345/DataAnalysisWithPython | /Foundations-of-Computational-Agents/code/ch01/utilities.py | 1,220 | 4.09375 | 4 | import random
def argmax(gen):
"""gen is a generator of (element,value) pairs, where value is a real.
argmax returns an element with maximal value.
If there are multiple elements with the max value, one is returned at random.
"""
maxv = float('-Infinity')
maxvals = []
for (e, v) in gen:
... |
a9d5fb016e798b766c6a160b35536b824df65632 | iAnafem/Python_programming | /1.12.5.py | 162 | 3.796875 | 4 | a, b, c = (int(input()) for i in range(3))
_list = [a, b, c]
print(_list.pop(_list.index(max(_list))))
print(_list.pop(_list.index(min(_list))))
print(_list[0])
|
8a231aa17e56a56261c1d55eb4c5486e830d766c | mcmerle30/GolfApplication | /hole.py | 1,223 | 3.875 | 4 | class Hole:
"""
Hole object derived from data in the golfCoursesInput.csv
Instance variables:
hole_id a unique id for this hole (to be used as a primary key when stored in the database)
course_id the id of the golf course where this hole is played
hole_num ... |
d042bbf5de9d9a9e8f881d435c005633f41467d3 | richzw/CodeHome | /Python/qsort.py | 160 | 3.609375 | 4 | def qsort(l):
if len(l) <= 1:
return l
else:
qsort([x for x in l[1:] if x<l[0]]) + [l[0]] + qsort([x for x in l[1:] if x>=l[0]])
|
af18398c668c799ba0cb62a20d0694f829cd48f7 | baloooo/coding_practice | /generate_all_parentheses.py | 4,604 | 4 | 4 | """
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses of length 2*n.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
Make sure the returned list of strings are sorted.
Idea:
As I understand, the idea is that we will a... |
df07222b035fee2b7d36d436deec9a4d1f7042f8 | arthurguerra/cursoemvideo-python | /exercises/CursoemVideo/aula23.py | 744 | 4.03125 | 4 | try: # onde geralmente ocorre o erro
a = int(input('Numerador: '))
b = int(input('Denominador: '))
r = a / b
except (ValueError, TypeError):
print(f'Tivemos um problema com os tipos de dados que você digitou.')
except ZeroDivisionError:
print('Não é possível dividir um número por zero!')
except Keyb... |
7321adcb9f408490ef7596fe006a29922287510c | AtindaKevin/BootCamp | /flow control/if.py | 1,018 | 4.0625 | 4 | name=input("Enter your name \n")
Class=input("Enter your class \n")
ClassTeacher=input("Enter class teacher \n")
maths=int(input("Enter maths Mark \n"))
eng=int(input("Enter Eng Mark \n"))
kisw=int(input("Enter kisw Mark \n"))
sci=int(input("Enter sci Mark \n"))
sst=int(input("Enter sst Mark \n"))
average=(maths+eng+ki... |
cea3fc8c87a5830dc310a9cf7c39f64c9af27dd3 | SR2k/leetcode | /4/543.二叉树的直径.py | 1,264 | 3.5 | 4 | #
# @lc app=leetcode.cn id=543 lang=python3
#
# [543] 二叉树的直径
#
# https://leetcode-cn.com/problems/diameter-of-binary-tree/description/
#
# algorithms
# Easy (56.63%)
# Likes: 988
# Dislikes: 0
# Total Accepted: 203.6K
# Total Submissions: 359.4K
# Testcase Example: '[1,2,3,4,5]'
#
# 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长... |
cd48c39e1acc00d146710ef097c2702df3e603df | stabradi/euler | /sam/euler_7.py | 377 | 3.75 | 4 | primes = [2, 3, 5, 7]
def is_prime(num, primes):
for p in primes:
if not (n % p):
return False
return True
prime_count = 4
n = 7
while True:
n += 1
if is_prime(n , primes):
#print "prime: {}".format(n)
primes.append(n)
prime_count += 1
if prime_count... |
b08662340a6f8fbf4f7ac1b5276e748d57336668 | daniel-reich/ubiquitous-fiesta | /jwiJNMiCW6P5d2XXA_7.py | 124 | 3.609375 | 4 |
def does_rhyme(txt1, txt2):
if txt1[len(txt1)-2].lower()==txt2[len(txt2)-2].lower():
return True
else:
return False
|
00a5795c39029a6e97fc77302fa61e5a4d6be3c1 | rabiaasif/Python | /BSTree.py | 4,699 | 3.734375 | 4 | #!/bin/python
class BSTree:
''' Note: keys appear at most one time in this tree '''
def __init__(self):
self._tree=BSTreeNull()
def delete(self, key):
self._tree=self._tree.delete(key)
def insert(self, key):
self._tree=self._tree.insert(key)
def is_empty(self):
return(self._tree.is_empty())
def print... |
4e6def2c9bbc328a98440cf20710cb05cb82f121 | goelhardik/programming | /leetcode/implement_queue_using_stacks/sol.py | 1,049 | 4.03125 | 4 | """
Implemented stack using the python list. Used standard stack operations only.
For the size of the stack, len operation is used. It means the same thing
effectively.
"""
class Queue(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.s1 = []
sel... |
7f080b48e2512963087e2437daaabf7a54cff021 | pecholi/jobeasy-python-course | /lesson_5/homework_5_1.py | 1,326 | 4.1875 | 4 | # FOR LOOPS EXERCISES
# Enter your name, save it in name variable and create function print_name_three_times which return value is equal to
# your name three times
name_1 = 'Jimmy'
def print_name_three_times(name):
if name == name_1:
return name*3
# pass
# Modify your previous program so that it w... |
1d6b8ddc5c4e6e6ca196ac420edbdbf62c726707 | aford4074/HackerRank | /python/regex/intro.py | 618 | 4.03125 | 4 | '''
Introduction to Regex Module
Sample Input
4
4.0O0
-1.00
+4.54
SomeRandomStuff
Sample Output
False
True
True
False
'''
def verify():
inputs = ['4.0O0', '-1.00', '+4.54', 'SomeRandomStuff', '+-4.0', '', '4.-0', '+.2']
answers = [False, True, True, False, False, False, False, True]
for i, a in zip(in... |
3f82d06bce690a1cd6a2b9e174b247c817ec1c64 | EdwaRen/Competitve-Programming | /Leetcode/395.longest-substring-with-at-least-k-repeating-characters.py | 1,918 | 3.71875 | 4 | import collections
class Solution(object):
def longestSubstring(self, s, k):
# Two pointer solution
"""
We iterate 1-26 to still be O(n) but also enforcing times to change the left pointer
Otherwise, we would not know when to increase/decrease each two pointer bound
"""
... |
995ff158ba3f0eed8cc016ea198eae3f9e0c2c36 | Ljubica17/xo4 | /xo4_fcn.py | 3,681 | 3.75 | 4 | def create_board():
return ['-', '-', '-',
'-', '-', '-',
'-', '-', '-']
def prepare_board_for_display(board):
return 'Koordinate su \n 1|2|3 \n 4|5|6 \n 7|8|9\n' + "--------------\n" +\
board[0] + '|' + board[1] + '|' + board[2] + "\n" + \
... |
82c1507ea124f1b7bd2b53c86eafb092f829f09e | chvyqnne/nims-and-stone | /nims-stone.py | 2,938 | 4.09375 | 4 | # constant variables
max_stones_global = 5
total_stones_global = 100
def game(total_stones, max_stones):
"""
This is an interactive two-player game called Nims and Stone. Each player can draw between 1 and a
maximum number of stones from global max_stones, calling on the validity_check function to check i... |
e00148f901d20f83aa0460834b51ab4bbcbc20d9 | janash/oop_design_pattern | /iterator.py | 950 | 4.09375 | 4 | """
Iterator class in Python.
"""
class Iterator(object):
def __init__(self, start, end, step):
self.start = start
self.end = end
self.step = step
def __iter__(self):
# any pre init
self.current = self.start
# you have to return iter object
return... |
1403102c9f8ba9e79c840efbe10c505341998680 | AbiramiRavichandran/DataStructures | /Tree/SortedArrayToBalancedBST.py | 1,294 | 3.765625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def sortedArrayToBst(elements, start, end):
if start > end:
return None
mid = (start + end) // 2
root = Node(elements[mid])
root.left = sortedArrayToBst(elements, start, mid-1)... |
f732303a24769232425c90c7881f70bb156a3f9c | PangXing/leetcode | /common/BlackRandom.py | 524 | 3.5 | 4 | # coding:utf-8
import random
class Solution(object):
def __init__(self, N, blacklist):
self._N = N
self._blacklist = blacklist
def pick(self):
random_num = random.randint(0, self._N-1)
while random_num in self._blacklist:
if random_num == 0:
random_... |
900ae29821766f3e169c0fed5e16b839aba5fad8 | Maguilarbagaria/DailyCodingProblem | /Problems/PROBLEM 4 #STRIPE#HARD.py | 739 | 3.921875 | 4 | #This problem was asked by Stripe.
#Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
#For example, the input [3, 4, -1... |
2cddb0c06c8077d1c70dd5dcf76f7b085a9e0309 | jaleonro/Classic-algorithms | /bucketSort.py | 736 | 3.765625 | 4 | import math
def quickSort(array, p, r):
if p<r:
q=partition(array,p,r)
quickSort(array,p,q-1)
quickSort(array,q+1,r)
def partition(array,p,r):
x=array[r]
i=p-1
for j in range(p,r):
if array[j]>=x:
i=i+1
temp=array[i]
... |
4a07f2914de177c42a3ae77cffb88098c69aa01b | gaurav-kc/En_dec | /file_encode_types.py | 2,268 | 3.71875 | 4 | # this file is to handle various file encoding and decoding schemes as per the value of mode
# in the pipeline, create an object of class file_encode_mode and call encodeFile or decodeFile with mode value
# Also, while creating the object for class file_encode_mode, there params need to be given
# 1. flags -> for code... |
2de9a8e68a3caefb2f75be342bcaaebb85a90479 | YashSaxena75/GME | /calcu.py | 1,793 | 3.53125 | 4 | import sys
import re
#import os
import time
w="So u wish to continue...."
class color:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[93m'
WARNING = '\033[92m'
FAIL = '\033[91m'
# Formatting
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
# End colored text
END = '\033[0m'
c=''... |
69ac7c89e71758ce6ae30dcc1c6033e2a54ad3e0 | aritraaaa/Competitive_Programming | /Number_Theory/EulerTotientFunc.py | 694 | 3.703125 | 4 | '''
Author: @amitrajitbose
Problem : https://www.hackerearth.com/practice/math/number-theory/totient-function/practice-problems/algorithm/euler-totient-function/
'''
def SieveOfEratosthenes(n):
prime = [True for i in range(n+1)]
p=2
while(p * p <= n):
# If prime[p] is not changed, then it ... |
933ef0a7be213c9a7bb36f447d2a0c916a1ccd9c | f-fathurrahman/ffr-MetodeNumerik | /chapra_7th/ch06/chapra_example_6_1_with_func.py | 655 | 3.609375 | 4 | # Simple fixed-point iteration
# f(x) = exp(-x) - x
# The equation is transformed to
# x = exp(-x) = g(x)
#
# x_{i+1} = exp(-x_{i})
import numpy as np
def f(x):
return np.exp(-x) - x
def g(x):
return np.exp(-x)
def root_fixed_point(g, x0, NiterMax=100, TOL=1e-10):
# Initial guess
x = x0
for i ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.