blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f2cb4c235e9fdbed76c69ddcfb207a959f0b88bc | sinusk8/Lessons | /Home_work_L1_3.py | 252 | 3.875 | 4 | number = int(input('Введите любое число: '))
n = 0
if number < 10:
n = number
while number > 10:
a = number % 10
number //= 10
if a > n:
n = a
print('Наибольшая цифра в числе {}'.format(n))
|
d4b68e0f3e7d829962c0f20e6329db84522547e6 | I-G-P/Python | /Programming Basics/Simple Operations and Calculations - Exercise/04. Tailoring Workshop.py | 524 | 3.65625 | 4 | number_of_tables = int(input())
lenght_of_tables = float(input())
width_of_tables = float(input())
price_of_cover = 7
price_of_square = 9
total_area_of_cover = number_of_tables * (lenght_of_tables + 2 * 0.3) * (width_of_tables + 2 * 0.3)
total_area_of_square = number_of_tables*(lenght_of_tables / 2) * (lenght_of_tabl... |
4ddb1878b6ecedda9f274801aef997ef838dfd24 | Damian1724/Hackerrank | /Algorithms/Sorting/InsertionSort-Part2.py | 663 | 4 | 4 | /*
Author: Damian Cruz
source: HackerRank(https://www.hackerrank.com)
problem name: Algorithms>Sorting>InsertionSort-Part2
problem url:https://www.hackerrank.com/challenges/insertionsort2/problem
*/
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the insertionSort2 function below.... |
d06f20026f517acbc3b20e7c105faed16dd36852 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_79_size_of_object.py | 212 | 3.65625 | 4 | """Write a Python program to get the size of an object in bytes."""
import sys
def give_me_size(object):
return sys.getsizeof(object)
print(give_me_size("Basic_Part_I/ex_59_feet_inches_to_centimeters.py")) |
7ec979896471be5f23be68bc220af9107d43ca06 | serrotsabin/graphics_assignment | /Midpoint Circle Drawing Algorithm.py | 728 | 3.765625 | 4 | from Tkinter import *
r = int(raw_input("Radius: "))
root=Tk()
root.title("CIRCLE")
height=500
width=500
canvas=Canvas(root,height=height,width=width)
canvas.pack()
xc=int(height/2)
yc=int(width/2)
x=0
y=r
p=1-r
while(x<y):
if(p<0):
x=x+1
p=p+2*(x+1)+1
else:
x=x+1
y=y-1
... |
dc162897191f97407f21e5c84766409127a60712 | NicolasRementeria/university-institute-and-courses | /Courses/the-python-mega-course/1- Introduction/1- Basics/15. Type Attributes, 16. How to Find Out What Code You Need/Excercise3.py | 185 | 4.1875 | 4 | # Modify String (E)
# Find the proper function or method that converts the string in username into lowercase letters and print the output
username = "Python3"
print(username.lower()) |
7c70504d9addca4c0e1292d2281027bbbbde64ca | gciotto/learning-python | /part6/exercise5/sets_operations.py | 1,814 | 3.8125 | 4 | class Set():
def __init__ (self, value = []):
self.data = []
self.concat(value)
def intersect (self, other):
res = []
for x in self.data:
if x in other:
res.append(x)
return Set(res)
def union (self, other):
... |
ac9af52e60547eb4e8ff250792e3b48ff716b017 | serleonc/experimento-git | /ordenmiento.py | 354 | 3.578125 | 4 | # lista =[2,5,1,4,9,7,8,6]
# for i in range(1, len(lista)):
# j = i
# while j > 0 and lista[j] < lista[j-1]:
# lista[j],lista[j-1] = lista[j-1],lista[j]
# j-=1
# print(lista)
lista =[2,5,1,4,9,7,8,6]
for i in range(1, len(lista)):
j = i
while j > 0 and lista[j-1] < lista[j]:
lista[j],lista[j-1] = lista[j... |
3dc9b0aa3a45aad8ab820764f09af0bc8836b9f8 | acailuv/WarehouseOS | /WarehouseOS.py | 18,239 | 3.6875 | 4 | import pickle
#utility function to get input etc.
def invalid_input_string(): #a string that will be displayed if something is invalid
print("Invalid Input. Please try again.", end='')
def get_valid_int(caption=""): #returns a valid integer
while True:
try:
n = int(input(caption))... |
2f342fb25d35880e004e0159cbf61fc0c7a12ecf | shishengjia/PythonDemos | /字符串和文本/字符串_在开头或结尾作文本匹配_P38.py | 456 | 4.1875 | 4 | """
使用str.startswith(),str.endswith()
需要注意的是在传入参数时不能传入列表或者集合,必须首先转化成tuple
"""
filename = 'spam.txt'
print(filename.endswith('.txt')) # True
url = 'http://www.python.org'
print(url.startswith('http:')) # True
import os
filenames = os.listdir('../') # 上一层目录下的文件
print(filenames)
# 查找py文件
pyfile = [name for name in fil... |
dd60c8e96ae77a9da6a60c5d096f16c80aebe746 | obligate/python3-king | /it-king/day09-thread/04_0queue_队列.py | 1,726 | 4.375 | 4 | # Author: Peter
# queue队列
# queue is especially useful in threaded programming when information must be exchanged safely between multiple threads.
# class queue.Queue(maxsize=0) #先入先出
# class queue.LifoQueue(maxsize=0) #last in fisrt out
# class queue.PriorityQueue(maxsize=0) #存储数据时可设置优先级的队列
# Constructor for a... |
8e7cabf9c01a30bb4642c5d174076699c1e1c89a | Sakura1221/Python-100-Days | /Day01-15/My_Code/Day04/for4.py | 322 | 3.703125 | 4 | """
输入一个正整数判断它是不是素数
"""
from math import sqrt
num = int(input("请输入一个正整数:"))
is_prime = True
if num == 1:
is_prime = False
else:
for i in range(2, int(sqrt(num)+1)):
if num % i == 0:
is_prime = False
break
print(is_prime) |
8a14c0c4edc86c413051d5fa75a0d0986f184f58 | bennysetiawan/DQLab-Career-2021 | /Machine Learning with Python for Beginner/27.tugas-praktek-6.py | 691 | 3.59375 | 4 | from sklearn.metrics import mean_squared_error, mean_absolute_error
import numpy as np
import matplotlib.pyplot as plt
#Calculating MSE, lower the value better it is. 0 means perfect prediction
mse = mean_squared_error(y_test, y_pred)
print('Mean squared error of testing set:', mse)
#Calculating MAE
mae = mean_abso... |
4f17a5ac376ed4ac536e7a2efccf833b9fe9bb25 | screnary/Algorithm_python | /stack_227_caculator_II.py | 2,911 | 3.84375 | 4 | """ 实现字符串中包含:数字,+, -,*, / 的基本计算器
" 3+2* 2 "
计算:先将所有数字压栈,最后直接对栈内元素求和
"""
import pdb
class Solution:
def calculate(self, s):
""" input| s: str
output| res: int
"""
priority = {'+': 1,
'-': 1,
'*': 2,
'/': 2}
def... |
cd82ff1acac72ddad839e846bcaf99dd893c201f | keithmannock/LaTeX-examples | /documents/Numerik/Klausur6/aufgabe2.py | 252 | 3.9375 | 4 | from math import exp, log
def iterate(x, times=1):
#x = x - (2.0*x - exp(-x))/(2.0+exp(-x)) #Newton
x = 0.5*exp(-x) #F_1
#x = (-1)*log(2.0*x) #F_2
if times > 0:
x = iterate(x, times-1)
return x
print(iterate(0.5,6))
|
bfb86b87dc58d3566a5169e13c5bbe2e8d882909 | phanisai22/GCTC-Challenges | /04_neural_hack/00_max_sum.py | 750 | 3.78125 | 4 | def max_sum(input1, input2, input3):
row_sum = []
col_sum = []
s = 0
for i in range(input1):
j = i * input2
for _ in range(input2):
s += input3[j]
j += 1
row_sum.append(s)
s = 0
for i in range(input2):
for j in range(input1):
... |
158571ca461f14044b7050f3ab7ef81f1b7bcb57 | yoedhis/latihan-git | /main.py | 711 | 4.09375 | 4 | print('Hello Python')
height = 10
base = 2
area = height*base/2
print "Area is", area
def calculate_triangle(height,base):
return height*base/2
result1=calculate_triangle(10,2)
result2=calculate_triangle(30,5)
result3=calculate_triangle(15,2)
print"Result 1 = ", result1
print"Result 2 = ", result2
print"Result 3 ... |
ffa44619807e3179968aecf7e1666c071681b414 | rmcl/interview_prep | /dynamic_programming/punchcards_total_cost.py | 2,166 | 3.984375 | 4 | class OptimalPunchcarding(object):
"""Dynamic programming solution to find an optimal set of punchcards to run.
Original problem from: https://medium.freecodecamp.org/demystifying-dynamic-programming-3efafb8d4296
The original problem asked a similar question. I modified it to just find solutions that w... |
3db6d323b018d8f374e5f536ea6a5937e28c5b2a | peterhchen/200_NumPy | /03_NumPy/0310_Iterate/08_Enumerate.py | 102 | 3.546875 | 4 | import numpy as np
arr = np.array([1, 2, 3])
for idx, x in np.ndenumerate(arr):
print(idx, x) |
218fa689fc8b10666bf52040f0750dad1a25ff90 | allenwhc/Algorithm | /Company/Google/BTLongestConsecutive(M).py | 1,019 | 3.734375 | 4 | class TreeNode(object):
def __init__(self, x):
self.val=x
self.left=None
self.right=None
class Solution(object):
def longestConsecutive(self, root):
# @param root: TreeNode
# @return: int
if not root: return 0
res=[0]
def dfs(root, target, count, res):
# @param root: TreeNode
# @param target: i... |
619ecea20b374866f5a76382a0baa339c458ad67 | Am-dexter/90daysPythonProjects | /Day6/sets.py | 461 | 4.375 | 4 | #
shopping = {'cereals', 'milk', 'bread', 'butter', 'sodas', 'beer'}
#loop through the set
if 'milk' in shopping:
print("Buddy, you already have milk! ")
else:
print("You need to buy milk!")
#Add items to the set
shopping.add('oranges')
print(shopping)
#add multiple items to the set
shopp... |
3d9771c358dd074bd473a57dba37e415bc0b7b7e | Luweyh/Hash-Map-and-Min-Heap | /min_heap.py | 9,362 | 3.796875 | 4 | # Course: CS261 - Data Structures
# Assignment: 5
# Student: Luwey Hon
# Description: This program represent a min heap which
# is like a tree but all nodes child must be greater than
# the parent's node. It implements several ADTS for
# the min heap.
# Import pre-written DynamicArray and LinkedList classes
from a5_i... |
e411266560b681e1656180912c2f50b0cd4a9007 | goldiekapur/algorithm-snacks | /leetcode_python/1060.Missing_Element_in_Sorted_Array.py | 479 | 3.671875 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Time complexity: O()
# Space complexity: O()
# # https://leetcode.com/problems/missing-element-in-sorted-array/
class Solution:
def missingElement(self, nums: List[int], k: int) -> int:
i = 0
j = len(nums) - 1
while i < j:
mid = (i + j... |
201d36b5caf100dbb83c5823d9da58d31eeccf6a | Sene68/python_study | /basic_data_types/tuple.py | 318 | 4.15625 | 4 | # Given an integer, n , and n space-separated integers as input, create a tuple, t , of those n integers.
# Then compute and print the result of hash(t).
#
# Note: hash() is one of the functions in the __builtins__ module, so it need not be imported.
if __name__ == '__main__':
i = [1,2]
print(hash(tuple(i))) |
946d2d959d63070f9ff97811be091ec3cc59bfd7 | cblkwell/advent-of-code-2018 | /day2/day2a.py | 1,101 | 4.1875 | 4 | from sys import argv
# Counter will create a dictionary that pairs characters with counts --
# perfect for what we need!
from collections import Counter
script, inputfile = argv
def process_line(line, threes, twos):
# Use counter to get us a dict of the letter frequencies.
counts = Counter(line)
add_three... |
07654eb200f29bca8a54110731bebf5319de753d | oviazlo/ML_tools_and_libs | /plotly/plots_3d.py | 936 | 3.609375 | 4 | import plotly as py
import pandas as pd
import plotly.express as px
from sklearn.datasets import make_blobs
py.offline.init_notebook_mode(connected=True)
def get_cluster_data():
centers = [(-5, -5, -5), (5, 5, 5), (4, 5, 4.5)]
cluster_std = [0.8, 1, 0.5]
X, y = make_blobs(n_samples=100, cluster_std=cluste... |
0bf607f88de7a941b1d6485b42052b849b2a28fe | krishna9477/pythonExamples | /setAllMethods.py | 644 | 3.6875 | 4 | s1={1,2,4,3,5,6}
s2={'sweet','hot','sexy',1,2,3,4}
#s1.intersection_update(s2)
#print(s1)
s1.intersection(s2)
print(s1)
print("===========================")
# clear method
l={1,2,4,3,5,6}
l2={'sweet','hot','sexy',1,2,3,4}
print(l2)
l2.clear()
print(l2)
print("===========================")
# add()
p1={1,2,3}
p1.ad... |
0df08ed69e465aa37c86a9503e62f6bf15d156c2 | bullet1337/codewars | /katas/Python/6 kyu/Build Tower 576757b1df89ecf5bd00073b.py | 195 | 3.515625 | 4 | # https://www.codewars.com/kata/576757b1df89ecf5bd00073b
def tower_builder(n_floors):
return [' ' * (n_floors - i - 1) + '*' * (2 * i + 1) + ' ' * (n_floors - i - 1) for i in range(n_floors)] |
5644b7149e2fd49a4845928a9865b3fbe7c31de5 | darrentweng/streamlitrandom | /stock.py | 1,342 | 3.5625 | 4 | import yfinance as yf
import streamlit as st
import datetime
import numpy as np
import pandas as pd
Snp500=pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')[0]
st.write("""
# Simple Stock Price App
Shown are the stock closing price and volume of Stonks!
""")
stocks = st.sidebar.multiselect(
... |
74df4c815b7d310b9322d71d19615402d0cf2431 | GuidoBR/learning-python | /coin-determiner/backend/appengine/coin.py | 889 | 4.1875 | 4 | # http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
# http://www.algorithmist.com/index.php/Coin_Change
def CoinDeterminer(num):
"""
input - an integer
output - least number of coins, that when added, equal the input integer
Coins [1, 5, 7, 9, 11]
>>> CoinDeterminer(1)
1
>... |
8218794f2adf214d8ad13fd44272e0e1d189894f | przemo1694/wd | /zadanie3.py | 225 | 3.625 | 4 | zakupy = {"jajka": "sztuki",
"ziemniaki": "kg",
"pomarańcze": "sztuki",
"mąka": "opakowania"}
sztuki = {klucz: wartosc for klucz, wartosc in zakupy.items() if wartosc == "sztuki"}
print(sztuki) |
49dbdc3f84f1188e8005d51b5cb0a586713c1885 | Behario/algo_and_structures_python | /Lesson_1/3.py | 767 | 4.28125 | 4 | # 3. По введенным пользователем координатам двух точек вывести
# уравнение прямой вида y = kx + b, проходящей через эти точки.
def makeFixed(num_float, digits):
return f"{num_float:.{digits}f}"
X1 = float(input("Введите значение координаты x1: "))
Y1 = float(input("Введите значение координаты y1: "))
X2 = float... |
ec52d495555b8f17e9bed06b40e1e8a04e35ee8a | MasoodAnwar838/CertifiedPythonProgramming | /Assignment2.py | 2,224 | 4.375 | 4 | ##Question # 1
print("*** Marksheet ***")
English= int(input("Enter your marks of English out of 100 = "))
Urdu= int(input("Enter your marks of Urdu out of 100 = "))
Chemistry= int(input("Enter your marks of Chemistry out of 100 = "))
Physics= int(input("Enter your marks of Physics out of 100 = "))
Maths= int(inp... |
67c62c8fd82c3b11a304ec0b694855c27a27b19d | DavidJoanes/My-Standard-Calculator | /Scientific_Calculator.py | 14,371 | 3.78125 | 4 | from tkinter import *
import math
import tkinter.messagebox
class Calculator():
def __init__(self):
self.total = 0
self.current = ""
self.newNumber = True
self.opPending = False
self.operation = ""
self.equation = False
def get_variables(self, num):
sel... |
a11c504cda6b4d17f01f4ec73c8195d1366daea6 | SteveBlackBird/EM_HW | /Chapter_10/10_4_EM.py | 406 | 3.671875 | 4 | # Guest book
prompt = 'Enter your name, please: '
filename = 'guestbook.txt'
active = True
while active:
message = str(input(prompt))
if message == 'N':
print('Bye-bye!')
active = False
else:
print(f"Dear {message.title()} now you're our guest! Take a rest!")
with open(fil... |
d2d4f556f5f2895abe4cc02dbc1d076469db5737 | GauravKodmalwar/PythonIBM | /Day_1/session6.py | 997 | 3.5 | 4 | varList = [2, 5, 7, 8, 9, 10]
print(varList.pop(3))
print(varList)
for i in zip(varList):
print(i)
print("addition in list ", varList + [5])
print("multiplication in list ", varList * 2)
print(varList[3:6:2])
# get an iterator using iter()
my_iter = iter(tuple((5, 6, 8)))
# fetch next value from iterator using ... |
7ae716b2560eec858e95fe2a1baab66dfc96792a | smferro54/Codecademy-projects | /AreaCalculator.py | 1,439 | 4.46875 | 4 | # A calculator than can compute the area of a given shape, as selected by the user. The calculator will be able to determine the area of the following shapes:
# Circle
# Triangle
from math import pi
from time import sleep
from datetime import datetime
now = datetime.now()
print("Calculator is starting up")
Cu... |
21ff8fecfb8a905dce8e344c8262ffdd6e322ad6 | iancrosby/SimGame | /game.py | 5,916 | 3.5 | 4 | __author__ = 'iwcrosby'
import pygame
from pygame.locals import *
from functions import *
from sales_screen import *
pygame.init()
import var
#Setting up some initialization stuff
done=False
scr_size = [1024,768]
screen=pygame.display.set_mode(scr_size)
pygame.display.set_caption("SimGame")
clock=pygame.time.Clock()... |
4c373baeea2054df1f9c5581e4da5f724be94928 | David-L-Garcia/Ciphers | /Caesar Cipher/V0.1/cipher.py | 1,438 | 3.84375 | 4 | #Caesar Cipher
def loOver(x):
new = x - 122
new += 96
return chr(new)
def upOver(x):
new = x - 90
new += 64
return chr(new)
def loUnder(x):
new = 97 - x
new = 123 - new
return chr(new)
def upUnder(x):
new = 65 - x
new = 91 - new
return chr(new)
def upCryp(x, key):
z = ''
... |
8f0ea908970bd2bb52a3298012139571f3284cca | carloantoniocc/PensamientoComputacional | /iterators.py | 362 | 4.03125 | 4 | frutas = ['manzana', 'pera', 'mango']
iterador = iter(frutas)
print(next(iterador))
#manzana
print(next(iterador))
#pera
print(next(iterador))
#mango
print(next(iterador))
Traceback (most recent call last):
File "c:/Users/carlos/Desktop/Introducción al pensamiento computacional/code/i
terators.py", line 9, in <module... |
fbc25d8b63a68caa346c39e988bbd982ffbf1a93 | Andrewzh112/Data-Structures-and-Algorithms-Practice | /Permutations.py | 779 | 3.6875 | 4 | class Solution:
"""
@param: nums: A list of integers.
@return: A list of permutations.
"""
def permute(self, nums):
# write your code here
results=[]
if not nums:
return [results]
seen=[False]*len(nums)
self.dfs(nums,seen,[],results)
... |
b8173540175cacd43a89c4a9b33209e5847886a9 | zhangdongxuan0227/loadDB | /import_test5.py | 608 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#import test5
'''
n = 1
while n <11:
if n >= 10: # 当n = 11时,条件满足,执行break语句
break # break语句会结束当前循环
print(n)
n = n + 1
print('END')
'''
d={'zxc':12,'ccc':13,'xxx':22}
c=[1,2,3,'zxc','dkjnihao']
s1=set([1,2,3,3])
s2=set([3,5.6])
e='abc'
e.replace('a','A')
#s... |
aa100dabde568bcd48522631a9871364d8ecfeb1 | levickane/Python-unit-1 | /guessing_game.py | 2,011 | 4.25 | 4 | """This is a number guessing game. While True: the game will continue to prompt you to guess
random number between 0 and 20. It will store the amount of guesses in a list and then when
you finally guess the correct number it will tell you how many guesses it took you to get it
correct.
"""
import random
current_guess... |
bab9038002e4eb5f501966fc36d6f3523368d121 | hanguyen0/MITx-6.00.1x | /payingdebtoff.py | 2,598 | 4.71875 | 5 | '''
# Test Case 1:
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
# Result Your Code Should Generate Below:
Remaining balance: 31.38
# To make sure you are doing calculation correctly, this is the
# remaining balance y... |
dc9295f5b0aaad9d9eb040afaa0a7909b9c278bc | niranjan-nagaraju/Development | /python/algorithms/arrays/sums/two_sums.py | 637 | 4.125 | 4 | '''
Find and return all pairs that add upto a specified target sum
'''
# Return all pairs with sum in a sorted array
def two_sums_sorted(a, target):
pairs = []
i, j = 0, len(a)-1
while i < j:
curr_sum = a[i]+a[j]
if curr_sum == target:
pairs.append((a[i], a[j]))
i += 1
j -= 1
elif curr_sum < target:
... |
2a39fc437e20049878b0a3482039455ee4c291cb | ClaudeU/Algorithm_Review | /MoonHyuk/08BRACKETS2/bracket2_stack.py | 567 | 3.9375 | 4 | ## 파이썬은 스택을 구현할필요가 없다!!
def brackets2(input_string):
li = []
for i, j in enumerate(input_string):
if j == '(' or j == '[' or j == '{':
li.append(j)
else:
if len(li) == 0:
return "NO"
elif (j == ')' and li[-1] == '(') or (j == ']' and li[-1] =... |
8c659a8458cc9c0ae0c4ba8af54c3a271e657b0a | akaliutau/cs-problems-python | /problems/dp/Solution85.py | 1,286 | 3.84375 | 4 | """ Given a rows x cols binary matrix filled with 0's and 1's, find the largest
rectangle containing only 1's and return its area.
Input: matrix = [
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6 Explanation: The maximal rectangle... |
9a82a572c3492f26b87cf9fcae08e9e4dff99af6 | aswinrprasad/Python-Code | /CODED.py/fact.py | 265 | 4.59375 | 5 | #Write a python function to calculate the factorial of a number. The function accepts the number as arguments.
n=input("Enter a number to find factorial :")
def fact(n):
fact1 = 1
while n!=0:
fact1*=n
n-=1
return fact1
print "The factorial is :",fact(n)
|
a122ae027566888b38182c1529e05f10b5718d20 | necarlson97/fencer | /point.py | 2,150 | 3.921875 | 4 | import math
class Point():
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def adde(self, p):
# plus equals
self.x += p.x
self.y += p.y
return self
def add(self, p):
# plus (returning new)
return self.copy().adde(p)
def sube(self,... |
4b44c9b6e0ce52e8b6867c53d4d6119516622507 | paramesh33/beginnerset4 | /cmp.py | 98 | 3.546875 | 4 | x,y=input().split();
a=len(x);
b=len(y);
if a>b:
print(x);
elif b>a:
print(y);
else:print(y);
|
fa501831788f62c71624f7cffbf4ed59d67caa2a | ArshanKhanifar/eopi_solutions | /src/protocol/problem_14_p_1.py | 2,049 | 3.578125 | 4 | from protocol.errors import EOPINotImplementedError
class Problem14P1(object):
def is_binary_search_tree(self, root):
raise EOPINotImplementedError()
class TreeNode(object):
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = righ... |
f59b586a4188b1952d8d1898b2f11d4c9166288e | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/rod_musser/lesson04/path_file_processing.py | 458 | 3.953125 | 4 | #!/usr/bin/env python3
import pathlib
# Print files in current directory with absolute file na,e
curr_pth = pathlib.Path('./')
for f in curr_pth.iterdir():
if (f.is_file()):
print(f.absolute())
# Copy file
file_to_copy = input("Enter in the name of a file to copy: ")
copy_of_file = input("Enter the name of ... |
d33cd710dedb0e92ac3f5b0d660a609971ae8b49 | McCoyGroup/McUtils | /McUtils/Parsers/Parsers.py | 1,365 | 3.640625 | 4 | """
A set of concrete parser objects for general use
"""
from .StringParser import *
from .RegexPatterns import *
__all__= [
"XYZParser"
]
XYZParser = StringParser(
RegexPattern(
(
Named(PositiveInteger, "NumberOfAtoms"),
Named(Repeating(Any, min = None), "Comment", dtype=str)... |
4ff02145b7c2aeb1c656b777045c002723a9bd2a | 953250587/leetcode-python | /SingleElementInASortedArray_MID_540.py | 2,124 | 3.78125 | 4 | """
Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once.
Example 1:
Input: [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: [3,3,7,7,10,11,11]
Output: 10
Note: Your solution should run in O(log... |
56d2619da1eef8bfb4b73eacf58063f4f3f094d6 | wafidanesh/CS5590Fall2017 | /ICE_2/prob_2.py | 358 | 3.78125 | 4 | str_example = '123eriororasd28opiu987654321'
digits = 0
letters = 0
somethingelse = 0
print(str_example.isdigit())
for i in str_example:
print(i)
if i.isalpha():
letters = letters + 1
elif i.isdigit():
digits = digits + 1
else:
somethingelse = somethingelse + 1
... |
2b58e901807bf98ddc3f494dffa4fb6978d9c3de | SiluPanda/competitive-programming | /codechef/search_word.py | 296 | 4.0625 | 4 | def how_many_times(given_string, word):
length = len(word)
start = 0
end = length
ans = 0
while end < len(given_string)+1:
if given_string[start:end] == word:
ans += 1
start += 1
end += 1
return ans
given_string = input()
word = input()
print(how_many_times(given_string, word))
|
2ef1f2d2e18f5fd236c8841be1458733c1f0319a | Darren1997/python-test | /py代码/体验继承.py | 307 | 3.796875 | 4 | # 继承:子类默认继承父类所有属性和方法
# 1.定义父类
class A(object):
def __init__(self):
self.num = 1
def print_info(self):
print(self.num)
# 2.定义子类 继承父类
class B(A):
pass
# 3.创建对象,验证结论
result = B()
result.print_info()
|
8f8cb95a7b2d467bf63b88b8a639ed961299fdef | darkamgel/mcsc-codes | /q.n9.py | 175 | 4 | 4 | #q.n 9
#Write a program to find the smallest integer n such that 3𝑛 ≥ 2000
n=0
while 1:
if (3**n>=2000):
break
n+=1
print("the number is ",n)
|
b245e6baab52b2ac0e817bc8219f3dca4c9bae03 | w940853815/my_leetcode | /easy/面试题 01.09. 字符串轮转.py | 713 | 3.984375 | 4 | # 字符串轮转。给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成(比如,waterbottle是erbottlewat旋转后的字符串)。
# 示例1:
# 输入:s1 = "waterbottle", s2 = "erbottlewat"
# 输出:True
# 示例2:
# 输入:s1 = "aa", s2 = "aba"
# 输出:False
class Solution:
def isFlipedString(self, s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
... |
c306473e2082b714b4cc3a15c9024d32b2aa8332 | JeffreyAsuncion/CodingProblems_Python | /Lambda/binarySearchAlgo.py | 1,074 | 4.0625 | 4 | # binary search
def binary_search(lst, target):
# set a min to 0
min = 0
# set a max to length of list minus 1
max = len(lst) -1
# iterate over the data while `max` is still less than `min`
while min < max:
# figure out what guess we want to make (get the middle index) do a floor divis... |
81e0072b16cc054125c779489171b4055a00464f | maxymilianz/CS-at-University-of-Wroclaw | /Text mining/Solutions/3+/question_answerer/abstract_question_answerer.py | 1,183 | 3.515625 | 4 | from enum import Enum
from typing import Container, Optional
class QuestionType(Enum):
GENERIC = 0
UNANSWERABLE = 1
BOOLEAN = 2
YEAR = 3
CENTURY = 4
HUMAN_NAME = 5
NAME = 6
ADAGE = 7
@staticmethod
def from_question(question: str):
if question.startswith('Czy '):
... |
3450c800387036cc6104263b29f8d37975f6d6ff | muskankumarisingh/function_2 | /w3resorce question2.py | 294 | 3.96875 | 4 | # def sum(numbers):
# total = 0
# for x in numbers:
# total += x
# return total
# print(sum((8, 2, 3, 0, 7)))
def sum(numbers):
total_sum=0
i=0
while i<len(numbers):
total_sum=total_sum+numbers[i]
i+=1
return total_sum
print(sum((8,2,3,0,7))) |
7de80473403f12adc1e8f4da48f1c8457205144a | joyonto51/python_data_structure_practice | /lists/smallest_number.py | 207 | 4.0625 | 4 | array = list(map(int, input("Enter the elements of list : ").split(' ')))
min_number = array[0]
for item in array:
if item < min_number:
min_number = item
print("smallest_number = ",min_number) |
30f502319112e12806513f93bcb28b04f3055380 | Seabass10x/hello-world | /CS50/WK6_Python/pset6/bleep/bleep.py | 897 | 3.828125 | 4 | from cs50 import get_string
from sys import argv, exit
def main():
# Check that a banned list was submitted as an argument
if len(argv) != 2:
print("Usage: python bleep.py dictionary")
exit(1)
# Open dictionary of banned words
banfile = open(argv[1])
banned = set()
... |
668ca0c20768c7b93a75f10ea56675e45a3c9f76 | MichaelSmeaton/Python | /model.py | 6,472 | 3.5625 | 4 | import requests
import re
from bs4 import BeautifulSoup
from decimal import Decimal
class WebScraper:
def is_correct(self, url):
"""
Method WebScraper.is_correct()'s docstring.
Check if URL is missing scheme. Only for HTTP and HTTPS URLS
Remove extra whitespaces
... |
0bf9ee82cea02acec94f75d5408ca6ddd91a9bcc | thestrawberryqueen/python | /3_advanced/chapter17/practice/set_creator.py | 377 | 4.125 | 4 | # Create an empty set and print the type of it. Create a
# set from a given dictionary(do set(given_dict)) and print it.
# Note: The set created from the given dictionary contains
# only the keys of the dictionary.
def set_creator(given_dict):
pass
# Remove pass and write your code in here
set_cr... |
072b8b714a2051ea64ef118bb168cb65cc0ce5f6 | Zli123123/POTW | /potw3.py | 2,710 | 3.71875 | 4 | #potw3 grind - hopefully it's not that bad\
import random #yes, but how to make each number unique
import time
random.seed(time.time())
yesorno = 1
yaxis = int(input("number: "))
xaxis = int(input("number: "))
maze = []
listwhole = []
listx = []
listy = []
l = xaxis * yaxis
colors = []
for i in range (l+1) :
... |
96c1393fe67c26fdbb1419d5de059874b82d34af | oakkub/Hacktoberfest-2k17 | /nishanthebbar2011/eratosthenes.py | 355 | 3.53125 | 4 | #Sieve of eratosthenes
n=int(input("Please Enter the positive number up till which you want the prime numbers to be printed"))
arr=[]
for i in range(n+1):
arr.append(int(i))
for i in range(2,int(n**(0.5))):
if arr[i] != -1:
k=2*i
while k<=n:
arr[k]=-1
k+=i
for i in arr:... |
605819f47748463952647486157b8d310d182be6 | mattjp/leetcode | /practice/medium/0143-Reorder_List.py | 848 | 3.921875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head: return
#... |
bf1aec1ff3b85d0d70ae8b0583c56b1c25c24728 | babosina/TestAssignment | /Part 1/1_1Multiplication.py | 248 | 4.34375 | 4 | # Write code that reads two numbers and multiplies them together and print out their product
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
print('The multiplication result of {} and {} is {}'.format(a, b, a * b))
|
808d1bfdade1c7c3c54b12929598ece566f769bc | viing937/codeforces | /src/469A.py | 206 | 3.53125 | 4 | # coding: utf-8
n = int(input())
x = [int(i) for i in input().split()]
y = [int(i) for i in input().split()]
if len(set(x[1:]+y[1:])) < n:
print('Oh, my keyboard!')
else:
print('I become the guy.')
|
0baa3c1ba7049b80920fc450f4596e2f65c891f2 | freddyfok/cs_with_python | /algorithms/searching_arrays/string_matching.py | 947 | 4.21875 | 4 | """
string matching
brutal force method works, but expensive. o(mn) (ie o(n2))
Rabin-Karp Algorithm uses hashing and rolling hash to find patterns
ie. to find str of size 3 in text
first iteration:
total = h(str[0]) X h(str[1]) X h(str[2])
text total = h(text[0]) X h(text[1]) X h(text[2])
second iteration... |
362abf886055ed5d624e932e016aae68a4bb547d | RMShakirzyanov/ttttt | /Задача №3.py | 333 | 3.921875 | 4 | x == float(input())
a == float(input())
y == float(input())
b == float(input())
print(' ', a / x, '')
print(' ', b / y, '')
print(' ', x // y, '')
|
34b829dd98b996a8eafca84a8676944473d44419 | gangab2/DataScience | /stats.py | 1,551 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 26 14:06:38 2016
@author: gangab2
"""
import pandas as pd
data = ''' Region,Alcohol,Tobacco
North,6.47,4.03
Yorkshire,6.13,3.76
Northeast,6.19,3.77
East Midlands,4.89,3.34
West Midlands,5.63,3.47
East Anglia,4.52,2.92
Southeast,5.89,3.20
Southwest,4.79,2.71
Wales,5.27,3.... |
c218a2587f78347e771bf666cc625352550a87fb | paloblanco/classiccompsci | /ch1/section12.py | 3,794 | 3.765625 | 4 | from typing import Union
class BitString:
def __init__(self, value: Union[int,str] = 0) -> None:
if type(value) == int:
self._value: int = value
elif type(value) == str:
try:
int_val = int(value,2)
self._value = int_val
except Valu... |
41a3b1b67e1dfcb2003c32c9be0bb25b85440a86 | brenoso/graph-theory-exercises | /Atividade 1/Problema 1/source/Aresta.py | 693 | 3.828125 | 4 | # -*- coding: utf-8 -*-
class Aresta (object):
'''
Construtor da classe
'''
def __init__(self, u, v, peso = 1):
self.__u = str(u)
self.__v = str(v)
self.__peso = peso
'''
Imprime a aresta
'''
def __str__(self):
return " (" + str(self.__u) + ", " + st... |
d8cf21aac77e12e6266b1c399ae55839dc0a5e5b | jh-lau/leetcode_in_python | /data_structure/stack/栈.py | 1,990 | 3.921875 | 4 | """
Created by PyCharm.
User: Liujianhan
Date: 2019/5/31
Time: 9:44
"""
__author__ = 'liujianhan'
class Stack:
# 列表最后元素作为栈顶元素
def __init__(self):
self.items = []
def push(self, elem):
self.items.append(elem)
def pop(self):
return self.items.pop()
def top(self):
... |
9f1364301f6c206b8c9d190a919280cdc555a4d7 | PacktPublishing/fastText-Quick-Start-Guide | /chapter2/remove_stop_words.py | 930 | 3.75 | 4 | """
Small script so that it is easy to work with the pipe operator and can be
plugged in easily with other bash commands.
Please ensure that the nltk english package is already downloaded before this.
>>> import nltk
>>> nltk.download('stopwords')
Usage: cat raw_data.txt | python remove_stop_words.py > no_stop_words... |
44ad0eda2239699794fb388a6f9f4f7cf6f455cb | Python-Repository-Hub/Learn-Online-Learning | /Python-for-everyone/02_Data_Structure/10_Tuple/08_sort_by_value.py | 549 | 3.765625 | 4 | #increase-order
c = {'a':10, 'b':1, 'c':22}
tmp = list()
for k, v in c.items() :
tmp.append( (v, k) )
print(tmp) # [(10, 'a'), (1, 'b'), (22, 'c')]
tmp = sorted(tmp)
print(tmp) # [(1, 'b'), (10, 'a'), (22, 'c')]
#decrease-order
c = {'a':10, 'b':1, 'c':22}
tmp = li... |
00629e1d1903e0021548b70c3526fb3b9a3263d1 | liuiuge/LeetCodeSummary | /125.ValidPalindrome.py | 582 | 3.921875 | 4 | # -*- coding: utf8 -*-
class Solution:
def isPalindrome(self, s: str) -> bool:
if not s:
return True
l, r = 0, len(s) - 1
while l < r:
while not s[l].isalnum() and l < r:
l += 1
while not s[r].isalnum() and l < r:
... |
00df019190e6997d4e5efe02b9706a23c99ac60d | jsanon01/python | /python-folder/slice.py | 387 | 4.03125 | 4 | """
"""
print("\nthe slice constructor returns the following syntaxes: ".title())
#print('\n- slice(stop)\n- slice(start, stop, step)')
print('\n----------------- Syntax: slice(stop) ----------------------')
print("\nstring = 'astring'")
print('\n- s1 = slice(3) => it means to stop at 3')
string = 'astring'
... |
789d71e5924fdd2bb85b60d87618fff71195bcc2 | Qunfong/CodeWars | /getSumBetweenTwoValues.py | 469 | 3.796875 | 4 |
def check_equal(a, b):
value = None
if a == b:
value = a
return value
def get_sum(a, b):
equal = check_equal(a, b)
if(check_equal(a, b) is not None):
return equal
largest = max(a, b) + 1
smallest = min(a, b)
sum = 0
for x in range(smallest, largest):
sum +... |
05aa91e9685090e452badc3be9a85c65d4210c16 | Shashankhs17/Hackereath-problems_python | /Implementation/led.py | 1,763 | 4.09375 | 4 | '''
Its Diwali time and there are LED series lights everywhere.
Little Roy got curious about how LED lights work.
He noticed that in one single LED Bulb
there are 3 LED lights, namely Red, Green and Blue.
State of the bulb at any moment is
the sum of Red, Green and Blue LED light.
Bulb works as follows:
R = R
G ... |
c57ff37251349a9260593496870ed0d8aff96c64 | apu1995/appucodes | /amt.py | 241 | 3.90625 | 4 | amt=float(input("Enter the amount?\n"))
rate=float(input("Enter the rate?\n"))
time=int(input("Enter the time?\n"))
val=0
year=1
while year<=time :
val=amt+(amt*rate)
print("Value for year %d is %.2f" % (year,val))
amt=val
year=year+1
|
237782f2bc42526762024522b54a9c12a97af630 | ZeroStack/hackerrank | /algorithms/implementation/1_gradingstudents.py | 407 | 3.578125 | 4 | #!/bin/python3
import sys
def solve(grades):
grades = [ grade if round(grade/5+0.5)*5 < 40 else round(grade/5+0.5)*5 if round(grade/5+0.5)*5 - grade < 3 else grade for grade in grades]
for grade in grades:
print(grade)
n = int(input().strip())
grades = []
grades_i = 0
for grades_i in ... |
e8fd5cc58c197c029e5534504b5fe2fd84832fa1 | danny-hunt/Problems | /bst_inorder_successor/bst_i_s.py | 979 | 4 | 4 | """
Given a node in a binary search tree, return the next bigger element, also known as the inorder successor.
For example, the inorder successor of 22 is 30.
21
/ \
5 30
/ \
22 35
\
27
\
28
You can assume each node has a parent pointer.
"""
# Given a node we need t... |
5b1bc57221a4f64bd5a1cbea7e08433c42429f44 | gmergola/python-oo | /wordfinder.py | 1,363 | 4.1875 | 4 | """Word Finder: finds random words from a dictionary."""
import random
class WordFinder:
"""reads a file and makes an attribute equal
to a list of words in file
>>> wf = WordFinder("/Users/gennamergola/Desktop/test.txt")
3 words read
>>> wf.random()
'cat'
>>> wf.random()
'cat'
... |
56b4b4b2b4ea586a212e2867050e7c1929c895f0 | fastso/learning-python | /atcoder/contest/solved/abc036_b.py | 176 | 3.515625 | 4 | n = int(input())
a = [list(input()) for i in range(n)]
for i in range(n):
line = []
for j in reversed(range(n)):
line.append(a[j][i])
print(''.join(line))
|
36a8bd1185dc7e28e3ecbe72d6368af8c3874235 | kgm7334/Python-Challenge | /PythonChallenge4/main.py | 2,142 | 3.796875 | 4 | import os
import requests
while True:
print("Welcome to IsitDown.py")
print("Please Write URL Or URLs You Want To Check. (Seperated comma)")
User_Input_URL = input("").replace(" ", "").lower()
if(User_Input_URL == ""):
continue
else:
if((".com" in User_Input_URL) and ("," in User_... |
a71b0fd8553a2969cc59d1f32dcf39f25b5bd7b4 | tmvinoth3/Python | /SortandReverse.py | 383 | 4.0625 | 4 | #code
l = [2,1,5,4,3]
m = l.copy()
str = 'this is string'
strlist = str.split() #string to list
m.sort()#sort
print(l)
m.reverse() #reverse
print("m : ",m)
l.sort(reverse=True)
print("l : ",l)#reverse
strlist.sort(key=len) #sort list
print(strlist);
print('*'.join(strlist)) #convert to string
n = sorted(l) #not ch... |
c7e09a585862f480a0d54a31fbb8ac7c5231e590 | Walaga/weekday-of-birth | /weekday of birth.py | 1,351 | 4.15625 | 4 |
#NAME WALAGA PRISCILLA N. EDITH
#REGISTRATION NUMBER 16/U/12253/PS
import calendar #importing inbuilt calendar module
a=input("What is your year of birth?\n")
b=input("Enter your month of birth (enter number e.g for december enter 12\n")
c=input("Enter the date on whic... |
531f268f34608f26ee9fc0db3802be301a65cc8d | zjw641220480/pythonfirst | /src/simple/simple_function.py | 2,210 | 3.8125 | 4 | #!/usr/bin/python3
#coding=utf-8 #必不可少的,不然容易报错
'''
Created on 2017年9月27日
用来演示python函数的相关操作
@author: lengxiaoqi
'''
#自己的第一个参数罢了
from keyword import kwlist
def myFirstFunction():
print("这个是我的第一个参数");
#有参数的python方法
def myFunctionParameter(parameter):
print("传递过来的参数为:"+parameter);
return parameter+"\tfa... |
d36552314147c6b95014eeaebe5f2e2ccf05da9b | tbartek9/Script-to-combine-files | /combine_files.py | 746 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 22 18:59:12 2021
@author: Bartosz Terka
"""
"""
This script combines files with the same extension.
1)put the script in the folder together with the folder containing the files
2)complete the names of folder and file in lines 13,14 and 17
"""
import os
name=op... |
32ee19d2bee60a004ae5e9782d4058d11fba2369 | Qocotzxin/python-course | /3 - Flows/G.py | 402 | 4.1875 | 4 | # Dadas dos listas, debes generar una tercera con todos los elementos
# que se repitan en ellas, pero no debe repetirse ningún elemento en la nueva lista:
lista_1 = ["h", 'o', 'l', 'a', ' ', 'm', 'u', 'n', 'd', 'o']
lista_2 = ["h", 'o', 'l', 'a', ' ', 'l', 'u', 'n', 'a']
lista_3 = []
for char in lista_1:
if char... |
4ae704007bd1396abe4fdef60aac94de5235da98 | ashwin-subramaniam/Guessing-Game | /guessingGame.py | 576 | 4.25 | 4 | import random;
number = random.randint(1,9)
chances = 5
guess = 0
print("Guessing Game(1-9)")
while number!=guess and chances > 0:
guess = int(input("Enter Your Guess:"))
chances = chances - 1
if(number>guess):
print("Your Guess was too low. Guess a number higher than ",str(guess))
... |
7628210ce964285a17605540c9e1f41c3f95b770 | JIN-YEONG/keras_example | /keras/0725/keras13_lstm_earlyStopping.py | 2,355 | 3.921875 | 4 |
# RNN (Recurrent Neural Network) 순환 신경망
# 시배열(연속된) 데이터의 분석의 유리
# 시배열(time distributed) -> 연속된 데이터
from numpy import array
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 1. 데이터
x = array([[1,2,3], [2,3,4], [3,4,5], [4,5,6], [5,6,7], [6,7,8], [7,8,9], [8,9,10], [9,10,11], [1... |
960e19fbd5ce77021ae4e82c74bafb03c9253de4 | shres-ruby/pythonassignment | /functions/q7_f.py | 692 | 4.34375 | 4 | # 7. Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters.
# Sample String : 'The quick Brow Fox'
# Expected Output :
# No. of Upper case characters : 3
# No. of Lower case Characters : 12
def func(s):
upper = 0
lower = 0
for i in s:
... |
86e74e6b83be3976ba48f90728a50334811df18a | cycho04/python-automation | /game-inventory.py | 1,879 | 4.3125 | 4 | # You are creating a fantasy video game.
# The data structure to model the player’s inventory will be a dictionary where the keys are string values
# describing the item in the inventory and the value is an integer value detailing how many of that item the player has.
# For example, the dictionary value {'rope': 1, ... |
b4008e51e84b1604c72c9dc17f03677ad70b26b3 | Zjly/Program-Python | /review/data_structure/fib.py | 411 | 3.859375 | 4 | def fib1(n):
if n == 1 or n == 2:
return 1
else:
return fib1(n - 1) + fib1(n - 2)
def fib2(n):
if n == 1 or n == 2:
return 1
else:
pre1 = 1
pre2 = 1
this = 2
for i in range(3, n + 1):
this = pre1 + pre2
pre1 = pre2
pre2 = this
return this
if __name__ == '__main__':
for i in range(1, 1... |
a3e1bc36279778dc5d7054b1de2c9a1fa5b663a4 | arnabid/QA | /trees/minHeightTrees.py | 1,398 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 6 08:11:03 2017
@author: arnab
"""
"""
Minimum height trees
reference: https://leetcode.com/problems/minimum-height-trees/description/
Notes:
There can be only 1 or 2 nodes with minimum height trees.
These nodes are the critical nodes in the sense that maximum distanc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.