blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
dd29d3f9517f34650eac43c95944a05a497ebaa3 | Igorok/machineLearning | /algorithms/sort_search.py | 15,229 | 3.953125 | 4 | # -*- coding: utf-8 -*-
'''
Когда элементы данных хранятся коллекцией в виде списка, мы говорим, что между ними линейные или последовательные отношения. Каждый элемент хранится на определённой позиции относительно прочих. В списках Python она задаётся индексом данного элемента. Поскольку значения индексов упорядочены,... |
18d1bee398318851dc4ca29e428f61c7b87eea25 | Teemperor/Nils | /test/PythonBasic1/prog.py | 1,267 | 3.90625 | 4 | # This program adds up integers in the command line
import sys
try:
total = sum(int(arg) for arg in sys.argv[1:])
print('sum =', total)
except ValueError:
print('Please supply integer arguments')
prices = {'apple': 0.40, 'banana': 0.50}
my_purchase = {
'apple': 1,
'banana': 6}
grocery_bill = sum(pr... |
49598471206b8e7fc31cc67985245c111c123c11 | SebaChuaqui/tienda-productos | /modulos/tienda.py | 798 | 3.515625 | 4 |
class Tienda:
def __init__(self, nombre):
self.nombre = nombre
self.productos = []
def __str__(self):
return f"Tienda: {self.nombre}"
def agregar_producto(self, nuevo_producto):
self.productos.append(nuevo_producto)
return self
def eliminar_producto(self, id)... |
0dba419a7e24f15f760db44472fe954961ee0da6 | changkuanshenhj/advanceDjango | /算法case/index_01.py | 802 | 3.796875 | 4 | def getduplication(numbers_2):
if len(numbers_2) <= 0 and numbers_2 is None:
return -1
start = 1
end = len(numbers_2) - 1
while end >= start:
middle = ((end - start) >> 1) + start
count_1 = countrange(numbers_2, start, middle)
if end == start:
if count_1 > 1:
... |
9460dc91feb91a54358b6b107792e6e1782239ab | changkuanshenhj/advanceDjango | /common/code.py | 537 | 3.8125 | 4 | import random
def _random_str(start, end):
return chr(random.randint(start, end))
# 少一部分修改,比如说验证码里面的内容不会重复出现
def new_code_str(len):
code_str = ''
for _ in range(len):
flag = random.randint(0, 2)
start, end = (ord('a'), ord('z')) if flag == 1 \
else (ord('A'), ord('Z')) if fla... |
c6c836d57478b8bff3a4b906d0dc094a2f95ff56 | sureshmecad/Python | /1_Cheat_Sheet/Solution Project 2.py.py | 1,181 | 3.59375 | 4 | #Data
sales = [14434.65, 21222.61, 16554.34, 15445.32, 16054.52, 19005.23, 22222.22, 17466.29, 11345.21, 14333.43, 14444.45, 21222.10]
profit = [1222, -500, 1343, 2222, 2122, 3122, 1000, 5330, 2123, 4332, 2221, 3213]
#Solution
#Calculate Profit ratio As The factor of Sales And Profit
profitratio = []
for i in ran... |
3e1499c6518e7a72390fda6e70bf92e34bb9b7d7 | sleepyzzzzzz/Statistical-Machine-learning---course-work | /hw3/one_vs_all.py | 3,137 | 3.734375 | 4 | from sklearn import linear_model
import numpy as np
import utils
class one_vs_allLogisticRegressor:
def __init__(self,labels):
self.theta = None
self.labels = labels
def train(self,X,y,reg):
"""
Use sklearn LogisticRegression for training K classifiers in one-vs-rest ... |
82ff78ef8a5408e21af77fc462bce043333de74e | sharmapradyumn/PYTHON-Adhoc | /Directory_file.py | 509 | 3.78125 | 4 | #!/usr/bin/python3
import os
dirname=input("Enter full path where you want to make files and directory:-")
if not os.path.exists(dirname):
os.mkdir(dirname)
# creating 200 directories
for i in range(1,201):
os.system("mkdir "+dirname+"/Dir"+str(i))
#creating 100 text files
for i in range(1,101):
os.system("tou... |
4e601604b832fdd2976e8364bdda15690036df87 | heecheol1508/algorithm-problem | /_swea/d3/병합정렬.py | 1,128 | 3.703125 | 4 | import sys
sys.stdin = open('input.txt', 'r')
def merge_sort(arr):
len_arr = len(arr)
if len_arr <= 1:
return arr
else:
mid = len_arr // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(arr_left, arr_right):
glob... |
11d20f10cb76bfd6586fd910a6c9dac4d93192e8 | heecheol1508/algorithm-problem | /_programmers/외벽 점검.py | 1,370 | 3.5625 | 4 | def checking(weak, dist):
n_weak = len(weak)
i = 0 # i <- index in weak
while i < n_weak:
if len(dist) == 0:
return -1
j = len(dist) - 1 # j <- index in dist
for k in range(i, n_weak): # k <- in range
if weak[k] > weak[i] + dist[j]:
... |
4e2e95637068ab95fbf864bf7735380db6bcb4a4 | heecheol1508/algorithm-problem | /_programmers/디스크 컨트롤러.py | 695 | 3.5625 | 4 | import heapq
def solution(jobs):
n = len(jobs)
requests = []
for job in jobs:
heapq.heappush(requests, (job[0], job[1]))
ms_total = 0
end = 0
waiting = []
while requests or waiting:
if waiting:
a, b = heapq.heappop(waiting)
ms_total += end + a - b
... |
3f2bd6556d0b5c127fa2003d377b4dc6f66a1fd6 | heecheol1508/algorithm-problem | /_swea/d2/1954.py | 137 | 3.6875 | 4 | N = int(input())
board = []
row = []
for i in range(N):
for j in range(N):
row.append(0)
board.append(row)
print(board) |
3009fb9c01ce917da84d11052f33dd50ba6ff007 | heecheol1508/algorithm-problem | /_programmers/가장 큰 수.py | 551 | 3.625 | 4 | def solution(numbers):
numbers = list(map(str, numbers))
numbers.sort(reverse=True)
N = len(numbers)
for i in range(1, N):
if len(numbers[i]) == len(numbers[i-1]):
continue
else:
for j in range(i, 0, -1):
if numbers[j-1]+numbers[j] >= numbers[j]+... |
7fc0fcb91fbc102322a40ba99a86d08e7035fc4d | heecheol1508/algorithm-problem | /_swea/d2/날짜 계산기.py | 1,036 | 3.796875 | 4 | # 날짜 세기
T = int(input())
for t in range(1, T + 1):
calender = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dict_day = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
first_Month, first_Day, second_Month, second_Day = map(int, input().split())
days = 0
if first... |
8743368bf8e419bb5f518906e938f2ce0df30b40 | heecheol1508/algorithm-problem | /_programmers/여행경로_dfs.py | 869 | 3.75 | 4 | import collections
def solution(tickets):
N = len(tickets)
answer = ['ICN']
def fly(k, path):
if k == N:
return path
departure = path[-1]
if routes[departure]:
for _ in range(len(routes[departure])):
arrival = routes[departure].pop(0)
... |
4ec1471af144c71f9735a125151470ae4f5e1124 | AbigailSayoj/P11-Single_sample_Z-test | /code.py | 2,921 | 3.9375 | 4 | import plotly.figure_factory as ff
import plotly.express as go
import statistics
import random
import pandas as pd
import csv
df = pd.read_csv("medium_data.csv")
data = df["responses"].tolist()
population_mean = statistics.mean(data)
print("Populaton mean:- ", population_mean)
# Code to find the mean ... |
b6f06dabaed7ee6646e19c7ec611df49e38278a6 | harmonsoftwaresolutions/hss-algorithms | /py/checknums.py | 538 | 4.25 | 4 | # Have the function SimpleAdding(num) add up all the numbers from 1 to num.
# For example: if the input is 4 then your program should return 10 because
# 1 + 2 + 3 + 4 = 10. For the test cases, the parameter num will be any number
# from 1 to 1000.
def CheckNums(num1,num2):
r = None
if num1 == num2:
... |
4ecfd45fe87b6e3f9901a8dd999d33d4f8483bc0 | fbolsen/Homebrew | /pwm.py | 1,950 | 3.578125 | 4 | # https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python
import time, traceback
import threading
import datetime
class PWM:
def __init__(self, period=5, power=0, levels=10):
self.period = period
self.power = power
self._... |
128801ab72cbb7f7480b18ac3cd556cc2c155b11 | Bugzey/Softuni-Python-Fundamentals | /05. Python-Fundamentals-Objects-and-Classes/06 Animals.py | 1,953 | 3.75 | 4 | # Just acting like we're animals
class Animal:
def __init__(self, *tokens):
self.type, self.name, self.age, self.attribute = tokens
self.age = int(self.age)
self.attribute = int(self.attribute)
attribute_label = {
'Dog': 'Number Of Legs',
'C... |
77ded4b466e5b6ec2b17a25c79b2e7be4b4320bc | Bugzey/Softuni-Python-Fundamentals | /08. Python-Fundamentals-Regular-Expressions/06 Replace tag.py | 492 | 3.609375 | 4 | # Replace the <a> html tag
import re
pattern = re.compile(r'<a[ ]?href=\"(?P<url>http[s]?://[a-z]+\.[a-z]+)\">(?P<name>(\w+\s*)+)</a>')
while True:
user_input = input()
if user_input == 'end':
break
match = re.finditer(pattern, user_input)
result = user_input
for instance in match:
... |
476d9042fc6c65ed7b9d321cc0122a6fca75abbf | Bugzey/Softuni-Python-Fundamentals | /03. Python-Fundamentals-Lists/10 Square numbers.py | 332 | 3.875 | 4 | # Print the square numbers from an input list
nums = input().split()
#result = [str(item) for item in nums if float(item)**(1/2) %1 == 0].sort()
result = [int(item) for item in nums if float(item) >= 0 and abs(float(item))**(1/2) %1 == 0.0]
result.sort(reverse=True)
print(" ".join([str(item) for item in result]))
#pr... |
9c48a238518491c2b319ecc75e22f0d22c7439a9 | Bugzey/Softuni-Python-Fundamentals | /Exams/exam prep 2018-03-08/04.py | 987 | 3.59375 | 4 | # Parse valid crypic messages
# A command is valid when the input starts with digits,
# continues to alphabetic characters and ends in any
# characters but alphabetical.
import re
pattern = re.compile(r'(?P<left>\d+)(?P<command>[A-Za-z]+)(?P<right>[^A-Za-z]*)$')
while True:
user_input = input()
if u... |
a385b0e1d48575f09aaee43aa9a9e92521691d54 | Bugzey/Softuni-Python-Fundamentals | /03. Python-Fundamentals-Lists/01 Sum List Items.py | 226 | 3.984375 | 4 | # Reads a list of integers
num_iterations = int(input())
list_items = []
for element in range(num_iterations):
list_items.append(int(input()))
result = 0
for element in list_items:
result += element
print(result)
|
3ddcef2b007e30172723e1676ac630fb09e7c470 | Bugzey/Softuni-Python-Fundamentals | /07. Python-Fundamentals-Strings-and-Text-Processing/05 String Value.py | 404 | 4.21875 | 4 | # Sum the ascii codes of a string
user_input = input()
count_which = input()
def is_what_we_seek(letter):
if count_which == 'LOWERCASE':
result = str.islower(letter)
elif count_which == 'UPPERCASE':
result = str.isupper(letter)
return(result)
ascii_codes = sum([ord(letter) for letter in... |
4c76dee3a61f176f024747db03f42c7835702d5b | Bugzey/Softuni-Python-Fundamentals | /Exams/exam prep 2018-03-08/03.py | 2,785 | 3.765625 | 4 | # Use regex to clean football results, custom pattern
import re
class Team:
def __init__(self, name):
self.name = name
self.points, self.goals, self.matches = 0, 0, 0
def win(self, goals):
self.points += 3
self.goals += goals
def loss(self, goals):
self.points +=... |
57d18136637d6aa7aa247f058db2e7f913fca193 | Bugzey/Softuni-Python-Fundamentals | /01. Python-Fundamentals-Python-Intro/05 Step.py | 178 | 3.65625 | 4 | # Ask for start number, end number and step
start_num = int(input())
end_num = int(input())
step_num = int(input())
for i in range(start_num, end_num, step_num):
print(i)
|
6883379a2bdd9baa0ec69462abf3796149f0c108 | Bugzey/Softuni-Python-Fundamentals | /02. Python-Fundamentals-Functions-and-Debugging/08 Evens by odds.py | 504 | 3.953125 | 4 | # Read an integer and multiply the sum of its evens
# by that of its odds
def multiply(number):
number = str(number)
num_length = len(number)
odds = range(0, num_length, 2)
evens = range(1, num_length, 2)
sum_odds = 0
sum_evens = 0
for i in odds:
sum_odds += int(number[i])
... |
8084962f12a6ec0f23fc753cb7e70d0fcfdfb01e | otisgbangba/julius-calculator | /julius calculator.py | 2,279 | 4.1875 | 4 | def welcome():
print("welcome to julius calculator.")
proceed = input("""Please select what you will like to do C for continue,E for exit""")
if proceed.upper() == 'C':
calculate()
elif proceed.upper() == 'E':
proceeding = input("""Do you really want to exit? Y for yes,N for no""")
i... |
c8b2e4eb75809f4dc8c55bad4b23fe2514f9271b | aceaulden/Team1 | /user.py | 2,702 | 3.5 | 4 |
# user class- adds, deletes, prints users
class user:
# This class is used to create and maintain user accounts
def __init__(self):
pass
#add a user to the database
#songID is AUTO_INCREMENT and votes has a default of 0, so no need to worry about them
def addUser(cursor, user, password):
#create q... |
5af23220d60ed0fda0cee287048f28e78304f930 | NOBarbosa/Exercicios_Python | /Mundo2/ex058.py | 755 | 4.09375 | 4 | '''Melhore o jogo do DESAFIO 28 onde o computador vai “pensar” em um número entre 0 e 10. Só que agora o
jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer.'''
from random import randint
num_pc = randint(0, 10)
print('Vamos jogar?')
print('Vou pensar em um númer... |
a64aff768cc9b9e6ee3db272aafcf56d54bb68bb | brennobrenno/learning-from-data-course | /Homeworks/Homework 2.py | 7,603 | 3.6875 | 4 | import random
import numpy as np
import matplotlib.pyplot as plt
# HOEFFDING INEQUALITY
# nu_1_list = []
# nu_min_list = []
# nu_rand_list = []
#
# for run in range(100000):
# coin_list = []
# for i in range(1000):
# count = 0
# for j in range(10):
# if random.randint(0, 1) == 1:
#... |
4e32df90a0f0b49302ec13c29e45e832a244f7a2 | albahnsen/scikit-learn | /sklearn/utils/_scipy_convexhull_backport.py | 2,804 | 4.0625 | 4 | """Convex Hull of a set of points
"""
import numpy as np
__all__ = ['ConvexHull']
class ConvexHull():
""" Private function that calculate the convex hull of a set of 2-D points
The algorithm was taken from [1].
http://code.activestate.com/recipes/66527-finding-the-convex-hull-of-a-set-of-2d-points/
... |
d109605317aec80d320f4d15bb5c71c1bb6c8ad2 | Lihuan-Nathan/row_offer | /旋转数组的最小数字.py | 712 | 3.734375 | 4 | #剑指 Offer 11. 旋转数组的最小数字
class Solution(object):
def minArray(self, numbers):
"""
:type numbers: List[int]
:rtype: int
"""
ref_value = numbers[0]
min = 0
max = len(numbers)-1
while(True):
mid = int((min+max)/2)
if numbers[mid]>... |
55851c1ac7318320747aabb55c932a1ed84d8744 | SeanEmac/Python | /NumberFun.py | 515 | 3.734375 | 4 | n = int(input())
possible = False
for _ in range(n):
a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
if a + b == c:
possible = True
elif a - b == c:
possible = True
elif b - a == c:
possible = True
elif a * b == c:
possible = True
elif b / ... |
3d5c11454971ada0397285a008105a48c2e67759 | SeanEmac/Python | /AlphabetSpam.py | 406 | 4.03125 | 4 | string = input()
length = len(string)
whitespace, lowercase, uppercase, symbol = 0, 0, 0, 0
for i in range(length):
if string[i] == '_':
whitespace += 1
elif string[i].islower():
lowercase += 1
elif string[i].isupper():
uppercase += 1
else:
symbol += 1
print(whitespace... |
2f247f7b38d3eb00e9594e39aff75bb907d5526a | SeanEmac/Python | /Filip.py | 200 | 3.671875 | 4 | nums = input().split()
first = nums[0]
second = nums[1]
one = ""
two = ""
for i in range(3):
one += first[2-i]
two += second[2-i]
if int(one) > int(two):
print(one)
else:
print(two)
|
1c0fc94a0e5a83bc9488056bb4f49c0418c3146e | Devendra0110/DailyCodeChallenges | /Aug-2020/001 String Peeler.py | 369 | 4.15625 | 4 | # Your goal is to create a function that removes the first and last letters of a string.
# Strings with two characters or less are considered invalid.
# You can choose to have your function return null or simply ignore.
def stringPeeler(inputString):
if len(inputString) > 2:
return inputString[1:-1]
pri... |
1594be838c934947df0cea381507d1af0b258715 | nandooliveira/air_conditioning_fuzzy_controller | /simulator.py | 965 | 3.6875 | 4 | # -*- coding: utf-8 -*-
from skfuzzy import control as ctrl
from controller import AirConditioningFuzzyController
# simulation
air_conditioning_controller = AirConditioningFuzzyController()
air_conditioning_controller.show_temperature_graph()
temperature = input('Inform the temperature:')
air_conditioning_controll... |
64de2b2335cc65164038a4df698569c635838ea5 | idzharulhuda13/pythonoop | /13 - Override.py | 565 | 3.796875 | 4 | class Hero:
def __init__(self, name, hp):
self.name = name
self.hp = hp
def showInfo(self):
print("{} \n\thp: {}".format(self.name, self.hp))
class Hero_int(Hero):
def __init__(self, name):
super().__init__(name, 100)
def showInfo(self):
print("{} \n\tRole: IN... |
25d908580619f5ff46283f5613b5c0cbec5e0991 | NightFury13/Daily_Coding_Problem | /Problem41_to_Problem56_May19/day_54.py | 1,535 | 4.1875 | 4 | """
This problem was asked by Dropbox.
Sudoku is a puzzle where you're given a partially-filled 9 by 9 grid with digits. The objective is
to fill the grid with the constraint that every row, column, and box (3 by 3 subgrid) must contain
all of the digits from 1 to 9.
Implement an efficient sudoku solver
"""
# Impor... |
ecf75511dc12150bd0c49550f764d52ad05304e6 | NightFury13/Daily_Coding_Problem | /Problem1_to_Problem23_March19/day_19.py | 996 | 4.03125 | 4 | """
This problem was asked by Facebook.
A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost
while ensuring that no two neighboring houses are of the same color.
Given an N by K matrix where the nth row and kth column represents the cost to build the nth ... |
e291288de595d192ef64b32f72efce8ed5beecfb | NightFury13/Daily_Coding_Problem | /Problem1_to_Problem23_March19/day_7.py | 917 | 4.21875 | 4 | """
This problem was asked by Facebook.
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded.
For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable. For example, '001' i... |
e9bb256ef533dd7cfeafdd7d327532077b3871c3 | NightFury13/Daily_Coding_Problem | /Problem1_to_Problem23_March19/day_23.py | 2,581 | 4.5 | 4 | """
This problem was asked by Google.
You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall. Each
False boolean represents a tile you can walk on.
Given this matrix, a start coordinate, and an end coordinate, return the minimum number of steps required to r... |
b380a5cde140214de89370591637764e73e80e6f | NightFury13/Daily_Coding_Problem | /Problem1_to_Problem23_March19/day_10.py | 499 | 3.859375 | 4 | """
This problem was asked by Apple.
Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
"""
import sched
import time
def printer():
print("Executed at : "+ str(time.time()))
def job_sched(scheduler, f, n):
scheduler.enter(float(n)/100, 1, f, ())
sc... |
9b6b8650abe642b0a3b382a2fc2a516bd3b037d0 | NightFury13/Daily_Coding_Problem | /Problem1_to_Problem23_March19/day_8.py | 1,311 | 4.15625 | 4 | """
This problem was asked by Google.
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
0
/ \
1 0
/ \
... |
986860a9db13cf4be29c3cb7de5d97c87baac5d6 | NightFury13/Daily_Coding_Problem | /Problem1_to_Problem23_March19/day_22.py | 1,288 | 4.125 | 4 | """
This problem was asked by Microsoft.
Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If
there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return
null.
For example, given the set of w... |
b8832be305a9a783215f92d6446f4bdcd3f0e869 | NightFury13/Daily_Coding_Problem | /Problem24_to_Problem40_April19/day_25.py | 1,355 | 4.5 | 4 | """
This problem was asked by Facebook.
Implement regular expression matching with the following special characters:
. (period) which matches any single character
* (asterisk) which matches zero or more of the preceding element
That is, implement a function that takes in a string and a valid regular expressi... |
bdd9181b9563b30a24ba6ee5a0b335214615b6bb | yusanlin/SNA-Algorithms | /dijkstra.py | 2,003 | 3.828125 | 4 | """
Dijkstra.py
@author: Yusan
@date: 2014/08/11
@description: implementationg of Dijkstra algorithm,
finding the shortest paths in a given network graph
"""
import numpy as np
VERY_BIG_NUMBER = 1000000
INF = float("inf")
def Dijkstra(Graph, source):
n_nodes = len(Graph)
dist = [0]*n_nodes
... |
a4982fa2d60a55788dbecd9ecb86c5cc997ce880 | antiface/Flashcards_pro | /flashcards.py | 11,053 | 3.5 | 4 | '''
flashcard program for studying.
'''
import os, sys, csv, pickle, collections, random, time, argparse
headers = []
terms = []
class GameOver(Exception):
pass
class ChangeGame(Exception):
pass
def getTermsFromInput(inp):
global terms
sniffer = csv.Sniffer()
dialect = sniffer.sniff(inp)
iter... |
7447191f00c1b3f2cdf410deb54be9e653b96028 | jw7sas/basic-api-rest-python | /app/database.py | 829 | 3.609375 | 4 | # imports
import sqlite3
class Database():
DATABASE_NAME = "jspython.db"
def getConn(self):
try:
return sqlite3.connect(self.DATABASE_NAME)
except ValueError:
print("Error de conexión DB")
def createTables(self):
""" Método de creación de tablas sqlite""" ... |
bc9b8267512a5c0fa4304e33b24829569d8acc94 | BBekmurat/Skill-Factory | /C2.2.py | 621 | 4 | 4 | class StaticClass:
@staticmethod # помечаем метод который мы хотим сделать статичным декоратором @staticmethod
def bar():
print("bar")
f = StaticClass()
f.bar() # вызывать статические методы через объекты так же никто не запрещает
#StaticClass.bar()
class Square:
def __init__(self, s... |
11a2075359f142db24815e02614b055bd75bb6ea | VithikShah/Nearest-neighbour-Maps-k-d-trees | /kdtree2.py | 3,713 | 3.90625 | 4 | #------------------------MODULE TO IMPLEMENT KD-TREE------------------------------
#import math for math functions
import math
#counter function to count no. of recursive search queries
def cnt():
cnt.count+=1
cnt.count=0
#function to calculate square distance between two points 'a' and 'b'
def square_distance(a,... |
ad4be5559eb9371dace0fa22e98930e54be442cc | KrShaswat/6.00.1x | /PSET1-1.py | 426 | 3.875 | 4 | #Assume s is a string of lower case characters.
#Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print:
#Number of vowels: 5
#Code below
v ='aeiou'
sum = 0
for n in range(len(s)):
... |
11790394b2853b4b365d900bc1f9bdaf82726244 | goofyjnr/game-code-2021-Alister | /platformer game/Final_code.py | 20,824 | 3.5625 | 4 | #simple platformer final code
#set up of my game
import pygame #Imports Pygame alowing us to make a game
from pygame.locals import * #this gives the all the local varabials e.g. pygame.quit
import sys #imports the sys
import random #imports random alowing for randomnes to happen
from pygame.mixer import pause
pyg... |
97d1c919bd10666772785bd11b244ae45ac63639 | Lintik/hackerrank | /Core CS/Algorithms/Warmup/Compare the Triplets/compareTheTriplets.py3 | 233 | 3.5 | 4 | size = int(input())
matrix = []
for _ in range(size):
row = input().strip().split(' ')
matrix.append(row)
d1, d2 = 0, 0
for i in range(size):
d1 += int(matrix[i][i])
d2 += int(matrix[-i-1][i])
print(abs(d1 - d2))
|
e306ff8c993c37e93825a331ae0e25ecf0464f88 | mokuren/workstation | /convert.py | 1,112 | 4.15625 | 4 | '''
python beginner math
'''
def print_menu():
print('1. Kilometers to Miles')
print('2. Miles to Kilometers')
print('3. Fahrenheit to Celsius')
print('4. Celsius to Fahrenheit')
def km_miles():
km = int(input('Enter distance in Kilometers:'))
miles = km / 1.609
print('Distance in mil... |
fcdfc7ffa25f7958a0094d40d755cef5a638e157 | 13299118606/My-Functions | /Python/TUTORIAL_dataframes_and_excel.py | 19,877 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 1 22:57:30 2017
@author: master
"""
"""
Show examples of modifying the Excel output generated by pandas
"""
import pandas as pd
import numpy as np
from xlsxwriter.utility import xl_rowcol_to_cell
# read excel:
df = pd.read_excel("../in/excel-comp-datav2.xlsx")
# We ne... |
260253373fe7b2ff48c9e1557639a156aa59ce66 | vino1990/social | /section1.py | 4,413 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 10 06:35:29 2018
@author: kunals
"""
'''
The general process to get from data to predictive model tends to involve three major components:
Getting to know the data.
Cleaning and preparing the data for modelling.
Fitting models and evaluating their performa... |
9d7709981a9fc8dbe3b4391e593c79060d71ad07 | radek-coder/ceasar_exercise | /encrypt.py | 451 | 3.8125 | 4 | def encrypt(plain_text, offset):
cipher_text = ""
for i in plain_text:
numerical_value = ord(i)
if i.isupper():
adj = ((numerical_value - offset - 65) % 26) + 65
cipher_text += chr(adj)
elif numerical_value == 32:
cipher_text += i
pass
... |
8b8d1523716b8597bb705a20531850ba7ef4916e | EduardoMerino/Sharing-for-Class | /wsq-16.py | 842 | 3.640625 | 4 | txt=open("93cars.dat.txt","r") # mode 'r' the file will only be read
cgm=0 #gas mileage in city
hgm=0 #gas mileage on highway
price=0 #price of the car
l=1 #this is a control for reading the lines
cars=0 #amount of cars
for line in txt: #divides the file by lines
if l%2==1: #reads every other line (the one with the... |
b529baba9e0e60465f719a00a75d9f9a4f7bd3ec | LiliTa1762/holbertonschool-web_back_end | /0x00-python_variable_annotations/6-sum_mixed_list.py | 253 | 3.59375 | 4 | #!/usr/bin/env python3
"""type-annotated function sum_mixed_list"""
from typing import Union, List
nums = Union[int, float]
def sum_mixed_list(mxd_lst: List[nums]) -> float:
"""Using Union to mxd list, return a float"""
return sum(mxd_lst)
|
d8277b5deeb3b9e90e145d703ac5697ee1abd4cb | josue-arana/ln-x- | /solution.py | 3,782 | 4.03125 | 4 | # Implement Natural Logarithm
# Description:
# Implement the ln() function, but don't use the library log functions or integration functions.
# Other library functions are fine
# Solutions should be within 1e-6 of the actual value (i.e. |student_ln(x) - ln(x)| < 1e-6)
# Hints:
# - This is for the sorting and searchin... |
49862286b99292f59e9393b17eae06ce3d13baf3 | Shreya24tiwari/ML-algorithms | /ALL_ALGORITHM_CODE.py | 12,845 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 16:44:27 2020
@author: adars
"""
##########################################################
####### LINEAR REGRESSION
###### LOGISTIC REGRESSION
##### DECISION TREE
#### RANDOM FOREST
### eXTREME GRADIENT BOOSTING
## K NEAREST NEIGHBOR... |
73aeef04b393f3e47a83d3fe51c9a4a402d378c3 | Chairmichael/ProjectEuler | /Python/Complete/0010a - Summation of primes.py | 351 | 3.796875 | 4 | '''
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
'''
from math import sqrt
prime_sum = 2
for num in range(3, int(2e6), 2):
is_prime = True
for div in range(3, int(sqrt(num))+1):
if num % div == 0:
is_prime = False
break
if is_prime:
prime_sum = p... |
9d71c304a4c0afa3a832611bce7f157f0bf96b6b | Chairmichael/ProjectEuler | /Python/Complete/0014a - Longest Collatz sequence.py | 988 | 4.0625 | 4 | '''
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1)... |
6caa8d0f78fb3519e0b115c3b5f055fd79e74cda | Chairmichael/ProjectEuler | /Python/Complete/0007a - 10001st prime.py | 453 | 3.953125 | 4 | '''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10,001st prime number?
'''
from math import sqrt
primes = [ ]
num = 3
found = False
while not found:
is_prime = True
for div in range(3, int(sqrt(num))+1, 2):
if num % div == 0:
is_prime = False... |
156222a7917d55a493c8dc3098ff8dfe3b5b03e0 | Rhaster/WIZUALIZACJA-DANYCH | /laby po 4 itp/lab 4/zad 4.py | 503 | 3.515625 | 4 | class NaZakupy():
def __init__(self,nazwa_produktu, ilosc, jednostka_miary, cena_jed):
self.x=nazwa_produktu
self.y=ilosc
self.z=jednostka_miary
self.k=cena_jed
def wyświetl_produkt(self):
return self.x, self.y, self.z, self.k
def ile_produktu(self):
return se... |
bc4394d9c15ece587289ec0f79404811efaaf363 | Rhaster/WIZUALIZACJA-DANYCH | /lab 3/zad 3.py | 201 | 3.609375 | 4 | xd = {"Mleko":"2zł",
"Ser": "3zł",
"soja": "200zł","złoto":"sztuki","diamenty":"sztuki"}
g={ key for key , value in xd.items() if value=="sztuki" }
print("sklep")
print(xd)
print("sztuki")
print(g) |
c6a099588e99adadc79925bdd5f4d139da9e14bf | Rhaster/WIZUALIZACJA-DANYCH | /lab 5/zad 3.py | 3,225 | 3.875 | 4 | class Ksztalty:
def __init__(self, x, y):
self.x=x
self.y=y
self.opis = "To będzie klasa dla ogólnych kształtów"
def pole(self):
return self.x * self.y
def obwod(self):
return 2 * self.x + 2 * self.y
def dodaj_opis(self, text):
self.opis = text
de... |
f94e1badc3bde1f4dec5fa3b9f604fcfe716ced1 | vivek-fulldev/zap | /Brands/run.py | 158 | 3.96875 | 4 | import re
#The search() function returns a Match object:
txt = "@.com"
x = re.search("([a-zA-Z0-9]+@|@)+[a-zA-Z0-9]+(.com|.in|.net|.co.in)", txt)
print(x)
|
1ae7b2ff48026ec521e2541f30437b712e03bede | Feng00000/bawei | /DAY5/t3.py | 167 | 4.09375 | 4 | #将一个列表的数据复制到另一个列表中,并反向排序输出
list=(1,5,6,8,9,2,4,78)
s1=[]
for i in list:
print(i)
s1.append(i)
print(s1)
|
9b9561fb58487d8c9de27566d5c8f7fabc3350ce | wilsonr19/Python-ML-works | /Python/bisection.py | 887 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 13:56:35 2019
@author: DELL
"""
def F(exp,x):
return eval(exp)#Defines the function here
#x*x*x - x*x + 2
#f=x*x*x - x*x + 2
input_exp=input("f(x)=")
a=eval(input("enter a="))
b=eval(input("enter b="))
#return f
def bisection(a,b):
... |
9d2dfa0a4754eafe90f3f2c02dd8b2d7d9d69d62 | fantasyfengxin/DataStructures-Algorithms | /bst.py | 5,458 | 4.15625 | 4 | """A simple implementation of binary search tree."""
class Node:
"""Tree node class."""
def __init__(self, value, left_child=None, right_child=None):
self.value = value
self.left_child = left_child
self.right_child = right_child
class BST:
"""A class for binary search tree."""
def __init__(self):
self.ro... |
4da4f0883881913b81afc468caa634e2372bfde0 | suhansuhail/Suhan-level-2 | /rpspython.py | 1,220 | 3.96875 | 4 | import random
import math
def play():
user = input("What's your choise? 'r' for rock, 'p' for paper, 's' for scissors\n")
user = user.lower()
computer = random.choice(['r', 'p', 's'])
if user == computer:
return "You and the computer have both chosen {}. it's a tie.".format(computer)... |
d1b8790a7df49794649e9b4a34bc410251da2fd1 | irenepeggy/python_course | /task3/mx_subsum.py | 263 | 3.515625 | 4 |
val = eval(input())
cur_subsum = val
total_max_subsum = val
while (val != 0):
val = eval(input())
if (val == 0):
break
cur_subsum = max(val, val + cur_subsum)
total_max_subsum = max(cur_subsum, total_max_subsum)
print(total_max_subsum) |
484be7ba0a5ce0a706259714feec5fadb460122a | EduardoMerino/Quiz09 | /q11-2.py | 244 | 3.625 | 4 | t=open("banana.txt","r")
#function:
def find_banana(t):
b=0
for line in t:
x=line.lower()
if(x.find('banana')==0):
b=b+1
return(b)
#code
ban=find_banana(t)
print("in this text there are ",ban,"bananas")
|
d47ef641656e38ba6d8e3bfd13dbd9e68a3c827f | triwahyuu/project_euler | /py/prob058.py | 506 | 3.5625 | 4 | ## bottom right most diagonal of current side 'n' is n^2
## and the diagonal before it is n^2-k*(n-1); k=0,1,2,3
from .euler import is_prime
import itertools
def compute():
np = 0 # number of primes
nd = 1 # number of diagonal
for n in itertools.count(3, 2):
nd += 4
for k in range(4):
... |
1a312ad460086f3a315cc1bde6e35e8189daf69b | triwahyuu/project_euler | /py/prob047.py | 1,154 | 3.515625 | 4 | ## using hardcoded memoization
from .euler import is_prime
import itertools
list_factor = {2:[2], 3:[3]}
seen_factor = {2,3} # used for searching
primes = [2,3,5,7,9,11]
seen_primes = {2,3,5,7,9,11}
C = 4 # numbers of consecutive num
D = 4 # numbers of distinct factors
def compute():
con = 0
for i in iter... |
b8b5b49062a34a2bc0550a1a8549145db3d095d5 | 100thgod/Python-Data-Structure | /Data Structure/Sorting,Hasing and Searching/binary_search.py | 861 | 3.9375 | 4 | def binary_search(a_list, item):
first = 0
last = len(a_list) - 1
found = False
while first <=last and not found :
mid = (first + last) // 2
if a_list[mid] == item :
found = True
else:
if a_list[mid] > item:
last = mid -1
else:... |
15ca89aef23a95b1860f499fcd588e491629bcfc | 100thgod/Python-Data-Structure | /Data Structure/Sorting,Hasing and Searching/sequential_search.py | 743 | 3.859375 | 4 | def sequential_search(a_list, item):
pos = 0
found = False
while pos <len(a_list) and not found:
if a_list[pos] == item:
found = True
else:
pos = pos + 1
return found
def ordered_sequential_search(a_list, item):
pos = 0
found = False
stop = False
... |
ce296f16a7d7c33630b19123a9c586e3a4432054 | Kchour/SphinxExample | /example_package/subpackage1/nummanip.py | 1,339 | 4.3125 | 4 | """ This submodule implements a class that can manipulate numbers """
class NumManip:
"""This class implements a few different types of methods to manipulate numbers
Variables:
class_variable (int): A simple integer
Attributes:
num1 (int, float): The first number
num2 (int, float)... |
4584e7a49df385d588639e103a706e422f528e05 | thomasgassmann/leetcode | /problems/longest-palindromic-substring/solution.py | 787 | 3.5625 | 4 | class Solution(object):
def exand_palindrome(self, s, l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return r - l - 1
def longestPalindrome(self, s):
if s is None or len(s) <= 1:
return s
longest_start, longest_end = 0, 0
... |
252b5ab40c10fbbfababdb7506a1a1d81ef94be4 | bquoctruong/CPSC471GroupProject | /pythonServer.py | 4,247 | 3.609375 | 4 | #Name: Brian Truong
#Date: 11/12/2017
#File Name: pythonServer.py
#File Description: Creates an FTP like server to run in conjunction with pythonClient.py
#NOTE: Done in Python 3.6
import os
from socket import *
import socket
import threading
import ftplib
# Function:RetrFile
# Date of code(Last updated): ... |
045a3ed75a9621e063596a1f5415e52c1a0664da | jcccookie/python-blackjack | /main.py | 6,167 | 3.640625 | 4 | import random, time
########################################################################################
########## Global Variables
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2,... |
0caf1222edb23e6379623fc9150d04b61055c1bc | GuillermoRS/Actividades-Python-ISC-161-Guillermo-Ruiz-Salazar | /entradas_por_teclado.py | 119 | 3.625 | 4 | # entradas por teclado sentencias input
print("Introduce un nombre: ")
entrada = input()
print("hola "+ entrada)
|
55bd236aac8e35a21fc4c4df28c43d83c4d1f91d | satato/old-python-projects | /LoopProj01.py | 1,640 | 4.03125 | 4 | __author__ = 'Amber Melton'
for x in range(0,10):
print("Amber")
for num in range(1, 101):
if num != 100:
print(num, end=" ")
else:
print(num)
for num in range(1, 101):
if num % 2 == 0 and num != 100:
print(num, end=" ")
elif num == 100:
print(num)
for num in ... |
6582ff64fd16602024a19c746ab75ae5292b0a4b | AndreyBMWX6/django-anfisa | /anfisa/services.py | 4,059 | 3.625 | 4 | import requests
def what_weather(city):
url = f'http://wttr.in/{city}'
weather_parameters = {
'format': 2,
'M': ''
}
try:
response = requests.get(url, params=weather_parameters)
except requests.ConnectionError:
return '<сетевая ошибка>'
if response.status_code =... |
997f4354f60556a257fdb47070fcc1859f6c3809 | lammyp/ref-man | /function_definitions/find_encoding.py | 919 | 3.859375 | 4 | #Determine the encoding of the input file. This will be either utf-8 or latin-1 (or one of its synonyms). Do this by attempting to open the file and read a line assuming utf-8 encoding; if this fails, close the file and reopen with latin-1. If this fails, return an error and exit. This may change as file encoding t... |
21c6ab8918b9bcee523a736ce37090e8f9f5367c | lammyp/ref-man | /Medline_extract_prototype.py | 5,257 | 3.71875 | 4 | """This is a prototype program designed to read lines from a Medline .txt file, determine where the records start, and assign the field data for each record to an instance of the class, "Reference". It includes a feature to determine which references are non-English and remove the square brackets from around them; at ... |
0c68f39d437e79193b6f148a38a2ea9da0ae0e1c | quanglam2807/cs-260 | /prefix2postfix.py | 1,776 | 3.734375 | 4 | # Quang Lam
import streamreader
import io
class SubtractionNode:
def __init__(self, left, right):
self.left = left
self.right = right
def eval(self):
return " ".join([self.left.eval(), self.right.eval(), '-'])
class AdditionNode:
def __init__(self, left, right):
self.lef... |
ffea3690fb9b2fa8cae3de6229f51ae806355956 | andreaslordos/MITx-6.00.1x | /Week2/PSET2/PSET2PR2.py | 1,211 | 4.03125 | 4 | annualInterestRate=0.18
#annualInterestRate=float(input("Input the Annual Interest Rate: "))
monthlyInterestRate=annualInterestRate/12
balance=999999
#balance=float(input("Input the Initial Balance: "))
OpeningBalance=balance
PaidOff=False
ClosingBalance=1
interest=0
#Duration=int(input("Input the number of months that... |
e7d393486777e981510e78030fead76daad08cce | andreaslordos/MITx-6.00.1x | /Midterm Exam/dict_invert.py | 746 | 4.78125 | 5 | def dict_invert(d):
"""
Takes in a dictionary with immutable values and returns the inverse of the
dictionary.
The inverse of a dictionary d is another dictionary whose keys are the
unique dictionary values in d.
The value of a key in the inverse dictionary is a ascending sorted list of
all ... |
f02a3bd2ff8acd9872b4d8fc4d9bbd796b85b9b5 | donngraphics/py_calc | /scalc.py | 4,177 | 4.0625 | 4 | import tkinter as tk
root = tk.Tk()
# e = tk.Entry(width=50, bg='white', borderwidth=5)
# e.pack()
# e.get()
# e.insert(0, 'Type your name here')
root.wm_title('TK Calculator')
answer_window = tk.Entry(width=35, bg='white', borderwidth=5)
answer_window.grid(row=0, column=0, columnspan=3, sticky='nsew')
def butt... |
eedd755173c2722c3e398fde8e95db481de60fe1 | sukhdeep/bioinformatic_algorithms | /codes/1_13_mismatches_iterations.py | 2,171 | 3.5 | 4 | #!/usr/bin/env python
'''
Compiled by Felix Francis (felixfrancier@gmail.com)
Description: A most frequent k-mer with up to d mismatches in Text is simply a string Pattern maximizing Countd(Text, Pattern)
among all k-mers. Note that Pattern does not need to actually appear as a substring of Text.
Example: AA... |
91f7f279c228de25f29670950d55e17eb51a12d2 | mahdifarhang/DA_CAs | /ca1/q2_2.py | 361 | 3.796875 | 4 | def calculate_max_sum_with_and_without_one_element(array):
if (len(array) == 0):
return 0, 0;
maxwith, maxwithout = calculate_max_sum_with_and_without_one_element(array[0:-1])
return maxwithout + array[-1], max(maxwith, maxwithout)
n = int(input())
arr = [int(x) for x in raw_input().split()]
print(max(calculate_ma... |
8ffe4989f6bb70fce2cbefcf05ca3f6848f0398c | masif088/cpc-ctf | /cpc/soal 4/solver.py | 399 | 3.71875 | 4 | from collections import OrderedDict
def removeDupWithOrder(str):
return "".join(OrderedDict.fromkeys(str))
def next_happy_year(year):
looper=True
while (looper):
year+=1
if (len(str(year))==len(removeDupWithOrder(str(year)))):
looper=False
return year
case=int(input())
for i ... |
143cfe05d4180fccb06df6a2ba945ecf8f528c2b | masif088/cpc-ctf | /cpc/soal 7/StringGenerator.py | 297 | 3.921875 | 4 | import random
import string
def randomString(stringLength=10):
"""Generate a random string of fixed length """
letters = "abcdefghijklmnopqrstuvwxyz "
return (''.join(random.choice(letters) for i in range(stringLength)))
print("100")
for i in range(100):
print (randomString(20))
|
b5ff139fe649ecfff3f54facc7d97c6aab24dcaf | davidodza/OverTheWire | /VigenèreKeyCracker.py | 4,030 | 3.78125 | 4 | '''
This script is for cracking the Vigenère Cipher
Krypton Level 3 → Level 4 (http://overthewire.org/wargames/krypton/krypton4.html)
Plan
1) Input 2 text files of cipher text.
2) Divide the cipher text into n seperate files where n = key length
3) Frequency analysis of every key space.
'''
from collections import Cou... |
8c44c8fb6bd852ccdf26fcfdd73de4ad0db4e83a | zbqmgldjfh/Exchange-rate-calculator | /main.py | 2,197 | 3.515625 | 4 | import os
import requests
from bs4 import BeautifulSoup
from babel.numbers import format_currency
os.system("clear")
url = "https://www.iban.com/currency-codes"
first_country = ""
second_country = ""
"""
Use the 'format_currency' function to format the output of the conversion
format_currency(AMOUNT, CURRENCY_CODE, l... |
346f2eb36a850a78c375c837a739ff2179965cde | arjacobs1/hilbert_order | /encode.py | 1,613 | 3.65625 | 4 | #!/usr/bin/env python3
# encode.py
# Implementation of encoding and decoding algorithms as described in
# "A new algorithm for encoding and decoding the Hilbert order" by Ningtao
# Chen, Nengchao Wang, and Baochang Shi
#
# Chen, N., Wang, N., & Shi, B. (2007). A new algorithm for encoding and
# decoding the Hilbert or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.