blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8f554b1dfaf1b15ad136b029ed866bba590a2243 | sungminoh/algorithms | /leetcode/solved/239_Sliding_Window_Maximum/solution.py | 3,811 | 3.8125 | 4 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 sungminoh <smoh2044@gmail.com>
#
# Distributed under terms of the MIT license.
"""
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k num... |
84b35e76c7fd1c9206f27f3f19879bf3785ab8e0 | ricardostange/classes | /new_base.py | 507 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 27 23:57:14 2017
@author: Ricardo
"""
def new_base(number, base):
nNumber = [] #number will be represented as a list of numbers
assert ((number > 1) and (number%1) == 0)
while number > 0:
c = number % base
number -= c
... |
aa90bf9ad2759bc245e8408e1a3a61e68dd84449 | matheusmrf/Linguagem-de-Programacao | /main.py | 4,515 | 4.03125 | 4 | # Nome: Bruno Pena Baeta e Matheus Rangel de Figueiredo
# Professor: Hugo Bastos de Paula
# Matéria: Linguagens de Programação
from lib.interface import *
from lib.arquivo import *
from time import sleep
########################################### Funcao 1 ######################################################
def ... |
85a64671094472f946234a26fa55e7cd9868c22a | shadydealer/Python-101 | /Solutions/week10/VehicleManager/src/queries/fetcher.py | 665 | 3.96875 | 4 | import sqlite3
from queries.sqlite3_handler import execute_and_fetch
"""
A class that is used to select/fetch from given database.
"""
class Fetcher:
def __init__(self, *, dbName):
self.dbName = dbName
"""
Fetches a row from the database by given columns.
@return value:
... |
09e97ca7073eeca611919fd59aaeda5a870c6105 | t9niro00/Python | /ExForReview/ex3.py | 1,011 | 4.03125 | 4 | import threading
import time
val = 0
lock = threading.Lock()
class Thread(threading.Thread):
def __init__(self, t, *args):
threading.Thread.__init__(self, target = t, args = args)
self.start() #start the thread
def increment():
global val
print(threading.currentThread()) #print the curr... |
431e5978c7ea9d0f557443e0def0f9341a1180fc | Grande-zhu/CSCI1100 | /LAB/LAB3/lab03_check3.py | 980 | 3.53125 | 4 | def find_next(bpop,fpop):
bpop_next = max((10*bpop)/(1+0.1*bpop)-0.05*bpop*fpop,0)
fpop_next=max(0.4*fpop+0.02*fpop*bpop,0)
return(bpop_next,fpop_next)
bpop=input("Numbers of bunnies==>")
print(bpop)
fpop=input("Numbers of foxes==>")
print(fpop)
bpop=int(bpop)
fpop=int(fpop)
print("Year 1: {... |
ace78408e561f77f81e1bf706ed8b266b30992a5 | simonesilvetti/teaching_2017_units_dmg_python | /Lez10/files/Expolish.py | 779 | 4.125 | 4 |
def isAnOperator( x ):
"""Return True if x is '+','-','*','/'"""
return (x=='+') or (x=='-') or (x=='*') or (x=='/')
def compute( op , x , y ):
"""Compute the value of expression 'x op y', where -x and y
are two integers and op is an operator in '+','-','*','/'"""
if (op=='+'):
return x+y
... |
4f79ecc3467a8ce226e40a3fb24901003fd9834b | nana-agyeman1/Global-code-py-2k19 | /fibonacci.py | 195 | 3.953125 | 4 | fibnum = int(input("Enter the number here: "))
def fib(n):
if n == 0 or n == 1:
return n
return fib(n-1) + fib(n-2)
print (list(map(fib, range(1,fibnum+1))))
print(fib(fibnum+1)) |
bf46193677af2e1abcedd29de35463f0961a9999 | umerfarooq01/OOP-in-Python | /class_fun.py | 349 | 3.84375 | 4 | # Here we learn how to create Python Class Functions
class course:
def __init__(self, name):
self.name="Python"
self.students=[]
def add_students(self,student):
self.students.append(student)
# c1=course("Python")
# c1.add_students("Umer")
# c1.add_students("Farooq")
# print(c1.studen... |
a1d3cd4ff558ec993afbb09351eab9c14514053c | LisaLen/code-challenge | /interview_cake_chals/find_repeat_space_edition.py | 1,559 | 4.125 | 4 | '''Find a duplicate, Space Edition™.
We have a list of integers, where:
The integers are in the range 1..n1..n
The list has a length of n+1n+1
It follows that our list has at least one integer which appears at least twice.
But it may have several duplicates, and each duplicate may appear more than twice.
Write a fu... |
3c372d5795cd918bd30cc6138313d85fc99430d1 | GamaCatalin/Facultate | /An1_sem1/Python/Seminar/Seminar 8/Client.py | 943 | 3.578125 | 4 | class Client:
def __init__(self, clientId, name, age):
self._clientId = clientId
self.Name = name
self.Age = age
@property
def Id(self):
return self._clientId
@property
def Name(self):
return self._name
@Name.setter
def Name(self, value):
if... |
6a0dc338b01871fa14dd54353870eb2114094c22 | taniamichelle/Sprint-Challenge--Intro-Python | /src/oop/oop2.py | 1,296 | 4.0625 | 4 | # GroundVehicle class
class GroundVehicle():
# change it so the num_wheels defaults to 4 if not specified
def __init__(self, name = 'Bob', num_wheels = 4):
self.name = name
self.num_wheels = num_wheels
# add method drive() that returns "vroooom".
def drive(self):
return ("vrooo... |
099f76cf84cef7876162dea49aff47b44c10ee44 | guiconti/workout | /leetcode/148.sort-list/148.sort-list.py | 1,752 | 3.9375 | 4 | # 148. Sort List
# Medium
# 2038
# 102
# Add to List
# Share
# Sort a linked list in O(n log n) time using constant space complexity.
# Example 1:
# Input: 4->2->1->3
# Output: 1->2->3->4
# Example 2:
# Input: -1->5->3->4->0
# Output: -1->0->3->4->5
# Definition for singly-linked list.
# class ListNode:
# d... |
15eb83fef03b64c1a0170c5d768d28cdda155222 | jyt0532/Trie | /trie.py | 2,143 | 3.640625 | 4 | class TrieNode:
def __init__(self, count, depth):
self.count = count
self.depth = depth
self.children = Trie()
def add_count(self, count):
self.count = self.count+count
class Trie:
def __init__(self):
self.tree = {}
def add_words(self, words, count, depth):
... |
7221bdcb89acd281939e4b41da274489a664fbe0 | lvah/201901python | /day25/16_字符串的替换与分离.py | 623 | 3.78125 | 4 | """
文件名: $NAME.py
日期: 25
作者: lvah
联系: xc_guofan@qq.com
代码描述:
"""
import re
s = 'westos is a company'
print(s.replace('westos', 'fentiao'))
# 将westos和company都替换位cat
print(re.sub(r'(westos|company)', 'cat', s))
# 将所有的数字替换位0;
s1 = "本次转发数位100, 点赞数为80;"
print(re.sub(r'\d+', '0', s1))
def addNum(Obj):
# num是一个... |
d79e045bb012beb7d942ed0a6259f6e5a6408cf1 | Joz1203/COM404 | /1-basics/4-repetition/2-for-loop/3-range/bot.py | 367 | 3.921875 | 4 | #user input brightness level
print("What level of brightness is required?")
brightness = int(input(""))
print()
print("Adjusting brightness...")
print()
#brightness increasing
for number in range(2, brightness + 1, 2):
print("Beep's brightness level:", number * "*")
print("Bop's brightness level:", number * ... |
2653880ea9174d601ea8347dcc3e6cfc0a5bcc3c | Telmo465/AI-B | /aplic8.py | 241 | 3.578125 | 4 | import random
s=1
n = int(input("Número de elementos"))
a = [0 for i in range (n)]
for i in range(n):
a[i]=random.randint(0,1000)
if i%2 == 0:
s*= a[i]
print(a)
if s != 1:
print("Produto dos números de indice par:", s)
|
d08084271f5394620541adc010f196144fe312a8 | joymaxnascimento/python | /hackerrank/python-mutations.py | 286 | 3.6875 | 4 | """
https://www.hackerrank.com/contests/linguagens-de-programacao-para-ciencia-de-dados/challenges/python-mutations
"""
def mutate_string(string, position, character):
string = list(string)
string[position] = character
string = ''.join(string)
return string
|
036f0cf31b5bd9dc0ab0a7d4e2750d0f43982651 | Deanwinger/python_project | /python_fundemental/148_Diameter_of_Binary_Tree.py | 886 | 3.953125 | 4 | # leetcode 543. Diameter of Binary Tree
# 程序员代码面试指南 P169
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 这一题有点tricky的就是, 有三种情况, 最长直径在左树, 或者是右树, 还可能是跨越左右树
class Solution:
def diameterOfBinaryTree(sel... |
d7e383992ce3ece3a756c9598ad595075c715efa | NWChen/tshirt-shooting-robot | /Code/sim/Wheel.py | 1,168 | 4.28125 | 4 | import math
from Point import Point
"""
Implements an independent swerve module as a wheel.
"""
class Wheel(object):
"""
Creates a Wheel object.
@type center: Point
@param center: The center of mass of the rectangle representing the wheel's shape
@type speed: number
@param speed: The speed with which the wheel ... |
77930e259dcee9191ac3608d5dd41cf0c41d84d1 | muskansaini017/Calculator-GUI-Tkinter | /main.py | 5,701 | 3.53125 | 4 | import tkinter as tk
from tkinter import *
from tkinter import messagebox
value=''
int_value=0
operator=''
# functions
def btn1_clicked():
global value
value=value + "1"
data.set(value)
def btn2_clicked():
global value
value= value+"2"
data.set(value)
def btn3_clicked():
global value
... |
21ac9ce105bc80c334246e34b568587283443c2d | Qiumy/leetcode | /Python/349. Intersection of Two Arrays.py | 842 | 4.09375 | 4 | # Given two arrays, write a function to compute their intersection.
#
# Example:
# Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
#
# Note:
# Each element in the result must be unique.
# The result can be in any order.
class Solution(object):
def intersection(self, nums1, nums2):
"""
... |
15191d3fe67a6833d147bec33dac3bfcabda6440 | AyushSingh445132/What-I-have-learnt-so-far-in-Python | /11.2.Python Exercise 3 - Guess the number.py | 1,078 | 4.375 | 4 | # Create a Program to guess a given number
# Rerun the program to a specific number of turns
# After every turn print whether the typed number is "greater" or "lesser" than the number to be found
# If the user cannot guess the number after all turns are finished print "Game Over"
# If the user won print the number of g... |
85f479e8f3248fd718125af703bcbb3cfb440079 | anniemaa/OOP-Python | /20-valid-parentheses.py | 840 | 3.703125 | 4 | class Solution:
def isValid(self, s: str) -> bool:
pastParens = []
for i in s:
if self.isOpenParens(i):
pastParens.append(i)
elif len(pastParens) == 0:
return False
else:
op = pastParens.pop()
cl = i
... |
7ee6fa12cc6b26d97c2c53228871c4509baaee8a | Anitha710/265441_Daily_Commits | /dictionaries.py | 679 | 4.0625 | 4 | # dictionaries
ages = {"Dave": 24, "Mary":42, "Jhon": 58}
print(ages["Dave"])
print(ages["Mary"])
# use of get
pairs = { 1: "apple", "orange": [2, 3, 4],
True: False,
None: "True",
}
print(pairs.get("orange"))
print(pairs.get(7))
print(pairs.get(12345, "not in dictionary"))\
#example
fib =... |
5328876f4bca08519a70ee63158fe2e0c6fa04ef | emotrix/Emotrix | /emotrix/TimeBuffer.py | 1,169 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import time
class TimeBuffer:
dataBuffer = None
timestamps = None
seconds_back = 0
def __init__(self, seconds_back):
self.dataBuffer = []
self.timestamps = []
self.seconds_back = seconds_back
def insert(self, value):
"""
Insert an ... |
122a11eac175b7b8764c8d7410a4702ecd0d0c7e | wtyqqq/lzu_ds_review_2020 | /CS171/lab11/ex5.py | 758 | 3.71875 | 4 | def printSubStr(str, low, high):
for i in range(low, high + 1):
print(str[i], end="")
print(' ')
def longestPalSubstr(str):
n = len(str)
maxLength = 1
start = 0
for i in range(n):
for j in range(i, n):
flag = 1
for k in range(0, ((j - i) // 2) + 1):
... |
3c9f1841ed07919237ad8eea4b2ab1a603b71a58 | ivnxyz/practicas-programacion-inviertete | /CAROLA/trabajo de CAROLA.py | 537 | 3.84375 | 4 | r=1.1
pi=3.1416
area= pi*(r*r)
print(area)
#DEVUELVE EL VALOR ABSOLUTO
n=1
d=21
diferencia= n-d
print (diferencia)
#propinas
total=44.50
propina=10
t= total/10
prpo= t+total
print(prpo)
#calcula tu peso en otro planeta
p= 70
gt= 9.78
gm= 3.72
total = p*gm
print(total)
# strings
m="hola"
m*100
#mensaje con varea... |
c5231793ee131cbaa7bed37fb3b4f19ee4c9234f | singhdharm17/Python_Edureka | /Question_6.py | 312 | 3.84375 | 4 | # 6. Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000
# and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line.
lst = [i for i in range(2000, 3000) if i % 7 == 0 if i % 5 != 0]
print(lst)
|
4544c39b2de51f2fd3e0361618a1164b3e682475 | MakrisHuang/LeetCode | /python/300_longest_increasing_subsequence.py | 1,443 | 3.75 | 4 | class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
# in brute force it gives us O(n^2) time complexity
# here we will maintain a global array that store the longest chain
# To maintain this, every time we iterate the element, we insert the
# elements with binary search. T... |
eeb1fdca8c77326defe6728765df1d6f70282ead | deequez/Exercise03 | /calculator.py | 1,106 | 4.03125 | 4 | from arithmetic import *
while True:
user_input = raw_input("> ")
tokens = user_input.split(" ")
if len(tokens) == 2 or len(tokens) == 3:
tokens[1] = int(tokens[1])
if len(tokens) == 3:
tokens[2] = int(tokens[2])
if tokens[0] == 'q':
break
elif tokens[0] == '... |
760774bf6f254646c5283eb11a1cdb7b0edc6e2b | Kaichloe/algo_expert | /Easy/valid_seq.py | 163 | 3.515625 | 4 | def isValidSubsequence(array, sequence):
counter = 0
for num in array:
if num == sequence[counter]:
counter += 1
return counter == len(sequence)
|
1c664719abb52c8fafb1d05814ab96581b00550e | phroiland/forex_algos | /forex/src/pricing/currency.py | 3,020 | 4.21875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed May 31 07:17:05 2017
@author: jonfroiland
"""
"""
Be sure to include docstrings at the module, class, and method levels.
"""
"""
The advantage of class definitions in general is to achieve code reuse via
inheritance.
"""
class Currency:
... |
15130f2b5d21d2da894a83d546905c8e602cdabf | cloudoutloud/learn-python | /entry-level/bio.py | 439 | 4.21875 | 4 | # This script pulls user data and prints as a string
name = input("What is your name? ")
color = input("What is your favorite colour? ")
age = int(input("How old are you today? "))
# Use end=" " to place print all on same line
# print(name, end=" ")
# print("is " + str(age) + " years old", end=" ")
# print("and love... |
d5bfc5be15cc515cc8d5b239ad0e296e4f2466e4 | amj4379/cti110 | /P2HW2 - Tip Tax Total.py | 415 | 3.765625 | 4 | # CTI-110
# P2HW2 - Tip Tax Total
# Anthony Jackson
# 2/20/18
BillTotal =float(input("Enter Bill Total $ "))
tip = 0.18 * BillTotal
salesTax = .07 * BillTotal
total = BillTotal + tip + salesTax
print ("Bill Total $" + format(BillTotal, ",.2f"))
print ("tip $" + format(tip, ",.2f"))
prin... |
0fef8977a674085aa2e06732c6357be85a90baea | hianp/Exercicios_Curso_em_video_Py | /Ex036.py | 381 | 3.71875 | 4 | v = float(input('Qual o valor da casa: R$'))
s = float(input('Qual seu sálario: R$'))
a = int(input('Vai pagar em quantos anos? '))
m = a * 12
prest = v / m
porc = (s * 30)/100
print(f'Para pagar uma casa de R${v:.2f} em {a} anos a prestação será de R${prest:.2f}')
if prest > porc:
print('Empréstimo negado'... |
fe66bcfada0493272468203cb0d496899da93bda | RomyRobi/Homework3-Python | /PyPoll/main.py | 2,020 | 3.53125 | 4 | # Import Dependencies
import os
import csv
# Create file path
csv_path = os.path.join("Resources", "election_data.csv")
# Open file as cvs file and skip headers
with open(csv_path, newline='') as csv_file:
csv_reader = csv.reader(csv_file, delimiter = ',')
next(csv_reader)
# Create counter/dictionary for ... |
d517544485061403429d5c51aefd791e3af308fd | daniel-reich/ubiquitous-fiesta | /hmt2HMc4XNYrwPkDh_19.py | 96 | 3.875 | 4 |
def invert(s):
if s == "": return ""
return s[len(s)-1].swapcase() + invert(s[:len(s)-1])
|
563694cf32aed11ad54be215c46d732fd25b3b7c | RMolleda/Python__init__ | /exercises/practice.py | 105 | 4.0625 | 4 | x = " | "
y = "___"
for num in range(8):
print(y * 8, sep="")
print(x * 8, sep="")
print(y *8)
|
1331a65410c8cf1b61dda59afebaa048904097de | ivklisurova/SoftUni_Python_Advanced | /Functions_advanced/operate.py | 534 | 4.03125 | 4 | def operate(fargs, *args):
result = 0
for i in range(len(args)):
if i == 0:
result = args[i]
else:
if fargs == '+':
result += args[i]
# elif fargs == '-':
# result -= args[i]
elif fargs == '*':
result... |
1588126651e2370e9d44ae8e72c72bde52634471 | lucaGazzola/sudoku-solver | /sudoku.py | 829 | 3.609375 | 4 | import numpy as np
def is_possible(sudoku,i,j,n):
return n not in sudoku[i] and n not in sudoku[:,j] and n not in sudoku[(i//3)*3:(i//3)*3+3, (j//3)*3:(j//3)*3+3]
def fill(sudoku):
global counter
for k in range(0,len(sudoku)):
for j in range (0,len(sudoku[k])):
if sudoku[k][j] == 0:
... |
91695f7be1e9ceba3818ef808d9dee0d61a82c6c | brittani-ericksen/dec2020-dir | /week_01/python2/list.py | 914 | 3.984375 | 4 | # appending to list
power_rangers = []
power_rangers.append("Jason")
power_rangers.append("Trini")
power_rangers.append("Billy")
power_rangers.append("Zack")
power_rangers.append("Kim")
print(power_rangers)
##############################
# while loop
power_rangers = []
power_rangers.append("Jason")
power_rangers.... |
bb843863c940ce7ff71124ed78b86af6c38867ea | Chloe5/event-driven-gainiangu | /1_weibo_hot_events_detection/Crawler/DynamicCrawler/DynamicCrawler/Utility.py | 658 | 3.515625 | 4 | def loop_increase(integer, base):
"""
increase integer by 1 if it exceeds base then reset integer
:param integer:
:param base:
:return:
"""
return (integer + 1) % base
def reset_dict(dict):
for key in dict:
dict[key] = ''
def test_exception(func):
"""
... |
f0d0dfbf3d13aec99ffb9b92e5f050a107d48104 | edneipdemelo/1stWeek | /014.py | 210 | 4.125 | 4 | # Leia um ângulo em graus e apresente-o convertido em radianos.
print('Digite o ângulo em graus:')
degree = float(input())
radian = degree * 3.14 / 180
print(f'O ângulo convertido em radianos é: {radian}') |
e8734ddaf8f0081b397f647b27da5245c87e0061 | Elida2000/Tarea2 | /exercise02-result/main_app.py | 1,721 | 3.765625 | 4 | from proyecto_finanzas import ProyectoFinanzas, Ingresos, Egresos
print("Inicio ProyectoFinanzas: \n")
proyectoFinanzasObj = ProyectoFinanzas()
while True:
print("Menu: \n")
print("(0) salir")
print("(1) registrar ingreso")
print("(2) registrar egreso")
print("(3) ver reporte de ingr... |
8a325206ebc3ce89fe8de904ffc4c53d37bec287 | lxconfig/BlockChainDemo | /Python_Workspace/final/Person.py | 1,050 | 3.796875 | 4 | class Person:
def __init__(self, name, dob, sex, zipcode, illness):
self.name = name
self.dob = dob
self.sex = sex
self.zipcode = zipcode
self.illness = illness
def __repr__(self):
return "{0}, {1}, {2}, {3}, {4}\n".format(self.name, self.print_dob(), self.print_... |
0e34d5081c469ab4205da4cbd85b401d58d57255 | addyp1911/Python-week-1-2-3 | /python/Algorithms/Anagrams/AnagramsBL.py | 429 | 4.0625 | 4 | # ----------------------------------anagrams prg-----------------------------------------------
# Anagrams.py
# date : 26/08/2019
# method to check if two user entered strings are anagrams of each other
def checkAnagrams(str1,str2):
string1=sorted(str1)
string2=sorted(str2)
if(string1==string2): #to che... |
9e8eca45d64d46395b9cf4ee1c1022dede0bfa94 | Hemanthtm2/python-magic | /fileops.py | 434 | 3.984375 | 4 | #!/usr/bin/python
##instaed of f.close() function we can use with statement ##
with open('my_new_file.txt',mode='r') as f:
print(f.read())
with open('my_new_file.txt',mode='a') as f:
f.write("This is thrid line")
with open('my_new_file.txt',mode='r') as f:
print(f.read())
with open('mypython.txt',m... |
c8331e6471d6b846fb3ec0b1fd21a3081c42def6 | koiic/python_mastery | /AUB/ass9/segment.py | 618 | 3.734375 | 4 | import math
class Segment2D:
"""
"""
def __init__(self, arg1, arg2):
self.first_tuple = arg1
self.second_tuple = arg2
def length(self):
x1, y1, = self.first_tuple
x2, y2 = self.second_tuple
line = math.sqrt(
pow(2, (x2 - x1)) + pow(2, (y2 - y1))
... |
9d9820141542e81b8e481453aa765ad0613f2fc8 | Voulzy/blockc | /Iota/cleardb.py | 212 | 3.78125 | 4 | import sqlite3
conn = sqlite3.connect("car.db")
c = conn.cursor()
sql = 'DELETE FROM car'
cur = conn.cursor()
cur.execute(sql)
conn.commit()
for row in c.execute("SELECT * FROM car"):
print(row)
conn.close() |
ee86e83fcc9319df5e3476fa946a67f52aff1bf0 | nanigasi-san/nanigasi | /AtCoder/ABC/008-B.py | 218 | 3.578125 | 4 | N = int(input())
list = []
maxname = ""
maxtime = 0
for n in range(N):
list.append(input())
for _ in list:
cou = list.count(_)
if cou > maxtime:
maxtime = cou
maxname = _
print(maxname)
#ac
|
730524a46e77d4b54642cb6dfd9497a030e3f146 | thasleem-banu/python | /Aasetpro69.py | 314 | 3.734375 | 4 |
bh,sbt=map(str,input().split("|"))
cct=input()
if len(bh)>len(sbt):
if len(bh)==len(sbt)+len(cct):
print(bh+"|"+sbt+cct)
elif len(bh)<len(sbt):
if len(sbt)==len(bh)+len(cct):
print(bh+cct+"|"+sbt)
elif len(bh)==len(sbt) and len(cct)>1 or (len(sbt) or len(bh)):
print("impossible")
|
4066e1f032374e5a30b71df868c7c061387e2ecb | GauravPadawe/Universities-Students-and-Fees | /Enrollments and Fees.py | 1,692 | 4.0625 | 4 | usa_univs = [ ['California Institute of Technology',2175,37704],
['Harvard',19627,39849],
['Massachusetts Institute of Technology',10566,40732],
['Princeton',7802,37000],
['Rice',5879,35551],
['Stanford',19535,40569],
['Yale',11701,405... |
af27c954e8167e57c3881c549be3d7d366a16e2c | akki8087/HackerRank | /Staircase.py | 327 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 16 22:39:53 2018
@author: NP
"""
#!/bin/python3
import math
import os
import random
import re
import sys
def staircase(n):
for i in range(1,n+1):
print(('#'*i).rjust(n,' '))
if __name__ == '__main__':
n = int(input())
stairca... |
5d51673f4e28988f5d0ad19171e13a14e2433da5 | depchen/arithmetic | /剑指/03.py | 901 | 3.703125 | 4 | # 题目描述
# 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self,x):
self.val = x
self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(listNode):
# write code here
a=[]
while listNode:
a... |
b5e2d7dd4053cc95c0a06a032b0b697adcc493ea | swordsx/leetcode | /Implement strStr().py | 317 | 3.5 | 4 | class Solution:
# @param {string} haystack
# @param {string} needle
# @return {integer}
def strStr(self, haystack, needle):
lenH, lenN = len(haystack), len(needle)
for i in range(lenH - lenN + 1):
if haystack[i:i+lenN] == needle:
return i
return -1
|
2698848b8a1d10822631f2315ed32463995e8dd5 | marcoslimafpv/Desafio-Capgemini | /cadastroanuncio.py | 1,116 | 3.84375 | 4 | cadastro = '====Dados do anúncio===='
print(cadastro)
visu1 = 30
investimentoDia = int(input('Valor do investimento por dia: '))
cadastro = 'Cadastro de anúncio, preencha os dados.'
nome = str(input('Digite o nome do anúncio: '))
cliente = str(input('Digite o nome do Cliente: '))
dataInicio = int(input('Data Iní... |
dc6282fd2889d2c462148ac8f202cefc53c540cd | ambrocio-gv/PythonConsoleApps | /3a.py | 1,170 | 4.0625 | 4 | #In
#The first line of input consists of an integer N, representing the number of test cases.
#Each test case is composed of two lines, each containing a positive integer. These two
#integers represent Hashmat and is compared to his opponent by using a function named
#difference(a, b), which returns the difference betw... |
f2c525b3eb33e328cc90eb8e8703a0ff8aec929f | mumat0103/etc | /removeFile.py | 439 | 4.0625 | 4 | import os
def removeExtensionFile(filePath, fileExtention) :
if os.path.exists(filePath):
for file in os.scandir(filePath):
if file.name.endswith(fileExtention):
os.remove(file.path)
return 'Remove FIle : ' + fileExtention
else :
return "Directory No... |
c182b361b97bc512b60fe1af29802b24111cc89e | chenshanghao/Interview_preparation | /Company/Amazon/Leetcode_98/my_solution.py | 775 | 4.09375 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: True if the binary tree is BST, or false
"""
def isValidBST(self, root):
# write ... |
60eddb21aef02bfdff50cefff5c2841eddf0e7dc | quantum109678/IT_3 | /dsa/lab1/p6.py | 120 | 3.921875 | 4 | s1=input("Enter String1")
s2=input("Enter String2")
s3=input("Enter String3")
a=s1[:]
b=s2[:]
d=a.replace(b,s3)
print(d) |
b83fb3d2882e49de46d35ee8394781a97e005476 | Bharath-Gopal/python | /rps.py | 1,674 | 4.09375 | 4 | #Rock, Paper, Scissors
import random
print("\n")
print("-"*50)
print("Rock, Paper, Scissors")
print("-"*50)
print("\n")
while True:
print("Pick your choice : ")
print("1. Rock\n2. Paper\n3. Scissors\n")
choice = int(input())
if choice==1:
cn="Rock"
elif choice==2:
... |
baeea8a24eb6e66b86229e720b287c0ea2d8b455 | A432-git/Leetcode_in_python3 | /56.py | 700 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 20:27:10 2020
@author: leiya
"""
class Solution:
def merge(self, intervals):
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
# if the list of merged intervals is empty or if the current
... |
9f1010fcacce4c17f51eb4b8cd1ac9c21f9c35ea | pushsing/Python | /assignments/ProgramsonFunctions/Sum&Multiply.py | 221 | 3.6875 | 4 | def sum(o):
s=0
for i in o:
s=s+i
return s
def multiply(o):
s=1
for i in o:
s=s*i
return s
l=[1,3,4]
tt=sum(l)
print("Sum:",tt)
rr= multiply(l)
print("Multiply:", rr ) |
2650b919085aedd35d5e28061d5448aa2f11032c | reporter-law/book_code | /二级/turtle画图.py | 703 | 3.609375 | 4 | """程序说明"""
# -*- coding: utf-8 -*-
# Author: cao wang
# Datetime : 2020
# software: PyCharm
# 收获:
import turtle,time
for i in range(4):
turtle.fd(80)
time.sleep(2)
turtle.right(90)
#turtle.done()
def draw_snake():
turtle.setup(1300,800,0,0)#画布
turtle.pensize(30)#画笔宽度
turtle.pencolor("blue")#画笔颜... |
6e3b8a82310a421a10e180b7166f3eb5d4979fb5 | FelicianoSachilombo/psr_21-22 | /Parte03/T/ExDicts/main.py | 451 | 3.53125 | 4 | #!/usr/bin/python3
import colorama
from collections import namedtuple
Complex = namedtuple('Complex', ['r', 'i'])
def addComplex(x, y):
a = x['r']
b = x['i']
c = y['r']
d = y['i']
return {'r': a + c, 'i': b + d}
def main():
cs = {'c1': {'r': 4, 'i': 8}, 'c2': {'r': 8, 'i': -4}}
print(... |
fb1ad3ffdca95cd0818a54d8aa7d757c0a9ce7e2 | olivares10/proyectoPython | /duplas/ejercicio2.py | 91 | 3.65625 | 4 | lista = []
for i in range(5):
tmp = int(input("Digite Nùmero:"))
lista.append(tmp) |
8e5520df95a7c3d2a143570dbfe6ab456db25b51 | bcc/adventofcode2020 | /03/03.py | 641 | 3.734375 | 4 | #!/usr/bin/python3
import sys
x_move1 = 3
y_move1 = 1
p2_move = [ [1,1], [3,1], [5,1], [7,1], [1,2] ]
lines = []
for line in sys.stdin:
lines.append(line.rstrip())
def check_slope(lines, x_move, y_move):
count = 0
x = 0
y = 0
while y < len(lines)-1:
for i in range(0, x_move):
... |
05cf025ce775e6e9ae90e2a57a45b993f754d770 | detcitty/100DaysOfCode | /python/unfinshed/koka.py | 469 | 3.546875 | 4 | # https://www.codewars.com/kata/58e8cad9fd89ea0c6c000258/train/python
import re
def kooka_counter(laughing):
#your code here
male_regex = r'HaHaHa'
female_regex = r'hahaha'
males = re.findall(male_regex, laughing)
females = re.findall(female_regex, laughing)
size_males = len(males)
size_f... |
7b2df4d802d9cf7436b1f32a9b22cc9960f2c370 | Monikabandal/My-Python-codes | /Finding Numbers in a Haystack.py | 190 | 3.625 | 4 | import re
fname = raw_input("Enter file name: ")
fh = open(fname)
count=0
for line in fh:
x=re.findall('[0-9]+',line)
for i in x:
count = count+int(i)
print count
|
b124c3df74c4c4f2b16b0db63ac7d3c72dcb2fb9 | BensyBenny/Bensybenny-rmca-s1A | /lengthp8.py | 290 | 4.15625 | 4 | def longestword(wlist):
word_len = []
for n in wlist:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][0], word_len[-1][1]
result =longestword(["Apple", "Mango", "Banana"])
print("\nLongest word: ",result[1])
print("Length of the longest word: ",result[0])
|
c0ed05e15dd1912dce1f153fa759cb2a4f4edd54 | Get-out/getout | /atlas_api/species_list.py | 933 | 3.53125 | 4 | from atlas_api.location import Location
class SpeciesList(object):
"""Knows how to get species for a location given a particular distribution of weightings"""
def __init__(self, location, species_weights):
self.location = location
self.species_weights = species_weights
def retreive(self, a... |
4ffd7ec53dbb49de34d74f8737999c583d6dd581 | asralabs/cseu | /CSEUUtil.py | 1,203 | 3.6875 | 4 | #askuser_sel: get selection from a user, sanitize input
#str title,str query,list opt {str}, str default
#return str
def askuser_sel(title,query,options,default):
while (1==1):
print "\n"+title
for i in options:
print i
sel=raw_input(query+"["+default+"]:")
if sel=="":
sel=default
for i in options:
... |
3095884f4c33f422358830674588cbb3a97aae39 | LilMarc0/SnakeAI | /Snake.py | 2,299 | 3.703125 | 4 | class Snake:
'''
length - snake's body length in pixels
x & y - head coordinates
'''
def __init__(self, length, x, y, boundX, boundY):
self.length = length
self.x = x
self.y = y
self.body = [[self.x, self.y-i] for i in range(self.length)]
self.direc... |
b11536247a52194fd72aa002ce1d680d107ddd0b | VataX/isn | /TP7/ex2.py | 224 | 3.875 | 4 | # -*- coding: utf-8 -*-
def compteMots(s):
count=1
for espace in s:
if(espace==" "):
count=count+1
return count
s=str(input("Saisissez une phrase :"))
a=compteMots(s)
print(a) |
2e6425a76c19959f479342c6a057c68bc1d3e511 | srk112006/quiz | /imyth.py | 1,544 | 4.03125 | 4 | print ("This is the Indian Mythology Quiz!! Get ready!")
print ("Type your answers as 'A','B','C' or 'D'")
print ("Who poisoned Bhima during their younger years? ")
ans = input("Your options are A-Dushasana, B-Shakuni,C-Vikarna,D- Duryodhana ")
if ans == "D":
print ("Good job! The questions will get harder!")
... |
c78e2c1202088b43cc939db5e9ff42bec1e9f96e | sakthi5006/epi-python | /Strings/stringsbootcamp.py | 605 | 4.03125 | 4 | # Strings are a special kind of array made out of characters.
# Comparison, joining, splitting, searching for substrings,
# replacing one string by another, and parsing are all operations
# commonly applied to strings that are not sensible for general arrays,
# so the book has a separate category for them.
# Book exa... |
1d3cdb735a56414d1c2b35796102f41416be64f4 | CodecoolMSC2016/python-pair-programming-exercises-2nd-tw-pklaudia_kzoli | /listoverlap/listoverlap_module.py | 337 | 3.890625 | 4 | def listoverlap(list1, list2):
c = []
for a in list1:
if a in list2:
c.append(a)
c = set(c)
c = list(c)
return c
def main():
x = listoverlap([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
print(x)
return
if __name__ == '__mai... |
ff3469075830650a01b403886bbba24dbfd0568e | ArexChu/python | /basic/dice.py | 269 | 3.75 | 4 | #coding: utf-8
from random import randint
class Dice():
sides = 6
def __init__(self,sides):
self.sides = sides
def roll_dice(self):
x = randint(1,self.sides)
print(x, end=' ')
dice = Dice(6)
for i in range(10):
dice.roll_dice()
|
c9f8eeef25afa2724cbcd1a8257f033c2dc4c139 | pra-kri/MP006-Random-Stuff | /python_practice.py | 9,905 | 3.5625 | 4 | """
To cover today:
--------------+
[/] - Enumerate
[/] - Lambdas
[/] - args/kwargs
[/] - testing membership within different data structures
[X] - debugging
[/] - generators
[/] - Functional programming concepts
[/] - map
[/] - filter
[/] - reduce
[/] - Ternary o... |
2523cf35647985f763d6a2518ca3c361d9a2bd63 | alparty/labs | /techlead/sort_colors.py | 1,056 | 4.28125 | 4 | """
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the l... |
ef1e19c29017acd11daeba861e883cb1119ab4ec | DaHuO/Supergraph | /codes/BuildLinks1.10/test_input/CJ_16_2/16_2_3_ana_valeije_C.py | 2,131 | 3.59375 | 4 | def add_dict(d, key):
if key not in d:
d[key] = 1
else:
d[key] += 1
def find_doubles(firsts, seconds, topics):
doubles = []
for topic in topics:
if topic[0] in firsts and topic[1] in seconds:
doubles.append(topic)
return doubles
def choose_doubles(doubles):
f = {}
s = {}
for topic in doubles:
add_d... |
1a0e0a5267eac3d753cdcc857cdddb45f9f1b14d | vineel96/PythonTrack-Exercism | /clock/clock.py | 781 | 3.78125 | 4 | class Clock(object):
out_hour=0
out_minute=0
def __init__(self, hour, minute):
self.hour=hour
self.minute=minute
self.total_minutes=hour*60+minute
self.update()
def __repr__(self):
return '%02d:%02d' % (self.out_hour,self.out_minute)
def __eq__(self, other... |
6e95a70e8cd1e21b528f4f4a39eb32b4b1044163 | Chiva-Zhao/pproject | /cookbook/multithread/thread_lock.py | 5,406 | 4.09375 | 4 | # 给关键部分加锁
# 需要对多线程程序中的临界区加锁以避免竞争条件
# 在多线程程序中安全使用可变对象,需要使用 threading 库中的 Lock 对象
import threading
class ShareCounter:
'''
A counter object that can be shared by multiple threads.
'''
def __init__(self, init_value=0):
self._value = init_value
self._value_lock = threading.Lock()
def... |
19932da3cd64679a5f908f5212ab995fa216feb9 | Kalliojumala/School-Work | /Week 13/13.3.py | 304 | 3.8125 | 4 | #13.3
#Combine two tuples
t1 = (5,4,3)
t2= (9,2, 12)
T = t1 + t2
#print("T =",T)
#13.3.1
#checks if user input in tuple
T = (23, 45, 93, 59, 35, 58, 19, 3)
try:
print(int(input("Anna luku: ")) in T)
except ValueError:
pass
#13.3.2
#average of T
print(f"T:n keskiarvo: {sum(T)/len(T)}")
|
3f8880b102a07287db695ab2e4e562a978ce4500 | naxolorca/MCOC-Nivelacion | /20082019/001452.py | 138 | 3.71875 | 4 | def convert(miles): # funcion para convetir miles a km
km = 1.6 * miles
print str(miles) + " millas son " + str(km) + " km"
convert(20) |
d5a06d38a17a537dfe79d742901670525a558a65 | RayMJK/sparta_algorithm | /week_1/homework/01_find_prime_list_under_number.py | 749 | 3.796875 | 4 | input = 20
list = []
# 소수는 자기 자신과 1 외에는 아무것도 나눌 수 없다.
# 주어진 자연수 N이 소수이기 위한 필요 충분 조건은
# N이 N 제곱근보다 크지 않은 어떤 소수로도 나눠지지 않는다.
# 수가 수를 나누면 몫이 발생하는데, 몫과 나누는 수 둘중 하나는 반드시 N의 제곱근 이하
def find_prime_list_under_number(number):
# 이 부분을 채워보세요!
for i in range(2, number+1):
check = 0
for j in range(2, i):
... |
02a61de6dcbced112520079e9c3f15073cde48f4 | peterzhang45/Python_Exercises_01 | /01. Character_Input/character_input.py | 370 | 4.03125 | 4 | import datetime
now = datetime.datetime.now()
name = input("Please enter your name: ")
age = input("Please enter you age: ")
time = int(now.year)+ (100 - int(age))
string = ("Hi "+ name + ", in " + str(time) + ", you will turn 100 years old!\n")
print(string)
times = input("How many time you want to print out the... |
b65ef5fea6a0f4feebe13535d419e88fb2a9fc3d | skybrim/practice_leetcode_python | /top_interview_questions_in_2018/classic/super_egg_drop.py | 1,289 | 3.640625 | 4 | #!/usr/bin/env pytho
# -*- coding: utf-8 -*-
def super_egg_drop(K, N):
T = 1
while helper(K, T) < N+1:
T += 1
return T
def helper(K, T):
if K == 1:
return T
if T == 1:
return 2
return helper(K-1, T-1) + helper(K, T-1)
def superEggDrop(self, K: int, N: int) -> int:
... |
9b1276a4bf49429e304c2043a786eae8ce582072 | ElAmirr/python_tutorial | /my_python_documentation/strings.py | 801 | 4.5625 | 5 | # Strings in python are surrounded by either single or double quotation marks. Let's look at string formatting and some string methods
name = 'Brad'
age = 37
# Concatenate
print('Hello my name is ' + name + ' and I am ' + str(age))
# String Formatting
# Arguments by position
print('My name is {name} and I am {age}'... |
65a3a0c48725a3c0ceaf04d65ce2e9ba7e0620c6 | deathlyhallows010/Interview-Bit-Python | /Arrays/Set Matrix Zeros.py | 1,148 | 3.640625 | 4 | # https://www.interviewbit.com/problems/set-matrix-zeros/
# Set Matrix Zeros
# Input 1:
# [ [1, 0, 1],
# [1, 1, 1],
# [1, 1, 1] ]
# Output 1:
# [ [0, 0, 0],
# [1, 0, 1],
# [1, 0, 1] ]
# Input 2:
# [ [1, 0, 1],
# [1, 1, 1],
# [1, 0, 1] ]
# Out... |
be95522a5b4004f0652b557b08c66cf25664dd5b | firewut/data-transform-pipelines-api | /src/core/utils/url.py | 478 | 4.0625 | 4 | """
https://stackoverflow.com/questions/1793261/how-to-join-components-of-a-path-when-you-are-constructing-a-url-in-python
"""
def urljoin(*args):
"""
Joins given arguments into an url. Trailing but not leading slashes are
stripped for each argument.
"""
url = "/".join(map(lambda x: str(x).rstrip... |
b5f5ab0e5ffd77703bf633f6582b6dd25384f93f | JunHwaPark/ProblemSolveByPython | /Binary search/부품 찾기 - 한빛.py | 560 | 3.5625 | 4 | n = int(input())
arr1 = list(map(int, input().split()))
m = int(input())
arr2 = list(map(int, input().split()))
arr1.sort()
def b_search(start, end, val):
mid = (start + end) // 2
if start > end:
return False
elif arr1[mid] == val:
return True
elif val < arr1[mid]:
return b_se... |
03dcb27c84d92928e4780af218f9b5b14d760a8d | SCERush/Crypto-System | /autokey.py | 2,736 | 3.515625 | 4 | # -*- coding: UTF-8 -*-
# @File: autokey.py
# @Author: SCERush
# @Contact: 1037920609@qq.com
# @Datetime: 20/7/6 13:57
# @Software: PyCharm
"""
文件说明:
"""
import re
def removePunctuation(text, filter='[^A-Z]'):
return re.sub(filter, '', text.upper())
def encryptPlain(text, keyword):
"""
... |
0dfed8616136c7eae01d7a55457904accbaebbd8 | robertrowe1013/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/12-roman_to_int.py | 418 | 3.5 | 4 | #!/usr/bin/python3
def roman_to_int(roman_string):
rom_n = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
prev = 0
roman_sum = 0
if type(roman_string) is str:
for n in roman_string:
if rom_n[n] > prev:
roman_sum -= prev
else:
... |
73bfe706df16947f75c5de53f1e05f583cb6a8e4 | Coaxecva/COMP4030-Design-and-Analysis-of-Algorithms | /Codes/assignment2.py | 1,967 | 3.65625 | 4 |
'''
Q3. Explain why
(i) 10n + 2n^2 is in O(n^2)
[By definition, this means: 10n + 2n^2 <= c*n^2 for all large values of n.]
Answer:
10n + 2n^2 <= 10n^2 + 2n^2 = 12n^2 for n>1.
Therefore, we found c to be 12.
(ii) 10n + 2n^2 is in Omega(n^2)
[By definition, this means: 10n + 2n^2 >= c*n^2 for all large va... |
3a3600127741a8b4970e5295538eb6b4db2156b8 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/910 Smallest Range II.py | 1,867 | 3.703125 | 4 | #!/usr/bin/python3
"""
Given an array A of integers, for each integer A[i] we need to choose either
x = -K or x = K, and add x to A[i] (only once).
After this process, we have some array B.
Return the smallest possible difference between the maximum value of B and the
minimum value of B.
Example 1:
Input: A = [1], ... |
fe3b750259f0974c204a249c9d47355aea1496fa | Linkney/LeetCode | /BasicSort/draft_paper.py | 1,268 | 3.6875 | 4 | class POINT:
def __init__(self, x, y):
self.x = x
self.y = y
def cross(p1, p2, p3):
x1 = p2.x - p1.x
y1 = p2.y - p1.y
x2 = p3.x - p1.x
y2 = p3.y - p1.y
return x1 * y2 - x2 * y1
def if_two_line_intersection(p1, p2, p3, p4):
if max(p1.x, p2.x) >= min(p3.x, p4.x) and max(p3.... |
cdc2934583142502e34362f9dd53bdddef2bcc55 | dongzeyuan/Practise | /CP2/ICPP2_1.py | 310 | 3.84375 | 4 | # coding=UTF-8
# 通过键盘输入一系列值,输入0则表示输入结束,将这些值(不包含0)建立为一个列表
# 然后再输出该列表的各元素
data_list = []
a = 1
while a:
x = int(input("请输入数字: "))
data_list.append(x)
a = x
data_list.pop()
print(data_list) |
33a96a0ff635e53ef60cd56a5d563dfe9b74e269 | niujinshuchong/stochastic_processes | /hw4/mm1_queue.py | 2,904 | 3.671875 | 4 | import numpy as np
import random
import math
import matplotlib.pyplot as plt
arrival_rate = 2
arrival_service_ratio = 0.8
service_rate = arrival_rate / arrival_service_ratio
print(1. / ( service_rate - arrival_rate), arrival_rate / (service_rate * (arrival_rate - service_rate)))
# simulation
trial = 100000
# since ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.