blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
04fd43b02302b2a0b9c0ee1254d5c5d246fea65d | ksercs/lksh | /2014/Работа в ЛКШ/Python/Зачет/4-/dictionary.py | 947 | 3.671875 | 4 | def merge(a, b):
i = 0
j = 0
c = []
while len(a) > i and len(b) > j:
if a[i] < b[j]:
c.append(a[i])
i += 1
else:
c.append(b[j])
j += 1
return c + a[i:] + b[j:]
def merge_sort(a):
if len(a) <= 1:
ret... |
0c2b106922cba23effa358b57f4bb439f54512bf | anishihara/Extremely-Simple-Search-Engine | /Index/add_to_index.py | 1,150 | 3.5625 | 4 | #Define a procedure, add_to_index,
#that takes 3 inputs:
# - an index: [[<keyword>,[<url>,...]],...]
# - a keyword: String
# - a url: String
#If the keyword is already
#in the index, add the url
#to the list of urls associated
#with that keyword.
#If the keyword is not in the index,
#add an entry to the index: [keyw... |
455d1c6cd3cc0cacfa0af40e8964c9224b208e05 | lhliew/flood-warning | /Task1B.py | 994 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 29 16:13:48 2017
@author: laide
"""
"""prints a list of tuples (station name, town, distance) for the 10 closest
and the 10 furthest stations from the Cambridge city centre, (52.2053, 0.1218)."""
from floodsystem.geo import stations_by_distance
from floodsystem.stationda... |
c6aba21fbf37f63ad68af55eba72810364a870f3 | wlau88/data_science_knowledge | /oop/blackjack.py | 1,573 | 3.625 | 4 | '''
This script has all the functionalities to play blackjack
'''
from blackjack_player import *
from utilities import *
from deck import *
class Blackjack(object):
def __init__(self):
self.dealer = Dealer()
self.player = Player()
self.deck = Deck()
self.play()
def play(self):
while self.player.money >... |
c6682dd152882ad52cd884894f8d0af17ce2482a | hkd8/ChengJoeHW | /HW3(Python)/ChengJoeSolution/PyRollCHENGsolved.py | 2,540 | 4 | 4 | #ALL I DO IS IMPORT
import csv
import os
csvpath = 'C:\\Users\\cheng\\Desktop\\UKED201811DATA5\\02-Homework\\03-Python\\Instructions\\PyPoll\\Resources\\election_data.csv'
with open(csvpath, 'r') as csvfile:
#READERS AND SKIP THAT HEADER
csvreader = csv.reader(csvfile, delimiter=',')
next(csvreader,None)
#MAK... |
b0f95c0297eaf2d93558674e0935e9c1c3fd9fe6 | karlloic/python-for-everybody | /PythonAccessWebData/bsAssgn1.py | 404 | 3.5 | 4 | # Scraping Numbers from HTML using BeautifulSoup
import urllib
from BeautifulSoup import *
content = urllib.urlopen('http://python-data.dr-chuck.net/comments_279060.html').read()
bso = BeautifulSoup(content)
spanTags = bso('span')
total = 0
for spanTag in spanTags:
total += int(spanTag.contents[0])
print('Count ... |
7de25dd92ba804f5a80c3b818524cbb50b97cd1c | jose01carrillo30/Table-7-Shared-Repo | /stats.py | 1,803 | 3.609375 | 4 | # By submitting this assignment, I agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
# Names: Alexander Bockelman
# Jose Carrillo
# Patrick Chai
# Jackson Sanders
# Section: 211
# Assign... |
1b7c08513aad3d25055a4ad6d91d8decbffc2c30 | lzzhang212/PythonEx | /LeetCode/060.permutationSequence/permutationSequence.py | 1,423 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: lzzhang
# @Date: 2018-06-08 14:41:43
# @Last Modified by: lzzhang
# @Last Modified time: 2018-06-12 14:45:14
import math
class Solution:
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""... |
cf25b1ec130d998540bbeadf5a9896de4a4ad346 | vishalamc/pythonexamples | /pandasEx3.py | 189 | 3.984375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame(np.random.rand(10, 3), columns =['a', 'b', 'c'])
print(df)
df.plot.bar()
plt.show()
|
5f371145a27d18ad49212e358201f651f3902f35 | jjmarrs/PythonScripts | /Games/TicTacToe.py | 1,809 | 4.15625 | 4 | #This program is not yet finished
import random
def displayGrid():
print(" | | ")
print(" 1 | 2 | 3 ")
print(" | | ")
print("---------------------")
print(" | | ")
print(" 4 | 5 | 6 ")
print(" | | ")
pr... |
015e218286b5bf8b9f1f645d9505c6ee5d6a40e2 | AI888666/Tedu | /regex2.py | 364 | 3.5 | 4 | """
正则表达式演示2
"""
import re
s = "1949年10月1日,中国人民共和国成立"
it = re.finditer(r"\d+", s)
for item in it:
print(item.group())
# 匹配开头位置
obj = re.match(r"\d+", s)
print(obj.group())
# 匹配第一处
obj = re.search(r"\d+", s)
print(obj.group())
# 完全匹配
obj = re.fullmatch(r".+", s)
print(obj.group()) |
0d607d64f27e07690ffe736a567fa81713274d6d | masterdungeon/code-cademy | /python/Lists and Functions/3. Appending to a list.py | 63 | 3.546875 | 4 | n = [1, 3, 5]
# Append the number 4 here
n.append(4)
print n |
11a2b45a58b566c8fedab474107f642baae94b50 | LeslieWilson/python_playground | /chapter-five/Chapt5.py | 2,829 | 4.40625 | 4 | # what is a class?
# a class is an instance of an object. For example leslie is the class of human, and it describes the props I'll have. An example of a class is how I called the point below, "center". Thats the classname for the instance of the object.
# a method is a function that lives inside the object, invoked ... |
158aade14b46d1ca61b9159d119a730c0a1e59b2 | gowriaddepalli/Leetcode_solutions | /daily-temperatures/daily-temperatures.py | 1,669 | 3.859375 | 4 | '''
The logic is as follows:
The Brute force is to do O(n^2). Compare each element with the rest of the array elements.
But a better approach is to take a stack and start iterating through the index from the end.
Algo:
1. Iterate the array from the rightmost part of the array (Reason we need to see the future to ca... |
54c681ba6c425f697fec6a8699b53da3a544148b | engelsong/DataStructure | /08-图7 公路村村通 & Kruskal算法.py | 5,024 | 3.890625 | 4 | class MinHeap(object):
def __init__(self, MinData=0):
self.Size = 0
self.Data = [(0, 0)]
self.Dict = {(0, 0): 0}
def IsEmpty(self):
res = False
if self.Size == 0:
res = True
return res
def Comp(self, item1, item2):
res = False
if... |
cc29c8c51f5b263ae3e006b946506df694846415 | Akhichow/PythonCode | /contrived.py | 219 | 4.03125 | 4 | numbers = [7, 42, 30, 12, 60]
for number in numbers:
if number % 8 == 0:
# Reject the numbers
print("The numbers are unacceptable")
break
else:
print("All values are acceptable") |
2af20201b9f89c85e392bcf9f134f52e90542820 | OblakM/FizzBuzz | /FizzBuzz.py | 355 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
print "Dobrodošli v igri FizzBuzz!"
izbor = int(raw_input("Izberi številko med 1 in 100: "))
for x in range(1, izbor+1):
if x % 3 == 0 and x % 5 == 0:
print "Fizzbuzz"
elif x % 3 == 0:
print "Fizz"
elif x % 5 == 0:
print "... |
a859c4d13018d55a739e285899f57be3527a984f | kirillzx/my_python | /HW_5/postfix.py | 736 | 3.8125 | 4 |
def calc(expr):
'''
>>> calc("1 2 + 4 * 3 +")
'15'
>>> calc("1 2 3 * + 2 -")
'5'
'''
stack=[]
for i in expr:
if i.isdigit():
stack.append(int(i))
elif i == '+':
first = stack.pop()
second = stack.pop()
stac... |
4ad94356a9812833910b6c66deccadb4276f73fb | yoshimura19/samples | /python/kisoen/kisoen/day4/test60b2.py | 441 | 3.53125 | 4 | #coding:utf-8
#csvモジュールver
import csv
import StringIO #文字列をCSVとして処理
import sys
#f = open(sys.argv[0], "r")
output = []
try:
while True:
s = raw_input()
fh = StringIO.StringIO(s) #擬似的なファイルを作成
reader = csv.reader(fh)
for row in reader:
output.append(row)
except:
p... |
b2813712e2ee69ce36a0e83256af197316115fb3 | jonr10/acebot | /expert_finder.py | 666 | 3.96875 | 4 | # Code to return a list of names of who in the team knows a certain skill.
import pandas as pd
def return_expert (skill):
'''Function which searches skills matrix for experts, returning their names.'''
skills_df = pd.read_csv('/Users/admin/Documents/Away_Days/acebot/skills_matrix.csv')
try:
experts = s... |
7d246bba3683cf245f7e01369664d6f0cfffc4bc | mardiaz353/workingThruBool | /printfives.py | 1,274 | 3.984375 | 4 | for x in range(0,100):
if x % 5 == 0:
message = "%s is divisible by 5."
print(message % x)
#integer variables
x = 20
#string variables
text = "I like coding."
#lists
groceries = ["apples", "bananas", "milk", "eggs"]
#boolean variables
#These can be set to equal True or False
#wearingHat = False... |
731bd4fa1059f7167fa6a9147b8e5ad1a8539e99 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/word-count/2cc92142d8e54a388a3804b6a2a1c412.py | 1,159 | 3.78125 | 4 | import string
import re
class Phrase:
def __init__(self, input_phrase):
"""Keep the constructor unit test happy. May as well create member phrase."""
self.phrase = input_phrase
def simplified_phrase(self):
"""Prepare and butcher phrase into a string of single-space separated words."""
... |
4d93c23e5c5f484082cbdef237320ddb83f078e8 | samlee916/Python-Crash-Course | /StringReplace.py | 152 | 4.25 | 4 | #An example of string replacing
a = "Hello World"
#implementing the replace function
a = a.replace("Hello", "Goodbye")#replaces hello with goodbye
print(a)
|
abdb89d988b4963cfd557b5cc31743385a37991a | shikhinarora/basic-data-structures | /stack.py | 711 | 3.734375 | 4 | class Stack:
top = None # add and remove form here
def __init__(self):
self.top = None
def is_empty(self):
return self.top is None
def peek(self):
if self.top is None:
return 'Empty stack'
else:
return self.top.data
def push(self, data):
... |
9135cf2281ac4e479a814cc9adf2acc5aa8fca4c | lalitsiraswa/TicTacToe | /Tic-Tac-Toe Multiplayer.py | 3,544 | 4.0625 | 4 | game_board = {1 : " ", 2 : " ", 3 : " ", 4 : " ", 5 : " ", 6 : " ", 7 : " ", 8 : " ", 9 : " "}
def print_game_board():
print(" | | ")
print(f" {game_board[1]} | {game_board[2]} | {game_board[3]} ")
print(" | | ")
print("-----------------")
print(" | | ")
... |
f2f47deb6c48a0bc979a40412dfba59c0998c84b | tammytdo/SP2018-Python220-Accelerated | /Student/tammyd_Py220/Py220_lesson10/jit_test.py | 3,877 | 3.515625 | 4 | """
Exploring PyPy
Code with notes
"""
# pypy is a fast, compliant alternative implementation of the Python language with several advantages and distinct features
# speed = it is a just in time compiler that is faster than python
# memory usage
# compatibility
# stackless
import math
import time
TIMES = 10000000... |
1d5e315f7aaba915a01b88326dd4e2f91b31cf0f | devil122/Leetcode | /009.isPalindrome.py | 1,039 | 4.34375 | 4 | '''第9题:
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
链接:https://leetcode-cn.com/problems/palindrome-number/
'''
class solution:
#方法1:将整数转换为字符串
def isPalindrome1(self,x):
if x >=0 :
x_str = str(x)
x_palindrome = x_str[::-1]
x_converse = int(x_palindrome)
r... |
6602ebeb4713997bffd5eb83828b87c5d23b897c | PierreVieira/Python_Examples | /Generators.py | 280 | 3.84375 | 4 | """
Generators seriam as tuple comprehension.
"""
print(all(nome[0] == 'C' for nome in ['Carlos', 'Camila', 'Cassiano']))
gen = (i for i in range(10))
for c in gen:
print(c)
#Na segunda utilização já não tem mais nada disponível em gen
for c in gen:
print(c) |
eeae711847e9e4fde225b527f79f4e0ea1399298 | genedeh/8gradeGame | /PowerClass.py | 575 | 3.578125 | 4 | class Power:
Energy = "50%"
def __init__(self, speed, strength, agility):
self.speed = speed
self.strength = strength
self.agility = agility
def __str__(self):
return f"({self.agility}, {self.speed}, {self.strength})"
def __eq__(self, other):
return... |
c3f0ea2c9f5a45b7ac607e025040e7dd022c0a38 | pi-2021-2-db6/lecture-code | /aula03-vars-e_s/antecessor_sucessor.py | 236 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Dado um inteiro positivo, calcular o antecessor e o sucessor
@author: Prof. Diogo SM
"""
x = int(input("Digite um inteiro: "))
print(f"Antecessor: {x - 1}")
print(f"Sucessor: {x + 1}")
|
a0f530a838a9ee225ebfd03628757d4430fcd37d | noahjeffers/CS50 | /pset6/cash.py | 1,087 | 4.15625 | 4 | from cs50 import get_float
# Main method for determining how much change is owed to a person
def main():
cents = valid_input()
# multiplies the change owed by 100 to find out how many cents are owed
cents = cents * 100
# Converts the float to an int to round down every time
# Divides the cents by... |
5b3d002343c49658febf6e645cd754c9b9ab05dd | dbmccoy/sample | /Python/ex9.py | 583 | 3.8125 | 4 | import random
playing = True
play_counts = 0
while playing == True:
n = random.randint(1,9)
isInt = False
print('let\'s play a a game')
print('type "exit" to quit')
while isInt == False:
try:
i = float(input('enter a number> '))
except:
if(... |
1bd275df7a0de790414b6394c46dcf9b85de8c41 | sophieball/BiggerLab_2019_winter | /pong_2_balls/ball.py | 1,429 | 3.828125 | 4 | import pygame
class Ball:
def __init__(self, c, r, d_x, d_y, i_p):
self.color = c
self.radius = r
self.delta_x = d_x
self.delta_y = d_y
self.spot = i_p
self.lose = False
self.point = 0
def draw_ball(self, screen):
pygame.draw.circle(screen, self.color, self.spot, self.radius)
def move_ball(self, w... |
80ac29fda6653fe9ab1ebd4190ce7a0d0f98adf7 | tranphibaochau/LeetCodeProgramming | /Medium/validate_stack_sequences.py | 536 | 3.75 | 4 | #Given two sequences pushed and popped with distinct values,
#return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
#Hint: Greedy Algorithm
def validateStackSequences(pushed, popped):
result = []
l = 0
for n in pushed:
... |
fc829327a7e52b62bc8d5e328e4adafd331ef9df | Qudratullo/ocr | /neural/layers.py | 4,793 | 3.515625 | 4 | import numpy as np
def l2_regularization(W, reg_strength):
"""
Computes L2 regularization loss on weights and its gradient
Arguments:
W, np array - weights
reg_strength - float value
Returns:
loss, single value - l2 regularization loss
gradient, np.array same shape as W - gra... |
a782a9e0bcf49591bb1b10860f4a6a68bae87c35 | annazwiggelaar/Python_assessment | /Program 3 Anna Zwiggelaar & Lieke Spoelstra.py | 2,856 | 3.890625 | 4 | # Program by Anna Zwiggelaar and Lieke Spoelstra.
import random
bingo_list = []
random_bingo_list = []
with open("bingo.txt", "r") as myfile: # add file words to bingo list
for word in myfile:
bingo_list.append(word.rstrip("\n"))
def generate_random_list(word_list, rand_list):
while len(rand_... |
d0b102940a2cd39fa058d2a900b7bbf337ff7500 | JohnWZ/l_c_repo | /1_two_sum.py | 239 | 3.578125 | 4 | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for num1 in List:
for num2 in List:
if num1 + num2 == target and num1 != num2:
return arr[num1, num2]
|
3c27bf63ce070fae59b1caf936b161f85d98ddc2 | lifeoftheone/python-program | /pythoncode/practical 4.py | 226 | 3.984375 | 4 | a=int(input("enter the marks"))
print("your grade is")
if(a>=80):
print("A")
elif(a>=60):
print("B")
elif(a>=50):
print("C")
elif(a>=45):
print("D")
elif(a>=25):
print("E")
else:
print("F") |
e54513a17a4369032de04030d24aed373bbcb748 | thekevinsmith/leetcode-python | /problems/two_sum.py | 1,201 | 4.0625 | 4 | # Okay, we have an input list and a target sum, we need to achieve the
# target sum through the use of integers in the input list/array.
# 1. take the target and subtract until we reach zero, allow a backtrack option
# 2. add to a variable and compare, until we get what we need.
# 3. find the closest highest possible i... |
4ea5fce725b7622cb6a5743f830fe4ec28adb4eb | shen-huang/selfteaching-python-camp | /19100101/raoxin007/d3_exercise_calculator.py | 941 | 4.03125 | 4 | #简易加减乘除计算器程序
#定义加法函数
def add(x,y):
return x+y
#定义减法函数
def subtract(x,y):
return x-y
#定义乘法函数
def multiply(x,y):
return x*y
#定义除法函数
def divide(x,y):
return x/y
#定义执行方式,当执行脚本本身,执行如下代码
if __name__ == '__main__':
print("选择运算:")
print("1、加")
print("2、减")
print("3、乘")
print("4、除")
... |
cd18dd5a85a09408c18666e47f3c7f528e28c296 | DanielG1397/mdrp-sim | /utils/datetime_utils.py | 2,177 | 3.890625 | 4 | import math
from datetime import time, datetime, date, timedelta
from typing import Union
def min_to_sec(minutes: float) -> Union[float, int]:
"""Convert minutes to seconds"""
return minutes * 60
def hour_to_sec(hours: float) -> Union[float, int]:
"""Convert hours to seconds"""
return hours * 3600... |
81ca9e9631e82dfb321dce30f1e4d3b118d7cc5f | vishalpmittal/practice-fun | /funNLearn/src/main/java/dsAlgo/leetcode/P4xx/P496_NextGreaterElementI.py | 1,643 | 4.125 | 4 | """
Tag: array, integer
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s
elements are subset of nums2. Find all the next greater numbers for
nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater numbe... |
cd4b296072962c76d49e09393822a9cbbff13ec3 | shivesh01/Python-Basics | /Numpy/Numpy_2.py | 195 | 3.5625 | 4 | # Numpy Array
import numpy as np
A = np.array([[1, 2, 3], [3, 4, 5]])
print(A)
A = np.array([[1.1, 2, 3], [3, 4, 5]])
print(A)
A = np.array([[1, 2, 3], [3, 4, 5]], dtype=complex)
print(A)
|
8d77834aaefbfa28a31150c6ad8359362b6b4326 | Rounak259/HackerEarth | /Basic Programming/roy_and_profile_picture.py | 356 | 3.625 | 4 | acc_dim = int(input())
test_case = int(input())
for i in range(0, test_case):
w, h = input().split()
w = int(w)
h = int(h)
if (w==acc_dim and h==acc_dim) or (w==h and w>acc_dim):
print("ACCEPTED")
else:
if w<acc_dim or h<acc_dim:
print("UPLOAD ANOTHER")
... |
5bec8158c4c96392342872da7d0650c4abb8d4f5 | pasaunders/code-katas | /src/scores.py | 144 | 3.53125 | 4 | """Average the values in a list and round to the nearest whole number."""
def average(scores):
return int(round(sum(scores)/len(scores)))
|
aaf21059cf4f6b0bab503c4c1bf152bf59fcf79b | MarcosFantastico/Python | /Exercicios/ex076.py | 727 | 3.578125 | 4 | print('=' * 40)
print(f'{" LISTAGEM DE PREÇOS ":^40}')
print('=' * 40)
produtos = ('Lapis', 1.50, 'Borracha', 1.00, 'Cola', 4.69, 'Caderno', 3.50, 'Mochila', 120.30)
'''print(f'{produtos[0]:.<30}R${produtos[1]:>7.2f}\n{produtos[2]:.<30}R${produtos[3]:>7.2f}\n{produtos[4]:.<30}R$'
f'{produtos[5]:>7.2f}\n{pr... |
d5a1a4875974bd2237cebfa9803dbb27997367d0 | AlexOvey/pythonDoc | /pythonSwitch.py | 1,555 | 4.1875 | 4 | import sys
import os
import turtle
# def PrintBlue():
# print("You chose blue!\r\n")
# def PrintRed():
# print("You chose Red!\r\n")
# def PrintOrange():
# print("You chose Orange!\r\n")
# def PrintYellow():
# print("You chose Yellow!\r\n")
# def PrintGreen():
# print("You chose Green!\r\n")
# colorSelect... |
8d77275a231e3c324403d1ca6dd1e1271c1d37f5 | BrettMcGregor/dailyprogrammer | /easy_30.py | 503 | 4.125 | 4 | # Write a program that takes a list of integers
# and a target number and determines if any two
# integers in the list sum to the target number.
# If so, return the two numbers. If not, return
# an indication that no such integers exist.
from itertools import permutations as perm
def sum_target(nums, target):
a ... |
59c6d3458d61cf65aa045b2e8917e205728ae4cf | ldunphy1/504 | /Additional_Files/dijkstra_timedtests.py | 6,521 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 9 13:41:35 2016
@author: montgomt
"""
from itertools import combinations
from imp import reload
import csv
from graph import Graph
from time import time
import dijkstra
reload(dijkstra)
import os
def graph_from_file(filename,num_nodes):
'''reads edgelist from file a... |
e081e86479fef455e3a3ccba073a570101730206 | RenanBertolotti/Python | /Uri Judge - Python/URI-1097.py | 307 | 3.921875 | 4 | """Você deve fazer um programa que apresente a sequencia conforme o exemplo abaixo.
Entrada
Não há nenhuma entrada neste problema.
Saída
Imprima a sequencia conforme exemplo abaixo."""
valor = 7
for i in range(1, 10, 2):
for j in range(valor, (valor - 3), -1):
print(f"I={i} J={j}")
valor += 2 |
d089f2a07d66d6f247393e5168e08e7171bc79cd | andymc1/ipc20161 | /lista1/ipc_lista1.12.py | 376 | 3.71875 | 4 | #ipc_lista1.12
#Professor: Jucimar Junior
#Any Mendes Carvalho - 1615310044
#
#
#
#
#Tendo como dados de entrada a altura de uma pessoa, construa um algoritmo que calcule seu peso ideal, usando a seguinte fórmula: \n (72.7*altura) - 58
altura = input("Digite sua altura em metros, separa por ponto (ex: 1.70): ")
vT =... |
ffa48e13ca56b07b0e65d00de1e0e8a27e8b84db | ElliotPenson/cryptography | /stream.py | 2,315 | 3.96875 | 4 | #!/usr/local/bin/python
"""
stream.py
@author Elliot and Erica
"""
import sys
import random
from cryptography_utilities import (string_to_binary, file_to_binary,
binary_to_file)
def psuedo_random_register_fn(key):
"""Provide a register function that gives the next bit in the
keystream. In this case use ... |
4a4b999ff1fbc251760559241300abb465c3b82e | PlumpMath/DesignPattern-1033 | /python/templateMethod/templateMethod.py | 1,243 | 3.859375 | 4 | #! /user/bin/env python
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
class AbstractDisplay(metaclass = ABCMeta):
@abstractmethod
def openChar(self):
pass
@abstractmethod
def printInput(self):
pass
@abstractmethod
def closeChar(self):
pass
def display(self):
self.open... |
32158d2c15e3eb87c0c7cf25aad6dad286b8750d | korean5078/osp_repo | /py_lab/fibo_num.py | 256 | 3.96875 | 4 | #!/usr/bin/python3
count = 1
n = int(input("fibonacci number? "))
a = 1
b = 1
c = 1
print(1,end=',')
while count < n:
if n != count+1:
print(c,end=',')
else:
print(c)
final = c
a = b
b = c
c = a+b
count = count+1
print("F%d = %d" %(n, final))
|
876ea3c0d443f7b69822dacee8af2beb7bf7cd6a | bmareddy/leetcode | /Python/709_to_lower_case.py | 184 | 3.609375 | 4 | class Solution:
def toLowerCase(self, str: str) -> str:
return "".join(chr(ord(c) + ord("a") - ord("A")) if ord(c) >= ord("A") and ord(c) <= ord("Z") else c for c in str) |
c8f3a45a62faf37272b1c43b8495fa9577f35b45 | nee-datascience/Softmax-Classification-Machine-Learning | /classifier.py | 16,003 | 3.828125 | 4 | import os
import sys
import numpy as np
import pandas as pd
from sklearn.linear_model import SGDClassifier
# Do not change the code above
# These libraries may be all those you need
LABELS = ['setosa', 'versicolor', 'virginica']
# Insert your code below
class SoftmaxModel:
""" A softmax classifier to fit, predic... |
5e07e78406addc23540d1a8a684619d34945a367 | JunaidQureshi05/FAANG-ques-py | /01_Two_no_sum.py | 498 | 3.625 | 4 | # O(n^2) Time | O(1) Space
# Brute Force Approach
def pair_with_sum_1(array,target):
for i in range(len(array)):
for j in range(i+1,len(array)):
if array[i] + array[j] ==target:
return [i,j]
return []
# Optimized
def pair_with_sum(array,target):
memoize ={}
for i in range(len(array)):
potentialMatc... |
b27d723eff7750a2cfcd9d6db72854bdf1da7e73 | RianGirard/python_selection_sort | /selection_sort.py | 821 | 4.125 | 4 | arr = [5,9,8,4,3,1,2,6]
print(arr)
def selection_sort(lis):
for i in range(len(lis)): # this loop defines our outer passes through the array, starting with "i=zero"
index = i # this is our "marker" index, a placeholder for the lowest value found
for j in range(i+1, len(lis)): # this... |
4e8ac2336ffb6c09f9451c938e457e0f80a7b655 | alanchu394/New-York-Education-Analysis | /Functions/Function8.py | 599 | 3.5 | 4 | #written 12/8/2020
import numpy as np
#function expects 2 inputs: a 1d numpy array and a bound
def Function8(data, x):
writtenBy = "Alan Chu"
#sort the 1d numpy array
data = np.sort(data)
length = len(data)
#calculate lower and upper mass
lowerM = (100 - x)/2
upperM = (100- lowerM)
... |
bac20f3fb924c45d304d1154f9f69db718effa7b | urinaldisa/Algorithms-Collection-Python | /Algorithms/other/counting_inversions.py | 1,230 | 4.125 | 4 | def merge_sort(array):
total_inversions = 0
if len(array) <= 1:
return (array, 0)
midpoint = int(len(array) / 2)
(left, left_inversions) = merge_sort(array[:midpoint])
(right, right_inversions) = merge_sort(array[midpoint:])
(merged_array, merge_inversions) = merge_and_count(left, righ... |
69abfa0f1ca56011f0ceb984978036c5c1f0aa60 | serdarkuyuk/LeetCode | /106-construct-binary-tree-from-inorder-and-postorder-traversal.py | 1,267 | 3.84375 | 4 | inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, inorder: List[int], postorder: List[i... |
91ac929124db647820e98b9f88382d0e9d5c5ec8 | angela-andrews/learning-python | /ex8.py | 518 | 3.796875 | 4 | # printing {} formatting
formatter = "{} {} {} {}"
# passing the format function a tuple to be interpolated into the 4 brackets
# in the formatter variable.
print(formatter.format(1,2,3,4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(True, False, True, False))
print(formatter.format(fo... |
c3283528e0cff87d2ca7ab2e52c8f31297126ab1 | jels/ple-ieslosenlaces | /ficheros/carta_personalizada.py | 759 | 3.6875 | 4 | """
0. Crear los dos ficheros externos
1. Abrir desde el programa y mostrar en pantalla
"""
# Abrir ficheros --> f = open(ruta)
fcarta = open("carta.txt")
fclientes = open('clientes.txt')
# leer fichero --> contenido = f.read()
carta = fcarta.read()
#clientes = fclientes.read()
for cliente in fclientes:
... |
4f5c905209845ad929b731df0adc366a49150006 | Yucheng7713/CodingPracticeByYuch | /Algorithm/countInversion.py | 1,064 | 3.5 | 4 | class countInversion:
def mergeCount(self, lst_a, lst_b):
i = j = 0
merged_lst = []
numOfInv = 0
while i < len(lst_a) or j < len(lst_b):
if i < len(lst_a) and (j == len(lst_b) or lst_a[i] < lst_b[j]):
merged_lst += [lst_a[i]]
i += 1
... |
0d85e7978ec7204305a6292ce3ea77d76944e9cb | FBK-NILab/app-classifyber | /subsampling.py | 4,715 | 4.125 | 4 | """Functions to get a subset of objects that represents the initial
dataset. The objects in such subset are sometimes called landmarks or
prototypes.
"""
import numpy as np
def furthest_first_traversal(dataset, k, distance, permutation=True):
"""This is the farthest first traversal (fft) algorithm which selects... |
89cf7af5a1a5fe08800a5ccc8370c7a2fdb14493 | PEGGY-CAO/ai_python | /exam1/question5.py | 562 | 4.28125 | 4 | # Use NumPy random-number generation to create an array of twelve random grades in the range 60 through 100,
# then reshape the result into a 3-by-4 array.
# the averages of the grades in each column
# and the averages of the grades in each row.
import numpy as np
array = np.random.randint(60, 101, size=12).reshape(... |
88dbc16990dc98abbd983c8f3895bfe46aee490b | serebryakov-d/PyNEng_3.6 | /exercises/06_control_structures/task_6_1b.py | 1,602 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Задание 6.1b
Сделать копию скрипта задания 6.1a.
Дополнить скрипт:
Если адрес был введен неправильно, запросить адрес снова.
Ограничение: Все задания надо выполнять используя только пройденные темы.
'''
#ip_addr=input('Enter dotted decimap IP address:')
#ip_addr='6... |
3f8c2e18484dc189ac0aae8f7698b14551b120d7 | Yutapotter/naturelan-_100 | /chapter2/script16.py | 473 | 3.5 | 4 | import math
def file_nsplit(url,n):
with open(url) as f:
lines=f.readlines()
count=len(lines)
unit=math.ceil(count/n)#1行あたりの行数
for i,offset in enumerate(range(0,count,unit),1):
with open("chile_{:02d}.txt".format(i),"w") as out_file:
for line in lines[offset:offset+u... |
e62de9875d5c634af8706791a7a52e8aa840c2a5 | Tottoro932/Optimization | /home_work_2.1.py | 1,468 | 3.625 | 4 | import math
import math
#f(x)=tg(x)-2*sin(x)
def f(x):
return(math.tan(x)-2*math.sin(x))
def f1(x):
return((1/math.cos(x)**2)-2*math.cos(x))
def f2(x):
return(2*math.sin(x)/math.cos(x)**3+2*math.sin(x))
a=0
b=math.pi/4
E=0.03
col_steps=0
# метод касательных
print("медод касательных")
c=0
kol... |
b88ec320b1e1cfc5d4f5587f94a4cb85c80031df | gregseda/Python-Programming-Fundamentals | /Homework 3/HW3_test.py | 3,267 | 3.796875 | 4 | """ CLI program to test HW3 homework """
# Greg Seda
# For each test function, test *all* the cases shown in the instructions
import argparse
from HW3 import words_containing, len_safe, unique
def test_words_containing():
"""Return True/False if the test of words_containing passes/fails"""
sentence = "Anyone ... |
8950d4f29e4013b39195ea9bc38fa6f124a6f169 | vidstige/aoc | /2017/6.py | 1,063 | 3.71875 | 4 | def reallocate(memory):
selected = memory.index(max(memory))
tmp = list(memory)
redist = tmp[selected]
tmp[selected] = 0
n = selected + 1
while redist > 0:
tmp[n % len(tmp)] += 1
redist -= 1
n += 1
return tuple(tmp)
def count(initial):
history = set()
memo... |
d6d4df8b2053057f69e157dc5242f2bbfe4b68f1 | VihaanS22/Python-User-Intro-Form | /countWords.py | 318 | 4.25 | 4 | introString=input("Enter string :")
characterCount=0
wordCount=1
for i in introString:
characterCount=characterCount+1
if(i==' '):
wordCount=wordCount+1
print("Number of words in the string:")
print(wordCount)
print("Number of characters in the string:")
print(characterCount) |
c1af2e8b1a9d7afb418226cb973913ce62c4e70d | Ocho262/Python_Challenges_2 | /simple_math_2.py | 499 | 3.90625 | 4 | first_number = raw_input("What is the first number?")
second_number = raw_input("What is the second number?")
int_1 = int(first_number)
int_2 = int(second_number)
addition = int_1 + int_2
subtraction = int_1 - int_2
multiplication = int_1 * int_2
division = int_1 / int_2
simplemath = []
simplemath.append(addition)
s... |
57ad5b452b7918fb82fdc3606011e655c8bec5f4 | zhoulouzhu/feng | /python scripts/PageObject/related/args.py | 341 | 3.5625 | 4 | def fun_args1(args):
print("args,is %s" %args)
def fun_args2(args1,args2):
print("args1 is %s args2 is %s"%(args1,args2))
def fun_var_args(*args):
for value in args:
print("args:",value)
# fun_args1('51zxw')
# fun_args1()
# fun_args2('51zxw','Python')
# fun_args2('51zxw')
#fun_var_args("sd "... |
591f083a525e2a99dbcbc0f3dfa0f70f0555432d | rush2catch/algorithms-leetcode | /Basic Data Structures/array/leet_268_MissingNumber_bit.py | 774 | 3.75 | 4 | # Problem: Missing Number
# Difficulty: Easy
# Category: Array
# Leetcode 268:https://leetcode.com/problems/missing-number/#/description
# Description:
"""
Given an sorted array containing n distinct numbers taken from 0, 1, 2, ..., n,
find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] re... |
022744b7df7f642e808e03aab83c5841955a65a1 | MarvAntero/Pokemon_game | /Pessoa.py | 9,403 | 3.765625 | 4 | from Pokemon import * #Importando todos os dados de Pokemon.py para Pessoa.py
from Item import *
##Tem muito nos games: RNG - Random Name Generate
#random.ranint(a,b) - Gera n aleatorio entre a e b
#random.ranchoice(lista) - escolhe randomicamente um elemento do interior da lista
#random.uniform(a,b) - retorna float ... |
12650633f7e8f6142afd1360d192fc12acb0e662 | MarianDanaila/Competitive-Programming | /LeetCode_30days_challenge/2022/January/Linked List Cycle II.py | 631 | 3.671875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if not head or not head.next:
return None
slow = head.next
fast = head.next.next
... |
97cfdbb8bfb33247bfdf106fe9f14b491646f195 | Vasilic-Maxim/LeetCode-Problems | /problems/575. Distribute Candies/2 - Sorting.py | 358 | 3.515625 | 4 | from typing import List
class Solution:
"""
Time: O(n * log(n))
Space: O(1)
"""
def distributeCandies(self, candies: List[int]) -> int:
candies.sort()
kinds = 1
for i in range(1, len(candies)):
if candies[i] != candies[i - 1]:
kinds += 1
... |
200c57e49dccbbd8de055184684a74dfc637d38f | WiseAngel/python_algorithms | /sort/quick_sort.py | 1,825 | 3.9375 | 4 | import random
arr = random.sample(range(0, 20), 10)
print (arr)
def quick_sort(arr):
if len(arr) <= 1:
return (arr)
sep = arr[0]
# sep = arr[random.randint(0, len(arr)-1)]
left = [x for x in arr if x < sep]
right = [x for x in arr if x > sep]
mid = [x for x in arr if x == sep]
re... |
af3418fc2361ccb52a7a68e6e59f97b19e51fed1 | wadefletch/advent-of-code-2020 | /09/solution.py | 886 | 3.59375 | 4 | def part_one(input):
preamble = 25
input = [int(x) for x in input]
for i, line in enumerate(input):
if i < preamble:
continue
space = input[i - preamble:i]
solves = 0
for x in space:
for y in space:
if x + y == line:
... |
957258317de79d11ba5fb90fe4bfa537706c9b07 | github-wombat/netc | /sample/env/python_env | 295 | 3.625 | 4 | #!/usr/bin/python3
import os
import sys
#print("環境変数")
#env = os.environ
#for key,value in env.items():
# print('{0}: {1}'.format(key,value))
#print()
#print("標準入力")
#data = sys.stdin.read()
#print(data)
#print(data.swapcase())
argv = sys.argv
for v in argv:
print(v)
|
4280a54c2029aee024ae384751cbec19586e9358 | sujata-c/Evaluation-Criteria-Assignment-8 | /type_conversion.py | 2,062 | 4.71875 | 5 | # different data types in python
def implicit_type_conversion():
"""Implicit Type Conversion is automatically
performed by the Python interpreter. """
integer_type = 20
bool = True
float_type = 30.87
complex_type = 8j
print("Data type of interger_type before type conversion: ", type(inte... |
1702eb3928da14c80a2a6ba3e92e8d635f7850a8 | ashishchovatiya/python | /pr27.py | 195 | 3.65625 | 4 | a, b = map(int, input("enter the two number A & B for A/B = ").split(' '))
try:
c = a / b
except ZeroDivisionError:
print('Division by Zero Exception')
else:
print('A/B = ', c) |
8ccbec13b55f537ce3090038a8f250370b5ad962 | CodeForContribute/Algos-DataStructures | /HotQuestions/Array/lastIndexOne.py | 227 | 3.625 | 4 | def lastIndex(string, n):
for j in range(n-1,-1, -1):
if string[j] == '1':
return j
return -1
if __name__ == '__main__':
string = '000000001'
n = len(string)
print(lastIndex(string, n))
|
0f63507e8747323838916fdef504fb0985253dad | joelrorseth/Snippets | /Python Snippets/Data Structures/doubly_linked_list.py | 1,655 | 4.09375 | 4 | #
# Doubly Linked List
#
# This implementation maintains a next and previous pointer for each node,
# and each list maintains a head and tail. This yeilds improvements over
# singly linked lists, including the ability to insert / remove from either
# end in O(1), as well as easy fwd / bkwd traversal in O(n).
#
# Joel R... |
1225edfa8266f7bb791260a8d5036cd85e8d0bfc | dmt1100/gb-python-intro | /hw2/task5.py | 252 | 3.640625 | 4 | # задача №5
my_list = [7, 5, 3, 3, 2]
print(f"Текущий рейтинг: {my_list}")
rating = int(input("Введите рейтинг: "))
y = 0
for i in my_list:
if rating <= i:
y += 1
my_list.insert(y, rating)
print(my_list)
|
0996a041df3e1c8ec6372d9f8c2f88a1bc71c5ff | mve17/SPISE-2019 | /Pygame Day 2/test_triangleutils.py | 1,200 | 4.21875 | 4 | import unittest
from math import pi as PI
from triangleutils import *
class TestRotateTriangleUtilMethods(unittest.TestCase):
"""
This is a unit test class to test the functions in the traiangle_utils module.
See https://docs.python.org/2/library/unittest.html
"""
def test_degrees_to_radians(self... |
9c888a4a237a66dc88a8f0d705d700a04119c966 | fabioeomedeiros/Python-Base | /087_Matriz_v2.py | 925 | 4.03125 | 4 | #087_Matriz_v2.py
matriz = [[0, 0, 0], [0, 0, 0,], [0, 0, 0]]
sp = st = m = 0
print("")
for i in range(0,3):
for j in range(0,3):
matriz[i][j] = int(input(f"Digite um número: [{i}, {j}] "))
print("")
print(matriz)
print("")
for i in range(0,3):
st += matriz[i][2]
for j in range(0,3):
prin... |
5e9a2f86c8c017cd9e087a5702c783076031a1ad | shreyrai99/CP-DSA-Questions | /HackerRank/Extra Long Factorials/Extra Long Factorial.py | 213 | 3.84375 | 4 | """It's very easy to handle large numbers in python. To calculate the factorial
Just import the factorial function from the math module and apply it"""
from math import factorial
n=int(input())
print(factorial(n)) |
4bf7dec801926644f238381c25a566abebfc12d2 | shekhar270779/ML_Python | /Python_Intro.py | 427 | 3.640625 | 4 | import sys
import time
print(sys.version) # to find python version
print("Hello and Welcome to Python")
seconds = time.time() # returns no. of seconds passed since epoch
local_time = time.ctime(seconds) # returns local time
print(local_time)
# adding additional time commands
tm = time.localtime(seconds)
print(tm.tm_... |
e4561e1d38ceed8a8b61c06d9ab113baf8fa2fc1 | soothy/MIT-OCW-2016-python | /hangman.py | 6,422 | 3.828125 | 4 | import random
import string
WORDLIST_FILENAME = "../../../../Desktop/ps2/ps2/words.txt"
myList = []
strl = " "
guesses = 6
checklist=[]
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while t... |
1888ad50141c5cd66143cfd3d71eaa6b77128949 | rhiannon-17/python-kokonut | /mes_fonctions.py | 306 | 3.703125 | 4 | def eratosthene(b):
liste = [True]*(b+1)
liste[0],liste[1] = False, False
for i in range(b+1):
if liste[i] == True:
yield i
for k in range(i**2, b+1, i):
liste[k] = False
def main():
print("kokonut song")
print("kiki et bibi et koko")
|
96ec108cb0ac2c756220ac07685f16e393ef7706 | x4nth055/pythoncode-tutorials | /general/url-shortener/cuttly_shortener.py | 589 | 3.5625 | 4 | import requests
import sys
# replace your API key
api_key = "64d1303e4ba02f1ebba4699bc871413f0510a"
# the URL you want to shorten
url = sys.argv[1]
# preferred name in the URL
api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}"
# or
# api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}&... |
4125b19e8db1174e22ed26ea533e3d5a3ef027f8 | Thaysfsil/short_exercise | /codeValidation.py | 3,080 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 19 22:00:15 2018
@author: thayssilva
"""
import re
def Inwardcode(InwardCode):#Verify Inward Code
validationInward= False
#Letter Exceptions:
resemble_digits=['C', 'I', 'K', 'M', 'O', 'V']
#verify 9AA format
if Inwar... |
efffe1ee43653fece102beba2d3a9509cb028e7e | AmanPriyanshu/genetic-algorithms | /linear_regression_with_ga.py | 2,822 | 3.671875 | 4 | import numpy as np
import random
import matplotlib.pyplot as plt
def create_dataset(n, slope):
data = np.empty([n, 2])
for i in range(n):
x = random.randint(-100, 100)
y = slope*x
data[i][0], data[i][1] = x, y
return data
def lr_predict(X, w):
y_pred = X*w[0]
return y_pred
def lr_cost(y_pred, Y):
rms = ... |
e943961f0962786b347265c976174e24cfc8319a | supershinu/hagman-game | /my_hangman.py | 3,955 | 3.96875 | 4 | import random
def hangman():
word = random.choice(["steve","ironman","thor","loki","thanos","blackpanther","spiderman","blackwidow","wanda","hulk"])
valid_letters ='abcdefghijklmnopqrstuvwxyz'
guessmade = ''
turns = 10
while len(word)>0 :
main=""
for letter in word :
... |
31864e54abeeb272432b83c9b4141e6ad246e854 | sumanblack666/datacamp-python-data-science-track | /Natural Language Processing Fundamentals in Python/Chapter 1 - Regular expressions & word tokenization.py | 5,109 | 4.59375 | 5 | #---------------------------------------------------------------------------------------------------------------#
#Chapter 1 Regular expressions & word tokenization
#---------------------------------------------------------------------------------------------------------------#
##Practicing regular expressions: re... |
d7218ce32a135c39624faa843d903877ae423a4f | vmred/Coursera | /coursera/python-basic-programming/week5/hw19.py | 269 | 3.71875 | 4 | def greaterThanNeighbourhoods(items):
arr = list(map(int, items.split()))
count = 0
for i in range(1, len(arr) - 1):
if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:
count += 1
return count
print(greaterThanNeighbourhoods(input()))
|
8aaae4fc1a863357a7135bb39396cf95460b9da4 | SRG08/Searching-Sorting-and-Pointers-Algorithms | /Merge_Sort.py | 2,539 | 4.3125 | 4 | from random import randint
# Merge Sort:
# This divide and conquer algorithm splits a list in half, and keeps splitting the list by 2 until it only has singular elements.
# Adjacent elements become sorted pairs, then sorted pairs are merged and sorted with other pairs as well.
# This process continues until we get a... |
568a8197fbcc1db3abc15be5472c797e4dcbab62 | andrewlee1807/boring | /binary_search.py | 434 | 3.640625 | 4 | def binarySearch(low, high):
# mid = (low + high) // 2
print(low, high)
mid = int(low + (high - low) * (k - a[low]) / (a[high] - a[low]))
print(mid)
if a[mid] == k:
return mid
if low == high:
return -1
if a[mid] > k:
return binarySearch(low, mid-1)
if a[mid] < k:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.