blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f9e5997cd081b33a4a540d12e9460f13d873c4ca | dhnanj2/TS-Codes | /pangram2.py | 371 | 4.03125 | 4 | import string
all_alphabets = set(string.ascii_lowercase)
def isPangram(input_string):
return set(input_string.lower()) >= all_alphabets
input1 = "Pack my box with five dozen liquor jugs"
input2 = "Old brother fox jumps over the lazy dog"
if(isPangram(input1) == True):
print("Yes")
else:
print("No")
if(isPangram(... |
0ddc33f9f61658e171d76996c16bd613555b9a3a | AlaaBejaoui/AberdeenProject | /AberdeenProject/utilities/loadPickledData.py | 377 | 3.65625 | 4 | import pickle
def loadPickledData(filepath):
"""
This function reads the pickled representation of an object from a file
:param filepath: Path to the pickled file
:type filepath: String
:return: The reconstituted dataframe
:rtype: Pandas dataframe
"""
with open(filepath, 'rb') as f:... |
dfb5e4b89f823133862a7004858ce8ce8f395801 | Airomantic/alogrithm_ACM | /完整整理/动态规划/鸡蛋掉落_困难_动态规划+二分查找(递归).py | 1,633 | 3.71875 | 4 |
"""
https://leetcode-cn.com/problems/super-egg-drop/solution/ji-dan-diao-luo-by-leetcode-solution-2/
视频:https://leetcode-cn.com/problems/super-egg-drop/solution/ke-shi-hua-dpguo-cheng-by-alchemist-5r/
状态描述:
动态规划表练习:
https://alchemist-al.com/algorithms/egg-dropping-problem
"""
class Solution:
def superEggDrop(s... |
9d3aa39c4695a218200f8aa47f214224b324c8dc | alexsunseg/CYPAlejandroDG | /libro/problemas_resueltos/capitulo3/Problema3_19.py | 237 | 3.609375 | 4 | N=int(input("Ingrese un número: "))
I=1
for v in range (0,N,I):
SUM=0
J=1
for i in range (1,(I//2),J):
if (I%J)==0:
SUM+=J
J+=1
if SUM==J:
print(I, "Es un número perfecto")
I+=1
|
1ee4bee98f3b06da88ae8b407a28c8e74bf92181 | jwbaker/projecteuler | /PE30.py | 575 | 3.9375 | 4 | '''
Created on: 2013-06-28
Problem 30:
Surprisingly there are only three numbers that can be written as the sum of the fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of all these numbers is 1634... |
d5ae4327d29f6c19927c0ff598d2e7abc1391389 | hacktoolkit/code_challenges | /project_euler/python/015.py | 1,056 | 3.625 | 4 | """http://projecteuler.net/problem=015
Lattice paths
Starting in the top left corner of a 2x2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20x20 grid?
Solution by jontsai <hello@jontsai.com>
"""
from utils im... |
03a7388706d34c92c866548024c3cecb24af9d1f | pecata83/soft-uni-python-solutions | /Programing Basics Python/For Loop/11.py | 585 | 3.625 | 4 | lily_age = int(input())
washingmachine_price = float(input())
single_toy_price = int(input())
money_sum = 0
last_bday_money = 0
brother_money = 0
toys_sum = 0
for bday in range(1, lily_age + 1):
if bday % 2 == 0:
last_bday_money += 10
money_sum += last_bday_money
brother_money += 1
els... |
46a1e92098d9e280ad5b0723d6840e676e55d0cc | RaduMatees/Python | /Exam/24. Limita sir medie aritmetica.py | 257 | 3.671875 | 4 | """Limita unui sir recurent dat de media aritmetica"""
a = float(input("a= "))
b = float(input("b= "))
eps = float(input("eps= "))
x = float(a)
y = float(b)
while abs(x - y) >= eps:
z = (x+y)/2
x = y
y = z
print("Limita este" ,format(x,'.5f')) |
b11999fef45b46e6865c502afa69a2962a618c4c | bardayilmaz/270201019 | /lab9/example1.py | 95 | 3.5 | 4 | def harmonic(n):
if n == 0:
return 0
else:
return 1/n + harmonic(n-1)
print(harmonic(5)) |
60e49ddc186acb571954e51b06c00a2b9952aaa2 | david6666666/cwq | /1-11python基础/51__call__方法和可调用对象.py | 510 | 3.828125 | 4 | '''
定义了__call__方法的对象,称为“可调用对象”,即该对象可以像函数一样被调用。
'''
class SalaryAccount:
'''工资计算类'''
def __call__(self, salary):
yearSalary = salary*12
daySalary = salary//30
hourSalary = daySalary//8
return dict(monthSalary=salary,yearSalary=yearSalary,daySalary=daySalary
,hourS... |
4db8bc8d8cd9d33def71f864373acab6b9669f16 | Henrysyh2000/Assignment10 | /exist_pair.py | 988 | 3.96875 | 4 | def exist_pair(L, X):
""" Detect whether we can find two elements in L whose sum is exactly X.
:param L: List[Int] -- a python list of integers
:param X: Int -- integer X
Required runtime: Expected O(len(L))
:return: True if we can find two elements in L whose sum is exactly X. False otherwise.
... |
20630a65d9f6715309554d4686aa841077971dbf | CKanja/pythonTasks | /Arithmetic_Game.py | 983 | 4.125 | 4 | print("Welcome to the number game!")
num1 = int(input("Enter the first number "))
num2 = int(input("Enter the second number "))
operation = input("Choose an operation: addition, subtraction, division, multiplication, modulus: ")
guess = int(input("Before we calculate the answer for you, what do you think the answer is... |
e6db806d8d4c9226ec880f1cd4fd0fce5fd4699f | Winni-Lina/CodingTest | /문제08-보조.py | 192 | 3.703125 | 4 | # 8.01 문자열 arr이 "abcdefg" 일 때 다음의 값을 나타내시오(에러가)
arr = "abcdefg"
# print(arr[len(arr)]) : 에러
print(arr[3])
print(arr[6])
print(arr[0])
print(arr[-1]) |
b4eb5b7509029915d0d5ee55be9d1ca1cbe43eba | neochen2701/TQCPans | /程式語言 V2答案檔/Python/608.py | 197 | 3.59375 | 4 | score = 0
input_list = []
for i in range(10):
n = int(input())
input_list = [x + n for x in input_list]
input_list.append(n)
print('score = ' + str(sum(i > 3 for i in input_list)))
|
e09621cb976110fe291794e71c58797378d3796b | MaxKmet/Tic_Tac_Toe | /board.py | 1,997 | 3.6875 | 4 | class Board:
CELL_EMPTY = ' '
CELL_X = 'x'
CELL_0 = 'o'
CELLS = [CELL_EMPTY, CELL_X, CELL_0]
PLAYER_0 = 'x'
PLAYER_1 = 'o'
PLAYERS = [PLAYER_0, PLAYER_1]
def __init__(self, values=None):
if values is None:
values = self.CELL_EMPTY * 9
if not all(map(lambda ... |
34bc854299321af0f92852bc1fbcf44e12582efd | LoveDT/leetcode | /28 Implement strStr()/solution.py | 832 | 3.5 | 4 | class Solution:
# @param {string} haystack
# @param {string} needle
# @return {integer}
def strStr(self, haystack, needle):
length, inlen = len(haystack), len(needle)
if inlen == 0:
return 0
if length == 0:
return -1
h,n,result = 0,0,0
whil... |
dbc1e8bca05e99bb7027c81305484f2c2958bb90 | rocky/pycolumnize | /test/test_columnize.py | 5,825 | 3.5 | 4 | #!/usr/bin/env python
# -*- Python -*-
"Unit test for Columnize"
import pytest
import sys
from unittest import mock
from columnize import columnize
def test_basic():
"""Basic sanity and status testing."""
assert "1, 2, 3\n" == columnize(["1", "2", "3"], 10, ", ")
assert "1 3\n2 4\n" == columnize(["1",... |
14149875d7892406cbc90cb0e566fc71c835e720 | soumya9988/Python_Machine_Learning_Basics | /MachineLearning_udemy/sample_program2.py | 559 | 3.53125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3,4]].values
from sklearn.cluster import KMeans
wcss = []
for i in range(1, 11):
kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)
kmeans.fit(X)
wcss.append(kmeans.iner... |
53587309ca24195df44a5a69e4d3d35ee4e0f2d0 | kksante/iTrack_myLearning | /Twitter_Analytics/src/words_tweeted.py | 1,297 | 3.515625 | 4 | # Processing Data Files
# kksante
# 05JULY2015
# This program opens tweet.txt, reads it contents, determines the
# frequency of the words used and writes the results to ft1.txt
import sys # Used to handle inputs from command prompt
import os # Used to manipulate files and directories
# Variables to hold input and ou... |
d244352292bd521d5085ec7f64aac2d1411cbb07 | guptaShantanu/Python-Programs | /capitalize.py | 312 | 3.578125 | 4 | line=input().split(" ")
word=""
for i in line:
if i[0].isalpha()==False:
word=word+i+" "
else:
word=word+i.title()+" "
if word[:len(word)-1]=="Q W E R T Y U I O P A S D F G H J K L Z X C V B N M Q W E R T Y U I O P A S D F G H J K L Z X C V B N M":
print(True)
else:
print(False)
|
eda57ce1a33249da2d45ee2a959d70fcafcce691 | jogusuvarna/jala_technologies | /constructor_call.py | 164 | 3.65625 | 4 | #Try to call the constructor multiple times with the same object(*)
class A:
def __int__(self):
self.x = 10
obj = A()
obj = A()
print(obj)
print(obj)
|
55c80830dd9f346f5dd2d65d56984ea66213b2d4 | mariaelisa492/Fundamentos_python | /semana_3/programas/errado.py | 865 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 08:28:06 2021
@author: Digital
"""
# Vamos a crear una función que reduzca el número de intentos y muestre
# el mensaje al usuario para volver a ingresar el dato
def errado(cont_intentos, intentos,numero_sugerido,numero_ingresado):
# vemos si tiene chances todavia... |
70406d44a50e1ea54d451094146e87de44104ae1 | nstickney/exercism | /python/kindergarten-garden/kindergarten_garden.py | 668 | 3.65625 | 4 | class Garden(object):
species = {
'C': 'Clover',
'G': 'Grass',
'R': 'Radishes',
'V': 'Violets'
}
def __init__(self, diagram, students=None):
self.rows = diagram.split('\n')
if students is None:
self.students = ["Alice", "Bob", "Charlie", "David",... |
21018763231d9fbf0dd5bece1d6e7ce7750e43b9 | Yolanda599/Maze | /AStar.py | 12,226 | 3.515625 | 4 | from tkinter import Button
from tkinter import Tk
from tkinter import Canvas
import numpy as np
class Maze(object):
def __init__(self):
self.blockcolorIndex = 0
self.blockcolor = ['black', 'green', 'red', 'yellow'] # 障碍颜色为黑色、起点绿色 终点红色、路径黄色
self.mapStatus = np.ones((15, 15), dtype=int) ... |
8e670ce1ff3c71f6756590121cb01a5d6df70326 | goodsosbva/algorithm | /328.py | 717 | 4.125 | 4 | # 328. odd even linked list
from LinkedList import Node
def oddEvenList(head: Node) -> Node:
if head is None:
return None
odd = head
even = head.next
even_head = head.next
# 반복하면서 홀짝 노드 처리
while even and even.next:
odd.next, even.next = odd.next.next, even.next.... |
e7c4952babc496aba214d33670130aa26528b237 | ManoMambane/Python-PostgresSQL | /A Full Python Refresher/33_first_class_functions/divider.py | 258 | 3.8125 | 4 | def divide(dividend, divisor):
if divisor == 0:
raise ZeroDivisionError("Cannot divide by 0")
return dividend / divisor
def Calculate(*values, operator):
return operator(*values)
result = Calculate(25, 5, operator=divide)
print(result) |
0dcb701abfef4500d352bff0d030a8887f016461 | ThoStart/amstelhaegenezen | /library/start.py | 2,479 | 3.921875 | 4 | # Request user input the first time
def start():
print("1: Random")
print("2: Random + Hill climbing")
print("3: Random + Simulated annealing")
print("4: Greedy")
print("5: Greedy + Hill climbing")
print("6: Greedy + Simulated annealing")
# let user choose the algorithm
chosen_algorithm... |
e882792dab53595efd61b95cceb7080f0992cf30 | maigimenez/cracking | /chapter_02/tests/test_08.py | 784 | 3.65625 | 4 | import unittest
from chapter_02.src.answer_08 import circular_node
from chapter_02.src.LinkedList import LinkedList, Node
class TestIntersection(unittest.TestCase):
def test_empty_list(self):
self.assertIs(circular_node(None), None)
self.assertEqual(circular_node(LinkedList()), None)
def tes... |
791846071c882eab3924e3cddb1b4bbe5e2e942a | FaroukAjimi/holbertonschool-interview | /0x16-rotate_2d_matrix/0-rotate_2d_matrix.py | 493 | 4.03125 | 4 | #!/usr/bin/python3
"""
Rotation function
"""
def rotate_2d_matrix(matrix):
"""matrix - that roatates
2d matrix
@matrix: the matrixe to rotate"""
l = len(matrix)
for i in range(l // 2):
for y in range(i, l - i - 1):
temp = matrix[i][y]
matrix[i][y] = matrix[l - 1 - y... |
777dc6f2a80be80ab97281515cdd7234cf26dfa3 | DanPsousa/Python | /QPythonparaZumbi1.py | 173 | 4.15625 | 4 | num = int(input("Digite um numero de 0 a 10:"))
while (num < 0 or num > 10):
num = float(input("Invalido,Digite uma numero de 0 a 10: "))
print("Numero valido:",num)
|
bdff9232242963e92658b186dda002f41f5ce385 | vikramzsingh/Python | /1_2_3___n.py | 109 | 4.0625 | 4 | #Display 1,2,3,...n
n=int(input("Enter the value of n: "))
i=1
while(i<=n):
print(i)
i=i+1
|
ea32d41cb5aa1096becd4f1f8fdcea8b52f633c9 | onursengul01/Ping_Scanner_Automation- | /Ping_Scanner.py | 673 | 3.625 | 4 | import os
import pyfiglet
class Ping:
def __init__(self):
pass
def ping(self):
result = pyfiglet.figlet_format("Ping Scanner")
print(result)
ping = input("Enter an ip address to scan or a website domain\n")
os.system(f"ping {ping}")
print()
if ping == "":
... |
e5c75011af367bea4f8b636d9993cd40767f1c48 | jordanforbes/queuealgos | /sllalgos.py | 1,873 | 3.921875 | 4 | class Node:
def __init__(self, valueInput):
self.value = valueInput
self.next = None
class SLL:
def __init__(self):
self.head = None
def removefront(self):
if self.head == None:
return self
else:
self.head = self.head.next
retur... |
f7efcd2aa686c1127e362de558969e394a730e74 | umeshror/data-structures-algorithms | /palindrome/palindrome_number.py | 1,201 | 4.34375 | 4 | """
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
Example 1:
Input: x = 121
Output: true
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From ... |
e0067f4dabb6427ecc7d5a68f5faa252d02aec8b | nicolasmonteiro/Python | /Exercício(tuplas,listas e dicionário)/Q3Lista.py | 339 | 3.5 | 4 | import random
lista_Num = list()
lista_Num_Sorteados = list()
qnt_Jogos = 0
for l in range(0, 60):
lista_Num.append(l+1)
qnt_Jogos = int(input('Quantos jogos você quer sortear?'))
for h in range(0, qnt_Jogos):
lista_Num_Sorteados.append(random.sample(lista_Num, 6))
print('Jogo ', h+1, ': ', sorted(lista_N... |
6c1e5a087bcc526b237596e3d84f7504ac29334f | rcgalbo/advent-of-code-20 | /Advent2020/day1.py | 384 | 3.5 | 4 | # rcgalbo day 1
with open('data/day1.txt') as f:
EXX = f.read()
def parse_input(inString):
numbers = [int(i) for i in inString.split('\n')]
for number1 in numbers:
for number2 in numbers:
for number3 in numbers:
if number1+number2+number3 == 2020:
... |
acbac4308ac023b4eb2246e84c1cd8f7615e2215 | Jubayer-Hossain-Abir-404/Problem-Solving-Using-Python-and-Numerical-Methods | /ultimate newton divided interpolation.py | 936 | 3.75 | 4 | def newton(x,y,n,x1):
b=[0.0]*(n+1)
for i in range(0,n+1):
if(i==0):
b[i]=y[i]
elif(i==1):
b[i]=((y[i]-b[i-1])/(x[i]-x[0]))
elif(i==2):
b[i]=(((y[i]-y[i-1])/(x[i]-x[i-1]))-b[i-1])/(x[i]-x[0])
else:
bm=(((y[i]-y[i-1])/(x[i]-x[i-1]))-... |
a890ad334ef766a5210e095a767d59d26602905b | MalteMagnussen/PythonProjects | /week2/Exercises/one.py | 3,678 | 4.5625 | 5 | # ## Exercise 1
# 1. Create a python file with 3 functions:
# 1. `def print_file_content(file)` that can print content of a csv file to the console
# 2. `def write_list_to_file(output_file, lst)` that can take a list of tuple and write each element to a new line in file
# 1. rewrite the function so that it gets... |
ff42afe3cab4fe3a37752cbf0fb6c46c98bf11c3 | valentinegarikayi/Getting-Started- | /MIT/PS_0.py | 406 | 4.25 | 4 | #!/usr/bin/env python
#Find a positive integer that is divisible by both 11 and 12
counter =0
while True:
if counter>=10:
break
counter = counter+1
Ten_integers=int(input('Please enter an integer:'))
if Ten_integers%2==0:
print ('You have just entered an even number')
else:
p... |
93397bc295c5c6fe46ed9c69decc6f12f92d3a66 | leoflotor/numerical_computation | /condition_number_estimation/condition_number.py | 3,888 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# Author: Leonardo Flores Torres
# Student ID: S32015703W
import numpy as np
# Initial matrix and vector of the system of equations ofthe
# form Ax = b to be used for the computation of the conditional
# number k*.
matrixA = np.array([[1, 1/2, 1/3],
[1/2, 1/... |
4df90ed337cc21a0cae4b8cf118b5f937ce70b75 | zudcow/prog2_assignment | /b50-39_soviet_housing.py | 3,085 | 3.9375 | 4 | import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
time = input("Time (HH.MM.): ")
def time_conversion(time):
# converts input string time to int minutes
try:
hour, minutes = time.strip('.').split('.')
hour, minutes = int(hour), int(minutes)
except ValueError:
... |
960f46aed0e4d4dd88d0d093ad381fcf975181d3 | ICimpoes/python-train | /scripts/functions/function_arguments.py | 727 | 3.5 | 4 | def f(*args):
print(type(args), args)
f()
f(1)
f(1, 2)
def f(**args):
print(type(args), args)
f()
f(a=1)
f(a=1, b=2)
f(a=1, b=2, c='3')
# *args -> tuple, **kwargs -> dict
def f(a, *args, **kwargs):
print(a, args, kwargs)
f(1)
f(1, 2)
f(1, 2, 3, 4, 5)
f(1, 2, 3, 4, 5, b=1, c=2, key=3)
f((1, 2, 3, 4,... |
1c0c6acdeddf5cbf9a5ddaade2bb97cf8815984b | bhkangw/Python | /python_checkerboard_assignment.py | 912 | 4.5 | 4 | # Assignment: Checkerboard
# Write a program that prints a 'checkerboard' pattern to the console.
# Your program should require no input and produce console output that looks like so:
# * * * *
# * * * *
# * * * *
# * * * *
# * * * *
# * * * *
# * * * *
# * * * *
# Each star or space represents a square.
# On a... |
c7f2b96083e7487ab3a497b477764d728600595d | Dhaval2110/Python | /python_ closure.py | 538 | 4.1875 | 4 | def first(x):
def second():
#x=x+2
print(x)
second()
first(100)
'''
Advantages :
With Python closure, we don’t need to use global values. This is because they let us refer to nonlocal variables. A closure then provides some form of data hiding.
When we have only a few Python methods (usually, only one), we may u... |
5db93455ee82e140dfda24a7e0c6248c2649a352 | starkblaze01/Algorithms-Cheatsheet-Resources | /Python/EncryptionAlgo_Py/CaesarCipher.py | 1,082 | 4.09375 | 4 | def encrypt(text,key):
result=""
ascno_e=0
for i in text:
if i.isupper():
ascno_e=ord('A')+((ord(i)-ord('A')+key)%26)
result=result+chr(ascno_e)
elif i.islower():
ascno_e= ord('a')+((ord(i)-ord('a')+key)%26)
result=result+chr(ascno_e)
e... |
8df5e467c6577edc62e23339e2362fa067a23c64 | nayanex/Googleinterview | /Coursera/fibonacci.py | 262 | 3.65625 | 4 | # Uses python3
def calc_fib(n):
fib = []
fib.append(0)
fib.append(1)
if n < 2:
return fib[n]
for index in range(2,n+1):
fib.append(fib[index-1] + fib[index-2])
return fib[n]
n = int(input())
print(calc_fib(n))
|
7c6d4188dc3f52c072a1623f874d8e9f3939a2c6 | miono/aoc2017 | /7/7b.py | 2,233 | 3.5625 | 4 | #!/usr/bin/env python
f = open('input').readlines()
towerlist = []
resolved_tower = []
for i in f:
towerdef = i.split()
if len(towerdef) > 2:
tmplist = [towerdef[0], int(towerdef[1].strip('()')), map(lambda it: it.strip(','), towerdef[3:])]
else:
tmplist = [towerdef[0], int(towerdef[1].strip('()'))]
t... |
274e54d709d02a9c782ab0c2ebffeab8cacc55d7 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/nksvuy001/question2.py | 764 | 4.0625 | 4 | """program that uses a recursive function to count the number of pairs of repeated characters in a string
vuyolwethu nkosi
4 may 2014"""
msg=input("Enter a message:\n") #get message from user
def count_the_pairs(msg):
#message=input("Enter a message:\n")
if len(msg)<=1: #if the string is empty or if it ... |
50a9c3054108548dae3351d7cce4defcc41fa1a9 | mlui8518/GWC-Projects | /GWCProjects/social_network.py | 1,400 | 3.5 | 4 | class User:
def __init__(self, name):
self.name = name
self.id = id
self.connections = []
answer = input("Press 'a' to add connections; Press 'p' to make a post; Press 'm' to write a message; Press 'e' to exit")
selfConnections = {}
posts = {}
while answer != 'e':
def add_connections ():
... |
afac8e432cf378093d0d7541cb3e83d16bb56fa1 | nveenverma1/Dataquest | /Practice/15_Statistics_Intermediate/Measures of Variability-308.py | 5,973 | 3.84375 | 4 | ## 1. The Range ##
import pandas as pd
houses = pd.read_table('AmesHousing_1.txt')
def calc_range(arr):
min_arr = min(arr)
max_arr = max(arr)
return max_arr - min_arr
range_by_year = {}
years = houses['Yr Sold']
for year in years:
if year not in range_by_year:
range_by_year[year] = calc_ran... |
2156319e2fd1668d3c8ec88a0504cae8274e07d0 | Saurabh910/turtle-race | /main.py | 1,476 | 4.28125 | 4 | from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet!", prompt="Which turtle you bet would win?: ")
# Finish Line
def finish_line():
dec = Turtle()
dec.hideturtle()
dec.penup()
dec.go... |
702751ddda4aa0c9df8ee52c96e78b9aeaa2e866 | hangnew/python_studies | /210901 JtoP 07/07-1.py | 927 | 3.578125 | 4 | # 정규 표현식 Regular Expressions
# 복잡한 문자열을 처리할 때 사용하는 기법, 줄여서 정규식이라고도 한다
# 정규식 없이 코딩
# 주민등록번호를 포함하고 있는 텍스트의 모든 주민등록번호의 쥣자리를 * 문자로 변경해 보자.
data = """
park 800905-1049118
kim 700905-1059119
"""
result = []
for line in data.split("\n"):
word_result = []
for word in line.split(" "):
if len(word) == 14 and w... |
9f05c6935c956f6bf5455ef9b9652bf4eb657eb7 | In4y/1stpython | /python_test/dic_test.py | 1,047 | 3.71875 | 4 | # -*- coding:utf-8 -*-
# **FILENAME:
# **AUTHOR:
# **CREATED TIME:
# **FUN DESC :
# **MODIFIED BY :
# **MODIFIED TIME:
# **MODIFIED CONTENT:
# **REVIEWED BY:
# **REVIEWED TIME:
# **INPUT TABLE:
# **MID TABLE :
# **DIM TABLE :
# **OUTPUT TABLE:
score_dict = {
'yinandyi':88,
... |
a52be5bf95297d1287123473e7a02bb171664047 | nirajacharya/Python | /SmallProjects/PRJ3ROCKpappersiaaors.py | 2,100 | 4.21875 | 4 | import random
computer_score=0
user_score=0
while True:
option=['rock', 'paper', 'scissor']
computer_choosed_option=random.choice(option)
user_input=input('''enter Your option
1)Rock
2)Paper
3)Scissor
press Q to Exit
... |
e49cdd74796c267183216648b98dd3eaa44250d5 | kpu3uc/1824_GB_Python_1 | /Shishkin_Anatoliy_lesson_10/actions/my_iterators.py | 1,325 | 3.859375 | 4 | class IterObj: # просто класс-заглушка
pass
class IteratorEnergy:
"""Объект-итератор, имитация иссякающей энергии"""
def __init__(self, start=10):
self.i = start + 1
# У итератора есть метод __next__
def __next__(self):
self.i -= 1
if self.i >= 1:
return self.... |
86a7cebfdf665e9239370bcff32c3435490ba4f8 | rickruan/my_git | /python/test_exception.py | 871 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# 定义函数
def t_func(var):
try:
return int(var)
except ValueError as e:
print("参数没有包含数字\n", e)
try:
fh = open("ruan_test", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print("Error: 没有找到文件或读取文件失败")
else:
print("内容写入文件成功")
fh.c... |
4edf6765d220048afbe9000f39bc35f3e017cb66 | Ashish9426/Computer-Vision | /Computer Vision Tutorial/1. Reading and Writing Files/page2. reading pictures1.py | 399 | 3.53125 | 4 | # importing package
import cv2
import numpy as np
# step 1: open the file
img = cv2.imread('./messi5.jpg')
# step 2: perform operation(s)
# step 2.1: take an action
# step 2.2: generate output
# step 2.3: save the changes to a new file
# step 2.4: show the file on screen
cv2.imshow('messi', img)
# wait for user to ... |
b89c1b0895cdaf8253e4ed6685d2977228dad4d5 | magnushedin/AOC | /2015/dec_01/dec_01b.py | 469 | 3.6875 | 4 | def read_file(filename):
f = open(filename)
input = f.read()
f.close()
return input
if __name__ == "__main__":
filename = 'input'
input = read_file(filename)
pt = 0
for (iter, i) in enumerate(input):
#print("this char: {}".format(i))
if i == ')':
pt -= 1
... |
d45ede908c2f5977eed1a01d87cb78b2bc2a63b8 | Sandy4321/vw-spam-filter | /util/text.py | 1,706 | 3.609375 | 4 | import re
def process_text(text):
"""
General-purpose text pre-processing.
:param text:
:return:
"""
if text is None:
return ""
text = text.casefold()
# Remove 1 and 2 character alphabetic words
# (Uncomment if necessary)
# text = re.sub(r"\b[a-z]{1,2}\b", "", text)
... |
0484515467b9ff1caf1770b03159e94e79895acd | AdlerChan/Euler-Problem | /problem16.py | 336 | 3.6875 | 4 | def multiples(n):
a = n / 15
b = n % 15
return a, b
def sum1(n):
a, b = multiples(n)
result = (32768 ** a) * (2 ** b)
return result
if __name__ == "__main__":
print sum([int(i) for i in str(sum1(1000))])
print sum(map(lambda x: int(x), str(2 ** 1000)))
print sum([int(i) for i in s... |
bdce06a28c70a117aa470af18fce590a325ebd06 | tsuchan19991218/atcoder_achievement | /atcoder.jp/abc056/arc070_a/Main.py | 84 | 3.828125 | 4 | X = int(input())
x = 0
time = 0
while x < X:
time += 1
x += time
print(time) |
56b56fccff72bbc1b72515a965e1337838c1bd86 | sdramsey89/Election_Analysis | /Python_practice.py | 1,127 | 3.71875 | 4 | counties = ["Arapahoe","Denver","Jefferson"]
counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438}
#for county in counties_dict.keys():
# print(county)
#for county in counties_dict.values():
# print(county)
#for county, voters in counties_dict.items():
# print(county, voters)
voting_... |
5a259922e77f17a45435ac4a24bfa736e08b90b5 | WaterJames/resource | /mybaostock/my_queue.py | 529 | 3.515625 | 4 | class MyQueue:
def __init__(self):
self.items = []
def push(self, value):
self.items.append(value)
# 弹出首个数据
def pop(self):
if(self.items == []):
return 0
else:
return self.items.pop(0)
def sum(self):
total = 0.0
if(len(self.i... |
4e5cde47dda2ed6a615a4561d49136b6539c27fb | selahattintuncer/Python | /python-master/python-master/coding-challenges/cc-009-find-the-power-set/find-the-power-set.py | 291 | 3.609375 | 4 | def func (arr):
power_set = []
smalllist =[]
for i in arr:
smalllist = []
smalllist.append(i)
power_set.append(smalllist)
for a in power_set:
tmp = a.copy()
if i not in a:
tmp.append(i)
power_set.append(tmp)
print(power_set)
|
a0c083de32282fe9c540934de8b0135b9708c198 | pombredanne/classic | /test/test_shortest_path.py | 917 | 3.578125 | 4 | #!/usr/bin/env python
#
# This script is used for testing shortest path algorithm.
#
# Liang Wang @ University of Helsinki, Finland
# 2014.09.12
#
import os
import sys
import random
import networkx as nx
sys.path.append('../code')
def get_random_graph():
G = nx.erdos_renyi_graph(100, 0.1)
H = nx.Graph()
... |
99dc40d56e9e2a05fcfb9a726cd838f299454643 | YalingZheng/CIS475Spr20 | /FaultInjection.py | 2,344 | 3.578125 | 4 | #!/usr/bin/env python
## FaultInjectionDemo.py
## Avi Kak (March 30, 2015)
## This script demonstrates the fault injection exploit on the CRT step of the
## of the RSA algorithm.
## GCD calculator (From Lecture 5)
def gcd(a,b): #(1)
while b: #(2)
a,b = b, a%b #(3)
return a #(4)
## The code shown below uses ordi... |
4ed41be205d5352eae452091ef145e3b7ab20653 | pzp1997/Snippets | /Hangman.py | 1,785 | 3.71875 | 4 | #!/usr/bin/env python2.7
"""Hangman for Terminal"""
from urllib2 import urlopen, URLError
__author__ = 'Palmer (pzp1997)'
__version__ = '1.0.4'
__email__ = 'pzpaul2002@yahoo.com'
def main():
print 'Hangman.py (c) 2014, pzp1997'
print 'Input "exit" or "quit" to quit.'
print
while True:
e... |
84a0f11d530b1513475239f39eaf8796b1a49ecf | GeorgeSpiller/2015-2017 | /Python/Algorithms/Bubble sort.py | 1,086 | 3.90625 | 4 | #Bubble sort
#create unordered list from input
valueList = []
valueString = ""
pointerPos = 0
valueString = input("enter list of numbers only, max 10: ")
if len(valueString) > 10:
quit
i = 0
for i in range(0, len(valueString)):
valueList.insert(i, valueString[i])
print(valueList)
#for ... |
abd495fbb7988d790ec10d9e005f23e6715579d0 | nicopaik/Python-Projects | /session09/strings.py | 1,087 | 3.59375 | 4 | L = [
['Apple', 'Google', 'Microsoft'], # 0
['Java', 'Python', ['Ruby','On Rail'], 'PHP'], # 1
['Adam', 'Bart', 'Lisa'] # 2
]
len(L)
AFC_east = ['New England Patriots', 'Buffalo Bills', 'Miami Dolphins', 'New York Jets']
print('Buffalo Bills' in AFC_east)
# for team in AFC_east:
# for letter in t... |
977d272d8fc1a3c99a89d935dc8aa08de94dcad6 | NathanialNewman/ProjectEuler | /problems/1-9/7.py | 960 | 3.671875 | 4 | # Author: Nate Newman
# Source: Project Euler Problem
# Title: 10001st prime
# Description: By listing the first six prime numbers:
# 2, 3, 5, 7, 11, and 13
# we can see that the 6th prime is 13.
# What is the 10001st prime number
import time
from math import log
from math import floor
def sieve (limit,... |
fac2dad0abf44b033265c6dd2d973402ec256feb | Priyanshuparihar/Competitive_Programming | /Coding Question/Prime number.py | 166 | 4.03125 | 4 | n=int(input("Enter a no. "))
count=0
for i in range(2,n):
if n%i==0:
count+=1
if count>1:
print(n,"is not a prime no.")
else:
print(n, "is a prime no.") |
ac61bf3b9485e1eb778ef7a83acb7c1e9daa6727 | reesep/reesep.github.io | /classes/summer2021/127/lectures/examples/student_class.py | 1,963 | 4.09375 | 4 |
class Student():
#all students have a name, major, GPA, ID, Year
def __init__(self,name,major,student_id,gpa="Undefined",year="Freshman"):
self.name = name
self.major = major
self.student_id = student_id
self.gpa = gpa
self.year = year
self.champ_change = 0
... |
314747bd5eae3e1f3adb2968bc0c7460ba1cb9d5 | sservett/python | /PDEV/SECTION6/hw601.py | 297 | 3.546875 | 4 | def is_perfect(a):
list1 = []
i = 1
while i < a:
if (a % i == 0):
list1.append(i)
i += 1
b = 0
for i in list1:
b = b + i
if a == b :
print("{} is Perfect NUMBER".format(a))
for i in range(1,1000):
is_perfect(i)
|
49798f3942eb35c66e22f5c0157fd6d84d872ea5 | Karthik-bhogi/Infytq | /Part 1/Assignment Set 3/Question4.py | 813 | 4.15625 | 4 | '''
Created on Apr 23, 2021
@author: Karthik
'''
def check_palindrome(word):
#Remove pass and write your logic here
length = len(word)
letter_list = ""
n = 0
while(length>n):
letter_list = letter_list +" "+ word[n]
n = n +1
letter_list = letter_list[1:]
letter_... |
b573017ca336216332be4612d48206ba1eaa6b8c | SyureNyanko/asymmetric_tsp | /asymmetric_tsp/core.py | 1,957 | 3.765625 | 4 | # -*- coding: utf-8 -*-
import math
import time
import sys
class Timeout(object):
def __init__(self, limittime, starttime):
self.starttime = starttime
self.limittime = limittime
def get_timeout(self, time):
timeout = (time - self.starttime> self.limittime)
return timeout
def testlength(v1, v2):
'''Measur... |
4d020519004e3dd09dc27647a7e508bac68eaa83 | Iansdfg/9chap | /7HashHeap/401. Kth Smallest Number in Sorted Matrix.py | 663 | 3.578125 | 4 | import heapq
class Solution:
"""
@param matrix: a matrix of integers
@param k: An integer
@return: the kth smallest number in the matrix
"""
def kth_smallest(self, matrix, k):
# write your code here
heap = []
res = None
for row in matrix:
if not row:
... |
63739846b4f1202aa0db4007706c706ba5f055eb | alexsfo/uri-online-judge-python | /URI_1010.py | 277 | 3.5 | 4 | produto1 = (input().split(' '))
CP1 = int(produto1[0])
UP1 = int(produto1[1])
VP1 = float(produto1[2])
produto2= (input().split(' '))
CP2 = int(produto2[0])
UP2 = int(produto2[1])
VP2 = float(produto2[2])
valor = VP1 * UP1 + VP2 * UP2
print("VALOR A PAGAR: R$ %.2f" %valor)
|
1f5f5f2864a6714190b3812d7df43395e5cbc753 | implse/Code_Challenges | /CodeFights/InterviewPractice/Searching&Sorting/traverseTree.py | 900 | 4.03125 | 4 | # Given a binary tree of integers t, return its node values in the following format:
# The first element should be the value of the tree root;
# The next elements should be the values of the nodes at height 1 (i.e. the root children), ordered from the leftmost to the rightmost one;
# The elements after that should... |
d1f55923f71abb5a0092fcb46c351be467834bd8 | leninhasda/competitive-programming | /random-py/4.3-max.py | 473 | 3.6875 | 4 | def max(arr):
if len(arr) == 1:
return arr[0]
else:
m = max(arr[1:])
if m > arr[0]:
return m
return arr[0]
def test_max():
test_cases = [
{
"in": [1,2,3,4,5,6,7],
"out": 7
},
{
"in": [12, 2,3,4,5],
"out": 12
},
{
"in": [1,5,9,3,4,6],
... |
80817c535fa8a936e8276c5997e25194c561676a | sandeepmaity09/python_practice | /hackerrank/day8_rec.py | 141 | 4.1875 | 4 | #!/usr/bin/python3
def factorial(n):
if n==1:
return n
else:
return n*factorial(n-1)
num=int(input())
fact=factorial(num)
print(fact)
|
2af2b3366096b7799e0c0ffa118c0f60a26511fe | hamioo66/Test | /2018-1-19.py | 516 | 3.953125 | 4 | # -*- coding=UTF-8 -*-
"""
author:hamioo
date:2018/1/19
describle:格式化方法
"""
age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book' .format(name,age))
print('why is {0} playing with that python?'.format(name))
# 联立字符串
print name + ' is ' + str(age) + ' years old '
print('{} years old' .format(... |
51c3af3c34b5d2296cb23247f6e30bfaa608f12b | sleduap/PhoneContact | /action.py | 4,502 | 3.671875 | 4 | from os import path
from csv import DictWriter, DictReader
filename = "phonebook.csv"
class PhoneBook:
phone = []
counter = 0
def __init__(self):
if PhoneBook.counter == 0:
self.read(filename)
PhoneBook.counter = PhoneBook.counter + 1
self.book = {"Name": "", "Ph... |
51dd5e4f0dab829f37a3e96d9f5276239ff54f7f | JUNGEEYOU/Algorithm-Problems | /binary_search/baekjoon/10815.py | 538 | 3.53125 | 4 | import sys
def binary(target):
left = 0
right = n - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return 1
elif arr[mid] > target:
right = mid - 1
else:
left = mid + 1
return 0
n = int(sys.stdin.readline().rs... |
b495c57f134665710ca45fdb14f08a6ebf50059c | ajaycs18/ADA-4TH-SEM | /insort.py | 272 | 3.5625 | 4 | def inSort(arr):
for i in range(1, len(arr) - 1):
ele = arr[i]
j = i - 1
while j > -1 and arr[j] > ele:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = ele
arr = list(map(int, input().split()))
inSort(arr)
print(arr)
|
30ed4db764dd06481127040bb6548cebf102a5ba | adyadyat/pyprojects | /shultais_courses/data_types/comparsion_of_num_and_lines/max_num.py | 629 | 3.625 | 4 | import sys
d1 = int(sys.argv[1])
d2 = int(sys.argv[2])
d3 = int(sys.argv[3])
print(max([d1, d2, d3])) # метод max([])
"""
МАКСИМАЛЬНОЕ ЧИСЛО
Начинающий разработчик написал программу, которая выводит максимальное из трех чисел, однако код работает не так как было задумано. Исправьте ошибку, чтобы программа работала п... |
e6e56d1aa683d83c362382d150973c7b3c46a089 | geekfiktion/python | /sals_shipping.py | 1,057 | 3.6875 | 4 | prem_ground_ship = 125.00
def ground_shipping(weight):
flat_charge = 20.00
if weight <= 2:
cost = (weight * 1.50)
elif weight <= 6:
cost = (weight * 3.00)
elif weight <= 10:
cost = (weight * 4.00)
else:
cost = (weight * 4.75)
return cost + flat_charge
def drone_shipping(weight):
flat_ch... |
2bbb1ce80686c5a03e811d5d75ac11c4837761b1 | mrxder/simple-elevation-calculator | /main.py | 454 | 3.921875 | 4 | import math
print("Start")
print("start length:")
km_a = float(input())
print("start height:")
hm_a = float(input())
print("")
print("Target")
print("target length:")
km_b = float(input())
print("target height:")
hm_b = float(input())
distance = abs(km_a - km_b)
height = abs(hm_a - hm_b)
run = math.sqrt((math.pow... |
72274945b849c25defc47eedb60bf24252f89e8c | xatlasm/python-crash-course | /chap10/10-12.py | 521 | 3.90625 | 4 | #Favorite Number Remembered
import json
filename = 'pythoncc exercises/chap10/fav_num.json'
def get_fav_num():
fav_num = input('What is your favorite number? ')
with open(filename, 'w') as f_obj:
json.dump(fav_num,f_obj)
def read_fav_num():
"""Reads user's favorite number from JSON"""
wit... |
4a521c1d7774010774cb32938bd5a996a31d6578 | mario595/test-payments-app | /accounts/commands/transfer_command.py | 1,807 | 3.703125 | 4 | '''
Created on 6 Feb 2016
@author: mariopersonal
'''
from accounts.commands.commands import Command, CommandError
'''
This is a transfer command. It validates if the transfer is correct (Different account and enough funds) and
makes the transfer, updating both accounts involved and saving the transaction. In case of ... |
2fc74c047131a5ef5bcb2f341254fc159950cb3a | pdjani91/Python-Programming-Examples | /counter.py | 143 | 3.640625 | 4 | def word_counter(s):
count = {}
for char in s:
count[char] = s.count(s)
return count
print (word_counter('harshit')) |
9fb42528c2704a2e175ee9d5b5e5bf4e5eb6fe21 | asdrubalramirezb/higher_level_programming-master | /0x0A-python-inheritance/3-is_kind_of_class.py | 365 | 3.578125 | 4 | #!/usr/bin/python3
"""Module that verify if the object is an instances of a class given
"""
def is_kind_of_class(obj, a_class):
""" Function that receive an object and a class,
Returns true if object is an instances of a class,
otherwise return false
"""
if isinstance(obj, a_class):
... |
3c69f1fac636bd87bbd014798d072677e778e7cc | mlpetuaud/first_package | /my_shoes_pkg/my_shoes.py | 2,465 | 3.578125 | 4 | import random
import itertools
class Stock():
# donne un attribut de classe (on aurait aussi pu
# initialiser un compteur à 0 et l'augmenter de 1 à
# chaque instanciation d'objet via un +=1 dans le __init__)
#instances_counter = itertools.count().next
instances_counter = 0
def __init__(self)... |
6b4d29d8b96e1b8e384dc98dec24e675f7ef81ed | mikhail-kukuyev/Masters-Degree-Courses | /Python/lab4/mid_skip_queue.py | 1,948 | 3.5 | 4 | import pprint
import copy
class MidSkipQueue(object):
def __init__(self, k, iterable=None):
assert k > 0, "k should be positive"
self.k = k
self.elements = iterable[:] if iterable else []
def append(self, *args):
if len(self.elements) <= self.k:
append_amount = 2 *... |
998a4cb5909b6839e1b822e02a4d1e633df6c81d | michellejzh/power-and-prices | /ISO-NE/scripty/averageWind.py | 1,450 | 3.515625 | 4 | import csv
import sys
import os
import Queue
import numpy as np
import math
def averageWindByDay(windFile):
with open(windFile, 'rU') as csvfile:
reader = csv.reader(csvfile, dialect=csv.excel_tab, delimiter=',', quotechar='|')
row = "placeholder"
dates = [] # eventually need to write in date order
days = {}... |
dbf9704dd0f98528994ea6dbfdf4f4faf25445ee | SonBui24/Python | /Lesson03/Bai01.py | 1,063 | 3.90625 | 4 | from math import sqrt
print("Giải phương trình bậc 2")
a = float(input("Nhập số a: "))
b = float(input("Nhập số b: "))
c = float(input("Nhập số c: "))
delta = b ** 2 - 4 * a * c
if a == 0:
if b == 0:
if c == 0:
print("Phương trình có vô số nghiệm!")
else:
print("Phương trìn... |
fa6ffcea55953db6a8d91e3b07ca1782f9692705 | Denis-Oyaro/Data-structures-and-algorithms-with-Python | /quick_sort.py | 737 | 4 | 4 | """Implement quick sort in Python.
Input a list.
Output a sorted list."""
def quicksort(array):
QUICKSORT(array, 0, len(array) - 1)
return array
def QUICKSORT(array, p, r):
if p < r:
q = PARTITION(array, p, r)
QUICKSORT(array, p, q-1)
QUICKSORT(array, q+1, r)
def PARTI... |
8f3cd375b168fd32c25d318ae716d90c68e23c9d | leezichanga/Project-euler-toyproblems | /projecteuler6.py | 985 | 3.703125 | 4 | #Solution 1
def squares(num):
total = []
for i in range(1,num+1):
prod = (i*i)
total.append(prod)
you=sum(total)
return you
squares(10)
def sum_squares(num):
total = []
for i in range(1,num+1):
total.append(i)
you=sum(total)
return you**2
sum_squares(10)
d... |
6a2bdd423ec1a58632b64b1f9725abfe0c4575fe | jonchang03/PythonSpecialization | /GettingStartedWithPython/assignment4_6.py | 389 | 4.0625 | 4 | def computepay(h,r):
if h < 40 :
pay = h * r
else :
# Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate
# for all hours worked above 40 hours.
pay = 40 * r + (h - 40) * 1.5 * r
return pay
hrs = raw_input("Enter Hours:")
hrs = float(hrs)
rate = raw_inpu... |
18f0143f563abcae7ea347bb7fb183b0a61d60c7 | fsMateus/exerciciosPython | /fase8/exercicio4.py | 565 | 3.59375 | 4 | class Pessoa:
def __init__(self, nome, idade, peso, altura):
self.nome = nome
self.idade = idade
self.peso = peso
self.altura = altura
def envelhecer(self):
self.idade += 1
self.crescer(0.5)
def engordar(self, peso):
self.peso += peso
def emagr... |
36494ca08e8b13a992ecec4febc52db44b98532d | chaichai1997/python-algorithm | /array_allocate.py | 999 | 3.5 | 4 | # -*- coding: utf-8 -*-
# author = "chaichai"
"""
实现任务调度
方法:贪心
"""
def calculate_process_time(time, number):
if time is None or number <= 0:
return None
n_t = len(time)
p_time = [0] * n_t
for i in range(number):
min_time = p_time[0] + time[0]
min_index = 0 # 指机器数目
j ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.