blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c64ca0f36740727948fa9af6d82e8894fa8955c0 | MichalisPanayides/AmbulanceDecisionGame | /src/ambulance_game/markov/waiting.py | 18,662 | 3.90625 | 4 | """
Code to calculate the mean waiting time.
"""
import functools
import itertools
import numpy as np
from .markov import (
build_states,
get_markov_state_probabilities,
get_steady_state_algebraically,
get_transition_matrix,
)
from .utils import (
expected_time_in_markov_state_ignoring_arrivals,
... |
d05e8125d47e32945a7a29c5cf6a13a3c6f44247 | shmink/Waypointer | /phantom3.py | 3,626 | 3.515625 | 4 | #!/usr/bin/python
"""
Take the csv file created and then take legitimate waypoints and plot
them on google maps using their api.
@auther: Tom Nicklin
"""
import csv
import simplemap
import webbrowser
csvfile = 'FLY015.csv'
def get_coordinates(file):
with open(file, 'rb') as csvfile:
# printing specifics
readm... |
84dcfe0242f5bb366301cd513d26e695985d38e7 | ForritunarkeppniFramhaldsskolanna/Keppnir | /2023/problems/asciikassi/submissions/partially_accepted/chatgpt_0.py | 243 | 3.671875 | 4 | #!/usr/bin/python3
n = int(input().strip())
if n == 0:
print("++")
print("++")
else:
print("+" + "-" * (n * 2 - 2) + "+")
for i in range(n):
print("|" + " " * (n * 2 - 2) + "|")
print("+" + "-" * (n * 2 - 2) + "+")
|
db556074ad87c87989ca06a041d444196dc3e7b6 | Vishesh0412/MyCaptain_Assignments | /Print_positive_numbers.py | 104 | 3.703125 | 4 | myList = [71, 23, -64, 3, -11, -19]
num = 0
for num in myList:
if num >= 0:
print(num)
|
99d7c7e50f281b863818ad6289e08c160f9e6890 | MikePolinske/Samples | /Homework2B.python | 203 | 3.78125 | 4 | #!/usr/bin/python
price = input("What is the cost of the item? ");
salesTax = input("What is the sales tax rate (Expressed as 0.XX)? ");
print "The full price of the item is $", price * (1 + salesTax); |
959944451bc1b4fb36518f650069273fcfe11752 | rajatkashyap/Python | /ThreeSum.py | 653 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 21 10:11:46 2019
'[-1, 0, 1, 2, -1, -4]
'[-4, -1, -1, 0, 1, 2]
@author: u40mv02
"""
def threeSum(nums):
z=len(nums)-1
res=[]
nums.sort()
for x in range(len(nums)-2):
y=x+1
while(y<z):
s=nums[x]+nums[y]+nums[z]
... |
a02ff297937fcaa26391809692a2b14e7b71707e | Machendra/python_notes | /fetching_files.py | 681 | 3.96875 | 4 | import os
req_path=input("please enter your dir path: ")
if os.path.isfile(req_path):
print(f'the given path is file please enter a valid path of dir: ')
else:
all_f_dir=os.listdir(req_path)
if all_f_dir==0:
print(f'there are no files in the {req_path} please choose another dir')
else:
req_ex=input('please ente... |
c2e9ff5311a6441f45c19c0207062b6129e9f581 | Pulkit12dhingra/Python_and_the_Web | /Scripts/API/Random_Album_API/Random_Album_API/logics/app_logic.py | 968 | 3.53125 | 4 | import pandas as pd
import random
class GetRandomAlbum:
"""Class to get random album from dataset"""
def __init__(self, context):
""" """
self.context = context
self.__out = []
self.dataset = None
def load_dataset(self):
"""loading the dataset into pandas"""
... |
974fbf862f52cb201d31bfd4af684c7db641c57e | jayzane/leetcodePy | /linked_list/19_remove_nth_node_from_end.py | 3,968 | 3.578125 | 4 | """
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
"""
from common.init_data import ListNode, init_list_node, print_list_node, algorithm_func_multi_exec, linked_examples
class Solution:
"""
一次遍历
使用哈希表记录每个位置对应的结点,再将对应结点的前驱点接上其后继点
时间复杂度:O(n),n是链表长度... |
44970442e2e0bbcea4dd389310efa973b4d6117d | ValentinPortais/LPython | /function/month.py | 227 | 4.0625 | 4 | def MonthName(n):
"Function to find a month name"
mname=['January','February','March','April','May','June','July','August','September','October','November','December']
z=mname[n-1]
return z
#Usage
print(MonthName(1))
|
d011499a607a3376b384f05e4d2ad73762ef39dd | gerashdo/files-testing | /pruebas_aceptacion/edades/features/steps/edades.py | 451 | 3.59375 | 4 |
class Edad:
def calcularEdad(self, num = -1):
if isinstance(num, str):
return 'Solo numeros'
if num < 0:
return 'No existes'
if num < 14:
return 'Eres niño'
elif num < 18:
return 'Eres adolescente'
elif num < 66:
r... |
bcfcc7bae25fd9d76b109dd19ccf3187322dc158 | wmstack/gci_matrix_multiplication | /matmul_custom.py | 2,807 | 3.59375 | 4 | import numba
@numba.jit
def dot_loop_jit(x,y):
sum = 0
for i in range(len(x)):
sum+= x[i]*y[i]
return sum
@numba.jit
def matmul_jit(x, y):
#generic matmul
#not just matmul of n x n matrices
#matmul, the length of a row of the first matrix 'x'
#is equal to the length of a column o... |
729b45a3420e0dce798b8650cea28221c205814d | marythought/sea-c34-python | /examples/session06/tmnt.py | 1,031 | 4.21875 | 4 | class Turtle(object):
def __init__(self, name):
"""Initialize a turtle."""
self.name = name
def announce(self):
"""Print out an introduction."""
print("{name} says hello.".format(self.name))
class TMNT(Turtle):
def __init__(self, name, color, weapon):
"""Initiali... |
c87ccef39675a0d1a7f8039af416a26336ec5bb8 | Geoffrey-lusitano/Exercices | /Exercice 6.13.py | 816 | 4.03125 | 4 | # CONSIGNES
# Ecrivez un algorithme permettant, toujours sur le même principe, à l’utilisateur de saisir un nombre déterminé de valeurs. Le programme, une fois la saisie terminée, renvoie la plus grande valeur en précisant quelle position elle occupe dans le tableau. On prendra soin d’effectuer la saisie dans un prem... |
089d6424a5391b2f0af09c6450d301dc1f87324f | Voxny404/FahrenheitTOcelsius | /Fahrenheit to Celsius.py | 1,137 | 3.9375 | 4 | from tkinter import *
# main function
#-----------
root = Tk()
#-----------
#head Text
#------------------------------------------
Label(root, text="Fahrenheit converter").pack(ipadx = 5, ipady = 5, side = TOP)
Label(root, text="by Jessica Nicole Voxny404").pack(ipadx = 5, ipady = 5, side =BOTTOM)
Label(root, text... |
5a5b1e71fa04a3c0209f1414c80a0d88ab05a28e | kokot300/python-core-and-advanced | /classprogramer.py | 486 | 3.625 | 4 | class Programer:
def setName(self,n): #setter methid
self.name=n
def getName(self): #getter method
return self.name
def setSalary(self,s):
self.salary=s
def getSalary(self):
return self.salary
def setTech(self,t):
self.technologies=t
def getTech(self):
... |
df1fdca4ff230853b4ca0c2ade6e9e6917f43a79 | baHarmon1/SodaMachineTesting_repo | /test_soda_machine.py | 7,765 | 3.546875 | 4 | from cans import Cola
from coins import Quarter, Dime, Nickel, Penny
import unittest
from soda_machine import SodaMachine
import coins
class TestFillRegister(unittest.TestCase):
"""Test the register method for its size"""
def setUp(self):
self.soda_machine = SodaMachine()
def test_register_fille... |
3ef8d3c66be1757b05957af72209103710885f87 | master-walker/TestPython | /src/Test/TestDict.py | 435 | 4.0625 | 4 | #!/usr/bin/env python
#coding=utf-8
'''
Created on 2017年5月8日
@author: Administrator
'''
dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
#删除字典
print dict1
del dict1['Name']
print dict1
#清空dict
dict1.clear()
print dict1
#删除字典
# del dict1
# print dict1
#str(dict)
#输出字典可打印的字符串表示。
dict1 = {'Name'... |
786917cccddf87c7ea92a5dd1e4ad6574c21ee2e | amanda/practice | /euler/problem3.py | 238 | 3.65625 | 4 | num = 600851475143
def largest_prime_factor(n):
divided = n
for i in range(2, n+1):
while divided % i == 0:
divided = divided/i
if divided == 1:
return i
return n
if __name__ == '__main__':
print largest_prime_factor(num)
|
fef9baf7cb0839fbf351498e1dedd390d6df73ed | piantado/LOTlib3 | /Examples/EvenOdd/Model.py | 3,191 | 3.734375 | 4 | """ A simple exmaple to show use of a Lexicon """
WORDS = ['even', 'odd']
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Grammar
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
8ff36e200c5df95d22af1c74b1ed80312d119948 | hemanthkumar25/MyProjects | /Python/BinarySearch.py | 483 | 4 | 4 | def binarySearch(arr,item):
start = 0;
end = len(arr)-1;
found = False
while(start<=end) and not found:
mid = (start+end)/2
if(arr[mid])==item:
found = True
else:
if(item > arr[mid]):
start = mid+1
else:... |
e2ae9875008937afb9a05d5abbbfa94ea6276f7d | panditaot/tarea1 | /divisible3.py | 187 | 3.984375 | 4 | def n(m):
x = m%3
if x == 0:
return True
else:
return False
m = int(input("Ingrese un número entero para comprobar si es divisible entre tres "))
print(n(m))
|
75975bb15cd668ab7feb4e38df3a8ac77a211d6a | arnabs542/interview-notes | /notes/algo-ds-practice/problems/stack_queue/print_backet_number.py | 752 | 4.0625 | 4 | '''
Given an expression exp of length n consisting of some brackets.
The task is to print the bracket numbers when the expression is being parsed.
Example:
Input:
3
(a+(b*c))+(d/e)
((())(()))
((((()
Output:
1 2 2 1 3 3
1 2 3 3 2 4 5 5 4 1
1 2 3 4 5 5
Explanation:
Test case 1:The highlighted brackets in the given ex... |
7c7aecc94288280ea36d48a25d4c05fd3ed8e2aa | ChangxingJiang/LeetCode | /1301-1400/1324/1324_Python_1.py | 517 | 4.03125 | 4 | import itertools
from typing import List
class Solution:
def printVertically(self, s: str) -> List[str]:
return ["".join(elem).rstrip() for elem in itertools.zip_longest(*s.split(), fillvalue=" ")]
if __name__ == "__main__":
print(Solution().printVertically(s="HOW ARE YOU")) # ["HAY","ORO","WEU"]
... |
91bcab1432c55e4b8e304967285c23512ccefc61 | Uluturk0/python-Week1 | /lessons_score_calculation.py | 1,286 | 4 | 4 | '''
Developer: Ömer ULUTÜRK
Date: 01.02.2020
Purpose of Software: Reinforcement of learned Python Code and Self-improvement
What does program do? : The program takes the student name and surname,
names of lesson, midterm scores and final scores.
And it gives average score and result that specify as "pass" or "fa... |
7781f152ca85f3683aa8af0bc2a9f1ee7ebabbdb | mdsahil369/Python-Problem-Solve | /divide apple each other.py | 550 | 3.59375 | 4 | # 10 apple mn=2,mx=4--->2 is divisor of 10,3 isn't divisor of 10,4 is divisor of 10.
# 1.get input
# 2.processing
# 3.and give output
amound_of_apple = int(input('Which amound of apple avelable in harry : '))
min_number = int(input('min number : '))
max_number = int(input('max number : '))
if min_number != max_number... |
a49dd72d6cbff23a1d4849d9026356a5f7c27961 | ferhsilvestre/algoritmos | /Lista 5/ex7.py | 839 | 3.828125 | 4 | # 7. Faça um algoritmo que calcule e apresente a média de alturas superior a 1,80 de 10 alunos. Informe também quantos e quais (índice/posição) são os alunos. Não use nenhuma função pronta da linguagem Python.
import sys
altura = []
altura_m = 0
cont = 0
indice = []
for i in range(10):
altura.append(float(input("... |
633f974163bd72327fed9c796a7d56d93c72749f | chenbokaix250/ForSomeForMySelf | /python算法实践/排序/select_sort.py | 489 | 3.734375 | 4 | # __*__ coding=utf-8 __*__
def select_sort_simple(li):
li_new = []
for i in range(len(li)):
min_val = min(li)
li_new.append(min_val)
li.remove(min_val)
return li_new
def select_sort(li):
for i in range(len(li)-1):
min_loc = i
for j in range(i+1,len(li)):
... |
8b204926dbcaa5e110d761fb581965a30f923d54 | brunpersilva/python-treino2 | /ex13.py | 133 | 3.859375 | 4 | c = float(input('Qual a temperatura em Ceusius?'))
f = float(c * 1.8) + 32
print('{} celcius é igual a {} fahrenheit'.format(c, f))
|
add62ff5570798b15ca80e521da1cd2f76763afd | Ahha5775/Knights-Tour-Python | /bye.py | 3,229 | 3.765625 | 4 | #NOTE: assumes board already exists and is only compatible with board as list of coordinates!
def coor_sub(a,b):
"""Subtracts coordinate list b from coordinate list a."""
return [a[0]-b[0],a[1]-b[1]]
def test_legal(move,k_cor):
"""Checks proposed move to chess coordinates on chessboard for the knight at k_... |
7c363ec6da74d132b968c871db3087f1c5e1af41 | MirsadHTX/Temp | /TestChat1.py | 344 | 3.515625 | 4 | from chatterbot import ChatBot
chatbot = ChatBot(
'Ron Obvious',
trainer='chatterbot.trainers.ChatterBotCorpusTrainer'
)
# Train based on the english corpus
chatbot.train("chatterbot.corpus.english")
while (True):
textToChat = input('Ask something')
textFromChat = chatbot.get_response("textToChat")... |
58cc33c91679dd439470b41db7e1340fe83ad5dd | Mahiuha/skaehub-assignment | /day3/2-numpy_weekdays.py | 343 | 3.859375 | 4 | #import the numpy library
#prompt the user for the year
#prompt the user for the month
#print to the user the number of weekdays as output
import numpy as np
print('Enter From Day YYYY-MM e.g 2021-07')
start_count = input()
print('Enter To Day YYYY-MM e.g 2021-07')
stop_count = input()
s= np.busday_count(start_count,... |
640f78e0876c034f8a536b1ec1523d4481540f55 | Aasthaengg/IBMdataset | /Python_codes/p02948/s122102819.py | 2,240 | 3.609375 | 4 | """
案件を報酬を受け取るまでにかかる時間で降順ソートしておく。
"""
class segTree:
def __init__(self,n,identity):
if bin(n).count("1") == 1:
self.leaves = 2**(n.bit_length()-1)
else:
self.leaves = 2**n.bit_length()
self.identity = identity
self.tree = [[self.identity,-1] for i in range(sel... |
0de90e08a4ca3ec1ff6cc10b183283fbd78d47bd | anaxmnenik/Mk-PT1-41-21 | /Tasks/ostrovski_oleg/task_1/quadratic equation.py | 578 | 4.03125 | 4 | import math
print("Введите коэффициенты для уравнения")
print("ax^2 + bx + c = 0:")
a = int(input('введите число a = '))
b = int(input('введите число b = '))
c = int(input('введите число c = '))
print()
d = b ** 2 - 4 * a * c
print("Дискриминант D = " + str(d))
if d > 0:
x1 = (-b + math.sqrt(d)) / (2 * a)
x... |
03645ac61136f955936792a66211e2cb7a0cf65a | xyl5869/learnpy | /day2/dict.py | 522 | 3.625 | 4 | #!/usr/bin/python
# encoding:utf8
# Author:Along
ab = {
'Swaroop': 'swaroop@swaroopch.com',
'Larry':'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'
}
print("Swaroop's address is",ab['Swaroop'])
print("Larry's address is",ab['Larry'])
del ab['Spammer']
print('\nTher... |
4dc6e032212649d5e47ad94991f818fb5c9f8169 | terrameijar/PythonUnitConverter | /modules/metric/centimeters.py | 1,673 | 3.796875 | 4 | def centimeters_millimeters(n, api=False):
b = float(n) * 10
if api == True:
return b
if float(n) == 1:
print str(n) + ' centimeter = ' + str(b) + ' millimeter(s).'
else:
print str(n) + ' centimeters = ' + str(b) + ' millimeter(s).'
def centimeters_decimeter... |
fb4c58d9c7933bed25058badd5e4049861807ff7 | dondropo/holbertonschool-higher_level_programming | /0x0B-python-input_output/3-write_file.py | 331 | 4.1875 | 4 | #!/usr/bin/python3
"""
Module that writes a string to a text file (UTF8)
and returns the number of characters written
"""
def write_file(filename="", text=""):
"""Write a text inside a file"""
writer = 0
with open(filename, mode='w', encoding='UTF-8') as file:
writer = file.write(text)
ret... |
1bb51313810c310908942af99eb85268e533cb50 | satlawa/ucy_dsa_projects | /Project_2/problem_2.py | 4,094 | 4.375 | 4 | #------------------------------------------------------#
# problem 2 - Search in a Rotated Sorted Array
#------------------------------------------------------#
def find_pivot(array):
'''Find pivot index in Rotated Sorted Array
args:
array(list): a sorted array of items of the same type
returns:
... |
83a11a434ab57e11db71f1103c8a83017be086ca | Hndz93/1erParcialEjercisios | /ejercisio3.py | 263 | 3.921875 | 4 | InicioSesion = ("Nombre y clave")
print ("Ingrese Usuario : ")
usuario = input("Parcial")
print ("Ingrese Clave : ")
clave = int(input(1234))
if (usuario=="Parcial" and clave==1234):
print("nombre usuario incorrecto")
else:
print("Clave de acceso incorecto") |
3a32700eefa0e3c6a2389829fbdd2a3aef830ad7 | aliceslombardi/exercicios-algoritimos | /lista-exercicios-computacional-thinking/exercicio04.py | 73 | 3.609375 | 4 | x = int(input("x"))
y = int(input("y"))
potencia = x ** y
print(potencia) |
48fe2fbb091316a82c366f567aef9c089e73a574 | TejasviniK/Python-Practice-Codes | /getCaptitals.py | 255 | 4.125 | 4 | def get_capitals(the_string):
capStr = ""
for s in the_string :
if ord(s) >= 67 and ord(s) <= 90:
capStr += s
return capStr
print(get_capitals("CS1301"))
print(get_capitals("Georgia Institute of Technology"))
|
35c00de7dd44c25b0da2f21bb64202399e88a6f2 | Xiangtuo/leetcode | /python/JZ26_二叉搜索树与双向链表.py | 797 | 3.6875 | 4 | # 题目描述
# 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.head = None
self.pre = None
def Convert(self, pRootOfTree):
i... |
eaf08fbd48a086ca0558b91fc0bcb00f64c9084f | zaferwer/my-first-repo | /Hello.py | 248 | 3.9375 | 4 | <<<<<<< HEAD
print("Hello World")
yas = input('yasını gir')
chronic = input ('hastalık')
risk = bool (yas == 'yes' or chronic =='yes')
print(risk)
help(len)
=======
print("Hello World")
>>>>>>> a08daceccaba833f5aa10f5808b7c0c0adb23f7c
|
96419b3914b2c75aa7452b8e83becef2497aa204 | tsgreenwood-flatiron-data-science/dsc-1-final-project | /haversine.py | 660 | 3.6875 | 4 | from math import radians, cos, sin, asin, sqrt
def distance_from_flatiron(coords_tuple):
#'''47.610361, -122.336107'''
'''COPIED FROM STACKOVERFLOW MICHAEL DUNN
INSPIRED BY DAVID KASPAR THE RAINBOW UNICORN'''
lon1, lat1, lon2, lat2 = coords_tuple[1], coords_tuple[0], -122.336107, 47.610361
... |
65a29b4b2fa58957a3ae89711fd923fd94113f10 | moabdelmoez/road_to_pythonista | /Lec 6/7- removing vowels.py | 246 | 4.1875 | 4 | def remove_vowels():
word = input("please enter a word: ")
no_vowel = ''
for ch in word:
if ch in 'aoei':
continue
else:
no_vowel = no_vowel + ch
print(no_vowel)
remove_vowels()
|
8f136aa7054e7ba1cb02671fe4cf4cfbd3189a71 | debajyoti-ghosh/Pythonshala | /OOPs/Empty_class.py | 670 | 3.90625 | 4 | class student:
pass # as class without any attribute or method are not allowed so pass statement is added.
student1= student() # object,named student1 of class, named student is created
student2 = student() # another instant or object of the same class
student1.name = "Rajib" # attributs added to the objec... |
123ab02be57e6c137f96882ebc47c8aeace786ea | NadiaAlmutlak/Intro-Python | /Desktop/IntroPython/Homework2/1.py | 3,972 | 3.890625 | 4 |
#stock risk and return simulation - Homework 2 - Nadia AlMutlak Na2736
import pandas as pd
import matplotlib.pyplot as plt
import math
import argparse
import numpy as np
#Code from data_access.py. to compute the average value for a list of number
def compute_average(num_list):
count = len(num_list)
total =... |
d82d2c78d40b13f7a13f786181f1d27c34425302 | orasraf1241/World_Weather | /python/types_and_loops.py | 1,101 | 4.25 | 4 | def is_even(arg):
""" This funcs check is the number is even or odd"""
if arg % 2 == 1:
print("not even")
else:
print("even")
def print_str(string, number=1):
"""This func print the string number of time but if the user dont insert number the func s print the str once"""
for x in r... |
03c0f6fd551be9e8d81dcf244643c68cb152132a | suhairmu/pythonprograms | /object oriented programmimg/bank.py | 1,030 | 3.75 | 4 | '''
bank
bname
acc no
balance
createaccount()
deposit()
withdrawl()
balEnq()
'''
import datetime
class Bank:
bname="sbi"
def createAccount(self,bname,accno,balance):
#self.bname=bname
self.accno=accno
self.balance=3000
def deposit(self,amt):
self.balance+=amt
pri... |
2cf6f866760610a9bcc8b9ba2e94f189cc116d5a | ymmy1/CS50_HW | /pset7/houses/roster.py | 612 | 3.6875 | 4 | import sys
from cs50 import SQL
# validating the arguments
if len(sys.argv) != 2:
print("Usage python roster.py house")
exit(1)
# setting db
db = SQL("sqlite:///students.db")
stName = db.execute("SELECT first, middle, last, birth FROM students WHERE house = ? ORDER BY last, first",
sys.arg... |
8ca96f86ecd666624afce9dfa90fb4c3861e4aa3 | nishant-sethi/HackerRank | /EdgeverveCodingChallenge/Hockey_stick.py | 439 | 3.5625 | 4 | '''
Created on Jun 1, 2018
@author: nishant.sethi
'''
import math
def rowColEntry(n,r):
return math.factorial(n)/(math.factorial(r)*(math.factorial(n-r)))
n,l=(11,3)
lst=[]
x=1
a=n
while x!=l-1:
lst.append(rowColEntry(a,x))
a+=1
x+=1
print(lst)
ans=[1]
a=1
for i in lst:
print(a+... |
a45ffeadf7c60bf9d957c6bf54e532ecc03b36cd | hoctor/median | /main.py | 461 | 4.03125 | 4 | fname = raw_input("(Entre com o nome do arquivo) Enter file name: ")
num_words = 0
num_char = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
num_char += sum(len(word) for word in words)
median = float(num_char/float(num_words))
print("(Numero ... |
d0476a44ecf86885e12f4f86c70c7cf37429e5b9 | ojudz08/Python-Beginner | /Exercises/Chapter 5/Exercise1.py | 528 | 3.953125 | 4 | print('\nExercise 1. Edited Listing 5.3: Add Non Negative')
print('Exits when negative values are inputed and then sums all non negative values')
entry = 0 # Initialize, make sure loop is entered
sum = 0 # Intialize sum
print('\nEnter numbers to sum, negative number ends list: ')
while entry >= 0:
entry =... |
40714ee3b84c3463abdc95ca86d4d5803a4f94d3 | samir-0711/Leetcode-Python | /212. Word Search II.py | 3,250 | 3.734375 | 4 | class Solution(object):
def findWords(self, board, words):
result = []
row = len(board)
col = len(board[0])
if row == 0 or board == None or words == []:
return result
trie = Trie()
for word in words:
trie.insert(word)
visited = [[Fals... |
5c674ffcae4d6aaa4849ba8b1e044e82c883750b | rickthegeek/Week15FinalProject | /Week15FinalProject/Week15FinalProject.py | 15,981 | 3.875 | 4 | #Project: CIS 177 WEEK 15 FINAL PROJECT
#Project Location: projects\cis177\Week15Project
#File: Week15FinalProject.py
#Purpose: This is an implementation of a student information system for XYZ Community college
# for Week 15 - the final project of the year
# NOTE: The program depends on StudentC... |
57a0e0c8a92291c6444c2452d1ec43edf276b636 | NIihLopes/Projetos_Pessoais | /Jogo_da_sorte.py | 829 | 3.8125 | 4 | import random
def gerando_numero_da_sorte():
numeros_da_sorte = random.randrange(1,60)
return numeros_da_sorte
def continuar():
print('** Digite 1 para gerar um Numero! **')
print('** Digite 2 para encerrar! **')
gerar_numero = int(input("digite:"))
if gerar_numero == int(1):
resposta ... |
9727980d6ec22cbd23b393d00dbc3a2253bc0356 | unamfi/sistop-2020-2 | /tareas/1/LoidiJavier/elevador.py | 1,190 | 3.671875 | 4 | #!/usr/bin/python3
from threading import Semaphore, Thread
from random import randint
from time import sleep
lugares = Semaphore(5)
alumnos_a_bordo = []
total_alumnos=20
def proviene():
return randint(1,5)
def destino(este_no):
dest = randint(1,5)
while dest == este_no:
dest = rand... |
d5aae4ec195d06cd401c8f90a9039fe2c5adf0ba | surajwate/file-finder | /getfiles.py | 531 | 3.609375 | 4 | import os
def scantree(path):
"""Recursively scan a directory tree
:param str path: path to scan
:rtype: os.DirEntry
:return: DirEntry via generator
"""
for entry in os.scandir(path):
yield entry
if entry.is_dir(follow_symlinks=False):
yield from scantree(entry.path)... |
8d8da8964fe8d75111b51d070f4fc8ef31421479 | amitropp/HackIDC | /maps_utils.py | 1,959 | 3.734375 | 4 | import requests
from dataframes import branches
FILE_NAME = "branches_distances.csv"
# The maximum duration travel we are allowing from out source to the destination
MAX_DURATION = 1800
our_key = "AIzaSyBcFvf4T7TWk-DQgq-YxU5Z6yZn0GvDGPs"
url = "https://maps.googleapis.com/maps/api/distancematrix/json" + \
"?un... |
dc6becdd2babfa4cc04f1e7f307ba0090f2d45bc | sachin121103/Small-Projects | /prime-numbers.py | 295 | 4.125 | 4 | # Find if a given number is prime
def isPrime(num):
factors_list = []
for i in range(2, num):
if num % i == 0:
factors_list.append(i)
if factors_list:
print("The number is not prime")
else:
print("The number is prime")
isPrime(4)
|
a39229aa20fbdd0140cb1281b25779c955bd2be9 | pallabbarman/python | /Basic/ifelse.py | 193 | 4.0625 | 4 | x = 10
y = 20
z = 30
if x > y:
print('x is greater than y')
elif x < y:
print('y is greater than x')
elif x == y:
print('x is equal y')
else:
print('z is greater than x and y')
|
d1266f2981bb3406f2080879dc6eded4dfabe1e9 | JLMarshall63/myGeneralPythonCode | /DateTimeFunc.py | 3,005 | 3.96875 | 4 | from datetime import datetime
dt = datetime.now()
print '%s/%s/%s' % (dt.month, dt.day, dt.year)
print dt
print dt.month
print dt.day
print dt.year
print '%s-%s-%s' % (dt.month, dt.day, dt.year)
print dt.hour
print dt.minute
print dt.second
print '%s:%s:%s' % (dt.hour, dt.minute, dt.second)
p... |
11ebf63c43d1e274c5af7b6815d983f3c07dc0d6 | wudongdong1000/Liaopractice | /practice_20.py | 576 | 3.75 | 4 | #请把下面的Student对象的gender字段对外隐藏起来,用get_gender()和set_gender()代替,并检查参数有效性:
class Student(object):
def __init__(self,name,gender):
self.name=name
self.set_gender(gender)
def get_gender(self):
return self.__gender
def set_gender(self,gender):
if gender.title()=='Male' or 'Female':
... |
ebae059dce9e615d264ddb5b97332eb2e3f9650b | PDXDevCampJuly/Summer_Lyn1 | /Week 3/test_die_roll.py | 1,610 | 3.828125 | 4 | __author__ = 'summerlynbryant'
import unittest
from Wk3_mon_die import Die
class DieRollTest(unittest.TestCase):
"""Test the functionality of the Die class' roll function"""
def setUp(self):
self.possible_values = [1, 2, 3, "Dog", "Cat", "Hippo"]
self.new_die = Die(self.possible_values)
... |
aedad14914db7624e8d65e910a1ed91beb769f45 | RomanSchigolev/Python__Lessons | /Conditional_Operator/final_work.py | 9,915 | 4.21875 | 4 | # 1. Напишите программу, которая определяет, оканчивается ли год с данным номером на два нуля.
# Если год оканчивается, то выведите «YES», иначе выведите «NO».
#
# Формат входных данных
# На вход программе подаётся натуральное число.
#
# Формат выходных данных
# Программа должна вывести текст в соответствии с условием ... |
566e5c2d334b0ceb7b5bc6bd868f5a381b08ac15 | zentabit/pythonjects | /cipher.py | 1,293 | 4.21875 | 4 | # Nicer cipher by Email
from cipher_keys import bin_key
from cipher_keys import caesar_key
# Conversion from letters to binary
def binariate(text, key):
output = ""
output += "In my encoding, this would make:\n"
for c in text:
output += format(key.index(c), '06b') + ' '
output += "\nIn ASCII... |
81c80c0dd8d7a8406b87018546fd4c8d72fa69d4 | adriaanbd/data-structures-and-algorithms | /Python/trees/binary/dfs_traversals.py | 1,444 | 4.28125 | 4 | """
DFS Workbook
In this workbook we will try out the three main types of
Depth First Binary Tree Traversal: Pre-order, In-order and Post-order.
In each of the cells below you will implement a pre, in and post order
traversal of the tree by printing the node's value when you visit it.
Before we traverse anything thou... |
29eb123a0c24bdfef14fcc900b2c8faa7e819dea | Dr-Jinay/Hacker-Rank-Python-coding-practice | /writeafunction.py | 407 | 3.9375 | 4 | # Write a function in Python - Hacker Rank Solution
def is_leap(year):
leap = False
# Write your logic here
# Write a function in Python - Hacker Rank Solution START
if year%400==0 :
leap = True
elif year%4 == 0 and year%100 != 0:
leap = True
return leap
# Wri... |
4a0ebcc56687b2d5752b87dde72cee4d8adcf6fd | sivaprasadreddynooli/Python_tutorials_for_beginners- | /Fibonacci_series.py | 414 | 4.1875 | 4 | #cube = lambda x: # complete the lambda function
def fibonacci(n):
l = []
if n == 1:
l= [0]
if n == 2:
l = [0,1]
if n > 2:
l = [0,1]
for i in range(2,n):
l.append(l[i-1] + l[i-2])
return l
# return a list of fibonacci numbers
def cube(x):
return ... |
e1cc06636717ff5574b2e11a1ec00639a1adda85 | gabrysb/210CT | /Question11.py | 1,444 | 4.28125 | 4 | class Node(object):
def __init__(self, value):
self.value=value
self.next=None
self.prev=None
class List(object):
def __init__(self):
self.head=None
self.tail=None
def insert(self,n,x):
#Not actually perfect: how do we prepend to an existin... |
7affe1ed4c561ae915784ac28020c7a6c73df24d | duanxuepeng11/Alive | /pythonDemo/函数式编程/高阶函数.py | 1,389 | 3.609375 | 4 | print(abs(-19))
# abs = 10
# print(abs(-19))
# 函数可以作为参数传递
def add(x,y,f):
return f(x) + f(y)
print(add(-3,5,abs))
def f(x):
return x*x
r = map(f,[1,2,3,4,5])
print(list(r))
print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
from functools import reduce
def add(x,y):
return x+y
print(reduce(add,[1,2,... |
c52fbe1111d1d26b4b558a5f94f24b9109f41d43 | davidadamojr/data_science_from_scratch | /network_analysis/centrality.py | 3,270 | 3.625 | 4 | from collections import deque
def shortest_paths_from(from_user):
# a dictionary from "user_id" to *all* shortest paths to that user
shortest_paths_to = { from_user["id"] : [[]] }
# a queue of (previous user, next user) that we need to check
# starts out with all pairs (from_user, friend_of_from_user... |
f70b182127d08471d093c0b2615b1392fbd2e16c | HBharathi/Python-Programming | /Class.py | 202 | 3.734375 | 4 | class Point:
def move(self):
print("draw a line")
def join(self):
print("join the points")
point1 = Point()
point1.x=10
point1.y=20
point1.join()
point1.move()
print(point1.x)
|
f441571b92d50bbefd70bd4a7d448aef8ddb2b68 | wliustc/study_higher_python3 | /LEGB/装饰器.py | 533 | 3.734375 | 4 | # coding=utf-8
def outer(func):
print('ahaha')
def inner(msg):
print('before do...')
func(msg)
print('after do...')
return inner
print('1')
@outer
def do(msg):
print('do %s...' % msg)
print('2')
def outer1(func):
def inner():
print('outer 1')
func()
retur... |
7e853e907e0c71bf739de178ffe1bb1f0e6b6145 | douglasmsi/sourcePython | /loop.py | 184 | 3.953125 | 4 | #!/usr/bin/python3
soma = 0
while True:
num = int(input("Digite um numero ou 0 para sair : "))
if num == 0:
break
soma += num
print('Total: {}'.format(soma))
|
8579af3991fd9d9e766e429d42cf003aeb087980 | pallavipsap/Two-Pointers-2 | /240_search_a_2D_matrix_II.py | 803 | 3.90625 | 4 | # June 11, 2020
# Try different approaches ( think if heaps can work)
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
# Time complexity : O(m^n)
# Pass through the entir... |
9be5654c5c67e0e61b08aff76fa535436eed2edf | fwang1395/LeetCode | /python/String/ReverseInteger.py | 1,059 | 4.21875 | 4 | #!/usr/bin/python
# _*_ coding:UTF-8 _*_
'''
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed i... |
ded38559de45675f052939817c994c12a4b14fa2 | harish-999/my_py_codes | /cube of a number.py | 93 | 4.0625 | 4 | num = float(input('enter a number'))
cu = num * num * num
print('the cube of',num,'is :',cu)
|
0eb04051faba307307c14e6836ea736effebab30 | FrodeWY/Python_test01 | /src/test04/CustomizeClass.py | 3,196 | 3.984375 | 4 | class Student:
def __init__(self, name):
self.name = name
def __str__(self):
return 'student name:' + self.name
s = Student('wy')
print(s)
class Fib:
def __init__(self):
self.a, self.b = 1, 1
# 如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法,
#... |
a9146b87d9662332ca08b4dbdf0b17d9b80c9566 | samruddhi221/Python_DS_Algo | /OOP_in_python/Examples/AmazonLockerHub.py | 6,522 | 4.15625 | 4 | """
Problem Statement:
1. Find the right locker for the package according to its size.
lockerSize >= packageSize
2. only 1 package in a locker
Functional Requirements:
1. User:
- Open the locker with the code
- pick the package
2. Delivery Guy:
- place the package to the locker
3. Locker System:
- find the available... |
85bf81464ccc8ba3fd96219906d0a2b3b58f66f6 | bongjour/effective_python | /part2/doco.py | 1,032 | 4.09375 | 4 | import time
class Timer(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
start_time = time.time()
result = self.func(*args, **kwargs)
end_time = time.time()
print("실행시간은 {time}초 입니다.".format(time=(end_time - start_time)))
... |
7b4d2c66b712d4c1d69cdde950dfa1fbefd51471 | hjlarry/practise-py | /standard_library/Concurrency/Subprocess/subprocess_basic.py | 2,081 | 3.625 | 4 | """
subprocess 模块提供了了三个 API 处理进程:
1. Python 3.5 中添加的 run() 函数,是一个运行进程的 API,也可以收集其输出
2. call(),check_call() 以及 check_output() 是从 Python2 继承的较早的高级 API。
3. 类 Popen 是一个低级 API,用于构建其他的 API 以及用于更复杂的进程交互。Popen 构造函数接受参数设置新进程,以便父进程可以通过管道与它通信。
"""
import subprocess
print("一、 subprocess.run()")
completed = subprocess.run(["ls", "... |
689ef61a7cfa09496ae8d5861add63d3311cee7a | mingyyy/onsite | /week_01/05_lists/Exercise_02.py | 502 | 4.09375 | 4 | '''
Given the two lists below, find the elements that are the same
and put them in a new list.
Put the elements that are different in another list.
Print both.
'''
list_one = [0, 4, 6, 18, 25, 42, 100]
list_two = [1, 4, 9, 24, 42, 88, 99, 100]
common_list = []
other_list = []
for i in list_one:
if i in list_two... |
36fa465f0e35dc493b3fadc587464ca4e7921be1 | aflaxman/performance_of_insilicova_replication_archive | /src/metrics.py | 13,539 | 3.796875 | 4 | from __future__ import division
import math
import pandas as pd
import numpy as np
def calc_sensitivity(cause, actual, predicted):
"""Calculate sensitivity for a single cause
Sensitivity is also known true positive rate, recall, or probability of
detection. It is the number of correct predictions for th... |
b3d079787e65ec9f494d7e0f36f04d5c47af0174 | BrentLittle/100DaysOfPython | /Day019 - Instances, State and Higher Order Functions/turtleRace.py | 945 | 4.0625 | 4 | from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width = 500, height = 400)
isRaceOn = False
userBet = screen.textinput(title = "Make a Bet", prompt = "Enter a color: ")
turtleColors = ["red", "orange", "yellow", "green", "blue", "purple"]
turtleObjects = []
xLoc, yLoc = -230, -100
for c... |
741b65cb559112836b72bd80663ce104cb9db149 | foobar167/junkyard | /simple_scripts/polygon_drawing.py | 21,505 | 3.546875 | 4 | # Drawing polygon on the image
import tkinter as tk
from tkinter import ttk
from datetime import datetime
from PIL import Image, ImageTk
class AutoScrollbar(ttk.Scrollbar):
""" A scrollbar that hides itself if it's not needed.
Works only if you use the grid geometry manager """
def set(self, lo, hi):
... |
30ffb079040aa70adea8e5bee3b937f4abede977 | zekiahmetbayar/python-learning | /Bolum1_Problemler/yakit_hesapla.py | 388 | 3.890625 | 4 | # Bir aracın kilometrede ne kadar yaktığı ve kaç kilometre yol yaptığı bilgilerini alın ve sürücünü toplam ne kadar ödemesini gerektiğini hesaplayın.
km_yakit = float(input("Kilometrede kaç tl yaktığınızı giriniz : "))
km_yol = int(input("Kaç kilometre yol yaptığınızı giriniz : "))
print("Yaktığınız toplam yakıt : {}... |
059ab1e030ac7c23a0eac0052a3921745e1b71f5 | Kovitwk/IT1805Grp2 | /Record.py | 957 | 4.0625 | 4 | class Record:
def __init__(self, height, weight, date):
self.__height = height
self.__weight = weight
self.__bmi = (float(weight)/(float(height)*float(height)))
self.__level = ''
self.__date = date
def get_date(self):
return self.__date
def get_he... |
ac251afc06df77f854a3b6ebe4e8785d92244726 | Freshield/LEARN_Python_Crawler | /example/13/╡┌13.8.py | 880 | 4.03125 | 4 | # 导入concurrent.futures模块
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import datetime
# 线程的执行方法
def print_value(value):
print('Thread' + str(value))
# 每个进程里面的线程
def myThread(value):
Thread = ThreadPoolExecutor(max_workers=2)
Thread.submit(print_value, datetime.datetim... |
e4c2d6aafc02e7ff24d24f3eabfd2f0aed5b4539 | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/sbysiz002/piglatin.py | 1,028 | 3.53125 | 4 | def getFirstVowel(w):
#return the position of the first occurence of a vowel in a string
for i in range(1,len(w)):
if w[i] in "aeiou":
return i
def toPigLatin(s):
vowel = ['a','e','i','o','u']
newSent = ''
for word in s.split(' '):
if word[0] in vowel:
... |
10d4d994d6ddaa3fcb20720bfe970121d81b5588 | vietthanh179980123/VoVietThanh_58474_CA20B1 | /page_63_project_10.py | 1,275 | 3.96875 | 4 | """
Author: Võ Viết Thanh
Date: 05/09/2021
Program: An employee’s total weekly pay equals the hourly wage multiplied by the total
number of regular hours plus any overtime pay. Overtime pay equals the total
overtime hours multiplied by 1.5 times the hourly wage. Write a program that
takes as inputs the hourly wag... |
b1ac7cbae6acd087af2e34360b398fc7574a2b98 | Artembbk/fmsh | /Python/quadric.py | 744 | 3.78125 | 4 | from math import sqrt
a, b, c = map(int, input("Введите коэфиценты квадратного уравнения через пробел: ").split())
if a != 0:
d = b**2 - 4*a*c
if d > 0:
x1 = ( -b-sqrt(d) )/2*a
x2 = ( -b+sqrt(d) )/2*a
print("x1 = {}; x2 = {}".format(x1, x2))
elif d == 0:
x = -b/2*a
print("x1 = x2 = {}".format(x))
... |
d233f630f471758bdd628b3f46de1077e009d753 | Heast1/HHWCS | /RemoveVowels.py | 339 | 3.984375 | 4 | def RemoveVowels(str):
vowels = "AaEeIiOoUu" # a string of vowels
for i in str:
if(i in vowels):
str = str.replace(i, "") # replaces the char with space
return str
print("Enter a line: ")
string = input()
print("The mutated string is ", Re... |
9ee41caafa204624d48dd57d2dd39cfc8ccb3829 | yuninje/Algorithm_Solve | /Baekjoon/[ 01914 ] 하노이 탑.py | 328 | 3.953125 | 4 | # https://www.acmicpc.net/problem/1914
def Hanoi(start, end, height):
if height == 1:
print(str(start) + " " + str(end))
return
Hanoi(start, 6-start-end, height-1)
print(str(start) + " " + str(end))
Hanoi(6-start-end, end, height-1)
N = int(input())
print((1<<N)-1)
if N <= 20:
Hano... |
77358a70ba80e9727ba9b13715debec30fa63ff1 | lucascmb/Sistemas_Distribuidos | /Modulo 1/Laboratório 1/echo_passivo.py | 964 | 3.5625 | 4 | import socket
#define o host e a porta de conexão que a parte passiva irá receber conexões
HOST = ''
PORT = 5000
#instancia o socket
socket_passivo = socket.socket()
#define o host e a porta ao qual esse socket estará ouvindo
socket_passivo.bind((HOST, PORT))
# define o limite maximo de 5 conexoes pendentes e coloc... |
8e267b6b2496aa362ea7bd4149fd347f68caf7da | renbstux/geek-python | /Tipo String.py | 1,520 | 4.28125 | 4 | """
Tipo String
Já vimos que em Python um dado é considerado do tipo string sempre que:
Estiver entre aspas simples -> 'uma string', '234', 'a', 'True', '42.3'
Estiver entre aspas Duplas -> "uma string", "234", "a", "True", "42.3"
Estiver entre aspas simples triplas -> '''uma string''', '''234''', '''a''', '''True'... |
22589da04067c0a56b0e9b74bc990ba89ed3adff | sbeaumont/AoC | /2020/AoC-2020-14.py | 859 | 3.546875 | 4 | #!/usr/bin/env python3
"""Solution for Advent of Code challenge 2020 - Day 13"""
__author__ = "Serge Beaumont"
__date__ = "December 2020"
with open("AoC-2020-14-input.txt") as infile:
program = [line.strip() for line in infile.readlines()]
print(program)
def to_binary(i):
return [c for c in bin(i)[2:].zf... |
82e00ed3c84090cb57be08e0e049bebd2cb48ba4 | RPCodeBox2/06_EDA_Matplotlib | /01_MatPlotLib_Basic_Code.py | 1,759 | 3.921875 | 4 |
# In[1] - Documentation
"""
Script - 01_MatPlotLib_Basic_Code.py
Decription - Basic coding pattern of Matplotlib
Author - Rana Pratap
Date - 2021
Version - 1.0
#!/usr/bin/env python
#coding: utf-8
"""
print(__doc__)
# In[2]: Import and Jupyter Notebook Settings
import matplotlib.pyplot as plt
#get_ipython().run_line_... |
3508a62600789b1121c97427a134c3b2f928fbd9 | chandanrawat176/Python | /encoded message.py | 411 | 4.03125 | 4 | alphabet = 'abcdefghijklmnopqrstuvwxyz'
key = 3
newMessage = ''
message = input('Please enter a message: ')
for character in message:
if character in alphabet:
position = alphabet.find(character)
newposition = (position + key) % 26
newchar = alphabet[newposition]
#print('The new character is:', newchar)
ne... |
e4ec993995906a229fd22a8066769ec2df407395 | BrianBalayon/50white | /Python/gui.py | 1,359 | 3.59375 | 4 | import tkinter as tk
from tkinter import filedialog
import percentCalc
_root = tk.Tk()
_txt_box = tk.Text(_root, height=3, width=30)
_choose_btn = tk.Button(_root, text='Choose a File', height=2, width=30, command=lambda: choose_file())
_calc_btn = tk.Button(_root, text="Calculate Whitespace", height=2, width=30,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.