blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
34e40c0c0a03ff7962e2ef4d31eca21e4d90962b | Origamijr/MusicFun | /analysis/utils.py | 524 | 3.9375 | 4 | def rationalize(x, N):
""" Rational approximation using farey's algorithm """
a, b = 0, 1
c, d = 1, 1
while (b <= N and d <= N):
mediant = float(a+c)/(b+d)
if x == mediant:
if b + d <= N:
return a+c, b+d
elif d > b:
return c, d
... |
3aa38b8a48b971e4d413bf0b51f4e96d4ee261d5 | chaderdwins/interview_problems | /Python/l476.py | 966 | 3.84375 | 4 | # Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
# Note:
# The given integer is guaranteed to fit within the range of a 32-bit signed integer.
# You could assume no leading zero bit in the integer’s binary representation.
# Example 1:
... |
1484de4271f86d8ed0436910d372d5a055f68e63 | mandark97/MazeSolving1 | /myMaze.py | 8,300 | 3.953125 | 4 | # Author: William Zhang
# Description: This is a maze solving algorithm. This is an implementation of the Wall Follower Algorithm.
# It uses the "left hand" of the robot as a means to solve the maze.
# Date: April 23, 2018
# Copyright 2018
import sys, pygame
from pygame.locals import *
import random
from entities impo... |
78cc09b08fe901023131cdf1705493604982eab0 | venkateshsuvarna/box-plot-python | /assignment2.py | 406 | 3.515625 | 4 |
#Necessary imports
import pandas as pd
import matplotlib.pyplot as plt
# Reading data locally
df = pd.read_csv('/Users/Venkatesh Suvarna/PycharmProjects/DataMining_Assignment2/winequality-red.csv',sep=';')
#plotting boxplot
ax = df.plot(title = 'Box Plot of Various Parameters for Red Wine Dataset', kind = 'box')
ax.... |
d743a49af0739e7c5ed29dc5e341dbc7a1b1f9e9 | sbtries/Class_Polar_Bear | /Code/Derrick/Python/lab5_Blackjack/blackjack_helper.py | 1,881 | 3.828125 | 4 | import random
# vars #
cards = {
'A': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10,
'J': 10,
'Q': 10,
'K': 10,
}
playerCards = {
'firstCard': input('What is your first card'),
'secondCard': input('What is your second card... |
1a6ec2ec6572e629fc49f64ae34dd0c6f1d56397 | dineshkumarsarangapani/leetcode-solutions | /python/source/dynamic_programming/max_subarray.py | 483 | 3.625 | 4 | import sys
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if not nums:
return 0
current_sum = best_sum = ~sys.maxsize
for i in range(0, len(nums)):
current_sum = max(nums[i], current_sum + nums[i])
best_sum = max(... |
be79a446df8c29d80bfabf93ccc24658b5fe4e2d | Yuuuuumk/DS | /hw/HW3Solution/Question4_pascal.py | 330 | 3.546875 | 4 | def pascal(n):
if n ==1:
return [[1]]
else:
newline = [1]
for i in range(n-2):
ele = pascal(n-1)[n-2][i]+pascal(n-1)[n-2][i+1]
newline.append(ele)
newline.append(1)
return pascal(n-1)+[newline]
#print(pascal(1)) # [[1], [1, 1], [1, 2, 1], [1,... |
b3c9e5b73f0bfcdddebac325bcd2d8cc8d74e00a | xiaokexiang/start_python | /csv/_write_.py | 437 | 3.765625 | 4 | """
csv写入
"""
import csv
class Write:
def __init__(self, filename):
self.filename = filename
def write(self):
with open(self.filename, 'w', newline='') as f: # 取消换行
writer = csv.writer(f)
for row in [['1', '2', '3'], ['4', '5', '6']]: # 写入数据到csv
write... |
c7c0f857c94c378841927cfcbb3faf5f6229f9e5 | denysdenys77/Beetroot_Academy | /data_structures/queue.py | 966 | 4.125 | 4 | # Реализовать работу очереди (добавление/удаление элементов) на основе связного списка.
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return f'Data: {self.data}. Next node object: {self.next.data}'
class Queue:
def __init__(self):
... |
90b9f7bf07d3b19e5357e7b257ec53ac8603b500 | HarperHao/python | /exercise/021.py | 933 | 4 | 4 | """
题目:将一个正整数分解质因数。
例如:输入90,打印出90=2*3*3*5。
"""
def fun(number):
list1 = fun1(number)
list2 = []
for i in list1:
while number != 1:
if number % i == 0:
number = number / i
list2.append(i)
else:
break
return list2
# 求出[2,n... |
75969f36ee2aee9d3b0f9083393193a58a58db32 | Dania-sl/KOL_2 | /22.py | 381 | 3.671875 | 4 | '''
Знайти добуток елементів масиву, кратних 3 і 9. Розмірність масиву - 10.
Заповнення масиву здійснити випадковими числами від 5 до 500.
'''
import numpy as np
X = np.random.randint(5, 500, 10)
s = 1
for i in X:
if i % 3 == 0:
s *= i
print(X)
print(s)
|
e5d3b28b071fcef8f63f0ebce85f027f57f92650 | tinawu-23/christmas-2019 | /d1/rocket2.py | 259 | 3.734375 | 4 | def getfuel(fuel):
fuel = fuel // 3 - 2
if fuel < 9:
return fuel
fuel += getfuel(fuel)
return fuel
total = 0
with open('input.txt') as f:
for line in f:
mass = int(line.strip())
total += getfuel(mass)
print(total)
|
599f604d8db57cb72aeca89f75e8998175fe8550 | JohnOiko/python-learning-projects | /school_database/school_database.py | 14,401 | 3.78125 | 4 | from pupils import Pupils
from teachers import Teachers
from lessons import Lessons
def input_menu_choice():
# read action type choice
action_type_choice = input("Available actions:\n"
"1. Manage pupils\n"
"2. Manage teachers\n"
... |
f2065463f3c9e0f69a6f5f5f8e84f8806bdbc233 | HenDGS/Aprendendo-Python | /python/while.py | 161 | 4.09375 | 4 | numero=1
while numero<6:
print(numero)
numero+=1
mensagem=input("Digite 'quit' para sair: ")
while mensagem != "quit":
print(mensagem)
mensagem=input()
|
ec7fcea25d4300af41c68517818f08347cb3e725 | soo-youngJun/pyworks | /exercise/test03.py | 896 | 3.796875 | 4 | # p. 146 1번
a = "Life is too short, you need python"
if "wife" in a:
print("wife")
elif "python" in a and "you" not in a:
print("python")
elif "shirt" not in a:
print("shirt")
elif "need" in a:
print("need")
else:
print("none")
# 2번
result = 0
i = 1
while i <= 1000:
if i % 3 == 0:
re... |
da20d6f568ec568428815be0bd8e9689060f4138 | ucaiado/Customer_Segments | /eda.py | 7,472 | 3.5 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Library to explore the the dataset used
@author: ucaiado
Created on 05/16/2016
"""
# load required libraries
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def features_boxplot(all_data, samples, indices, b_log=False):
'... |
63693d3d7a2e22471bd212f1efe14d2324eff391 | rishinkaku/Software-University---Software-Engineering | /Programming-Basics/For Loop/Number sequence/Number sequence.py | 173 | 3.71875 | 4 | n = int(input())
min = 0
max = 0
l = list()
for i in range(n):
num = int(input())
l.append(num)
l.sort()
print(f"Max number: {l[-1]}")
print(f"Min number: {l[0]}")
|
7ad3a64a8e1d676c7af64c7df1d9871d3f0859cc | Reshma081996/Python_Django | /variable_length_args/nested_dict_employee.py | 1,510 | 4.125 | 4 | employee={
1000:{"id":1000,"name":"tom","salary":25000,"exp":1},
1001:{"id":1001,"name":"jhon","salary":30000,"exp":2},
1002:{"id":1002,"name":"danie","salary":35000,"exp":2},
1003:{"id":1003,"name":"jack","salary":30000,"exp":2}
}
# nested dictionary
#if 1000 in employee: # key 1000 values
#print(e... |
71b86a27ddaeffe23134c5da30269184a1d33c9f | UlianaDzhumok/dog-breed-image-classifier | /adjust_results4_isadog.py | 2,463 | 3.703125 | 4 | def adjust_results4_isadog(results_dic, dogfile):
"""
Adjusts the results dictionary to determine if classifier correctly
classified images 'as a dog' or 'not a dog' especially when not a match.
Demonstrates if model architecture correctly classifies dog images even if
it gets dog breed wrong (no... |
a95d0896f29a022f1332875cd00363c541ded514 | ledbagholberton/holbertonschool-machine_learning | /unsupervised_learning/0x02-hmm/1-regular.py | 1,083 | 3.6875 | 4 | #!/usr/bin/env python3
"""
P is a is a square 2D numpy.ndarray of shape (n, n) representing
the transition matrix
P[i, j] is the probability of transitioning from state i to state j
n is the number of states in the markov chain
Returns: a numpy.ndarray of shape (1, n) containing
the steady state probabilities, or None ... |
f35841fe3426df7d89cdb0238cdebbec3b649ead | MaksimKatorgin/module17 | /task1.py | 1,331 | 3.671875 | 4 | #Команде лингвистов понравилось качество ваших программ, и они решили заказать у вас функцию для анализатора текста, которая
#создавала бы список гласных букв текста, а заодно считала бы их количество.
#Напишите программу, которая запрашивает у пользователя текст и генерирует список из гласных букв этого текста
#(... |
6d86e3817e8f657833806f81d98708e05f264b7e | youfeng243/hackerrank | /Domains/Data Structures/Reverse a linked list/Reverse a linked list.py | 335 | 3.890625 | 4 |
def Reverse(head):
if head == None:
return head
if head.next == None:
return head
prepoint = head
point = head.next
prepoint.next = None
while point != None:
temp = point.next
point.next = prepoint
prepoint = point
point = temp
... |
82a051a683db4409b6abce482083f13a9b97426f | Galvin-wjw/DataAnalysis | /puncount.py | 163 | 3.734375 | 4 | aStr = "Hello,World!"
bStr = aStr[:6] + "Python!"
print(bStr)
count = 0
for ch in bStr:
if ch in ',.!?': #计算标点符号
count += 1
print(count) |
40205b9174355c744db2a5a4b7b7c897d6bcac06 | 89himanshu-dwivedi/Other_Language_Program | /python/continue.py | 115 | 3.71875 | 4 | for a in range(1,5):
while a<=5:
if a%2==0:
continue
print a
print "for go" |
be1de077d288000603faa6a52e1d386796ef1d9b | JakubKazimierski/PythonPortfolio | /Coderbyte_algorithms/Medium/LetterCount/LetterCount.py | 970 | 4.28125 | 4 | '''
Letter Count from Coderbyte
December 2020 Jakub Kazimierski
'''
import re
def LetterCount(strParam):
'''
Have the function LetterCount(str)
take the str parameter being passed
and return the first word with the
greatest number of repeated letters.
For example: "Today, is t... |
64be63ec9c731b72492e848f1adae9626839622c | Ken0706/Crash_Course_Book_Python | /5.4_Alien_Colors_#2.py | 723 | 3.703125 | 4 | import random
def check_input():
global alien_color
global second, first
color = ["green", "yellow", "red"]
first, second = random.sample(color,2)
while True:
try :
alien_color = input("Enter color (green, yellow, red) : ")
if alien_color in color:
break
elif len(alien_color) == 0:
print("You fa... |
73ceb39114c905708b650df42a9a5159d2dbdcc8 | rzalog/Random-Box-Game | /randbox.py | 6,802 | 3.546875 | 4 | # randbox.py
# Simple game where a box moves around, and user has to click on it
import random, pygame, sys
from pygame.locals import *
FPS = 30
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
SCREENCENTER = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
SCREENCENTERX = WINDOWWIDTH / 2
SCREENCENTERY = WINDOWHEIGHT / 2
MENUMARGIN = 50
XMAR... |
3d59d5d771c85cbeac3e44e55b54b997cd49c397 | yoderw/math121 | /hw/hw1/hw1_menu.py | 1,266 | 3.90625 | 4 | """
Restaurant name? Bobby's
First entree? Pasta verde
First entree price? 15
Second entree? Filet mignon w/ lobster and caviar
Second entree price? 107
Third entree? Hamburger with fries
Third entree price? 9
1234567890123456789012345678901234567890
Bobby's Entrees
---------------
Pasta verde....................... |
6eb156eb50314d0a0d4f4ecc29efa3b142727721 | curaai/EulerProject | /27.py | 651 | 3.625 | 4 | import math
def prime_check(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
elif i > math.sqrt(n):
return True
def formular(a, b):
for i in range(0, 1000):
res = pow(i, 2) + (i * a) + b
if prime_check(res) is Fal... |
fb2a6f52be2cd6ede0004fe9976b840e81fb183e | leonardokiyota/Python-Training | /LivroPythonInt/Exercises/Chapter 05 /5.3.py | 241 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
Faça um programa para escrever a contagem regressiva do lançamento de um
foguete. Conte de de 10 a 0 e Fogo.
'''
x = 10
while x >= 0:
print(x)
x = x - 1
print("Fogo!")
|
7cdf86bd0628f3c3beb48192a464a48723ff0926 | onkcharkupalli1051/pyprograms | /week4_dobblegame.py | 1,015 | 3.65625 | 4 | import string
import random
symbols = []
symbols = list(string.ascii_letters)
card1 = [0]*5
card2 = [0]*5
pos1 = random.randint(0,4)
pos2 = random.randint(0,4)
#pos1 and pos2 are same symbol positions in card1 and card2
samesymbol = random.choice(symbols)
symbols.remove(samesymbol)
if(pos1 == pos2):
card2[pos1... |
325e192c87d7bda9c92866342becf0e900b3c356 | in-s-ane/easyctf-2014 | /Obfuscation 1/obfuscated.py | 1,842 | 3.78125 | 4 | #! /usr/bin/python
# The output of this program is: NICEJOBFIGURINGOUTWHATTHISPROGRAMDOESTHEFLAGISVINEGARISTHEBESTCIPHER
text = "SWQHRGZZUSSWWBJWMRQTMRYVWVXJMADMKICSVBZCZXMENGJLVWEUDUQYVSEMKRWUBFJF"
apple = "FOODISYUMMY"
""" OLD CODE:
from itertools import starmap, cycle
def mystery(a, b):
a = filter(lambda _: ... |
1d53f8e1fc81980e3fdba675377506442db44baa | kucherskyi/pytrain | /lesson5/lesson1.py | 758 | 3.5 | 4 | import re
from nt import write
def print_empty():
out = open('alice01.txt', 'w')
lines = 0
for lin in open('alice.txt', 'r'):
if re.match('\n', lin):
lines +=1
else:
out.write(lin)
print '%s empty lines were found!' % lines
#print_empty()
def remove_whitespac... |
0d88489b1d3f2d470a1f0c17e90fdab348cfde1e | aewaddell/lpthw | /excercises/ex10.py | 1,271 | 3.78125 | 4 | tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
# You can use triple single quote instead
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)
# \\ : backslash
#... |
9a96b6728b364fd03104e5a2c7a9ddc610927669 | KristofferNyvoll/ntnu | /TDT4110_ITGK/Assignment_6/gangetabell_lister.py | 620 | 3.75 | 4 | # a)
def separate(numbers, threshold):
less_than = []
more_than = []
length = len(numbers)
for x in range(length):
if numbers[x] < threshold:
less_than.append(x)
else:
more_than.append(x)
return less_than, more_than
less_than, more_than = separate([0, 1, 2, ... |
a643d196184cc5360bc28e32a22e4ea420844908 | MaxXSoft/article-gen | /article_gen/wordfreq.py | 1,551 | 3.5 | 4 | class WordFreq(object):
def __init__(self, head_word=None, next_word=None,
head_pos=None, next_pos=None, word_pos=None):
self.head_word = head_word
self.next_word = next_word
self.head_pos = head_pos
self.next_pos = next_pos
self.word_pos = word_pos
def ... |
754ea34f3b23661761a1c63043b940b1d49f0291 | ChyanMio/LeetCode | /036_valid_sudoku.py | 836 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 2 13:21:27 2019
@author: zhang
"""
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
row = [[False for _ in range(9)] for _ in range(9)]
col = [[False for _ in range(9)] ... |
95bf212e7b5bbad9e11e25c6782a3a0482689a98 | INM-6/Python-Module-of-the-Week | /session35_generators/1_iterators_next.py | 739 | 3.875 | 4 | colors = ['mauve', 'taupe', 'teal', 'razzmatazz', 'gamboge']
class List_Iterator():
def __init__(self, ListyMcListface):
self.ListyMcListface = ListyMcListface
self.n = len(ListyMcListface)
self.current_element = 0
def __next__(self):
if self.current_element == self.n:
... |
45fdace6d1d4ffb7870c7d56131278b089d7417a | TD2106/Competitive-Programming | /ACM Contest/NorthWestPacific/recap/Alphabet/Alphabet.py | 1,613 | 3.96875 | 4 |
import sys
import pdb
def get_longest_increasing_subsequence(sequence):
p = [None for _ in xrange(0, len(sequence))]
m = [None for _ in xrange(0, len(sequence) + 1)]
l = 0
for i in xrange(0, len(sequence)):
# Binary search on lengths:
# bsearch for the largest positive j <= L such th... |
2950c1f25fa37b720644258a3b63bb686c6873d7 | shahakshay11/Backtracking-2 | /palindrome_partitioning.py | 1,835 | 3.640625 | 4 | """
// Time Complexity : O(n^2) n - number of characters in the string
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Your code here along with comments explaining your approach
Algorithm explanation
Recursive approach + backtrac... |
e67b28841d7e574082a9c99432c7e4c34a4212a9 | legeannd/codigos-cc-ufal | /ED/Estruturas de manipulação de dados/Lista/Prova_q2.py | 269 | 3.625 | 4 | from lista import chainedList
lista = chainedList()
lista2 = []
while True:
nome = input("Digite o nome (0 para sair )")
if nome == '0':
break
num = int(input("Digite o numero "))
lista2 = [nome, num]
lista.push(lista2)
lista.listPrint()
print(lista.search(0)) |
c0532f2a717c568cb0bad6cfeed6a39351dfdd6b | CodeHemP/CAREER-TRACK-Data-Scientist-with-Python | /09_Introduction to Data Visualization with Seaborn/02_Visualizing Two Quantitative Variables/05_Interpreting line plots.py | 1,310 | 3.71875 | 4 | '''
05 - Interpreting line plots
In this exercise, we'll continue to explore Seaborn's mpg dataset,
which contains one row per car model and includes information such as
the year the car was made, its fuel efficiency (measured in "miles per
gallon" or "M.P.G"), and its country of origin (USA, Europe, or Japan)... |
a93ce8c7ddf27dc7ed35ed2fc4fa045a72cfaf6b | hanzohasashi33/Competetive_programming | /Camp-Summer-Training/week1/5/testing.py | 556 | 3.625 | 4 | import unittest
from week1_5 import evenness
class TestSum(unittest.TestCase) :
def testcase1(self) :
n = 5
l = [2,4,7,8,10]
result = evenness(l,n)
self.assertEqual(result,3)
def testcase2(self) :
n = 4
l = [1,2,1,1]
result = evenness(l,n)
... |
f82b372c017a46f40ce511c9e85e1da0a077bae6 | amyanchen/Tower-of-Hanoi | /Tower of Hanoi.py | 20,024 | 3.9375 | 4 |
# coding: utf-8
# In[1]:
'''
Created by Div Dasani and Amy Chen
EECS 348
10/3/17
Assignment 1- Tower Of Hanoi
'''
from TOH_DFS import Solve_By_DepthFS
from TOH_BFS import Solve_By_BreadthFS
from TOH_TFS import Solve_By_BestFS
number_of_disks = 5
print ("Solve by Depth First Search method:")
Solve_By_DepthFS(nu... |
e6cd52ea2f93f9d6b604a86199e13e1062c077c6 | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/Learning Python/029_002_Indexing and Slicing __getitem__ and __setitem__.py | 1,711 | 3.65625 | 4 | # c_ Indexer:
# ___ -g ____ index
# r_ ? ** 2
#
# X = I.
# print('#' * 23 + ' X[i] calls X.__getitem__(i)')
# print(X[2]) # X[i] calls X.__getitem__(i)
#
#
# # for i in range(5):
# # print(X[i], end=' ') # Runs __getitem__(X, i) each time
#
#
# L = [5, 6, 7, 8, ... |
a89a070f334f385affe828fb48825fe57e7d8a2a | huberthoegl/start_python | /demos/math/glsys-2d/simple_numpy.py | 2,449 | 3.71875 | 4 | # simple_numpy.py
# H. Hoegl, November 2012, 2017
from __future__ import print_function
from __future__ import division
'''
Einfache Array und Matrizen Operationen
Literatur
Die wichtigsten Array und Matrix Operationen:
https://docs.scipy.org/doc/numpy-dev/user/quickstart.html
Dieser Text verweist auf... |
8f24d9ce06e00efb552d92a0554cf7bca51e3b87 | yifanzhou106/leetcode | /EncodeandDecodeStrings.py | 1,304 | 3.78125 | 4 |
"""
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Please implement encode and decode
"""
class Solution:
"""
@param: strs: a list of strings
@return: encodes a list of strings to a single... |
1277901d6a9661b1e6658bf4bccf09d72f3844e0 | xferra/ggrc-core | /test/selenium/src/lib/date.py | 793 | 3.84375 | 4 | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Module for date operations"""
import calendar
from datetime import datetime
def get_days_in_current_month():
"""Gets days in current month
Returns:
int
"""
now = datetime.now()
_, days_... |
8053d2fd3b292771e26b77c215d8838e814f2fd0 | rohithdara/CPE101-Labs | /LAB6/char.py | 654 | 4.21875 | 4 | #Lab 6 Character Manipulation
#
#Name: Rohith Dara
#Instructor: S. Einakian
#Section: 01
#This function returns True if the character is lowercase and False if not
#str->bool
def is_lower_101(char1):
if ord('a') <= ord(char1) <= ord('z'):
return True
else:
return False
#This function returns the rot... |
44e2b353d987fa105b2e0c1258b2500f7ac9125f | therealkevinli/ML_ipynb | /Scikit_knn/knn.py | 1,571 | 3.5625 | 4 | #example from this: https://www.youtube.com/watch?v=1i0zu9jHN6U
import numpy as np
from sklearn import preprocessing,cross_validation,neighbors
import pandas as pd
df = pd.read_csv('breast-cancer-wisconsin.data.txt')
df.replace('?',-99999,inplace=True) #this is to treat these as outliers when there is missing da... |
8d3b1c37477cd499fd19db3512c344bc2e3c4f2f | dubblin27/pythonfordatascience | /Movie_recommendation_adv.py | 4,630 | 3.546875 | 4 | #colloborative filtering will be used
# model based CF using singular value Decomposition and
# Memeory based Decomposition by cosine simularity
from math import sqrt
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split... |
369eb10dcff5d82e37a793cee695c913826ce7b7 | BrendanArthurRing/code | /katas/fraction-to-mixed-number.py | 10,778 | 4.28125 | 4 | # https://www.codewars.com/kata/simple-fraction-to-mixed-number-converter/train/python
'''
Task
Given a string representing a simple fraction x/y, your function must return a string representing the corresponding mixed fraction in the following format:
[sign]a b/c
where a is integer part and b/c is irreduc... |
e209dd20bca0f9ef8caba0a8785e9ffefa698757 | GabrielReira/Python-Exercises | /25 - Maioridade.py | 488 | 3.765625 | 4 | # PROGRAMA QUE LEIA O ANO DE NASCIMENTO DE X PESSOAS E DIGA QUANTAS PESSOAS
# SÃO MAIORES DE IDADE, UTILIZANDO A BIBLIOTECA DE DATAS.
from datetime import date
ano = date.today().year
maior = menor = 0
total = int(input('Qual o número de pessoas? '))
for x in range(total):
nasc = int(input(f'Em que ano a {x +1}... |
f0f7bedadacf48f40314d3d6fb8cbe51d31a5679 | RomanAdriel/AlgoUnoDemo | /RomanD/ejercicios_rpl/estructuras_basicas/ej_7_calculando_potencias.py | 733 | 4.3125 | 4 | """Escribir un programa que solicite el ingreso de un valor correspondiente a una base y un valor correspondiente
a una potencia e imprima por pantalla el resultado de elevar la base ingresada a la potencia ingresada.
El cálculo de la potencia debe ser realizado a través de la realización de multiplicaciones sucesivas.... |
6374e0c5c6d5aa58cbe34284f14bce9464e534b2 | lawalton/oo-project | /code/model/studentfactory.py | 1,256 | 3.640625 | 4 | import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from student import *
class StudentFactory(object):
"""
Creates different types of students
"""
def getStudent(self, studentType, name, year, args):
"""
Creates a type of Student based on the type.
:par... |
a46b979d5da3aa6cbc8b130717943d6fb74aead9 | wassimajjali/Astar | /Astar_Wirth-Ajjali/city.py | 819 | 3.78125 | 4 | # -*-coding:Latin-1-*
__author__ = "Wirth Jeremy & Wassim Ajjali"
class City:
def __init__(self, name, x,y, parent):
self.name = name
self.x = x
self.y = y
self.parent = parent
self.d = 0
self.h = 0
self.listConnection = []
def __repr__(self):
return self.name
def addConnection... |
cc03726ded912109d0de6f07c7ab23eee8d07cbc | Arnkrishn/ProjectEuler | /Problem2/problem2.py | 567 | 3.53125 | 4 | import time
def fibo(num):
return num if num in (1, 2) else fibo(num - 1) + fibo(num - 2)
def even_fibo_sum(val_limit):
fibo_sum = 0
i = 1
if val_limit <= 0:
print "Please have limit > 0"
else:
while 1:
fibo_num = fibo(i)
if fibo_num % 2 == 0:
... |
323ce23bf7083a6d648b56e95e9fc1e9b449b0f5 | Walop/AdventOfCode2017 | /millisecond4/millisecond4_1.py | 276 | 3.578125 | 4 | import re
with open("input") as file:
input_txt = file.read()
phrases = input_txt.split("\n")
valid = 0
invalid_re = re.compile(r"(\b\w+\b).*\1")
for phrase in phrases:
if invalid_re.search(phrase) == None:
valid += 1
print(valid)
|
caf87164d2fb434c38bcd5fbc2dec9621ea390a3 | ASaltedF1sh/jianzhi_offer | /字节跳动/Reverse_List.py | 291 | 3.6875 | 4 | class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if len(s) == 0:
return
tmp = s[0]
del s[0]
self.reverseString(s)
s.append(tmp)
|
551b9a22e660bc083f0e0422eee6c0fcb364f097 | RadkaValkova/SoftUni-Web-Developer | /Programming Basics Python/05 Loops Part 2/Sequence 2k+1.py | 241 | 3.765625 | 4 | n = int(input())
number = 1
while number <= n:
print(number)
number = number * 2 +1
# n = int(input())
# result = 1
# for num in range (1, n+1):
# print(result)
# result = result*2+1
# if result > n:
# break
|
dc7276102c023abe5aa2b379123f34be09996ade | Dhamastana/Quiz-4-Alpro | /Quiz43_DhamastanaDD_1201180226.py | 248 | 3.65625 | 4 | listGPA = [2.1,2.5,4,3]
def hadiah(GPA):
bonus = 500000
hadiah = GPA*bonus
return hadiah
for GPA in listGPA:
if GPA > 2.5 :
print("hadiah anda : Rp", hadiah(GPA))
else:
print("maaf coba lagi")
|
df59ae842e78a86d455c9877a0223a49c2b38978 | nrsimonelli/python-server-side-master | /main.py | 812 | 3.609375 | 4 | from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
# making a dictionary
names = {"nick": {"age": 30, "gender": "male"},
"danielle": {"age": 26, "gender": "female"}}
class HelloWorld(Resource):
# defining GET
def get(self, name):
# setting the return
... |
d02726cc7b03db8afe8414ad7b78238ace8477b2 | tri2sing/IntroPython | /HelloWorld.py | 259 | 3.984375 | 4 | if __name__ == '__main__':
name = input("Please enter your name: ")
print('Hello World from ' + name)
n = int(input("Please enter a number: "))
print(n)
print(type(n))
print("Hello " * n + name)
print(("Hello " + name + ' ' ) * 3)
|
f699d6da51f3ae6027e53ea19b68253f62933349 | treno/project-euler | /euler_7_bruteforce.py | 1,498 | 4.125 | 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?
"""
LIMIT = 100
list_of_primes = [2]
# since no prime numbers are even, we can loop over odds only (starting with 3 and step by 2)
for candidate_prime in range(3, LIMIT * LIMIT, 2)... |
53c32ca29e68d6f366f0dc4367a939b4f2b5dc94 | ajnirp/leetcode | /easy/even-digits.py | 199 | 3.796875 | 4 | # https://leetcode.com/problems/find-numbers-with-even-number-of-digits/
class Solution:
def findNumbers(self, nums: List[int]) -> int:
return sum(len(str(num)) % 2 == 0 for num in nums) |
010259d1d592c70211d0ab3d95627c5efd5af46a | joshuaBagnall/python_practice | /return_statement.py | 83 | 3.515625 | 4 |
def cube(number):
return number*number*number
result = cube(5)
print(result) |
6ceb7010f6b77ef0a9c616a068e55a5cbdd36a43 | BJV-git/leetcode | /math/add_digits.py | 131 | 3.515625 | 4 |
def add_digits(n):
if n == 0:
return 0
rem = n % 9
if rem == 0:
return 9
else:
return rem |
564fe6203c11f3866cb83aa2048cc61d426a1882 | Maxim-Krivobokov/python-practice | /Book_automation/ch4/allcats1.py | 478 | 3.84375 | 4 | print('Enter the name of cat №1:')
catname1 = input()
print('Enter the name of cat №2:')
catname2 = input()
print('Enter the name of cat №3:')
catname3 = input()
print('Enter the name of cat №4:')
catname4 = input()
print('Enter the name of cat №5:')
catname5 = input()
print('Enter the name of cat №6:')
catname6 =... |
d5e02ebb88fe4fcabfad56717a0ebabe0029b74d | manimanis/2SC | /progs/seance03.py/tortue_lievre_v2.py | 558 | 3.71875 | 4 | from random import randint
pos_lievre = 0
pos_tortue = 0
while True:
de = randint(1, 6)
print('dé =', de)
if de != 6:
pas = (de + 1) // 2
pos_tortue += pas
if pos_tortue > 8:
pos_tortue = 8
print("La tortue avance à la position :", pos_tortue)
else:
... |
75c831338f88e911a863ee8ef5d59951b462dc6a | ckopecky/Python-OOP-Toy | /src/ball.py | 3,569 | 3.921875 | 4 | import math
from pygame.math import Vector2
class Ball:
"""
base class for bouncing objects - base class is the root class that other classes inherit from
"""
def __init__(self, bounds, position, velocity, color, radius):
self.position = position
self.velocity = velocity
self.b... |
628717decff3b0e76e820a1003a48f1b6065566f | pbmuller/graph | /src/Node.py | 1,298 | 3.609375 | 4 | from src.Vector import Vector
class Node:
__special_status = ['none', 'sink', 'star']
__node_ids = set()
NULLNODE = None
def __init__(self, node_id, neighbors=set()):
if node_id not in Node.__node_ids:
self.node_id = node_id
Node.__node_ids.add(self.node_id)
el... |
9a540af3c2bf7a4f7fb3d43c86cb01b803387c56 | sanchezolivos-unprg/trabajo. | /verificador#02.py | 304 | 3.890625 | 4 | # verificador de la calculadora 02
nombre= "inercia"
aceleracion= 7.5
masa= 45
fuerza= masa*aceleracion
print("el calculo de una fuerza")
print("la masa es:", masa)
print("la aceleracion es:", aceleracion)
# verificador
verificador= (fuerza==337.5)
print("la fuerza es 337.5:", verificador) |
e31932be23e5f1c5c2e8125a4bf63c4fbb4b6579 | kopchik/itasks | /tallentbuddy.co/max_sum.py | 543 | 3.78125 | 4 | #!/usr/bin/env python3
from __future__ import print_function
cache = {}
def maxsum(v):
if v in cache:
return cache[v]
answer = 0
i = 0
while i<len(v):
answer = max(answer,v[i]+maxsum(v[i+2:]))
i += 1
cache[v] = answer
return answer
def find_max_sum2(v):
print(maxsum(tuple(v)))
def find_max_... |
f78ff6fa4059a963bad624b362c92a997032808a | Anz131/luminarpython | /flow controls/looping/while.py | 151 | 3.828125 | 4 | #looping
#for
#while
#syntax
# 1. Initialization
# 2. Condition
# 3. Statement
# 4. Incr/Decr
# i=1
# while(i<=10):
# print("Anz...")
# i+=1 |
098771be954cc6053a919b74cfc90f1bcad4b42b | kruglov-dmitry/algos_playground | /list_deep_copy.py | 787 | 3.5625 | 4 | #
# https://leetcode.com/problems/copy-list-with-random-pointer
#
class Node(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
def solution(head):
if not head:
return head
mapping = {None: None}
new_mapping = {None:... |
0ec50b652c2ab57ece97cbc2ced83a9af848eb9b | Lukas8733/pythonlesson1 | /talkToMe.py | 204 | 3.59375 | 4 | #talkToMe
print("Hello HTL Leoben!")
ich = input("Wie geht es dir?")
print("Schön dass es dir", ich, " geht! Mir geht es gut!")
name=input("Wie heisst du?")
print("Hallo, schön dich zu treffen", name, "!")
|
d38d393c93c5406b265a4016ffd00bc8cd6decf7 | erjan/coding_exercises | /longest_substring_with_at_least_k_repeating_characters.py | 2,507 | 3.734375 | 4 | '''
Given a string s and an integer k, return the length of
the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.
'''
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
cnt = collections.Counter(s)
st = 0
maxs... |
2f3b3e05fb1c7fc23affc91aab5a79ebbc837f2e | pandwon/Week-9 | /week7.py | 467 | 3.953125 | 4 | stocks = {"tsla":883.45,"amd":94.44,"dis":169.56,"pep":141.80,"nflx":561.93,\
"ko":49.29,"amzn":3326.13,"ebay":59.17,"aal":15.53,"tsn":66.57}
ticker = input("Enter a stock ticker symbol. Type quit to stop: ")
while not ticker == "quit":
if ticker in stocks:
print("{}:{}" .format(ticker, stocks[ti... |
d0e2ee64220bd5a1fcb846bfba6e638e9f7ea961 | RiverRobins/Python-App | /Main/practice/sort.py | 1,046 | 3.5 | 4 | def bubble(n):
changed = True
while changed:
i = 0
while i < len(n) - 1:
if n[i] > n[i + 1]:
temp = n[i]
n[i] = n[i + 1]
n[i + 1] = temp
changed = True
break
else:
changed = Fa... |
509dd98ad3c8200626fbe28acecda205e75df376 | AndreKauffman/EstudoPython | /Exercicios/ex103 - Ficha do Jogador.py | 316 | 3.546875 | 4 | def jogador(player= '<desconhecido>', gols = 0):
print(f"O jogador {player} fez {gols} gols na partida...")
nome = str(input("Nome: "))
gol = str(input("Gols: "))
if gol.isnumeric():
gol = int(gol)
else:
gol = 0
if nome.strip() == '':
jogador(gols = gol)
else:
jogador(nome, gol)
|
2badc00a7c73f0ba582ddec96d765289e586b605 | wtomalves/exerciciopython | /ex099funcao_valores.py | 454 | 4.09375 | 4 | from time import sleep
def numeros(*num):
maior = 0
sleep(1)
print('Analizados os valores passados...')
for valor in num:
print(f'{valor}', end=' ')
sleep(0.3)
if valor > maior:
maior = valor
print(f'Foram informados {len(num)} valores ao todo.')
sleep(1)
... |
35c34d9d3dd35c667a3654012890a9c5b71a5774 | OviDanielB/FoI17-18 | /esercizi_esame/problema5.py | 1,415 | 3.90625 | 4 | """
* Problema 5
* Si definisca una classe PoligonoRegolare. Ogni oggetto della classe ha come attributi
* il numero di lati e la lunghezza di un lato, e come operazioni due metodi che restituiscono,
* rispettivamente, la lunghezza del lato e il perimetro del poligono. Si definisca inoltre una classe
* Qadrat... |
48f15ec0da33187cba65ef622b7de5e5b2587bc6 | BaduMa/python-self-study | /list.py | 847 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/11/9 11:44
# @Author : maxu
# list是一种有序的集合,可以随时添加和删除其中的元素;list里面的元素的数据类型也可以不同
classmates = ['1', '2', '3']
classmates.append('4') #列表最后位置添加4
classmates.insert(3,'Ture') #列表第4个位置添加布尔True
classmates[1]='22222' #列表第2的位置换成22222字符串
print(len(classmate... |
a1501663a9b5964eb25d35b265d3dced4d792bda | walzate/machine-learning | /knn_fruits.py | 1,544 | 4.375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
# based on https://hub.coursera-notebooks.org/user/smppgbjoljzaooewjwbuoj/notebooks/Module%201.ipynb
fruits = pd.read_table('fruit_data_with_colors.txt')
print(fruits.head())
# create a mappin... |
a67ce9552dcb85833b22bc3f4d5e9d319c271ea8 | zufardhiyaulhaq/CodeChallenge | /hacker-rank/Interview Preparation Kit/Sorting/Sorting: Bubble Sort/program.py | 839 | 3.65625 | 4 | _ = input()
data = list(map(int,input().split()))
def bubbleSort(data):
global swapCount
for i in range(0,len(data)):
for j in range(0,len(data)-1):
if data[j] > data[j+1]:
data[j],data[j+1] = data[j+1],data[j]
swapCount += 1
return data
swapCount = 0
d... |
bca97e6de2ad75ff73d0432f58580561f6f5fd02 | JuanFuentes20/some-python | /Python/player.py | 1,769 | 3.609375 | 4 | '''
Created on 19 Nov 2018
@author: juan
'''
class Player:
def __init__(self,new_name):
self.__name = new_name
self.__no_of_games = 0
self.__total = 0
self.__record = 0
def get_name(self):
return self.__name
def get_no_of_games(self):
ret... |
89751989aec47167a601a5b8d1de4a7bbe2407a8 | Amir-Omidfar/C247 | /hw2/nndl/softmax.py | 8,600 | 4 | 4 | import numpy as np
class Softmax(object):
def __init__(self, dims=[10, 3073]):
self.init_weights(dims=dims)
def init_weights(self, dims):
"""
Initializes the weight matrix of the Softmax classifier.
Note that it has shape (C, D) where C is the number of
classes and D is the feature size.
"""
s... |
2c3d98aec03ca4f47f8036925482413e14b9c716 | thang14nguyen/PhythonHW | /lab8a.py | 7,678 | 3.78125 | 4 | ## LAB 8
## Section C
#Section C.1
import collections
Dish = collections.namedtuple('Dish', 'dish price calories')
def read_menu_with_count(file_name:str):
"Take file name as string, and return list of Dish"
file = open(file_name).read()
dishes = file.split(sep='\n')
dishes = dishes[1:]
num_of_d... |
c4b08b2f45576a408bff63b8e9f450c1c63f3419 | Kanazawanaoaki/software-memo | /soft2/lec06/python/selection-sort.py | 654 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def selection_sort(num):
for i in range(len(num)):
min = num[i] # 仮の最小値
min_pos = i # 仮の最小値の場所
for n in range(i+1, len(num)):
if num[n] < min : # 比較対象の数字が仮の最小値より小さければ,仮の最小値を更新
min = num[n]
min_pos = n
... |
047190be9ed6dd1c6f6cfd7c9b9279a528ff70aa | XuuRee/python-data-structures | /01 Queue, Stack, LinkedList/stack.py | 2,868 | 3.890625 | 4 | #!/usr/bin/env python3
class Item:
"""Trida Item slouzi pro reprezentaci objektu v zasobniku.
Atributy:
value reprezentuje ulozenou hodnotu/objekt
below reference na predchazejici prvek v zasobniku
"""
def __init__(self):
self.value = None
self.below = None
clas... |
29774f437fb40fef84743398c855fcb1a5b4cf33 | zsimo/MOOC | /cs101_introduction_computer_Science/unit05/unit05-time.py | 3,356 | 4.21875 | 4 | # -*- coding: cp1252 -*-
# Hash Table: in Python si chiama Dictionary
# a set of key/value pairs mutable
# the key can be either string or number
dic = {}
dic1 = {'uno': 1, 'due': 2}
dic2 = {1: 1, 'due': 2}
print dic2[1]
# Hash function: keyword -> number
# takes a keyword and produces a number that gives the positio... |
859fd88a7e2ea39de8bc8b8b51c4c8d03f9bb83e | jlehenbauer/python-projects-public | /random_card.py | 3,620 | 3.65625 | 4 | import random
def card():
return ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'][random.randint(0, 12)]
def suit():
return ['♠', '♦', '♥', '♣'][random.randint(0, 3)]
def pick_card_with_replacement(number_of_cards):
cards = []
for num in range(number_of_cards):
cards.append((card(), suit(... |
6603e7c30b5a27bd0d5be960dcd90fc5b0e21783 | THEBEAST310/LeetCode-May2020-31DayChallenge | /Kth_Smallest_Element_in_a_BST.py | 613 | 3.6875 | 4 | # 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
def recursive(curr,list1)->list:
if curr==None:
return list1
else:
list1.append(curr.val)
list1=... |
6227dc458adda55b0c25e15ac4035944faf6cbd1 | Cyberceptive/cs1-sullivan | /code/python/imageproc/image_processing.py | 3,608 | 3.8125 | 4 | import pygame as pg
################### PIXEL OPERATIONS ######################
# grayPixel: pixel -> pixel
# compute and return a gray pixel with the same intensity
# as the given pixel. A little complication: the intensity
# values in the 3D numpy array representing the pixels are
# expressed as 8-bit integers. The... |
9fd268aff523508d3dca7f1425b37b97143b276d | xiangcao/Leetcode | /python_leetcode_2020/Python_Leetcode_2020/68_text_justification.py | 4,429 | 3.90625 | 4 | """
Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has ... |
65b389de527814b3d085dbe8cbb6f327e9eb713b | cpe202spring2019/lab0-AndersonKyle324 | /planets.py | 352 | 3.796875 | 4 | def weight_on_planets():
# write your code here
earthWeight = int(input("What do you weigh on earth? "))
marsWeight = earthWeight * .38
jupWeight = earthWeight * 2.34
print("\nOn Mars you would weigh", marsWeight, "pounds.\nOn Jupiter you would weigh", jupWeight, "pounds.")
if __name__ == '__... |
cfd2af7c0db1e118173f4fcb580dc55d6df8d25f | davidbezerra405/PytonExercicios | /ex061.py | 210 | 3.828125 | 4 | a1 = int(input('Informe o 1º termo da PA: '))
rz = int(input('Informe a razão da PA: '))
termo = 1
while termo <= 10:
print('{:3}, '.format(a1), end='')
a1 += rz
termo += 1
print('')
print('fim')
|
31ae1ee8261304327b207dd3f11c5ee0349335ef | BrayanStewartGuerrero/Basic_Concepts_of_Python | /strings.py | 537 | 4.0625 | 4 | myStr = "Brayan Guerrero"
# print(dir(myStr))
# print(myStr.upper())
# print(myStr.lower())
# print(myStr.swapcase())
# print(myStr.capitalize())
# print(myStr.replace("Hello", "Bye").upper())
# print(myStr.count("l"))
# print(myStr.startswith("Hello"))
# print(myStr.endswith("World"))
# print(myStr.split())
# print... |
aa67687d05586e837ccc1228d25fb2fe49ba8dca | Emmandez/MachineLearning_A-Z | /Part 2 - Regression/Section 5 - Multiple Linear Regression/Multiple_Linear_Regression/My_multiple_linear_regression.py | 2,254 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 3 23:27:47 2018
@author: eherd
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#importing the dataset
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,-1].values
#Encoding categorical data
#encoding t... |
897c2ebfbc64710a25d98517561ac805e0e1f873 | treedbox/python-3-basic-exercises | /class/app.py | 621 | 4.125 | 4 | """Class building example."""
class calculator:
"""Calculate basic operations."""
def addiction(x, y):
"""Adiction."""
added = x + y
print(added)
def subtraction(x, y):
"""Subtraction."""
subtracted = x - y
print(subtracted)
def multiplication(x, y):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.