blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
57fa084afcfb0091f6c766b5949814a45ccf583c | orenlivne/euler | /rosalind/conv/rosalind_conv.py | 2,276 | 3.984375 | 4 | '''
============================================================
http://rosalind.info/problems/conv
A multiset is a generalization of the notion of set to include a collection of objects in which each object may occur more than once (the order in which objects are given is still unimportant). For a multiset S, the mu... |
842e59304fab535a9bb458d825dc438ada322848 | RS-Yoo/Algorithms | /Kattis/inverted_deck.py | 681 | 3.65625 | 4 |
def invert_deck(n, li):
sorted_li = sorted(li)
left = 0
right = n - 1
while left < n and li[left] == sorted_li[left]:
left += 1
if left == n:
left = n//2
right = n//2
else:
while li[right] == sorted_li[right]:
right -= 1
result = []
result ... |
ffd3d4896c62590682ad78d59b3968a286505ea4 | pucminas-luigidomenico/comp-grafica | /py-paint/pypaint/algorithm/bezier.py | 2,015 | 3.640625 | 4 | from functools import lru_cache, reduce
@lru_cache(maxsize=None)
def pascalTriangle(n):
""" Retorna a enésima linha do triângulo de pascal.
@param n int iniciando de 0
@return lista de inteiros contendo os valores referentes a
enésima linha do triângulod e pascal.
"""
# Inicializa o triâ... |
a7cb3b3b19b45eea40b794f2088cbcbbe2098a04 | TheEnjoy/Hyperskill | /Python/Problems/Half-life/task.py | 203 | 3.734375 | 4 | atoms, quantity = (int(input()) for i in range(2))
# N == atoms, R == Quantity, T == half_life
half_life = 0
while quantity < atoms:
half_life += 12
quantity += 1
atoms /= 2
print(half_life)
|
cbd9097757079d0fac515932930e424df535bc3a | IvanBarlianto/PythonFundamental | /Python/00 - Template/Main.py | 9,178 | 3.890625 | 4 | """ Bab 1
Mari belajar Python Basic """
print("Hello")
print("World!!!")
# Contoh sebagai komen/penanda
a = 10 #disini juga bisa sebagai penanda
Panjang = 1000
"""Contoh komen
multiline"""
print(a)
print("Nilai Panjang = ", Panjang)
""" Bab 2
Penamaan """
nilai_y = 77
Juta10 = 10000000
"""Jika ada... |
5a4104edf511b89623f7ecaaa3ab5926a4ba5104 | gvyogeesh/python_dsa | /Heap/minrope.py | 1,422 | 4.5 | 4 |
'''
Connect n ropes with minimum cost
There are given n ropes of different lengths, we need to connect
these
ropes into one rope. The cost to connect two ropes is equal to sum
of their lengths. We need to connect the ropes with minimum cost.
For example if we are given 4 ropes of lengths 4, 3, 2 and 6.
We can co... |
2ea2272389fae63809ad3d549670a9171a6320aa | chrisreddersen/BookandInventory.py | /unittest.py | 810 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 4 11:39:31 2018
@author: chris
"""
import unittest
from book_inventory import Inventory as library
#created my test class after importing my book_inventory.py
class BookInventoryTester(unittest.TestCase):
# I struggled to get this to work. ... |
1a715fa3817a39de55102de9e4cdced168a2db48 | keyehzy/Kattis-problems | /filip.py | 249 | 3.515625 | 4 | def filip():
n1, n2 = map(list, input().split())
temp = n1[0]
n1[0] = n1[-1]
n1[-1] = temp
temp = n2[0]
n2[0] = n2[-1]
n2[-1] = temp
print(''.join(max(n1, n2)))
return
if __name__ == '__main__':
filip()
|
4b5955a5b67f8aef2ad04fa178ea7f22a1ddef29 | Ivanqza/Python | /Python Basics/pythonProject11/05. Account Balance.py | 296 | 3.921875 | 4 | total = 0
command = input()
while command != "NoMoreMoney":
current_amount = float(command)
if current_amount < 0:
print("Invalid operation!")
break
total += current_amount
print(f"Increase: {current_amount:.2f}")
command = input()
print(f"Total: {total:.2f}") |
ad2aaf476f69335bcf38919fa55417d4bf6e1ff6 | MersenneInteger/sandbox | /functional-py/lazyEval.py | 3,141 | 4.5 | 4 | ## lazy evaluation
#nested functions
def outer_function(x):
def inner_function(y):
print('outer function: {0}'.format(x))
print('inner function: {0}'.format(y))
inner_function('world')
outer_function('hello ')
#inner functions have access to outer functions variables
#inner function can chan... |
3fc828f869eecb2f993bcaa9b95d2294335b663c | kreativitea/ProjectEuler | /problems/euler021.py | 870 | 3.640625 | 4 | from eutility.eumath import divisors
def euler021(limit):
''' Amicable numbers
Let d(n) be defined as the sum of proper divisors of n (numbers less than n
which divide evenly into n). If d(a) = b and d(b) = a, where a != b, then a and b
are an amicable pair and each of a and b are called amica... |
d2e928a9cdef0825b01852dbd0ad1744b9368531 | fandres-92/pruebaPython | /06-iteradores.py | 198 | 3.75 | 4 | lenguajes = ["Python", "Java", "PHP", "JavaScript"]
#iterador
for lenguaje in lenguajes:
print(lenguaje)
for numero in range(0, 20, 2): # funcion de 0 al 20 mostrando de a 2
print(numero)
|
4e792f9191e33f565b49421e013ca882551e0530 | Jen-Monsayac/Game-of-Life | /gameoflife.py | 1,095 | 3.625 | 4 | import random
import os
import time
class GameOfLife:
row = 10
column = 10
board = []
def __init__(self, rows = 10, col = 10):
self.rows = rows
self.column = rows
self.board = self.create_grid()
def create_grid(self):
board = []
for row in r... |
86e9c47d2d0a7d4474a3179ac76c146d4929ac3f | akash20aeccse123/Python | /repeatednumber.py | 558 | 3.90625 | 4 | '''8. Program to input some numbers repeatedly and
print their sum.The program ends when the users
say no more enter(normal terminator) or program
aborts when the number entered is less than zero.'''
count=sum=0
ans='y'
while ans=='y':
num=int(input("Enter Number:"))
if num<0:
print("Number ... |
958e3b79c984b6c5c9ea49a89e0c819181473726 | esosn/euler | /24.py | 1,035 | 3.8125 | 4 | import time
import math
from queue import PriorityQueue
times = []
times.append(time.clock())
limit = 1000000
# count the number of choices represented by fixing most significant digit
# search based on desired index value
# 9! * 0 = 0 < 1000000 : 0
# 9! * 1 = 362880 < 1000000 : 1
# 9! * 2 = 725760 < 1000000 : 2
# 9!... |
adf5d793821c0d505a5d7d3459c98721068515f0 | Ahmedsebit/officespaceallocation | /tests/test_amity_functions.py | 9,509 | 3.5 | 4 | ''' Importing unittest '''
import unittest
from unittest import TestCase
from functions.amity_functions import AmityControls
from models.amity_models import Amity
from models.amity_person_models import Staff, Fellow
from models.amity_room_models import Office, LivingSpace
class AmityControlTest(TestCase):
''' Cre... |
a65e750a9c4da62d64c45c80f8698c95cba86bb4 | BenTildark/sprockets-d | /DTEC501-Lab3-2/lab3-2_q10.py | 960 | 4.4375 | 4 | """
Write a program to ask the user to enter a word whose letters are all lower case.
Display a message saying it is true or false (note the use of lower case) that the word they entered met this requirement.
Example's
Please enter a word whose letters are all lower case: lower
It is true that lower is in all lower ... |
1aca08e8520a7c674bfb9239afaf5544b8888d7d | danielchristie/The-Tech-Academy-Course-Work | /Python/Python 3 Essentials/files_Opening Files.py | 1,985 | 4.03125 | 4 | #!/usr/bin/python3
# functions.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
#opens file and places content into variable FH
#When just filename is specified the second argument of mode is
... |
3e215b7f86802d7ce73120dc8022651dcdbfc92a | Genskill2/02-bootcamp-estimate-pi-aayushpatidar04 | /estimate.py | 646 | 3.6875 | 4 | import math
import unittest
def wallis(n):
x = 1
for i in range(1,n+1):
x = x*(4*i**2)/(4*i**2-1)
return x*2
class TestWallis(unittest.TestCase):
def test_low_iters(self):
for i in range(0, 5):
pi = wallis(i)
self.assertTrue(abs(pi - math.pi) > 0.15, msg=f"Estimate with just ... |
e935dda79f532effba0f631ed70d2213c89124a4 | sagarkshathriyan/sagar | /sagarsln.py | 243 | 3.953125 | 4 | import random
ps=0
di=0
while True:
r=input("press r to roll the dice")
if r=="r":
di=random.randint(1,6)
print("you have got :",di)
if di==1 or di==6:
ps=di
break
print("congrats you have landed on the board.you are at:",ps) |
ddd7fbd550fb6aed13fe13a357092bc6a359f9bc | vishnuchauhan107/pythonBasicToAdvance | /python_notes_by_vishnu/python_basic_programs/program_started/factorial.py | 175 | 4.25 | 4 | num = int(input("enter the number:"))
fact = 1
for i in range(1,num+1):
fact = fact*i
print("factorial of",num,"is",fact)
# out-enter the number:5
# factorial of 5 is 120
|
24d087ac3cd262f92acb509b838faf1dbca1aaa5 | SigridHo/DenseBlockDetection | /Final-Submission/addLastColumn.py | 458 | 3.65625 | 4 | import csv
import sys
def main(infile, outfile):
out = csv.writer(open(outfile, 'w'))
f = open(infile, 'r')
lines = f.readlines()
for line in lines:
line = line.strip().split(',')
line.append('1')
out.writerow(line)
if __name__ == '__main__':
# sys.argv[1] is the original c... |
2d3d1010477ad1ebe97bac124b4352464251960c | YangStark/32ics | /Project2/echoclient.py | 5,221 | 4.59375 | 5 | # echo_client.py
#
# ICS 32 Spring 2017
# Code Example
#
# This is an example of the raw materials used to connect a Python
# program to another program using a socket. While there are things
# about our design that could probably be better, this at least
# demonstrates how the necessary parts of the Python St... |
e38900a3206b043fcc77ac54790f993655be4427 | jsong00505/CodingStudy | /coursera/algorithms/part1/week1/analysis_of_algorithms/binary_search_test.py | 781 | 4.15625 | 4 | import random
import unittest
from coursera.algorithms.part1.week1.analysis_of_algorithms.binary_search import BinarySearch
class MyTestCase(unittest.TestCase):
def test_binary_search_1(self):
n = random.randint(100, 1000)
l = [i for i in range(n)]
target = random.randint(0, n)
ex... |
2770bcf0df0cccb976c538157432ed4c8782bc25 | MariamBilal/TitanicSurvival_Kaggle | /Titanic_project/titanic_survival.py | 4,418 | 3.71875 | 4 | """
Titanic Survival Prediction
"""
""" ---------------------- Training ----------------------- """
# ------- importing liabraries
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn import tree
# --------- importing training dataset
train_dataset =... |
d9f1077561b83b6555ef39cbfc71c8eef091c88f | afifahfq/Tucil1-Stima-13519183 | /src/13519183.py | 6,447 | 3.765625 | 4 | # Nama : Afifah Fathimah Q
# NIM : 13519183
# Kelas : K-04
# PROGRAM PENYELESAIAN CRYPTARITHMATIC DENGAN BRUTE FORCE
import time
#### Procedure dan Function ####
def chartoint(huruf, angka, curr) :
# Fungsi untuk mengonversi huruf menjadi angka
'''
KAMUS LOKAL
indeks : integer
ALGORITMA
'''
... |
a12249656739ba0238f71defad329a53ba5fb45c | Rohit5551998/Complete-Python-Developer-2021 | /Error Handling/Error Handling 3.py | 377 | 3.90625 | 4 | #Error Handling
while True:
try:
age = int(input("Enter a number: "))
10/age
raise ValueError('Hey cut it out')
# except ValueError:
# print("Please enter a number.")
# continue
except ZeroDivisionError:
print("Please enter age higher than 0.")
break
else:
print("Thank You!")
break
finally:
pr... |
5347687c5562ef77d41e1cd9559c234e0fe8a07e | Megamusz/algorithmsilluminated | /algorithms/union_find.py | 1,650 | 3.875 | 4 |
class UnionFind(object):
def __init__(self):
self.leader = {} # record the leader for each object {x: x, y: x, z: x}
self.group = {} #record the items under each group, index by leader {x: {x, y, z}}
def insert(self, x):
assert(x not in self.leader)
self.leader[x] = x
s... |
7015b3ad96acc2d2baeab4d9aec1302c8b9b2c00 | dhruv4500/Python-Doctor | /My First Game Using Python.py | 3,183 | 4.09375 | 4 | # My First Game Using Python
#Game On Squaring numbers
#Patterns, Table of a number, Printing a factorial
#And a report Card
"""Following is for asking normal
... |
74170412a780a31ea3634389fce8eb44d99dea39 | DinakarBijili/Data-structures-and-Algorithms | /LINKED_LIST/Middle of the Linked List.py | 1,851 | 4.21875 | 4 | """
Middle of the Linked List
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.... |
e7b83ce24b3def7a7717f8a2d6805d678e8a6a60 | xirain/realpython-test | /sql/assignment3b.py | 903 | 4.3125 | 4 | # assignment3b.py
import sqlite3
import sys
sql = {"average":"SELECT AVG(num) FROM numbers",
"maximum":"SELECT MAX(num) FROM numbers",
"minimum":"SELECT MIN(num) FROM numbers",
"sum":"SELECT SUM(num) FROM numbers"
}
prompt="""
Select the operation that you want to perform [1-5]:
1. Average
2. Max
3. ... |
89d601003cb02b392c0a6b206ff30d62380599ee | Weltburger/Python | /Laba1/7/7.py | 566 | 4 | 4 | # text = str(input('Введите текст: ')).split()
# arr = [i for i in text] # Генератор списков
# print(arr)
# for i in range(len(arr)):
# if arr[i].startswith('www.'):
# arr[i] = 'http://' + arr[i]
# if not arr[i].endswith('.com'):
# arr[i] += '.com'
# print(arr)
def check(txt):
if txt.star... |
f630a4ede20c90197922f3a42cd8fcf02563ca59 | thaolinhnp/Python_Fundamentals | /PYBai_07_project/ex09_dict.py | 2,133 | 3.546875 | 4 | # Khởi tạo
dict1 = {1: "một", 2: "hai", 3: "ba"}
dict2 = {"một": 1, "hai": 2, "ba": 3}
dict3 = {'one': 'một', 'two': 'hai', 'three': 'ba'}
# Truy xuất, lấy value dựa trên key
k1=dict1[2]
k2=dict2['ba']
k3=dict3.get('five') # --Không có sẽ trả về None
# k4=dict3["five"] # --Không có sẽ báo lỗi
dict4 = {'x': [2, 3]... |
500b1f77e481c18ba8569b5d8fb583e1fa5a23b1 | MFry/pyAlgoDataStructures | /Cracking the Coding Interview/Arrays_and_Strings/question5.py | 994 | 3.9375 | 4 | """
Implement a method of compression
"""
def basic_string_compression(to_compress):
i = 0
compressed = [[to_compress[0], 0]]
while i < len(to_compress):
char_compress = to_compress[i]
t = compressed[-1]
if compressed[-1][0] == char_compress:
compressed[-1][1] += 1
... |
70566e44508fc5d46c75ac525448af354fc4c0af | loclincy10/AdvancedPython | /webscraping - BITCOIN.py | 688 | 3.640625 | 4 | from urllib.request import urlopen
from bs4 import BeautifulSoup
webpage = 'https://www.coinbase.com/price/bitcoin'
page = urlopen(webpage) # loads a webpage into a python object
soup = BeautifulSoup(page, 'html.parser') #using beautifulsoup to parse the html page
title = soup.title
print(title.text)
span =... |
78be6cc358688482cbceead0f4a1faca3ad995a4 | oo363636/test | /Leetcode/LC003.py | 1,324 | 3.625 | 4 | """给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。"""
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
""" 我写的复杂度太高,运行时间长,可以优化
if not s:
return 0
longest_count = 1
for i in range(len(s)):
count = 1
is_repeat = set(s[i])
for j in ... |
9b4fa46fffb333a08ee59a650cd6152e8bfbb92d | Danielarwj/CSE | /notes/Daniel Remington- Medium Challenges.py | 711 | 3.796875 | 4 | # This is challenge 5
def challenge1(radius):
return 3.14*(radius**2)
print(challenge1(1.1))
# This is challenge 6
def challenge2(radius):
return(4/3)*(3.14*(radius**3))
print(challenge2(5))
# This is challenge 7
def challenge3(number):
return number+(number+number)+(number+number+number)
print(... |
3a1cd5abb4967304dd1e6b0a70b420a5469c8537 | sssouth/south | /输入字符串(大写)到文件text中.py | 333 | 3.921875 | 4 | import string
str=input("Please input str:")#输入一个字符串
print(str)
STR=str.upper()#将所有小写转换成大写
print(STR)
fo=open("text.txt","w")#打开文件
fo.write(STR)#将字符串写入文件
fo.close()#关闭文件
print("文件是否被关闭:%s"%fo.closed)#判断文件是否被关闭,若返回true,则关闭
|
5a1ab19703177f9e6b876e5c0364508acb91bdfe | ys2542/Web-Server-and-UDP-Pinger | /UDPPingerServer.py | 1,366 | 3.6875 | 4 | # Name: Shen, Yulin
# NetID: ys2542
# UDPPingerServer.py
# The code is completely taken from companion website for the textbook in www.pearsonhighered.com/cs-resources
# I add an option in terminal command line to manually set server port number
# I add two print methods to see messages and cases of packet lost
# We ... |
3f015c9bec98b6cf44bfe11e2d563423e811b690 | FlorianMF/snippets | /live_plotting/live_plotting.py | 1,529 | 3.5 | 4 | import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random
from itertools import count
import pandas as pd
index = count()
def plot_data(filepath='data.csv'):
# read the csv file with the pandas lib and extract the values into lists
data = pd.read_csv(filepath)
x = ... |
d73628f376ab58a8e56bfe495eb1eae1c3926474 | wiput1999/leetcode | /to-lower-case.py | 126 | 3.71875 | 4 | """
LeetCode : To Lower Case (Easy)
Python 3
"""
class Solution:
def toLowerCase(self, str):
return str.lower()
|
00aa17db1af89fa8518807ee91f81b0a1a6d7bc4 | orengoa0459/cti110 | /P5HW2_RockPaperScissors_AnthonyOrengo.py | 3,000 | 4.46875 | 4 | # This program is a version of the game rock, paper, scissors.
# 07/04/2019
# CTI-110 P5HW2_RockPaperScissors
# Anthony Orengo
#
# 1.) Create funtion called main()
# 2.) Import random module
# create funtion called number = random.randint(1, 3)
#
# 3.) Declare variables
# rock = "Rock"
# ... |
e5a581e5256d2adcd95b5201bd3085ad7538dc38 | dehabalkis/PythonProject | /Quarter of Month.py | 454 | 3.671875 | 4 | #Welche Quarter of Month
def quarter_of(month):
zahl = int(month)
if 1 <= zahl <= 3:
return print(1)
elif 4 <= zahl <= 6:
return print(2)
elif 7 <= zahl <= 9:
return print(3)
elif 10 <= zahl <= 12:
... |
f2f2a1e1515282cbcc2786411437c037e146b7f8 | hujialiang2020/mycode | /python2/11.py | 545 | 3.75 | 4 | p_score=int(input('请输入您的Python成绩:'))
m_score=int(input('请输入您的数学成绩:'))
if p_score>=90:
if m_score>=90:
print('优秀')
elif m_score<60:
print('偏科')
else:
print('中等偏上')
elif p_score<60:
if m_score>=90:
print('偏科')
elif m_score<60:
print('很差')
else:
print... |
3a4013ee8050e8f56a91257fa660ec033da39e88 | jyl7094/blackjack | /blackjack.py | 7,983 | 3.6875 | 4 | from random import shuffle
class Card:
_values = {'Ace': 11, 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6,
'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10,
'King': 10}
def __init__(self, suit, rank):
self._suit = suit
self._rank = ... |
88682f0d5a8fe75156ed4338eae0fb008f1b8dcc | armandyam/euler_projects | /py/euler_55.py | 571 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Ajay Rangarajan, Jeyashree Krishnan"
__email__ = "rangarajan, krishnan@aices.rwth-aachen.de"
import numpy as np
import math
def is_palindrome(number):
rev_number = str(number)[::-1]
if(str(number)==rev_number):
return True
else:
return False
def fi... |
5fa1e0320ab45b83715785f4cddb5b18e4879017 | mehmetkarayel18/8.hafta_odevler-Fonksiyonlar | /8.hafta 1. ödevasal tesbiti.py | 723 | 3.5625 | 4 |
def fonk(a):
bölenler=[]
for i in range(1,a+1):
kalan=a%i
if kalan==0:
bölenler=bölenler+[i]
g_bölen=bölenler[:]
g_bölen.remove(1)
g_bölen.remove(a)
if len(g_bölen)==0:
return "Bu sayı asaldır"
else:
return "Bu sayı asal değildir"
wh... |
8c04438d7ff801a77ebd7cb456df4b423d26d742 | antoniorcn/fatec-2019-2s | /djd-prog2/noite-aula3/tabuada.py | 258 | 3.59375 | 4 | n = 1
while n <= 10:
indice = 0
while indice <= 10:
resultado = n * indice
# print(n, " X ", indice, " = ", resultado)
print("{} X {} = {}".format(n, indice, resultado))
indice = indice + 1
n = n + 1
print("")
|
a4de4a31122b5d0397793add9465a4a57cd1fc4a | carriegrossman/week_one | /small.py | 542 | 3.546875 | 4 | #ex1
# list = [1, 2, 3, 4, 5]
# print(sum(list))
# #ex2
# num = [12, 55, 326, 86, 119]
# print(max(num))
#ex3
# list = [403, 54, 1054, 11, 785]
# print(min(list))
#ex4
# list = [692, 139, 1234, 901, 16]
# for num in list:
# if num % 2 == 0:
# print(num)
#ex5
# list = [-12, 69, 429, -3, 75]
# for num in ... |
01a949535dcde4ef21dbe734bc614305100b34c9 | bhavya-variya/python-assignment-letsupgrade | /day6assignment1.py | 143 | 3.953125 | 4 | list1 = [1,2,3,4,5,7,8]
list2 = ['a','b','c','d','e']
d1 = {list1[each]:list2[each] for each in range(min(len(list1),len(list2)))}
print(d1) |
9d2890494b198cb07f35ed379b39563113e3c53d | bercik29/pythoncourse | /ulohastreda.py | 979 | 3.5 | 4 | #!/usr/bin/env pyhon
vals = '1@2@3@4@5@6@7@8@9@10'
splitted = vals.split('@')
print(splitted)
suma = 0
for i in splitted:
suma += int(i)
print(suma)
alpha = 0
digits = 0
other = 0
spaces = 0
numlines = 0
with open('data.txt') as f:
for lines in f:
while lines:
... |
b08b23bb2b7a650b803a64b54d59e920709a8f01 | ShikhaShrivastava/Python-core | /OOP Concept/Pickle Unpickle/EmployeeInfo.py | 265 | 3.609375 | 4 | import pickle
class Employee:
def __init__(self,name,age,salary):
self.name=name
self.age=age
self.salary=salary
def display(self):
print('Name:',self.name)
print('Age:',self.age)
print('Marks:',self.salary)
|
97afbab732235c2cc42c01a22c2333f91902c9be | freddycordovadd/python-examples | /BusquedaBinaria.py | 753 | 3.828125 | 4 |
# Busqueda binaria
"""
Optimiza las busquedas para tablas de grandes volumenes (millones
de filas) unicamente funciona con data numerica ordenada
"""
def b_binaria(numeros, n_to_find, low, high):
if low > high:
return False
mid = int((low + high) / 2)
if numeros[mid] == n_to_find:
retur... |
abf493b9d2d1d1f64716eb5431a1b9214a89692c | acnokego/LeetCode | /283_move_zeroes/try.py | 906 | 3.53125 | 4 | class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
"""
Complexity: O(n)
Space: O(1)
maintain the index of last zero, if there is nonzero value then swap
i... |
cd9d487f251717854cf59dc16b59341e34fc37fd | ToT-2020-PA/digital.chest | /TesteExercicios.py | 574 | 3.90625 | 4 | import math
#print ('Balanco de despesas domesticas')
#ana = float(input('Quanto gastou Ana? '))
#bia = float(input('Quanto gastou Bia? '))
#print()
#total = ana + bia
#print ('Total de gastos: R$ %s' % total)
#media = total/2
#print ('Gastos por pessoa: R$ %s' % media)
#if ana < media:
# diferenca = media... |
d8e2abecc9ea0abb67107e50ecf26b158055ef45 | Freshman23/algorithms_and_data_structures | /lesson_3/les_3_task_9.py | 838 | 4.1875 | 4 | """9. Найти максимальный элемент среди минимальных элементов столбцов матрицы."""
from random import randint
rows = 10
cols = 10
matrix = [[randint(0, 30) for col in range(cols)] for row in range(rows)]
print('Матрица:')
for row in matrix:
print(row)
row_mins = []
for col in range(cols):
min_el = matrix[0]... |
7b3f7555ce7adeda2aadaae1814a70f3697fdb2e | Subhasishbasak/Python | /Miscellaneous/while.py | 145 | 3.890625 | 4 | x = 10
while x > 0:
print(x)
x = x - 1
print("....")
for i in "Python":
print(i)
print("....")
for i in [1,2,3,4,5]:
print(i)
|
8406d08023b63704c4b4d9877039ac41c6e856c0 | BillyCussen/CodingPractice | /Python/Data Structures & Algorithms Module - Python/Week11/BubbleSort/BubbleSort.py | 587 | 4.15625 | 4 | """
BubbleSort.py
Billy Cussen
14/12/2020
"""
def bubbleSort(current):
for i in range(len(current)-1):
print("Starting Bubble Sort at Position "+str(i+1))
for j in range(len(current)-i-1):
if current[j] > current[j+1]:
print("Swapping "+str(current[j])+" with "+str(curre... |
27ad0d22248eec713ed9267cc0adf82231a3ec8c | vivekanandilango/Python | /practice/cash_register.py | 2,845 | 3.6875 | 4 | class CashRegister(object):
def __init__(self):
self.register = {25: 100, 10: 100, 5: 100, 1: 100}
self.total = 0
for denomination, count in self.register.items():
self.total += denomination*count
def getTotal(self):
return self.total
def getDenominations(self):
return self.register
def updateTotal(... |
5b8da4f022ee7a82e9bc2337308e3fde97388905 | rwieckowski/project-euler-python | /euler150.py | 519 | 3.71875 | 4 | """
In a triangular array of positive and negative integers we wish to
find a subtriangle such that the sum of the numbers it contains is the
smallest possible
In the example below it can be easily verified that the marked
triangle satisfies this condition having a sum of minus42
<div style="text-align:center;">
<i... |
5e1660ad9b99807dde920589af8d87f0dd2fdbe2 | davidlinrin/lighthouse-data-notes | /Week_2/Day_5/assessment-exam-student-python/answers/question_01.py | 326 | 4.21875 | 4 | """
Create a function that returns the mean of all digits.
Example:
mean(42) ➞ 3.0
mean(12345) ➞ 3.0
mean(666) ➞ 6.0
Notes:
- Function should always return float
"""
def mean(digits):
digit = str(digits)
l = len(digit)
sum = 0
for x in digit:
sum += int(x)
return(sum/l) |
574e9a0a5ddd1b96c45a12d4b51f4a5730365ecf | nomura-takahiro/study | /class/special_method.py | 745 | 3.859375 | 4 |
class Lion:
def __init__(self, name):
self.name = name
# 特殊メソッド
# print()にオブジェクトを渡すと、objectクラスから継承した__repr__メソッドを呼び出し、
# 返ってきた値を出力する
# __repr__メソッドをオーバーライドして出力したい内容に変更が可能
def __repr__(self):
return self.name
lion = Lion("Cha-")
# _repr__をオーバーライドしないとアドレスを表示する
print(lion)
print(Lion)
class AlwaysPositive:... |
9d266f72908ae46e74576df47fbad076979e0877 | JoannaEbreso/PythonProgress | /ThreeDigits.py | 137 | 3.609375 | 4 | x=100
counter=0
while x <=999:
if x%17==0:
print(x)
counter+=1
x += 1
print("The total is:"+ str(counter))
|
3baa7b4bb38cddfb280652b98eeac47a12395ba6 | solaimanhridoy/penguin-swe-intern | /task_3/services/Courses.py | 291 | 3.5625 | 4 | class Courses():
def __init__(self, course_name: list, teacher_name: str):
self._course = course_name
self._name = teacher_name
def course_list(self):
return f"{self._course}"
def course_assigned(self):
return f"{self._course}, {self._name}" |
2d4379fbecc997acb3a21a275d2b5073c0fd0a8a | Sayanik-tech/Simple_Linear_Regression | /Practice_Simple_Linear_Regression.py | 1,852 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# In[6]:
dataset = pd.read_csv('Salary_Data.csv')
print(dataset)
# In[7]:
dataset.info()
# In[9]:
x = dataset.iloc[:,:-1].values
y = dataset.iloc[:,-1].values
print(x)
# In[10]:
print... |
857721476df200f91a26bc88145dc54420219c28 | huilight/PythonPractice | /spider-l/test720.py | 995 | 3.6875 | 4 | """
7月20号练习
爬取知乎首页问题链接
"""
from urllib.parse import urljoin
import re
import requests
# re.match(pattern, string) 返回一个列表,第一项为匹配到的字符串
def main():
headers = {'user-agent':'Baiduspider'}
proxies = {'http': 'http://122.114.31.177:808'}
base_url = 'https://www.zhihu.com'
seed_url = urljoin(base_url, 'ex... |
7c70c4337c31c4baa3f718a3c10cd5cc86dfec83 | martybillingsley/tinkRworks | /turtleDraw/draw.py | 304 | 3.8125 | 4 | import turtle
# create a graphic window for the turtle to draw on
win = turtle.Screen()
# create a turtle named bob
alex = turtle.Turtle()
# put your code above this line
# this command is needed to make the GUI window work properly
# and should always be the last line in the program
turtle.done()
|
e42c89b391009fdbbf5a88eaaa92570a3128c648 | 102206502/math-questions-answer-marker | /answer marker/time_plus.py | 1,023 | 3.6875 | 4 | # -*- coding: utf-8 -*-
from datetime import datetime
time_zero = datetime.strptime('00:00:00', '%H:%M:%S')
'''add time string by format
paramater
----------
FMT : string
the format string of time string
time_str1 : string
time_str2 : string
'''
def time_str_plus(FMT, time_str1, time_str2):
time_zer... |
34fe43e115e30dac639f14f90dd48f3330d739e7 | thecourtofowls/LeetCodeChallenges | /LeetCodeChallenges/containerWithMostWater.py | 1,453 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
11. Container With Most Water
Given n non-negative integers a1, a2, ..., an , where each represents a point at
coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the
line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis
forms a contain... |
c41d87550b308b7a350f074778ca4fe97e56816c | forbearing/mypython | /Scrapy/1/2_网络爬虫/4_parse_library/3.2_bs4_节点选择器.py | 3,714 | 4.0625 | 4 | 1:选择元素
1:经过选择器后输出的类型是 bs4.element.Tag 类型,这是 BeautifulSoup 中一个重要的数据结构
2:Tag 具有一些属性,比如 string 属性
3:soup.p, 当有多个节点时,这种选择方法只会选择到第一个匹配的节点,其后的所有的节点都会被忽略
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class='title' name='dromous'><b>The Dormouse's story</b></p>
<p c... |
9efa0862a739d77dcc5b6b2aea6f2db55e0059c6 | authorofnaught/ling402-examples | /week/07/cards.py | 621 | 3.875 | 4 | #!/usr/bin/python3
import random
class PlayingCard:
def __init__(self, value, suit):
self.suit = suit
self.value = value
def __str__(self):
return self.value + " of " + self.suit
if __name__ == "__main__":
suits = ["♠︎", "♣︎", "♥︎", "♦︎"]
values = ["2","3","4","5","6","7","8",... |
fb64d6f2a61ee06aa606b0f7aace3666003984fc | guilhermebaos/Curso-em-Video-Python | /1_Python/Desafios/007_Média_dois_valores.py | 157 | 3.765625 | 4 | n1 = float(input('Escreve uma das tuas notas:'))
n2 = float(input('Agora escreve outra nota'))
s = (n1 + n2) / 2
print('A média das notas é {}'.format(s))
|
d9af0d4f2397f850eb78766e90830b9d14a77c14 | riversxiao/hackerrank | /python/map_and_lambda.py | 531 | 4.03125 | 4 | fib = lambda y: y if y < 2 else fib(y - 1) + fib(y - 2)
print map(lambda x: x**3, map(fib, range(input())))
###
cube = lambda x: x**3# complete the lambda function
def fibonacci(n):
# return a list of fibonacci numbers
lis = [0,1]
for i in range(2,n):
lis.append(lis[i-2] + lis[i-1])
return(lis[... |
efd7861b6a8bc1080ffe687c491379e2ebe0b1f0 | xc145214/practise | /python/test.py | 12,675 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
这一段是这个程序的注释内容:
所有代码来自w3c
"""
# 获取本机IP
import socket
hostname = socket.gethostname()
localIP = socket.gethostbyname(hostname)#得到本地ip
print localIP
#输出
print "hello Python"
#缩进
if True:
print "answer"
print "True"
else:
print "answer",
print "false"
#字符串
word = 'word'
sentence = "this... |
1bf421c2f999b5530e952147c2b2bb9f29ff9de5 | yummybian/python-practice-book | /ch02/wrap.py | 568 | 3.671875 | 4 | import sys
def wrap(filename, width):
res = []
w = int(width)
with open(filename) as f:
for line in f:
for i in range(0, len(line), w):
if len(line) <= i+w:
res.append(line[i:].strip())
break;
res.append(line[i:i+w... |
704f0c90e1da811145c39e6da2c144d794d94e08 | sponja23/Isaac | /physics.py | 9,968 | 3.640625 | 4 | import numpy as np
from functools import wraps
from copy import copy
from abc import ABC, abstractmethod
def vector_argument(function):
@wraps(function)
def vector_arg_only(self, arg):
if type(arg) is not Vector:
arg = Vector(*arg)
return function(self, arg)
return vector_arg_o... |
6d6de5609fe13b79d4a9788383c39a935ed36105 | kyooryoo/Python-For-Data-Science | /2_DataVisualization.py | 4,157 | 4.25 | 4 | # for installing the library of matplotlib:
# http://matplotlib.org/users/installing.html#installing-an-official-release
# this script is written and tested in windows 10 with python v3
from matplotlib import pyplot as plt
# use line chart to show the trend of some data
year = [1950,1960,1970,1980,1990,2000,2010]
gdp... |
b20d5474eddc0e1cbbd28a697eca7af2e9c64def | Banehowl/JuneDailyCode2021 | /DailyCode06082021.py | 440 | 4.125 | 4 | # -------------------------------------------------------------
# # Daily Code 06/07/2021
# "(One Line) Return the Subtration" Lesson from edabit.com
# Coded by: Banehowl
# -------------------------------------------------------------
# Create a function that takes two numbers as arguments and return the sub... |
5b0ef2afe873518dafbbeb10b2d9dcfd766a3738 | Mr-Coxall/Wed-08 | /the_lie.py | 393 | 3.8125 | 4 | # coding: utf-8
from copy import deepcopy
variable1 = 5
variable2 = variable1
variable1 = 6
print(variable1)
print(variable2)
print('')
# now the lie!
colours1 = ["red", "green"]
colours2 = colours1
colours2[1] = "blue"
print(colours1)
print(colours2)
print('')
# now the lie fix to the lie
thing1 = ["red", "green"]
... |
62cbd08e331101744cb6ad62cb35e9cf6f0cc041 | shen-huang/selfteaching-python-camp | /19100303/liyan2019/d5_exercise_array.py | 535 | 3.578125 | 4 | #将数组翻转
vec=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
vec.reverse()
print(vec)
#翻转后数组拼接成字符串
str1=[str(i)for i in vec] # 数字转成字符串
print(str1)
str2="".join(str1)
print(str2)# 字符串拼接
str3=str2[2:8]#字符串切片方式取出第3到底8个字符
print(str3)
str4=''.join(str3[i] for i in range(len(str3)-1,-1,-1)) #将字符串反转 意义待理解【@@@@】
print(str4)
a=int(str4) #将字符... |
19bf407a5e17658ba2e6415c46add2a89ca5f6d5 | oguerrerog/fundamentos-python | /Funciones Basicas II.py | 3,302 | 4 | 4 | # Ejercicios #1 - Cuenta regresiva : crea una función que acepte un número como entrada.
# Devuelve una nueva lista que cuenta hacia atrás en uno, desde el número
# (como el elemento 0) hasta 0 (como el último elemento).
# ... |
514f9ae7b6b72a339eacd56564043cb153f5879c | Repidus/python-and-ruby | /Input_Output/2.py | 226 | 3.84375 | 4 | in_str = input("Enter the password: ")
real_Albert = "22"
real_Bethany = "33"
if in_str == real_Albert:
print("Welcome, Albert!")
elif in_str == real_Bethany:
print("Welcome, Bethany!")
else:
print("Who are you?") |
441d1c3427fbcedd35b464a063b1f1c0fd37d107 | vrashi/python-coding-practice | /rectangle.py | 187 | 3.90625 | 4 | #program to find the area of recrangle
l = int(input("enter the length of the rectangle"))
b = int(input("enter the breath of the rectangle"))
print("area of the rectangle is "+ str(l*b)) |
9364c1aad37e9bd1ca6a6b8be2df12782b6aac90 | aguecig/Project-Euler | /Problems 71 - 80/pe_74.py | 759 | 3.546875 | 4 | import math
def factdigitsum(x):
summ = 0
for j in range(len(x)):
summ = summ + math.factorial(int(x[j]))
return summ
tracker = []
# So after brute forcing the approach, I realized that the output
# was showing that none of the values included a 5, 6 or 8. I'm
# not sure why this is the case mathematically, but... |
264ea4542b6d33eeba139e1195b6e25c2a2b8c6f | jlavileze/Project-Euler | /027. Quadratic primes/27. Quadratic Primes.py | 785 | 3.703125 | 4 | import math
def polynomial(n, a, b):
y = n ** 2 + a * n + b
return y
def isPrime(x):
for i in range(2, int(math.ceil(math.sqrt(x)))+1):
if x % i == 0:
return False
else:
return True
def test_polynomials_in_range(x):
largest_product = 1
prime_count = 0
max_prime... |
64aaca60e929d70008fe7ddd48f724c8fca4e906 | daniel-reich/turbo-robot | /Qqd2symFeFe4y5YGG_15.py | 932 | 4.21875 | 4 | """
The 2nd of February 2020 is a palindromic date in both _dd/mm/yyyy_ and
_mm/dd/yyyy_ format (02/02/2020). Given a `date` in _dd/mm/yyyy_ format,
return `True` if the date is **palindromic** in **both date formats** ,
otherwise return `False`.
### Examples
palindromic_date("02/02/2020") ➞ True
pali... |
25b364bb1fa536ec1f7c9dc95b1bfb43326d89ea | edu-athensoft/stem1401python_student | /py200727_python2/day31_py200818/func_recursive_2.py | 974 | 4.21875 | 4 | """
1 + 2 + 3 + 4 + ... + 10 + (996)
f(n) = n + f(n-1)
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
def f(n):
return n + f(n-1)
print(f(10))
advantages and disadvantages
advantages
1. recursive functions make the code look clean and elegant
2. a complex task can be b... |
017d5d9c8a881561b9805255df54a666dd1d2556 | anzhihe/learning | /python/source_code/AutomatePython/09-organize-file/filesize.py | 545 | 3.71875 | 4 | import os
import shutil
def search(dir, size):
# dir exists
if not os.path.exists(dir):
print('Directory ' + dir + ' not exists.')
# list all files in dir
for dirpath, dirnames, filenames in os.walk(dir):
for filename in filenames:
filepath = os.path.join(dirpath, filename)... |
0b541c06a55954a41a1cf02de616696c28d9abf8 | DayGitH/Python-Challenges | /DailyProgrammer/DP20121023B.py | 1,571 | 4.1875 | 4 | """
[10/23/2012] Challenge #106 [Intermediate] (Jugs)
https://www.reddit.com/r/dailyprogrammer/comments/11xjfd/10232012_challenge_106_intermediate_jugs/
There exists a problem for which you must get exactly 4 gallons of liquid, using only a 3 gallon jug and a 5 gallon
jug. You must fill, empty, and/or transfer liquid... |
2e3c2e67a579927e3f2f46c99da55bce05f98532 | maitreyir/RegularExpressions | /Demo1.py | 561 | 4.25 | 4 | #find match if it occurs at start of the string
import re
string =input("Enter string:")
#return match object
result = re.match(r"Master",string)
if result == None:
print("Match not found")
else:
print("match found")
#find the match any where from the string
import re
st =input("Enter string")
#... |
8eb57e13dabe175644f7b515e6c0fe3a9083fb36 | iamGauravMehta/Hackerrank-Problem-Solving | /Algorithms/Implementation/cats-and-a-mouse.py | 637 | 3.609375 | 4 | # Cats and a Mouse
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/cats-and-a-mouse/problem
# Reference: https://en.wikipedia.org/wiki/Euclidean_distance
# Function catch_mouse is big-O notation = O(1)
import math
def catch_mouse(x, y, z):
# Euclidean distance
cat_1 = math.sqrt((x ... |
8d073db5efd6d99b04bd2a6533627dffdc44da70 | nazhimkalam/Complete-Python-Crash-Couse-Tutorials-Available | /completed Tutorials/RegEx.py | 578 | 4.21875 | 4 | # A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
# RegEx can be used to check if a string contains the specified search pattern.
# Python has a built-in package called re, which can be used to work with Regular Expressions.
# Import the re module
import re
#Check if the strin... |
a9e4235e36e0a07080676759c79ee4bdb25f7221 | ShekhRaselMasrurAhmmadNissan/URI-Online-Judge | /Beginner/1003_simple_sum.py | 151 | 3.78125 | 4 | # Reading two Intiger...
A = int(input())
B = int(input())
# Sum of the number...
SOMA = A + B
# Printing the Sum...
print('SOMA = {}'.format(SOMA))
|
b2392ce65a665a541b67987e8472bf8aae252b89 | petr-tik/misc | /optimal_price.py | 714 | 3.671875 | 4 | #! /usr/bin/env python
# https://www.hackerrank.com/challenges/taum-and-bday
def solve(num_black, num_white, price_black, price_white, price_sub):
if price_black + price_sub < price_white:
return num_black*price_black + num_white*(price_black + price_sub)
elif price_white + price_sub < price_black:
... |
f24558a386bf28063201d6488aa485b69c19b5e9 | Baistan/FirstProject | /lists_tasks/Задача1.py | 91 | 3.640625 | 4 | numbers = [1,2,3,4,5,6,7]
i = 0
while i < len(numbers):
print(numbers[i])
i = i + 2 |
08cb5dc089373a3604f6c0bcc6397b61d352f5ce | jeffjeffjeffrey/advent-of-code | /2018-python/day20.py | 3,515 | 3.71875 | 4 | from queue import Queue
from re import match
data = input().strip()
def get_neighbor(room, direction):
dx = 0
dy = 0
if direction == 'N':
dy = -1
elif direction == 'S':
dy = 1
elif direction == 'E':
dx = 1
else: # 'W'
dx = -1
return (room[0] + dx, room[1] + dy)
def add_neighbor(grid, ro... |
5118c1c80a5f801fd04738a80cf7f0a5c434253b | balrog-nona/learning_python | /mini_programs/median.py | 388 | 3.609375 | 4 | seznam = []
print("Zadavej cisla a nakonec stiskni jen ENTER pro ukonceni zadavani.")
while True:
cislo = input("Zadej cislo: ")
if cislo == "":
break
cislo = int(cislo)
seznam.append(cislo)
index = int(len(seznam) / 2)
seznam_2 = sorted(seznam)
for i in seznam:
median = i - seznam_2[in... |
e4d34b0d227de3bf6fa8c6086b5e8344e43e2e98 | Kattenelvis/SocietySimulator | /logic/mapGeneration.py | 516 | 3.5625 | 4 | def generateTiles(xSize, ySize, width, height):
Map = [[None for i in range(xSize)] for j in range(ySize)]
for x in range(xSize):
for y in range(ySize):
#maths for this https://www.desmos.com/calculator/ttdj2hug5v
#Note: Please clean this stuff up later.
n = ceil(wid... |
e031b675f4c63817434e614bb4488ff6b003631e | carlosvcerqueira/Projetos-Python | /ex041.py | 479 | 4 | 4 | from datetime import date
ano = int(input('Ano de nascimento: '))
atual = date.today().year
idade = atual - ano
print('Atletas nascidos em {} tem {} anos em {}.'.format(ano, idade, atual))
if idade <= 9:
print('Sua categoria é a MIRIM.')
elif idade <= 14:
print('Sua categoria é a INFANTIL.')
elif idade... |
ee34a8e743c710b78d3447dab30ef430308271d2 | shekharkrishna/Amazon-2020-Prep | /Online Assesment/Largest Item Association/1LargestItemAssociation.py | 2,768 | 3.59375 | 4 |
# Most if not all of the top upvoted solutions on here are broken because you are not guaranteed that
# the order of the elements given in items array is in a way such that the root elements of a group are given first.
# Because most of the below solutions don't create a back edge from the 2nd item in the group to t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.