blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2e9ef545996a677286c77da9f055e70d9b6de325 | nafryer97/ppl_hw7 | /hw7.py | 952 | 3.734375 | 4 | def is_prime(n):
if n < 2 : return False
i = 2
while i * i <= n:
if n % i == 0: return False
i += 1
return True
def primes():
yield 2
i = 3
while True:
if is_prime(i):
yield i
i += 2
def square_primes():
yield 2*2
i = 3
while True:
... |
ee2d3a0f9c2edd9da9272313517a5d207df84ae9 | bopopescu/python-practice | /pycharm/telusko/constructor-self-comparing-objects.py | 469 | 3.90625 | 4 | class computer:
#--- __init__ method is a constructor
def __init__(self,cpu,ram):
self.cpu = cpu
self.ram = ram
def compare(self,other):
if self.ram == other.ram:
return True
else:
return False
c1 = computer('i3',16)
c2 = computer('i5',8)
c1.ram=8
#... |
66dc508edada577dd42c0c9f83cecbbe729a4602 | jasonpark3306/python | /.vscode/Sort/merge_sort.py | 913 | 3.9375 | 4 | import random
def merge_two_sorted_list(arr1 : list, arr2 : list, org : list) -> None :
i = j = idx = 0
len1 = len(arr1)
len2 = len(arr2)
while i < len1 and j < len2 :
if arr1[i] <= arr2[j] :
org[idx] = arr1[i]
i+=1
else :
org[idx] = arr2[j]
... |
d5060e0048054ccd11b8da9767e93c499b5201fd | byungjur96/Algorithm | /2442.py | 166 | 3.8125 | 4 | line = int(input())
for i in range(line):
for _ in range(line-i-1):
print(" ", end="")
for _ in range(2*i+1):
print('*', end="")
print()
|
7087096424871135b2f32a82bc33d29350099f1e | ArminOonk/AdventCode2016 | /day1.py | 2,310 | 4.0625 | 4 | # The Document indicates that you should start at the given coordinates (where you just landed) and face North.
# Then, follow the provided sequence: either turn left (L) or right (R) 90 degrees, then walk forward the given number
# of blocks, ending at a new intersection.
#
# There's no time to follow such ridiculous ... |
a2d24996713a7030961045d219dffa454696e41a | 824zzy/Leetcode | /D_TwoPointers/DifferentDirection/L1_581_Shorest_Unsorted_Continuous_Subarray.py | 499 | 3.71875 | 4 | """ https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
1. sort the array
2. find left&right most different elements by two pointers
Time: O(nlogn) due to sort function
"""
class Solution:
def findUnsortedSubarray(self, A: List[int]) -> int:
sorted_A = sorted(A)
l, r = 0, len(A)-1
... |
6629748d83bfc95c95abbb833f5663225dd87d8a | jokerGin/Password-Generator | /Password generator.py | 1,798 | 3.890625 | 4 | """
A simple password generator program that uses random numbers and letters to generate
passwords of desired length
"""
# import needed modules
from tkinter import *
from PIL import ImageTk, Image
import time
root = Tk()
root.title('Password Generator')
root.iconbitmap("icons/favicon.ico")
#... |
8307c7232958a95709d2cb8e5ae729e6fc974c1d | Arctiss/A2-Coursework | /Simulatorv4.py | 8,203 | 3.75 | 4 | import random, math, pygame, time, sys
class node():
def __init__(self, size, board, unhappy, blanks, bias, ratio, groups):
self.size = size
#self.coordinates = coordinates
self.population = 0
self.board = board
self.unhappy = unhappy
self.blanks = blanks
se... |
9603ff74c0bb6e7ef1b48b11077b7aeb002faf31 | PreslavaKuzova/Python101 | /week03/Queries/queries.py | 1,977 | 3.5 | 4 | import csv
from operator import itemgetter
def filter(file_name, **kwargs):
result = []
with open('data.csv', mode = 'r') as csv_file:
data = csv.DictReader(csv_file)
for row in data:
flag = True
order = False
index_to_order_by = ''
... |
4d34a5c481d97ece8e2291455a272b320792bdd7 | sealanguage/april2021refresh | /digit_sum/digit_sum.py | 1,397 | 3.890625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'superDigit' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. STRING n
# 2. INTEGER k
#
def superDigit(n, k):
# Write your code here
one = 1
sum... |
ff0f519ab9e9cf4346dc5ee93e44bc9e52a45189 | SamanehGhafouri/Data-Structures-and-Algorithms-in-python | /Experiments/find_minimum_element.py | 660 | 4.125 | 4 | # ############ Find the minimum number in an array ############# #
def find_smallest(arr):
if len(arr) == 0:
return None
smallest = arr[0]
for i in range(len(arr)):
if arr[i] < smallest:
smallest = arr[i]
return smallest
ar = [90, 69, 23, 120, 180]
print(find_smallest(ar))... |
c7b922f174da993f9f41b739d7afb37c88b68e71 | mrchary/oreilly-python-1 | /Exercises/check_string.py | 349 | 4.4375 | 4 | #!/usr/local/bin/python3
"""Check if a string is all upper case and ends with a period."""
uin = input("Please enter an upper-case string ending with a period: ")
if uin != uin.upper():
print("Input is not all upper case.")
elif uin.endswith("."):
print("Input meets both requirements.")
else:
print("Input d... |
77ea04c13f1ac07a6cca4c27bfec4fda44461e23 | tasnuva83/pythonlarning | /funtion_2.py | 203 | 3.78125 | 4 | def increasedprice(price):
newprice=price*1.20
print("revised price now:", newprice)
return newprice
x=increasedprice(12)
amount_increased=x-12
print("increased amount is:",amount_increased ) |
fa777902aa84dcc8ef5eff56c278c1dffb5eca1b | samaosborne/Uno | /players.py | 8,278 | 3.90625 | 4 | from cards import Pile, Card
class Player:
def __init__(self, name, hand=None, points=0):
"""
:param name: Name of player
:type name: str
:param hand: The player's hand
:type hand: Pile | None
:param points: The player's points
:type points: int
"""... |
4dcfb6585bc4d653ecbb5b67a6eb7745df32708e | booji/Exercism | /python/bank-account/bank_account.py | 1,882 | 3.84375 | 4 | import threading
class BankAccount(object):
def locking(func):
"""
Given a method returns a method that uses lock calls the given method
and then releases the lock
"""
def wrapper(self, *args):
with self.lock:
return func(self, *args)
retu... |
94868a226f27210b3b3e50660cd67df86b826434 | maveric-coder/practice_arena | /happy_ladybugs.py | 309 | 3.515625 | 4 |
import re
def happy(n,st):
if st.count("_") == 0 and len(re.sub(r'((.)\2+)', "", st)) != 0:
return "NO"
for i in st:
if i != "_" and st.count(i) == 1:
return "NO"
return "YES"
for j in range(int(input())):
n=int(input())
st=input()
print(happy(n,st))
|
3157866bad52cd919dfb09fd71560ada3ab77b58 | Sadegh28/AI99001 | /Codes/CSP/NQueen_HillClimbing.py | 1,494 | 3.515625 | 4 | import random
from matplotlib import pyplot as plt
class nqueen_csp:
def __init__(self, q_num):
#q_num: number of queens
self.size = q_num
def initial_assignment(self):
assignment = [random.randrange(self.size) for i in range(self.size) ]
return assignment
def next_a... |
d67a89c4e517af3478dedc63189866e865d77d26 | i35186513/270201057 | /Lab8/example1.py | 181 | 3.5625 | 4 |
def summ(a_list):
a_sum = 0
for i in range(len(a_list)):
a_sum += i
return a_sum
a_list = [12, -7, 5, -89.4, 3, 27, 56, 57.3]
a_sum = summ(a_list)
print(a_sum*a_sum)
|
b9d16e4a06e0485a6e4e5c26bf4673d063c1eb7e | JaydeepKachare/Python-Classwork | /Session3/Arithematic6.py | 429 | 4.125 | 4 | # addition of two number
def addition(num1, num2):
ans = num1+num2
return ans
num1 = int(input("Enter num1 : "))
num2 = int(input("Enter num2 : "))
ans = addition(num1,num2)
print("Addition : ",ans)
num1 = int(input("Enter num1 : "))
num2 = int(input("Enter num2 : "))
ans = ad... |
b615ccec79317abc4feee6a4793b6fa985c5a7a4 | miniyk2012/scratches | /scratch_32 | 12,088 | 4.375 | 4 | # Exercise2
import re
print('number')
def is_number(number):
# Write a function to match decimal numbers.
# We want to allow an optional - and we want to match numbers with or without one decimal point:
NUM_RE = re.compile(r'^-*(\d+\.|\.\d+|\d+.\d+|\d+)$')
print(NUM_RE.search(number), end=':')
retu... |
892270cc7bd25a39e8b899cfd2ebc7de5cc2fd10 | DahaLogy/homework | /hw_2_2.py | 547 | 4.15625 | 4 | fib_arr = int(input("Enter the number of array: "))
n1 = 1
n2 = 1
arr = {}
if fib_arr <= 0:
print("The number of terms should be positive")
elif fib_arr == 1:
print("Fibonacci sequence for", fib_arr, "is:")
print(n1)
else:
print("Fibonacci sequence for", fib_arr, "is:")
for count in ran... |
c35335bbdf6171e9f9fe55edba6c273dfaac174e | LukaszMalucha/Python-Various-Useful | /review/refresh_14_map-reduce.py | 379 | 3.78125 | 4 | # -*- coding: utf-8 -*-
maps = map(lambda x: x**2, range(5))
type(maps)
list(maps)
def add(t):
return t[0] + t[1]
list(map(add, [(0,0), [1,1], range(2,4)]))
######################################################################## StarMap
from itertools import starmap
def add(x,y):
... |
91cf37abf5ecc8758dc830f4a040032b01989e9d | amusabji/Coursera | /Algorithmic Toolbox/week2_algorithmic_warmup/4_least_common_multiple/lcm.py | 606 | 3.75 | 4 | # Uses python3
import sys
def gcd(a, b):
# assert 0 <= a <= 2 * 10 ** 9 and 0 <= b <= 2 * 10 ** 9
small = min(a, b)
big = max(a, b)
remainder = 1
while remainder != 0:
remainder = big % small
big = small
small = remainder
return big
def lcm(a, b):
assert 1 <= a <=... |
d72be5ac33387c91adf8a60336f6008757dcd29b | comicxmz001/LeetCode | /Python/224_BasicCalculator.py | 1,520 | 3.671875 | 4 | class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
# the string is actually converted to [+num1,-num2,-num3...]
# so, you should always get the sign before the number.
# There is a trap with ne... |
84a56dbd51f4416721af54c9eb834b33d4f04ced | Feng-Xu/TechNotes | /python/geektime/classCode/chineseZodiac.py | 319 | 3.515625 | 4 | # 记录十二生肖,根据年费判断生效
chinese_zodiac = '猴鸡狗猪鼠牛虎兔龙蛇马羊'
#print(chinese_zodiac[0:4])
#print(chinese_zodiac[-2])
year = 2018
print(year%12)
print(chinese_zodiac[year % 12])
print('狗' in chinese_zodiac)
print(chinese_zodiac + "heheheheh")
print(chinese_zodiac * 2) |
a3aacc8cf4ee0ac791836419cf576d93e8f00b5c | PoojaLokanath/PythonCode | /highest2no.py | 218 | 3.859375 | 4 | x = int(input("Enter value x : "))
y = int(input("Enter value y : "))
if x > y:
print("first")
high=x
elif y > x:
print("Second")
high=y
elif x == y:
print("Same")
print(high*high) |
6b623aeb8c9fdc1f09b8a076ddb5db6a9ac5b36d | BrianMath-zz/ExerciciosPython | /Exercicios - Mundo1/Ex026.py | 239 | 3.984375 | 4 | #Ex. 026
nome = str(input("Digite uma frase: ")).strip().lower()
print("\nQuantidade de letras 'a':", nome.count("a"))
print("Posição da primeira letra 'a':", nome.find("a")+1)
print("Posição da última letra 'a':", nome.rfind("a")+1)
|
d323a53c3ee287d4f560a9a01ca5ecbcc8f35dd5 | kidult00/NatureOfCode-Examples-Python | /chp04_systems/simplePolymorphism/Shape.py | 500 | 3.90625 | 4 | # The Nature of Code - Python Version
# [kidult00](https://github.com/kidult00)
# Example 22-1: Inheritance
class Shape(object):
def __init__(self, x_, y_, r_):
self.x = x_
self.y = y_
self.r = r_
def jiggle(self):
self.x += random(-1, 1)
self.y += random(-1, 1... |
d041770066425d495ecc159b045741f55ad7c43d | sevenhe716/LeetCode | /LinkedList/test_q082_remove_duplicates_from_sorted_list_ii.py | 882 | 3.5 | 4 | import unittest
from LinkedList.q082_remove_duplicates_from_sorted_list_ii import Solution
from common import ListNode
class TestRemoveDuplicatesFromSortedListIi(unittest.TestCase):
"""Test q082_remove_duplicates_from_sorted_list_ii.py"""
def test_remove_duplicates_from_sorted_list_ii(self):
s = Sol... |
6798b8438dc5f531ff47405dcdfbdb1f3d856df4 | thouseef46/MOHAMMED-THOUSEEF-S-ENLIST-BOOTCAMP | /days13.py | 1,112 | 3.578125 | 4 | import re
def is_allowed_specific_char(string):
charRe=re.compile(r'[^a-z,A-Z,0-9]')
string=charRe.search(string)
return not bool(string)
print (is_allowed_specific_char("ABCDEFabcdf123459"))
print( is_allowed_specific_char("122345@#$$%"))
#-------
def text_match(text):
patterns='\w*ab./w*'
... |
55f322c6b60ce3f480d1e4ffa214768513915907 | wujunlin21/Code | /Code 2/56 Merge Intervals.py | 868 | 3.984375 | 4 | # 56. Merge Intervals
'''
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
'''
#Array, Sort
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.... |
dc24ac98dbdd097b5e1b767e8f396a7abe6524c4 | kevincovey/fit-rossby | /scripts/fit_period_log.py | 10,890 | 3.59375 | 4 | # Originally written by Stephanie T. Douglas (2012-2014)
# Modified by Kevin Covey (2019)
# under the MIT License (see LICENSE.txt for full details)
import numpy as np
import emcee
import matplotlib.pyplot as plt
def quantile(x,quantiles):
""" Calculates quantiles - taken from DFM's triangle.py """
xsorted =... |
09cc3ca40043f129d237cf29cc5c72b34102c60b | gabriellaec/desoft-analise-exercicios | /backup/user_017/ch19_2020_09_11_01_33_04_265125.py | 178 | 3.734375 | 4 | def classifica_triangulo(a,b,c):
if a == b and a == c:
print("Equilatero")
elif a == b and a != c:
print("Isosceles")
else:
print("Escaleno")
|
2c075c079761d67075f9a24b6ff9158f60f8c7de | Cozoob/Algorithms_and_data_structures | /BIT ALGO/Programowanie Dynamiczne cz1/canConstruct.py | 1,404 | 3.53125 | 4 | # Created by Marcin "Cozoob" Kozub at 20.04.2021 08:45
def can_construct(target, words):
memo = [0 for _ in range(len(target) + 1)]
memo[0] = True
def rec_can_construct(target, words, memo):
if target == "":
return True
if memo[len(target)] != 0:
return me... |
404492ee7b98c9e86d7c140ac5369d58158dfa5c | arthurk/keylogger | /kla_text_input.py | 1,359 | 3.796875 | 4 | """
Reads the generated csv file from the keylogger
and outputs text input that can be entered into
https://patorjk.com/keyboard-layout-analyzer/
Since the KLA cannot process virtual keys such as Shift, Command
or Alt these are omitted from the output.
"""
import csv
import sys
import argparse
parser = argparse.Arg... |
7c2bb712bb125c103d7ef57adf3d687246579d4e | kiilkim/book_duck | /pythonPractice/test3.py | 3,524 | 3.84375 | 4 | #반복문 .\
#대량데이터를 많이 처리해야 하므로 for,while 등 사용
#반복되는 부분이 탭만큼 띄워짐
i=1
while i <= 10 :
print(i)
i+=1
#break 반복문 빠져나오기
#continue: 계속
#while 문 안에서도 if 문 쓰고 텝해서 써야 한다.
i = 0
while i<=10:
i+=1
if(i%3==0) :
continue #반복문 맨처음
print(i)
#130p예시 나무 꾼
treeHit = 0
while treeHit < 1... |
5c561e1b2efe09a05724e60b2f667f1cf86e670d | taichisano94/adventofcode2020 | /day12/main.py | 5,408 | 4.21875 | 4 | class Direction:
EAST = 0
NORTH = 1
WEST = 2
SOUTH = 3
@staticmethod
def get_direction_string(value):
if value == Direction.EAST:
return "EAST"
elif value == Direction.NORTH:
return "NORTH"
elif value == Direction.WEST:
return "WEST"
elif value == Direction.SOUTH:
re... |
c72412e26ed2f5148fc8520dd1450149c6c11755 | darshanjoshi16/GTU-Python-PDS | /lab5_7.py | 1,053 | 3.953125 | 4 | class point:
def __init__(self,x=0,y=0):
self.x = float(x)
self.y = float(y)
def translate(self,o,p,q):
self.x = self.x + float(o)
self.y = self.y + float(p)
self.z = self.z + float(q)
def __str__(self) :
print("({:.2f},{:.2f},{:.2f})".forma... |
1d4b3adf25c7eb35afad94a6eafe1c16e8966807 | anantpad/helloworld | /hello world.py | 360 | 4.3125 | 4 | """Type Hello World
x=("hello world")
print(x)"""
"""input("what is your name?")
print("It's nice to meet you")
"""
"""ask the user fortheir name, print the greeting that includes the name"""
"""x=input("What is your Name ?")
print ("welcome "+x)"""
"""print("Rashmi")"""
y=input("What is your name")
x=input("How a... |
d2feae638719ce8ac4cd51f209cc78ea91a8bb75 | brian-cai/CS4400 | /Old_Copy/jtest.py | 1,446 | 3.5625 | 4 | import sqlite3
import sys
connection = sqlite3.connect("{}.sqlite3".format("josetest"))
cursor = connection.cursor()
cursor.execute("""DROP TABLE IF EXISTS User""")
cursor.execute("""CREATE TABLE User (email varchar(30),username varchar(30) not null, password varchar(30) not null, primary key(email), unique(username))... |
dbe920acc8f45bdccf8368af47d92dc851d54567 | RohanKD/IDT-SMF-2021 | /SMF_3.py | 1,856 | 3.84375 | 4 | """
Rohan Dalal
20 January 2021
IDT
1st Period
SMF_3
"""
""" Imported libraries are here, I used the random library to generate pseudo random numbers for the random 8 ball statements
Without these libraries I couldn't have done this"""
import os, sys
import cs50
import random
#Pre-processor directivea to maek sure code... |
7fe380db5ce7c5b9c8e145c33dd763e87ed6998b | pccode21/Data-Structures-and-Algorithms | /List/Delete_duplicate_data.py | 1,654 | 3.796875 | 4 | """只能用于数字"""
List = [1, 3, 6, 3, 2, 2, 3, 4, 5, 4, 6, 7]
if List:
List.sort(reverse=True) # 把 List 重新排序,默认是升序
# list.sort( key=None, reverse=False)
# key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
# reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。
last = List[-1]
... |
2256436f5f656022fdb9021d913fd91ef8407b76 | om-henners/advent_of_code | /2019/day8/solution1.py | 883 | 4.125 | 4 | #!/usr/bin/env python
"""
Solution for day 8 part 1
"""
import io
import numpy as np
def make_image(path: str, cols: int, rows: int) -> np.ndarray:
"""
Use simple reshaping to make the array
"""
img = np.loadtxt(path, delimiter=' ', dtype=np.int)
img = img.reshape(-1, rows, cols)
return img
... |
3627648506f3f7f0b6001bf2d00e0db55baffea3 | ViranderSingh/DataTypes | /main.py | 11,570 | 4.375 | 4 | # 1. Fundamental Data Types
# int
# float
# complex
# str
# bool
# list
# dict
# tuple
# set
# 2. Classes -> Custom Types
# 3. Specialized Data Types
# 4. None
# Let's Start
# 1. Fundamental Data Types
# NUMBERS Data Types -> int and float
print(type(3 + 4))
print(type(3 - 4))
print(type(3 * 4))
print(type(3 / 4)... |
262ce4751f306afbc73e7f6eb21b9ecc1a1eb307 | allenlgy/Django-project | /08_面向对象基础/人狗大战.py | 891 | 3.703125 | 4 | class Dog(object):
role = 'dog'
def __init__(self, name, breed, attack):
self.name = name
self.breed = breed
self.attack = attack
self.life = 100
def bite(self,person): # 这里传进来的是一个对象
person.life -= self.attack
print("狗【%s】咬了人[%s]%s血,人还剩[%s]"%(self.name,per... |
97311b43012688109387a932c9eee73441f9325c | oliverdippel/Codewars | /Pathfinder1.py | 2,710 | 3.5625 | 4 | class Node:
def __init__(self, position, symb):
self.position = position
self.symb = symb
self.neighbours = []
class Graph:
def __init__(self, map):
# parsing
m = map.split('\n')
self.rdim = len(m[0])
self.cdim = len(m)
tupler = lambda i: (i // ... |
26b24f17bc07c3efdf8e2669db1ee5b3413bf315 | darup67/algorithms_and_data_structures | /python/sort/qsort_variations/quicksort_median.py | 2,474 | 3.828125 | 4 | import math
count = 0
def quicksort(inputList, lo=0, hi=None):
global count
## Default value for hi (not possible to assign in parameter list)
if hi == None:
hi = len(inputList) ## the hi value for range is exclusive
## Base case: if the subarray inputList[lo:hi] is of length 1 o... |
ab4eaaccd8c6a4de89332947d533de8e17774fb7 | inesjoly/toucan-data-sdk-1 | /toucan_data_sdk/utils/postprocess/math.py | 7,319 | 4.3125 | 4 | import operator as _operator
from typing import List
MATH_CHARACTERS = '()+-/*%.'
def _basic_math_operation(df, new_column, column_1, column_2, op):
"""
Basic mathematical operation to apply operator on `column_1` and `column_2`
Both can be either a number or the name of a column of `df`
Will create ... |
7466f8c6b3d05b1b251bb8cbe883e40ef5b46230 | MitaliSharma12052001/CS142_2020 | /linkedlist.py | 719 | 4.03125 | 4 | class Item:
def __init__(self, val):
self.val = val
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def insertAtBegin(self,val):
# Adds an item to front (head) of the linkedlist
newItem = Item(val) # Creates a new BOX
newItem.next = s... |
127d4fb8434b66e5830690f56bd165bdd960f2c2 | jinnygym/Prepro-Python | /function.py | 283 | 3.640625 | 4 | """function - DAY3"""
import math
math.ceil() # up
math.floor() # down
math.factorial()
math.sin()
math.cos()
math.tan()
math.radians() # Degrees to radians
math.degrees() # Radians to degrees
math.pi() #3.141592653589793
math.sqrt()
import math
def main():
"""function""" |
9197e6c5c5f5593004094773b1a36f781b8eb5fa | schoobydrew/132LAVA | /ImplentationOf GUI With Input/encryptv3.py | 1,002 | 4.09375 | 4 | ############################################
# ASCII encrypter v3
# Uses ASCII values to encrypt a user
# generated password.
############################################
from random import randint
MIN_VALUE = 65
MAX_VALUE = 122
# dictionary for later use
def encrypt(userPass):
newPass = ''
for char in userPass... |
daed03a96935178bde84ad4dbeb745d3d197ac41 | Greek-and-Roman-God/Athena | /codingtest/week08/level9_math2/taxicab_geometry.py | 179 | 3.890625 | 4 | # 택시 기하학
# 문과는 문제 이해부터 힘든 문제 흐윽
import math
r=int(input())
area1=round((r**2)*math.pi,6)
area2=round(r*r*2,6)
print(area1)
print(area2) |
20a1e44c1c10dc2d5088d9f17ea83d1acd3a7b6c | purna-manideep/Python | /Trees/depthFirstSearchBinary.py | 881 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from binaryTreeBetter import *
def depth_first_search_binary(root, fcn):
stack = [root]
while len(stack) > 0:
print("at node " + str(stack[0].get_value()))
if fcn(stack[0]):
return True
else:
temp = stack.pop(0)
if te... |
7d21b9c0353937e5756444ff11a521dd58563a3b | PeterCHK/hackerrank | /maxwater2.py | 1,004 | 3.59375 | 4 | def maxWater(height,n):
a = []
for i in range(n):
a.append([height[i],range(n)[i]])
b = sorted(a, key=lambda x : x[0])
minIndSoFar = b[n-1][1]
maxIndSoFar = b[n-1][1]
_max = 0
for i in range(n-2,0,-1):
#Current building paired with the building
#greater in height and... |
d7291857b8b2f2d79c8285e175eb2c4e1df148cc | iam-amitkumar/BridgeLabz | /DataStructureProgram/Test.py | 2,968 | 4.21875 | 4 | """This program takes the month and year as user-input
and prints the Calendar of the month. Store the Calendar
in an 2D Array, the first dimension the week of the month
and the second dimension stores the day of the week.
@author Amit Kumar
@version 1.0
@since 09/01/2019
"""
# function to check whether the entered ... |
3f2f5bc98eae7aab2700ad4d1c538b16a509c35c | Zelenskiy/informatics_10_prof | /Урок 29, 30. Функції/Функція з параметрами.py | 162 | 3.671875 | 4 | def avg(x):
sum_values = sum(x)
count_values = len(x)
return sum_values / count_values
x1 = [2, 3, 4]
x2 = (2, 3, 4)
print(avg(x1))
print(avg(x2))
|
88879e46f6b01992787566298b60821a3af45e27 | kentxun/PythonBase | /splitSearch/findPos.py | 901 | 3.84375 | 4 | '''
有一个有序数组arr,其中不含有重复元素,请找到满足arr[i]==i条件的最左的位置。
如果所有位置上的数都不满足条件,返回-1。
给定有序数组arr及它的大小n,请返回所求值。
测试样例:
[-1,0,2,3],4
返回:2
'''
# -*- coding:utf-8 -*-
class Find:
def findPos(self, arr, n):
# write code here
# 如果 头 小于 尾,则是逆序,
if arr[0] > n-1 or arr[n-1] < 0:
return -1
left ... |
48f9690797784aae42d1d8941f9e6bebb57d2233 | cybernuki/holbertonschool-higher_level_programming | /0x0B-python-input_output/12-student.py | 764 | 3.9375 | 4 | #!/usr/bin/python3
"""This module Defines a Student class"""
class Student():
"""Class that represents a student"""
def __init__(self, first_name, last_name, age):
"""Constructor method"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(... |
67da17f9b9f6a119243821358b753c1fd7868688 | rzhadev/PCsolutions | /projecteuler/projecteuler9.py | 158 | 3.671875 | 4 | def special_triplet(n):
for a in range(3,n):
for b in range(4,n):
c = n - a - b
if c**2 == a**2 + b**2:
return a*b*c
print(special_triplet(1000)) |
94d6639dd29219c37bf1fb8b5d87317da1c33a8a | 5l1v3r1/python-advance | /Thread communication queue in python.py | 1,750 | 4.34375 | 4 | #The queue class of queue module is useful to create a queue that holds the data produced by the producer.
#the data can be taken from the queue and utilized by the consumer.
#we need not use locks since queues are thread safe.
#creating queue object:
# from queue import Queue
# q=Queue()
#Queue mthods:
... |
308ff933752c75c0c43963a6b058010386285189 | thejaredchapman/JMC_Python | /GeneratorsExample.py | 629 | 4 | 4 | ## GENERATOR EXAMPLES
## Generate numbers from square
def gensquare(N):
for i in range (N):
yield i**2
for x in gensquares(10):
print(x)
## Generate numbers from range
import random
random.randint(1,10)
## Generate lowest and highest numbers in range
def rand-num(low, high, n):
for i in range(n):
yield ra... |
de79a6536a7ec1eefa64acc907361a338e707f42 | AbhishekDoshi26/python-programs | /Panda/math.py | 395 | 3.78125 | 4 | import pandas as pd
y = pd.read_csv('data.csv', squeeze=True, usecols=['Y-Axis'])
print(y.count()) # Counts number of rows
print(len(y)) # Counts number of rows
print(y.sum()) # Adds all data
print(y.mean()) # Calculates Average
print(y.std()) # Calculates Standard Deviation
print(y.min()) # Prints minimum value... |
0bf9333d263de5079e1b6ca6de9e163c756f6f91 | pdemeulenaer/spark-training | /spark-exercises/spark-ex-aggregations.py | 14,819 | 3.84375 | 4 | # Databricks notebook source
# MAGIC %md-sandbox
# MAGIC
# MAGIC ### Aggregations: GroupBy
# COMMAND ----------
# You have such a df.
df = spark.createDataFrame([("1991-11-15",'a',23),
("1991-11-16",'a',24),
("1991-11-17",'a',32),
... |
6d757b0b4d5de60e3d772546beb73fe090b92881 | Aasthaengg/IBMdataset | /Python_codes/p00001/s050837870.py | 90 | 3.609375 | 4 | s = [int(input()) for i in range(10)]
s.sort(reverse = True)
for i in s[:3]:
print(i)
|
2c0780bacbc416d53cb21701cf00fc67471c8afe | Salihbayraktar/Patika-Python | /CodeWars/4-Kyu/SumByFactors.py | 1,887 | 3.71875 | 4 | def find_and_sum_prime_numbers(n, resultDict):
rawN = n
n = abs(n)
i = 2
primeSet = set()
while i * i <= n:
if n % i:
i += 1
else:
n //= i
if i not in resultDict:
resultDict[i] = rawN
elif i not in primeSet:
... |
4f522dc2fe41a5c71b37d840c7a1309b6d1127c0 | kimjeonghyon/Algorithms | /Python/LG편의점.py | 1,257 | 3.515625 | 4 | # 물품 코드
# 커피 coffee 우유 milk 즉석밥 rice 물 water 휴지 paper 라면 ramen
codes = {'coffee':'커피','milk':'우유','rice':'즉석밥','water':'물', 'paper':'휴지','ramen':'라면'}
records = ['coeeff','COF%#@$eef','mi kl','ter%$^wa','MKIL','Mk%@#l$%i','water','WATER']
# 3-1 위의 판매 기록에서 특수문자 빈칸을 제거하고 소문자로 변경하여 출력하라.
# coeeff, cofeef, mikl, terwa,... |
6821af9f43f71bbe28a105c7cc01379e16ff72fa | kthure01/DevOps20 | /Python/exercises0/string-length/string_length.py | 222 | 3.78125 | 4 | def get_length(name):
return len(name)
length = get_length("Guido van Rossum")
print(length, "(Guido är skaparen av Python)" )
# The correct answer here should be `16`
# Gain some extra score by answering who "Guido van Rossum" is ;)
|
5e6e4499ba4a177e74d5df6dd493630078fb5638 | foleymd/boring-stuff | /debugging/raise_assert.py | 1,380 | 4.1875 | 4 | # the raise and assert statements
import traceback, os
# print a box
def box_print(symbol, width, height):
if len(symbol) != 1:
raise Exception('The input symbol must be a single-character string.')
if (width < 2) or (height < 2) :
raise Exception('Box width and height must be greater th... |
e7d2de023d38529bece8d7e4dface47796345c93 | chenyi229/Data-Structure | /chenyi_07_选择排序.py | 246 | 4.03125 | 4 | def selectSort(list):
for i in range(0,len(list)):
for j in range(i+1,len(list)):
if list[i]>list[j]:
list[i], list[j] = list[j], list[i]
print(list)
list=[0,12,2,1,5,1]
selectSort(list) |
b85e38178e74d80b2e59503ff90782f680a26c52 | OBigVee/Toy-projects | /pig Latin/pigLatin.py | 1,358 | 4.25 | 4 | """
this program encodes English-language phrases into pig Latin.
Pig Latin is a form of coded language. There are many different ways to form pig Latin phrases.
this application used the following algorithm:
Tokenize the phrase into words.
To translate each English word into a pig Latin word, place the first
letter o... |
339a1d48a6489132f726e87dbf39c6486e945448 | sushrut91/ComputerSecurity-Project1 | /Q2-GCD.py | 1,027 | 4.03125 | 4 | #!/usr/bin/python3
from _ctypes import FormatError
def main():
try:
n1 = int(input('Enter an integer: '))
n2 = int(input('Enter an integer: '))
if n1 == 0 or n2 == 0:
print('Enter n1 and n2 both should be greater than 0')
return -1 # Return error
else:
... |
880916cf018bf7ae2d23fd09ce23c803ca07b6fb | sgnajar/Wikipedia-web-crawl | /webCrawler.py | 2,349 | 3.59375 | 4 | # By: Sasan Najar
# Email: sasangnajar@gmail.com
# This code is to:
## STEP1: Go to a random Wikipedia page and click the fisrt link
## STEP2: Then on that page click the first link in the main body of the article text
import requests
import time
import urllib
import bs4
startURL = "https://en.wikipedia.org... |
12471d763e202b66f334cb53b5369cbe1a9b3167 | Tanavya/ProjectEuler | /EulerP43.py | 488 | 3.53125 | 4 | import itertools
import time
start = time.time()
primes = [2,3,5,7,11,13,17]
num = "0123456789"
perms = [ "".join(x) for x in itertools.permutations(num)]
def subStringDivisible(n):
if int(n[3]) % 2 != 0:
return False
for i in range(1,8):
if int(n[i:i+3]) % primes[i-1] != 0:
re... |
d3c91d01256cb28d136a2f459925d8ffca5b621f | s5003597/Python-Examples | /session_1/input_and_conditions/02_conditions.py | 230 | 4.09375 | 4 | command = input('Please enter a command: ')
if command == 'print':
print(command)
elif command == 'name':
name = input('Please enter your name: ')
print(name)
else:
print('The command you entered was not valid!')
|
3458c3efde5dc6e23fef3dac35687ddc7f5983f8 | oliviersamin/P7_Resolvez-des-problemes-en-utilisant-des-algorithmes-en-Python | /bruteforce.py | 4,272 | 3.921875 | 4 | # livrable = liste d'actions à acheter du type [{'name': 'action1', 'quantity': x},...]
# constraints : 1. buy only 1 action and only once
# 2. cannot buy a part of action but only a plain number
# 3.maximum money to spend = 500 euros
# 4. Read a file containing shares... |
e4baa866d15fe11ee18110b12c21246fd10ade79 | nathanbaja/Python-Exercises-CursoEmVideo | /ex075.py | 420 | 3.859375 | 4 | a = int(input('Digite um numero '))
b = int(input('Digite um numero '))
c = int(input('Digite um numero '))
d = int(input('Digite um numero '))
ns = (a, b, c, d,)
print(f'Voce digitou {ns.count(9)} vezes o numero 9')
if 3 in ns:
print(f'O primeiro 3 aparece na posicao {ns.index(3)+1}')
x = 0
print(f'Os num... |
4670312b1707a632dcfe9e6101c6558ba276fae1 | CharlesBasham132/com404 | /second-attempt-at-tasks/2-guis/window-layouts/1-place/bot.py | 1,287 | 3.90625 | 4 | from tkinter import *
class Gui(Tk):
# initialise window
def __init__(self):
super().__init__()
#set window attributes
self.title("Newsletter")
self.configure(bg="yellow",
height=500,
width=500)
self.add_heading_label()
... |
1244e619d427faaca90ffabf313b98db4c118e19 | burakunaltr/Project-Euler | /SORULAR/4 - Largest palindrome product.py | 539 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
__author__ = "Burak Ünal"
enBuyuk = 0
for i in ran... |
53d3ef9e55a7a6b6ec985a19798378502aa32fe2 | theianrobertson/movie-trivia | /pull_data.py | 6,580 | 3.734375 | 4 | """
Pull Data - some methods for pulling data out.
Author: Ian Robertson
"""
import datetime
import logging
import os
from bs4 import BeautifulSoup
import requests
def get_site(url, filename):
"""Pulls out the html from a site, and saves it."""
logging.info('getting {}'.format(url))
r = requests.get(url... |
7b167808b27694356410e4a951d5dfabe7a1ab19 | mindnhand/Learning-Python-5th | /Chapter18.Arguments/print3_alt2.py | 631 | 3.53125 | 4 | #!/usr/bin/env python3
#encoding=utf-8
#--------------------------------------------
# Usage:
# Description:
#--------------------------------------------
import sys
def print3(*args, **kargs):
sep = kargs.pop('sep', ' ')
end = kargs.pop('end', '\n')
file = kargs.pop('file', sys.stdout)
if karg... |
1f02670973604cf27409388a756d6e878ff5c39b | EduardoSanglard/ProjetoEstudos | /EstruturaSequencial/ex11.py | 385 | 4.09375 | 4 | try:
int1 = int(input('Primeiro Inteiro: '))
int2 = int(input('Segundo Inteiro: '))
real = float(input('Numero Real: '))
print('Dobro do primeiro com metade do segundo: ', (int1*2)+int2)
print('Soma do triplo do primeiro com o terceiro: ', (int1*3)+real)
print('terceiro elevado ao cubo: ', rea... |
6068bba4400e2009854af16d019df4738d051903 | sithugirish/march-2018 | /dona.py | 96 | 3.640625 | 4 | print"enter two number"
a=int(raw_input())
b=int(raw_input())
c=a-b
print"difference is"+str(c)
|
52c4f66b1426b8580ed327d1e8e730a54800963e | jditlee/tmdSurprise_leetcode_hot100 | /[139]单词拆分.py | 2,439 | 3.5 | 4 | # 给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
#
# 说明:
#
#
# 拆分时可以重复使用字典中的单词。
# 你可以假设字典中没有重复的单词。
#
#
# 示例 1:
#
# 输入: s = "leetcode", wordDict = ["leet", "code"]
# 输出: true
# 解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
#
#
# 示例 2:
#
# 输入: s = "applepenapple", wordDict = ["a... |
93627c8653e8f572b320cf4de701dff5fac5896b | S-Tim/Codewars | /python/deodorant_evaporator.py | 1,064 | 4.15625 | 4 | """
Deodorant Evaporator
This program tests the life of an evaporator containing a gas.
We know the content of the evaporator (content in ml), the percentage of foam or gas lost every day (evap_per_day) and the threshold
(threshold) in percentage beyond which the evaporator is no longer useful. All numbers are strictl... |
81162f76f77aaed4a5cec6305d7dee545bb26a03 | porigonop/code_v2 | /cours_POO/TP1/Joueur.py | 2,604 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Domino import *
class Joueur:
""" Classe représentant un joueur
:Attribut nom: String, représentant le nom du joueur
:Attibut main: liste, représentant la main du joueur courant,liste
represente l'ensemble des dominos qu'il a à joue... |
e201e45154ed465e225214665630fae33add8735 | layshidani/learning-python | /lista-de-exercicios/Curso Python mundo 1 fundamentos cursoemvideo/Exercício Python #007 Média Aritmética.py | 300 | 3.625 | 4 |
# coding: utf-8
print('Olá! Vamos calcular a média do aluno!')
nota1 = float(input('Qual foi a primeira nota? '))
nota2 = float(input('Qual foi a segunda nota? '))
nota3 = float(input('Qual foi a terceira nota? '))
nf = (nota1 + nota2 + nota3)/3
print('\nA média final é: {:.2f}'.format(nf))
|
ef157729ec3f973f5f9a38183f73cbf3799fdf94 | Wizmann/ACM-ICPC | /Leetcode/Algorithm/python/1000/00232-Implement Queue using Stacks.py | 507 | 3.921875 | 4 | class Queue(object):
def __init__(self):
self.a = []
self.b = []
def push(self, x):
self.a.append(x)
def pop(self):
if not self.b:
self.do_move()
return self.b.pop()
def peek(self):
if not self.b:
self.do_move()
... |
e23df7d253df0c33d7a7a33ac01b49b94cd47c4a | blazarus23/Pandas-tutorial- | /SalesData.py | 5,065 | 3.578125 | 4 | import pandas as pd
import os
df = pd.read_csv("Sales_Data/Sales_April_2019.csv")
pd.options.display.width= None
pd.options.display.max_columns= None
pd.set_option('display.max_rows', 3000)
pd.set_option('display.max_columns', 3000)
files = [file for file in os.listdir("Sales_Data")]
## create empty df to store all ... |
449ef891ba8c0b0e717a91bbd344fa325736e957 | Nethermaker/school-projects | /intro/code_hints.py | 942 | 4.59375 | 5 | #How do I rotate a letter?????
#I am going to give you two completely different methods.
#Method 1: The ASCII method!
#The ord() function will take a letter and return its ASCII value.
print ord('a')
print ord('J')
#The chr() function takes an ASCII value and returns its character.
print chr(97)
pri... |
f4c608184ed50110919bacf8563aaf8f81eba311 | Kevinkang0211/Advanced-Algorithm | /Minimum Spanning Tree/MST_kruskal.py | 2,326 | 3.703125 | 4 |
import numpy as np
import pandas as pd
# Kruskal's algorithm in Python
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
# Search function
def find(self, parent, i):
... |
048f0e42243aa8f5305f60e5bf902e16abaa18bf | puneet4840/Data-Structure-and-Algorithms | /Linked List in Python/2 - Doubly Linked List/10 - Count Total Number of Node.py | 1,864 | 4.15625 | 4 | # Count Total Numer Of Nodes in Doubly Linked List.
print()
class Node():
def __init__(self,data):
self.prev=None
self.data=data
self.next=None
class Linked_list():
def __init__(self):
self.start=None
def Insert_Node(self,data):
temp=Node(data)
... |
5982302f71cb6373cdabc725ff8d2fc6ac4ec4c1 | threedworld-mit/tdw | /Python/tdw/container_data/container_tag.py | 370 | 3.5625 | 4 | from enum import Enum
class ContainerTag(Enum):
"""
A tag for a container shape.
"""
on = 1 # An object on top of a surface, for example a plate on a table.
inside = 2 # An object inside a cavity or basin, for example a toy in a basket or a plate in a sink.
enclosed = 4 # An object inside ... |
abbd1a5905ac4ba4ca80181cc2b58abc5c8cae09 | medhini/ECE544-PatternRecognition | /mp1/train_eval_model_svm.py | 2,784 | 3.640625 | 4 | """
Train model and eval model helpers.
"""
from __future__ import print_function
import numpy as np
import sklearn
from models.support_vector_machine import SupportVectorMachine
import random
from sklearn.utils import shuffle
def train_model(data, model, learning_rate=0.001, batch_size=100,
num_steps... |
862e4140810e770ba062ad1a3bfd17ceee7c2756 | eleisoncruz/myPythonExploration | /deleteCreateContents.py | 649 | 4.21875 | 4 | # This will delete the contents of the file then the program will allow you to create new contents
# of the file.
from sys import argv
script, filename = argv
print "We will erase first the contents of %s file" %filename
print "Press CTRL-C to cancel."
print "Hit ENTER to proceed."
raw_input("? ")
print "Opening th... |
1ec3fc987b6671befb0194698407178c0c82c200 | Beat30/Exercise_CS1 | /1_3.py | 232 | 4 | 4 | #Ex. 1.2
#calculate nth root of a A>0
y=0.0
x=1.0
n=2
A=int(input('A= '))
x=A/2
def nroot(A,x,n):
x=1/n*((n-1)*x+A/x**(n-1))
return x
while x!=y:
y=x
x=nroot(A,x,n)
print(x)
print( 'nth root of A is ', x)
|
615a921bb959c82a186df0ffbb24e16e321750cd | ericksonlopes/PandasV1.2.3 | /10_minutos_para_os_pandas/07_agrupamento.py | 598 | 4.03125 | 4 | import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
"B": ["one", "one", "two", "three", "two", "two", "one", "three"],
"C": np.random.randn(8),
"D": np.random.randn(8),
}
)
print(df, '\n... |
061b9add0a375df2d2f319efbc0937c95506cf87 | kmehran1106/HackerRank-Python | /Easy/Save Prisoner/code_save_prisoner.py | 1,725 | 3.53125 | 4 | import pytest
from typing import List
def save_the_prisoner(prisoner_count: int, sweet_count: int, start_chair: int):
"""
[
if sweets > prisoners, then we need to find the remainder sweets after full passes
then, we'll be able to find out the last prisoner
the edge case here however is... |
4968572741bacc457beaa1851c83b38bea14bc06 | FarzanAkhtar/Intro-to-Webd | /Week 1 Practice Problems/1.py | 185 | 4.15625 | 4 | #Fibonacci numbers
n=int(input("Enter an Integer:"))
a=0
b=1
print("First",n,"fibonacci numbers are:")
print(a)
print(b)
for i in range(2,n):
c = a + b
print(c)
a=b
b=c
|
4e13e69478eff7a6e654b37c6e248745929b29a2 | bartoszmaleta/4th-Self-instructed-week | /errors_and_exceptions exercises3.py | 878 | 3.796875 | 4 | print('------------------------------------------------ 1')
person = {}
properties = [
("name", str),
("surname", str),
("age", int),
("height", float),
("weight", float),
]
for property, p_type in properties:
valid_value = None
while valid_value is None:
try:
value = ... |
6b22a0d77640e76b2ae9e5390a8dde752e396d94 | andersonvelasco/Programming-2020B | /Entrenamiento Algoritmico/primos.py | 603 | 4.03125 | 4 | '''Script que determina si un numero ingresado por el usuario es primo o compuesto
Teoria:
Que es un número primo:
SOn aquellos no. enteros divisibles unicamente entre 1 y por si mismo. Solo 2 divisores
'''
#Call packages or libraries
import os
os.system("cls") # thsi kine let you clear screen.
counter = 0
i =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.