blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
28f8810e9d2c074e83ea7fbd7bf52d5ec77da249 | alanmaranto/Basico-Algoritmos | /stringReverse.py | 180 | 4.0625 | 4 | string = "Hola a todos"
print(string[::-1])
# Recursividad
def reverse_string(string):
if not string:
return string
return reverse_string(string[1:]) + string[0] |
1acc2a11c00e52d431fa7303bb3d8b06a7503906 | ycybcnm/CS517-Final-Project | /graph_class.py | 3,056 | 3.53125 | 4 | class Graph(object):
def __init__(self, dictionary=None):
if dictionary == None:
dictionary = {}
self.adjacency_list = dictionary
self.vertices = []
self.edges = []
self.time = 0
self.count = 0
def add_vertex(self, vertex):... |
1421cbb6ce51471609b337d4ce46cd56c122067d | cam5/exercism | /python/reverse-string/reverse_string.py | 152 | 3.734375 | 4 | def reverse(input=''):
input_list = list(input)
ret = list()
for l in input_list:
ret.insert(0, l)
return ''.join(ret)
|
2c743531725c63f3cd566036e8f4cd6a33119923 | cam5/exercism | /python/space-age/space_age.py | 1,488 | 3.90625 | 4 | """
Exercism.ui problem set = spacage!
https://exercism.io/my/solutions/7e08cf5c963843f083dfca3a04d54acc
"""
"""
Orbital periods, relative to earth.
Ex. In the time it takes Mercury to make one full revolution of the sun, Earth
will only have orbited 0.2408467 of the way.
"""
ORBITAL_PERIODS = {
'EARTH': 1,
... |
1df188532085407dac5fb69a0a5103028e19ee4a | MaximeBastion/PythonExercices | /Part 1/exo2-if-else-argument-print-input.py | 1,454 | 4.09375 | 4 | """
1. Créer une fonction qui affiche dans la console si un age passé en paramètre est considéré majeur ou mineur.
Indice: utilise print(string) pour afficher du texte dans la console.
"""
#Solution
"""
def estMajeur(age):
if age >= 18:
print("Vous êtes majeur")
else:
print("Vous êtes mineur"... |
a50bb70162443b4d98cda9463b7e7ef2b54bf183 | mitchtz/Daily_Programmer | /249[I] - Hello World Genetic Algorithm/(OLD)hello_world_genetic.py | 5,188 | 3.578125 | 4 | import random, string, time
#String for list of letters, time for timing operation
letter_pool = string.ascii_letters
#Fitness function. Takes in goal string and string to eval. Returns number for fitness (0 <= fitness <= len(goal_str))
def fitness(goal, str_in):
fit = 0
for i in range(len(goal)):
if goal[i] == str... |
3e21b7bd5d61ae6830fc11caf2f5ea63cbf5f7ae | victordsgamorim/genetic_algorithm_np_1 | /cn_01/linked_list.py | 3,280 | 3.71875 | 4 | import math
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self._size = 0
def append(self, element):
if self.head:
pointer = self.head
while pointer.next:
... |
241617a564a5a64848f707706db7e49573b6da13 | cloudsecuritylabs/pythonProject_1 | /ch_01/20.typecasting.py | 106 | 3.703125 | 4 | '''
Let's learn about type casting
'''
my_tuple = ( 1,2,3,4,5)
my_list = list(my_tuple)
print(my_list[2]) |
ba44238e0fa6608e7a45b57a42f7705111e75d31 | cloudsecuritylabs/pythonProject_1 | /ch_01/15.stringproperties.py | 364 | 4.09375 | 4 | name = "Tintin"
print(type(name))
print("Tintin", " Captain", name)
# string has a lot of methods
print(name.isdigit())
print(name.upper())
# string properties
print(len(name)) # len is a function, name is the property
print(name.endswith("n"))
print(name.count("t"))
print(name.lower().count("t"))
# understand the... |
b25ed2f41e9de6cddfe7b9eb9a5ecb4c92979789 | cloudsecuritylabs/pythonProject_1 | /ch_01/expressiosandstatements.py | 567 | 3.796875 | 4 | #!/usr/bin/python3
# author: Ankan Basu
# expression -> anything that returns a value
# expressions (unit of execution) -> x = y
# expressions -> x = y
# expressions -> True
# expressions -> F()
# statement --> line of code
# statement --> does not require any semicolon at the end
# statement --> usually one statement... |
4c92c735e5966ba9de1cd9c0538c82040271139a | cloudsecuritylabs/pythonProject_1 | /ch_01/19.comparisonoperators..py | 812 | 4.125 | 4 | '''
Let's learn about comparison operators
'''
age = 0
if age <= 100:
print("You are too young")
elif age >100:
print("You are a strong kid")
else:
print("We need to talk")
if True:
print("hey there")
# this does not print anything
if False:
print("Oh No!")
string = "he he"
if string:
prin... |
e7b6bb1f898e3f202e16a5bcbc9ee2d1a44a63ec | cloudsecuritylabs/pythonProject_1 | /ch_01/12.math.py | 667 | 3.859375 | 4 | ## integers ##
# 2 + 10
# 10 - 2
# 10 / 5
# 2 * 3
# Python supports the order of operations too
# 3 + 3 * 4
## Floats ##
# any number with a decimal point a float.
# 2.01 + 10.88
# 10.66 - 2.34
# 10.99 / 5.22
# 2.34 * 3.33
# floating calculations may lead to some odd results!
# 0.2 + 0.1
# 3 * .1
# When we divide ... |
2317a738ce4d5f67cc7fc74963c19a85319f0bcf | CrazyIEEE/algorithm | /OnlineJudge/LeetCode/第1个进度/124.二叉树中的最大路径和.py | 1,671 | 3.703125 | 4 | #
# @lc app=leetcode.cn id=124 lang=python3
#
# [124] 二叉树中的最大路径和
#
# https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/description/
#
# algorithms
# Hard (42.94%)
# Likes: 648
# Dislikes: 0
# Total Accepted: 68.9K
# Total Submissions: 160.4K
# Testcase Example: '[1,2,3]'
#
# 给定一个非空二叉树,返回其最大路径和。
#
# 本... |
a529f6572fa378ba330f3c638a4bc671f7b9413f | CrazyIEEE/algorithm | /OnlineJudge/LeetCode/第1个进度/1518.换酒问题.py | 1,444 | 3.625 | 4 | #
# @lc app=leetcode.cn id=1518 lang=python3
#
# [1518] 换酒问题
#
# https://leetcode-cn.com/problems/water-bottles/description/
#
# algorithms
# Easy (69.25%)
# Likes: 25
# Dislikes: 0
# Total Accepted: 11.6K
# Total Submissions: 16.9K
# Testcase Example: '9\n3'
#
# 小区便利店正在促销,用 numExchange 个空酒瓶可以兑换一瓶新酒。你购入了 numBott... |
957d137f1fa348b1183cada3032b67c2cd6eaeed | CrazyIEEE/algorithm | /OnlineJudge/LeetCode/第1个进度/1441.用栈操作构建数组.py | 1,986 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=1441 lang=python3
#
# [1441] 用栈操作构建数组
#
# https://leetcode-cn.com/problems/build-an-array-with-stack-operations/description/
#
# algorithms
# Easy (64.57%)
# Likes: 8
# Dislikes: 0
# Total Accepted: 8.8K
# Total Submissions: 13.6K
# Testcase Example: '[1,3]\n3'
#
# 给你一个目标数组 target 和一个整... |
19f2c69ee241c1fcc5c86d91cafb35a7ae93a35d | CrazyIEEE/algorithm | /OnlineJudge/LeetCode/第1个进度/451.根据字符出现频率排序.py | 1,317 | 3.546875 | 4 | #
# @lc app=leetcode.cn id=451 lang=python3
#
# [451] 根据字符出现频率排序
#
# https://leetcode-cn.com/problems/sort-characters-by-frequency/description/
#
# algorithms
# Medium (64.73%)
# Likes: 167
# Dislikes: 0
# Total Accepted: 30.2K
# Total Submissions: 46.1K
# Testcase Example: '"tree"'
#
# 给定一个字符串,请将字符串里的字符按照出现的频率降... |
409aa7a774a8d170a32dfbe218e84104053b6671 | CrazyIEEE/algorithm | /OnlineJudge/LeetCode/第1个进度/535.tiny-url-的加密与解密.py | 1,477 | 3.5625 | 4 | #
# @lc app=leetcode.cn id=535 lang=python3
#
# [535] TinyURL 的加密与解密
#
# https://leetcode-cn.com/problems/encode-and-decode-tinyurl/description/
#
# algorithms
# Medium (82.30%)
# Likes: 89
# Dislikes: 0
# Total Accepted: 10.4K
# Total Submissions: 12.6K
# Testcase Example: '"https://leetcode.com/problems/design... |
c9e05c41ee43bd41fc57f5da76649fad20c261be | KingTom1/StudyBySelf | /视频学习练习/视频第二周学习_数据类型/列表类型.py | 1,426 | 4.21875 | 4 | # 列表(list)是有序的元素集合
# 列表元素可以通过索引访问单个元素
# 列表与元组不同的是: 列表的大小没有限制,可以随时修改
'''
<seq> + <seq> 连接两个序列
<seq> * <整数类型> 对序列进行整数次重复
<seq> [<整数类型>] 索引序列中的元素
Len(<seq>) 序列中元素个数
<seq>[<整数类型>:<整数类型>] 取序列的一个子序列
For<var> in <seq>: 对序列进行循环列举
<expr> in <seq> ... |
8673ca28ad11e72cdd17a27ceb67233557a31b04 | KingTom1/StudyBySelf | /02练习/练习01.py | 370 | 3.71875 | 4 | import 练习02
a=int('3122')
print(a)
b= abs(-1230)
print(b)
def fun(a,b) :
if a>0:
a=100;
else:
a=0;
print(a+b)
c=fun(2,3)
def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
d=f1(1,2,3,4,5,6,7,8)
def fact(n):
if n==1:
return 1
return n * fact(n - 1)
... |
75775de1bd44da7021fa2bcc7e2d9ebb9124e2e8 | ahmad-atmeh/my_project | /CA07/Problem 3/triangle.py | 2,036 | 4.1875 | 4 | # Class Triangle
class Triangle():
# TODO: Implement __init__ for this class use a,b,c and for the length of the sides
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def __str__(self):
tri = """
*
***
*****
******
... |
da2004b72fdf6dc722bd025c1c6580a9e9aaed8e | ahmad-atmeh/my_project | /CA10/3.py | 592 | 4.34375 | 4 |
# 3.You are given a list of words. Write a function called find_frequencies(words) which returns a dictionary of the words along with their frequency.
# Input: find_frequencies(['cat', 'bat', 'cat'])
# Return: {'cat': 2, 'bat': 1}
# Creating an empty dictionary
def find_frequencies(word):
freq ={}
fo... |
36cda705b3d2e83c671be0582bbaf1cb45b7484d | ahmad-atmeh/my_project | /CA10/4.py | 384 | 4.125 | 4 |
#4. You are given a list of integers. Write a function cumulative_sum(numbers) which calculates the cumulative sum of the list. The cumulative sum of a list numbers = [a, b, c, ...] can be defined as [a, a+b, a+b+c, ...].
# Input: numbers = [1, 2, 3, 4]
# Return: cumulative_sum_list = [1, 3, 6, 10]
lis = [1, 2, 3, 4]... |
2e2eccaa840f0fbf6bde633cf87834b7b4b62173 | ahmad-atmeh/my_project | /CA07/Problem 3/circle.py | 2,002 | 4.46875 | 4 | # Class Circle
import math
class Circle:
# TODO: Define an instance attribute for PI
def __init__(self, radius=1.0):
# TODO: Define an instance attribute for the radius
self.PI=3.14
self.radius=radius
# TODO: Define the string represent... |
3d7f26c1cdebf8e3cee70f6adf73ba0c5a17445d | AriusBlack/playing-with-python | /hangman.py | 1,527 | 4.09375 | 4 | #!/usr/bin/env python3
def hangman(max_tries, word):
tries = 0
guesses = []
word_show = list("-"*len(word))
word_to_find = [c for c in word]
while tries < max_tries:
if word_show != list(word):
guess = input("Guess a letter: ")
if len(guess) > 1 or len(guess) < 0... |
b163ac639e3521766e16c9859f14004996668482 | jkap13/py-calc | /test.py | 622 | 3.84375 | 4 | import re
run = True
hold = 0
print("Welcome to the Magical calculator")
def performcalculation():
global run
global hold
equation = ''
if hold == 0:
equation = input("Enter Equation")
else:
equation = input(str(hold))
if equation == "quit":
print("Th... |
ce314c4e7db6b1ea0d1b5133b2cfcba25d81514c | vchimishuk/Sort | /utils/generate_file.py | 561 | 3.546875 | 4 | import string
import random
from datetime import datetime
MAX_INT = 2 ** 31 - 1
def generate_email():
l = random.randint(10, 300)
return ''.join(random.choice(string.ascii_lowercase) for x in range(l))
def generate_time():
t = random.randint(0, MAX_INT)
return datetime.fromtimestamp(t).strftime(... |
d45d6b89689d0c002f08c1f2676b541ca73da319 | Edwin-96/conferencia_ipc2 | /playground.py | 3,351 | 3.5 | 4 | class Nodo:
def __init__(self, data, sig = None, pre = None):
self.data = data
self.sig = sig
self.pre = pre
def conectar(self, sig = None, pre = None):
self.sig = sig
self.pre = pre
return self
def conectar_sig(self, sig):
self.sig = sig
return self
def conectar_pre(self, pre):
self.pre = pre... |
372b38fde7d17e0c914199d533b19ff8e1d61832 | panindraprakash/learning-python | /learnpythonthehardway/ex8.py | 968 | 3.609375 | 4 | formatter = "%r %r %r %r" # assigning the valure %r %r %r %r to formatter
print formatter % (1, 2, 3, 4) # assigning the vale of 1,2,3,4 to formatter %r respectively and printing it in one line.
print formatter % ("one", "two", "three", "four") # assigning the value of one,two,three,four to formatter %r respectively a... |
65708223b1dae99cad36af9e76dbeaa00505bd61 | maxbogue/AI-TicTacToe | /tictactoe.py | 7,038 | 3.578125 | 4 | import json
import random
import sys
from nn import NeuralNet
# The size of a side of the game board.
N = 3
# Constants for player 1, player 2, and empty space.
P1 = 1
P2 = -1
ES = 0
def print_board(board):
"""Prints a very simple board representation.
X is used for player 1, O for player 2, and a - fo... |
ff157d9b1a6690e58650b123a55af1759bcbac51 | ronny152020/TRABAJO-DE-INVESTIGACION | /Proyecto_menu.py | 18,049 | 3.546875 | 4 | from menu import menu_principal
from calculadora import calEstandar,calCientifica,calculadora
from operacion_numeros import basico,intermedio
from Tratamiento_de_listas import tratamientolistas
from OperacionesDeCadena import cadena
import os
MAGENTA = '\033[35m'
RESET = '\033[39m'
YELLOW = '\033[33m'
opcion... |
eb954e96ab4f8a34e70891920d417a2d93822b44 | Dipin-Adhikari/Python-From-Scratch | /Dictionary/dictionary.py | 1,398 | 4.125 | 4 | """Dictionaries is collection of keyvalue pairs.it is ordered and changeable but it doesnot allow duplicates values.."""
dictionary = {
"python": "Python is an interpreted high-level general-purpose programming language.",
"django": "Django is a Python-based free and open-source web framework that follows the ... |
07604d6d6910ff0efa994121dd13f8784568634e | Aadit017/code_sharing | /type of triangle.py | 411 | 4.28125 | 4 | while True:
f= float(input("Enter first side: "))
s= float(input("Enter second side: "))
t= float(input("Enter third side: "))
if(f==s and f==t):
print("THE TRIANGLE IS AN EQUILATERAL TRIANGLE")
elif(f==s or f==t or s==t):
print("THE TRIANGLE IS AN ISOSCELES TRIANG... |
85b222d4afda9d077f79a10a694b92088f6f8746 | Aadit017/code_sharing | /deck_of_cards.py | 1,231 | 3.828125 | 4 | import random
class Cards():
def __init__(self):
self.tot_cards=[f"{x} of {y}" for x in ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] for y in ["Hearts","Clubs","Spade","Diamond"]]
def total_cards(self):
return self.tot_cards
class Deck():
def __init__(self):
self.cards52=Cards().... |
b578a4a9a57922b7b6a13472a074c1ad883b0421 | Aadit017/code_sharing | /month to days.py | 756 | 4.1875 | 4 | while True:
name=input("Enter name of month: ")
name=name.lower()
if(name=="january"):
print("days=31")
elif(name=="february"):
print("days=28")
elif(name=="march"):
print("days=31")
elif(name=="april"):
print("days=30")
elif(name=="may"):
... |
962cc6f1db72c1c9b8f7bf4cf77d6d31d6d9174a | Aadit017/code_sharing | /jupyter_function_question.py/3.py | 199 | 3.921875 | 4 | def old_macdonald(name):
if len(name) > 3:
return name[:3].capitalizecapitalize() + name[3:].capitalize()
else:
return 'Name is too short!'
print(old_macdonald("aadit ")) |
48d8a61933a1bbe1b665e0afec478871691650da | Aadit017/code_sharing | /zip.py | 178 | 3.734375 | 4 | def interleave(s1,s2):
z=list(zip(s1,s2))
l=[]
for i in z:
for j in i:
l.append(j)
return ''.join(l)
print(interleave('lzr','iad'))
|
c11aabbaedae6c43ba429d3570b22d2c17e2dfb5 | Aadit017/code_sharing | /radius of circle.py | 118 | 4.28125 | 4 | radius=int(input("Enter the radius of the circle(in cm): "))
pi=3.14
print("THE AREA IS= ",pi*radius*radius,"cm.")
|
276a6fa35f2b96a15e05cfc3cc43586d9a14e050 | Rajeshwarchennam/machine_learning1 | /posterior.py | 1,073 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def power(x,n):
y=1
for i in range(n):
y=y*x
return y
def polybasis(x,m):
l=len(x)
X=x
if m>1:
for i in range(2,m+1):
y=power(X,i)
x=np.column_stack((x,y))
z=np.column_stack((np.ones(l),x))
return ... |
00295d8bad84c7a151ad381045693de7a6a81699 | ntak1/Playground | /qt/RealPythonTutorial/00HelloWorld.py | 780 | 3.53125 | 4 | import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QWidget
# Create an instace of QApplication
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle("PyQt5 App")
# Set position (from top), width and height of window
ax = 100
ay = 100
wid... |
8800a005e9c373c0f334a85c41bee8829dd06e4d | georgeaholden/jimbot-py | /modules/harassment.py | 1,476 | 3.71875 | 4 | """Implementing a joke with the $hello command. If a user types $hello multiple times, the bot adapts its response and
eventually spams the user with friendly dms.
Response filename has following syntax:
a single integer n, the number of unique response lines
n lines each representing a single response
an arbitrary nu... |
cd82a45b924b50eca829fde7a81b78da79feed87 | gitsoftsun/Learn | /python/algorithms/Mixed.py | 761 | 3.71875 | 4 | # -*- coding: utf-8 -*-
__author__ = 'User19'
# 有序数组A和B的交集
import random
def mixed(a, b):
c = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] == b[j]:
c.append(a[i])
i += 1
j += 1
elif a[i] > b[j]:
j += 1
else:
i +=... |
58ad554fc115f8957edb643c473c615e06e063d8 | gitsoftsun/Learn | /python/HelloWorld/TFor.py | 98 | 3.8125 | 4 | #Test For loop
fruits = ['banana', 'apple', 'mongo']
for fruit in fruits:
print 'fruit : ', fruit |
657d71a5e79363be05c87240e533a92c5cc25b52 | rdlulu/Code-Practice | /Max_No_Balloons.py | 719 | 4.03125 | 4 | '''
1189. Maximum Number of Balloons
Difficulty:Easy
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
'''
class Solution(object):
def ma... |
325ed02c5c20e283a862e5d5eb27ce889cc75ed5 | grizax/blackjack | /blackjack/deck.py | 1,052 | 3.765625 | 4 | class Deck(object):
"""
Generates full deck, shuffles, and notes decksize after deal.
"""
deckSize = 52
suits = ["Diamonds", "Hearts", "Spades", "Clubs"]
values = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"]
def __init__(self):
random.seed()
self.sequen... |
a6759a0d5fb17142435d89d87ccbd4ce64629a39 | Abhilash11Addanki/cspp1-assignments | /Module 22 Week Exam/Check Sudoku/check_sudoku.py | 1,741 | 4.28125 | 4 | '''
Sudoku is a logic-based, combinatorial number-placement puzzle.
The objective is to fill a 9×9 grid with digits so that
each column, each row, and each of the nine 3×3 subgrids that compose the grid
contains all of the digits from 1 to 9.
Complete the check_sudoku function to check if the given... |
174ca0fb814021e716969bcd6b681fca98d5fbb9 | Abhilash11Addanki/cspp1-assignments | /Practice Problems/Code Camp matrix/matrix_operations.py | 2,042 | 4.125 | 4 | '''Matrix operations.'''
def mult_matrix(m_1, m_2):
'''
check if the matrix1 columns = matrix2 rows
mult the matrices and return the result matrix
print an error message if the matrix shapes are not valid for mult
and return None
error message should be "Error: Matrix shapes ... |
d6a8f1db08c16e1f10b281921ad5b0296cea6482 | qcrit/NHB-2018-OEstylometry | /meter_and_compounds/Python_code/isolate_compounds.py | 1,158 | 3.5625 | 4 | import sys
import re
def main(dict_file_name, inp_file_name):
list_of_words=[]
with open(dict_file_name,"r") as input_dict:
for line in input_dict:
data=line.split()
list_of_words.append(data[0])
print(list_of_words)
with open(inp_file_name,"r") as input_file:
words=[]
for line in input_file:
... |
a73c917c834665052c3e80eb1bb5e8f6ae8cd7a3 | bmispelon/pythonchallenge | /c14/solve.py | 1,371 | 3.671875 | 4 | # http://www.pythonchallenge.com/pc/return/italy.html
# The input is a 1px high, 10 000px wide image (wire.png).
# As the main image and the title of the page suggest, we need to "wrap" these pixels
# around a 100x100 image. This yields an image of the solution.
import Image
from itertools import chain
def wrap_around... |
56ef0f601661e8a2e533306e59046d20726a90c5 | bmispelon/pythonchallenge | /c2/solve.py | 332 | 3.875 | 4 | # http://www.pythonchallenge.com/pc/def/ocr.html
# Find letters in a message.
from __future__ import print_function
if __name__ == '__main__':
import fileinput
for line in fileinput.input():
letters = [c for c in line if c.isalpha()]
if letters:
print(''.join(letters), end='')
... |
5b7ae91a9c275feea1377278ebce10b60a95695b | dilya123/pythoMonth1 | /lesson4/lesson4_2.py | 143 | 3.984375 | 4 | name = input()
while name == "Atai":
name = input()
for i in range(10):
while True:
while False:
print("Hello")
|
ab53bf3d9d5bf80ef79ad1541979b23a6a55136c | dilya123/pythoMonth1 | /lesson1/lesson1_3.py | 358 | 3.890625 | 4 | name = input("Введите ваше имя! ")
surname = input("Введите вашу фамилию! ")
date_of_birth = input("Введите дату рождения! ")
username = input("Введите имя пользователя! ")
password = input("Введите пароль! ")
print(name, surname)
print(date_of_birth)
print(username, password)
|
3466033d7159c3735aec7be5201ad46e21115636 | vlad-danaila/machine-learning-workout | /3 - Classification/15 - K-Nearest Neighbors (K-NN)/knn.py | 1,972 | 3.640625 | 4 | # -*- coding: utf-8 -*
import numpy as np
import sklearn.preprocessing
import sklearn.model_selection._split
import sklearn.neighbors
import matplotlib.pyplot as plt
import matplotlib.colors
import pandas as pd
import sklearn.metrics
# Data load
data = pd.read_csv('C:/DOC/Workspace/Machine Learning A-Z Template Folde... |
493444fe9f024df10356bb5300797238ea5cdd57 | alishahwee/api-test | /helpers.py | 379 | 3.578125 | 4 | class Coordinates:
"""A coordinates object."""
def __init__(self, latlon: str):
"""Initialized by taking in a comma-separated latitude, longitude string (no whitespace)."""
self.latlon_as_list = [float(c) for c in latlon.split(",")]
self.latlon_as_str = latlon
self.lat = self.l... |
6ee1228d38ad0febeab79fd4a86cff70ff4462e8 | Minord/SinteticPixels | /SinteticPixels/operations/expand.py | 3,336 | 3.59375 | 4 | """
here are the functions for expand an image.
"""
import numpy as np
from SinteticPixels.img import types
from SinteticPixels.operations import utils
#i dont need import Image class ?
import pdb
supporter_img_types = ('gray_scale', 'rgb', 'binary')
#principal function in the module
#TODO: implement the expand v... |
9ec5e372d65a932d552fff27e872eb7be574e8b6 | dschloe/class_python | /step03_algorithm_interview/Palindrome.py | 1,045 | 3.71875 | 4 | #!/venv/bin/python
# -*- coding: utf-8 -*-
class Solution:
def isPalindrome(self, s: str) -> bool:
strs = []
for char in s:
if char.isalnum(): # isalnum(): 영문자, 숫자 여부 판별하여 False, True 변환
strs.append(char.lower()) # 모든 문자 소문자 변환하여 str에 입력
print('문자 처리: '... |
bda8e3bf77df61bf4d7135043367a3ba7c9a5d58 | georgesp90/codewars | /highlow.py | 382 | 3.578125 | 4 | def high_and_low(numbers):
numbers = numbers.split()
numbers = [int(x) for x in numbers]
numbers_low = min(numbers)
numbers_high = max(numbers)
high_and_low_num = "{} {}".format(numbers_high, numbers_low )
return high_and_low_num
# clever
def high_and_low_c(numbers): #z.
nn = [int(s) for s ... |
a7f8235090970051ef7f4a332367697b43473dad | karthick18/misc | /jump_steps/jump_steps.py | 3,339 | 3.78125 | 4 | # You are given a list of numbers and a starting position.
# Your goal is to find a sequence of jumps from the starting position to the end of the list.
# A valid jump at any position must be between zero and the value at that position in the list, i.e. list[pos], inclusive.
# You must return a list of valid jumps in s... |
5416618feda0c042c4d73af274d1784905a57111 | MaxPoon/Leetcode | /python/352.DataStreamasDisjointIntervals.py | 2,497 | 3.578125 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class SummaryRanges(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.summary = []
def addNum(self,... |
3ab3ff2e12a7bf30f41febfbde312a1df96c64de | MaxPoon/Leetcode | /python/288.UniqueWordAbbreviation.py | 893 | 3.859375 | 4 | class ValidWordAbbr(object):
def __init__(self, dictionary):
"""
initialize your data structure here.
:type dictionary: List[str]
"""
self.dictionary = set(dictionary)
self.count = {}
for word in self.dictionary:
if len(word)>=3:
abbr = word[0] + str(len(word)-1) + word[-1]
else: abbr = word
... |
438b93b0c0fc10372822038ad499da620a5d51e8 | MaxPoon/Leetcode | /python/329.LongestIncreasingPathInAMatrix.py | 860 | 3.53125 | 4 | def dfs(matrix, longest, rows, cols, row, col):
if longest[row][col]!=0: return
longest[row][col] = 1
for (r,c) in ((row+1, col), (row-1,col), (row,col+1),(row,col-1)):
if r<0 or r>=rows or c<0 or c>=cols or matrix[row][col]>=matrix[r][c]: continue
if longest[r][c] == 0: dfs(matrix, longest, rows, cols, r, c)
... |
03483000e0f9ab1d5db42be859d85ee770dc9e94 | MaxPoon/Leetcode | /python/23.MergeKSortedLists.py | 1,555 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
"""
@param lists: a list of ListNode
@return: The head of one sorted list.
"""
def mergeKLists(self, lists):
# write your code here
... |
56737300e64e475f25bdb5581c9d66db71e58701 | MaxPoon/Leetcode | /python/403.FrogJump_2.py | 877 | 3.5 | 4 | class Solution:
def canCross(self, stones: List[int]) -> bool:
stoneSet = set(stones)
lastStone = stones[-1]
if stones[1] != 1: return False
if len(stones) == 2: return True
if lastStone > stones[-2] + len(stones): return False
visited = set()
def canCrossRecu... |
fb4aab5010a6b97596b5830d26e779c1f4964c1d | MaxPoon/Leetcode | /python/604.DesignCompressedStringIterator.py | 774 | 3.546875 | 4 | class StringIterator(object):
def __init__(self, compressedString):
"""
:type compressedString: str
"""
self.i = 0
self.s = compressedString
self.count = 0
self.c = None
def next(self):
"""
:rtype: str
"""
if self.count > 0:
self.count -= 1
return self.c
elif self.i < len(self.s):
s... |
a4c073214452cb69ebc11d4852496d72d7de19da | MaxPoon/Leetcode | /python/501.FindModeInBinaryTree.py | 1,495 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None: return []
mode = []
... |
72088ee62a8b2fbab0aaec77cf5090b3e231d930 | MaxPoon/Leetcode | /python/332.ReconstructItinerary.py | 566 | 3.5625 | 4 | from heapq import heappush, heappop
from collections import defaultdict
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
fromTo = defaultdict(list)
for ticket in tickets:
heappush(fromTo[ticket[0]], ticket[1])
self.fromTo = fromTo
sel... |
0719f6fab2055b66e91b9bbd0c55257886a399f5 | MaxPoon/Leetcode | /python/56.MergeIntervals.py | 894 | 3.84375 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
result =[]
... |
0d4c13bdb36148a6d1a644a5c01dcf92d8510826 | anthony-talevi/Scripts | /boxplot.py | 1,327 | 3.609375 | 4 | # numpy is used for creating fake data
import numpy as np
import matplotlib as mpl
import sys
import csv
## agg backend is used to create plot as a .png file
mpl.use('agg')
import matplotlib.pyplot as plt
# Get the command line arguments
# Check for correctness
num_args = len(sys.argv)
if(len(sys.argv)>3... |
d8544870a7b9dad13f64831423bcdafe569647ee | osgcc/osgcc5-WilliamWallaceCastleDefender | /Vector.py | 1,165 | 3.90625 | 4 | #Vector
from math import sin, cos, atan, hypot
# The quick way to know how big the pie is
PI = 3.141592653589793238462643383
TwoPI = PI * 2.0
HalfPI = PI * 0.5
OneAndHalfPI = PI * 1.5
# new math function
def direction(x, y):
"""Return the direction component of a vector (in radians), given
cartesian coordinat... |
4593d94d66413d5e1a043e1f69c6d76595c8b518 | Reyaad510/Algorithms | /recipe_batches/recipe_batches.py | 2,710 | 4.03125 | 4 | #!/usr/bin/python
import math
# Pseudo
# DO a while loop
# Compare values of each and if they pass then subtract rec and ing
# Do batch++
# New value of ingredients compare to recipe again, if lower then break loop and return batch
# if equal or higher batch++ and subtract recipe and ingredients
# Rinse and repeat
... |
6485a65aaf4ecbcdbf3e86c954a792aeaa5c8948 | BabaYaga007/Second-1 | /stone_paper_scissor.py | 1,198 | 4.1875 | 4 | from random import randint
def print_menu():
print('1 for Stone')
print('2 for Paper')
print('3 for Scissor')
print('Enter your choice')
def print_score(a,b):
print('---Score---')
print('Player =',a)
print('Computer =',b)
choice = ['stone','paper','scissor']
a=0
b=0
while(... |
238f30f035a54ede9b8a3cae148c074bbd806ec3 | ralsouza/python_data_structures | /section7_arrays/searching_an_element.py | 440 | 4.1875 | 4 | from array import *
arr1 = array("i", [1,2,3,4,5,6])
def search_array(array, value):
for i in array: # --------------------------------------> O(n)
if i == value:# ------------------------------------> O(1)
return array.index(value) # --------------------> O(1)
return "The element does no... |
39d05e5885bbbb21236f4d6392e71db04687f04b | ralsouza/python_data_structures | /section8_lists/proj1_missing_number.py | 876 | 4.0625 | 4 | # Project 1 - Missing Number
# How to find the missing number in an integer array of 1 to 100?
# Trick: 1+2+3+...+n = n(n+1)/2
# Remove some value above to use the function
arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
... |
3f9c04833a87be9b112078e462c08aa7369dc9bc | ralsouza/python_data_structures | /section8_lists/chal6_pairs.py | 550 | 4.21875 | 4 | # Pairs
# Write a function to find all pairs of an integer array whose sum is equal to a given number.
# Example: pair_sum([2,4,3,5,6,-2,4,7,8,9], 7)
# Output: ['2+5', '4+3', '3+4', '-2+9']
my_list = [2,4,3,5,6,-2,4,7,8,9]
def pair_sum(list, num_sum):
output = []
for i in range(len(list)):
for j in r... |
49ab45268ba1099af5637316d5584e075a601dab | ralsouza/python_data_structures | /section28_sorting_algorithms/293_bubbles_sort.py | 490 | 4.25 | 4 | # Bubble Sort
# - Bubble sort is also referred as Sinking sort
# - We repeatedly compare each pair of adjacent items and swap them if
# they are in the wrong order
def bubble_sort(custom_list):
for i in range(len(custom_list)-1):
for j in range(len(custom_list)-i-1):
if custom_list[j] > custo... |
6adcebfeff79bf2c97bf0587a49e658e71b7b503 | ralsouza/python_data_structures | /section8_lists/proj3_finding_numer_in_array.py | 399 | 4.15625 | 4 | # Project 3 - Finding a number in a array
# Question 3 - How to check if an array contains a number in Python
import numpy as np
my_list = list(range(1,21))
my_array = np.array(my_list)
def find_number(array, number):
for i in range(len(array)):
if array[i] == number:
print(f"The number {numb... |
00cd380dc6e26062b37d3dd228ab90f3a809da8e | ralsouza/python_data_structures | /section7_arrays/access_array_element.py | 284 | 3.96875 | 4 | from array import *
arr1 = array("i", [1,2,3,4,5,6])
def access_element(array, index):
if index >= len(array):
print("There is not any element in this index.")
else:
print(array[index])
access_element(arr1, 1)
access_element(arr1, 8)
access_element(arr1, 6) |
c22fbab5afe23a79783eeaa86b6d0041c5c01b7d | viratalbu1/Python- | /AccesingInstanceVariable.py | 513 | 4.25 | 4 | #This Example is used for understanding what is instance variable
class test:
def __init__(self,name,rollno):
self.name=name
self.rollno=rollno
def info(self):
print(self.name)
print(self.rollno)
#In Above Example state creation of constructor and object method
# For Accessing it just create Obje... |
78e9924735898785f3963c59531b866f1f44138b | viratalbu1/Python- | /IteratorAndGeneratorExample.py | 695 | 4.875 | 5 | # Iterator is used for creating object for iteratable object such as string, list , tuple
itr_list=iter([1,2,3,4])
itr_tuple=iter((1,2,3,4))
itr_string=iter('String')
print('--------List ------')
for val in itr_list:
print(val)
print('-----Tuple----------')
for val in itr_tuple:
print(val)
print('--... |
48190eddee72cad9e2826582a63c6c95bcaaf661 | NPavl/Python_Lessons | /lessons/Les_10 (Словари_dict).py | 5,120 | 3.578125 | 4 | # Словари (dict)
# В питоне словари это по сути ассоциативный массивы , что такое ассоциативнй маcсив :
# к примеру в списках мы писали так : a = [234, 345 ] азного элимента и под своим индексом , в
# словарях эти индексы пропущены вместо них присутствую ключи к примеру,
# в питоне есть 4 разных метода благодаря котор... |
a170e81ecc92b7e088941c8a45369f8e4905f26d | charles3399/Hangman-Game | /hangman.py | 1,503 | 4.0625 | 4 | import random
def hangman():
word_list = ["Banana","Tree","Car","Smartphone","Cat"]
random_number = random.randint(0,4)
word = word_list[random_number]
wrong_guesses = 0
stages = ["",
"________ ",
"| | ",
"| 0 ",
"| ... |
86ad129dde99c77bbbd2a4cce1b07f8e07f6f764 | daiphuongngo/IBM-Data-Analytics-Certificate | /Python Basics for Data Science/Module 3 - Python Programming Fundamentals.py | 40,463 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 27 17:54:50 2020
@author: phuongdaingo
"""
"""Conditions in Python
Welcome! This notebook will teach you about the condition statements in the
Python Programming Language. By the end of this lab, you'll know how to use the
condition statements in... |
e9adba91c10866d34ec75d2ac4698fca080b843c | Nedas1123/Programavimo_kalbu_teorija | /lab1/lab1.py | 817 | 3.546875 | 4 | class Num:
def isPrime(self,n):
if n <= 1 or n % 1 > 0:
return False
for i in range(2, n//2):
if n % i == 0:
return False
return True
def findSmaller(self,num):
x=num
while not self.isPrime(x):
x=x-1 ... |
8ea3b89fd506f264399d0729f13e164f9fd47d27 | IanCarreras/Don-code-challenges | /vlad-apple_1.py | 549 | 3.921875 | 4 | # Given a sorted array, convert it into a binary search tree.
# Can you do this both recursively and iteratively?
class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __str__(self):
return f'{self.val}, ({sel... |
cc0e57b496877322c047a91d87ba78ab04a92cfb | a253844/demo-python | /python-DataTransaction/copilot_test.py | 291 | 3.75 | 4 | #write a program to download youtube video using python
import pytube
link = input("Enter the link of the video: ")
url = input("Enter the url of the video: ")
video = pytube.YouTube(url)
stream = video.streams.get_highest_resolution()
stream.download()
print("Download Completed!!")
|
a36947ba11a72bf6d613f635666069ea6d9c3492 | yash4302/MyCaptain | /Python/02_1.py | 130 | 3.640625 | 4 | pre = 0
cur = 1
n = int(input("Enter N : "))
i = 0
print(pre)
i += 1
while i < n:
i += 1
print(cur)
pre, cur = cur, pre+cur
|
7289edff51c4ab2709bc48260541617c32f59a56 | om-sonawane/object_oriented_programming | /inheritance_oops.py/operator_overloading.py/create_class_Pets.py | 179 | 3.609375 | 4 | class Animals:
animaltype= "mammal"
class pets:
colour="white"
class dog:
@staticmethod
def bark():
print ("bow bow!!")
d = dog()
d.bark()
|
a5fa18b87753a49e8cf2e399dc68d31380af894a | ht3886/GraphDB-Python | /file2.py | 811 | 3.921875 | 4 | import csv
# open required csv and read it as a text string
with open('file1.csv', 'r') as input:
csv_reader = csv.DictReader(input)
# open new file to save changes
with open('file2.csv', 'wb') as out_file:
fieldnames = ['ParkName', 'State', 'partySize', 'RateType', 'BookingType', 'Equipment']
... |
d914fe460dc737af2c7049d8aab6e3d7bb4bfd6a | kaylalooney/GE-Innovation-Project-Summer-2016 | /RFID/rfid.py | 4,113 | 3.546875 | 4 | # Python 3
# Kayla Looney -- GE Summer Intern Innovation Raspberry Pi 3 Project
# Import a bunch of stuff
import subprocess
from time import sleep
import sqlite3
import datetime
import sys
LOCATION= "front door" # global variable that is unique to each Pi
MASTER_DICT = {'a0 55 25 11': "white card", "04 f2 48 e... |
b82b2191e6e04cd83645613ab0b0a211e581a5cb | ManaBingsu/algo-study | /algorithm/week2/sjmjys954646_PS/boj1032.py | 287 | 3.5625 | 4 | #메모리 : 29076 KB 시간 : 76ms
T = int(input())
main = input()
mainlen = len(main)
for i in range(0,T-1):
st = input()
for t in range(0,mainlen):
if(main[t]!=st[t]):
li = list(main)
li[t] = '?'
main = ''.join(li)
print(main)
|
9b87bd9f0e8c3a9f831d659fbe63ea9ab130e034 | itsayellow/logrolling | /logrolling.py | 3,278 | 3.640625 | 4 | """An encapsulation of logging to make using it easier and more pythonic
"""
import logging
class IndentLogFormatter(logging.Formatter):
"""Formatter to be used with logging that puts indented message in lines
following the log meta-information
"""
def format(self, record):
out_str = super(... |
e90de2bac518ed17a4bbd1208e46cd3ef2290a6f | ram-jee/Python_projects | /guess_number.py | 835 | 3.953125 | 4 | # This code compares a number entered by user in a range specified by user
# Displays Won or lost message as per guess
import random
print('Levels: 2-Easy, 5-Medium, 10-Challenge')
level = int(input('Enter level: '))
computer_val = random.randint(1,level)
attempts = 1
user_val = int(input('Enter choice: '))
while Tr... |
a40ec465af8eb869f37adaf02c5bf071cc61779b | u2386/leet | /external/接雨水/slow_solution.py | 1,122 | 3.734375 | 4 | # coding: utf-8
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height:
return 0
total = 0
for h in range(1, max(height)+1):
i = water = 0
while i < len(height):
... |
68d52cd3c0001ec78b31dd286c8f45b97aa682ad | u2386/leet | /external/数组中的第K个最大元素/solution.py | 665 | 3.71875 | 4 | # coding: utf-8
import heapq
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
q = nums[:k]
heapq.heapify(q)
for n in nums[k:]:
if n < q[0]:
continue
... |
d62f477d743f88c767df98ee71b820ad37ed8f4e | u2386/leet | /external/三数之和/solution.py | 1,484 | 3.578125 | 4 | # coding:utf-8
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) < 3:
return []
nums.sort()
ret = []
for i, n in enumerate(nums):
if n > 0:
re... |
a57da4ad3edefaa6f6a947d480263fe23ed82e75 | u2386/leet | /655-输出二叉树/solution.py | 1,325 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
... |
25c24718e07b969ed71c10a3d29cd42dacb68078 | u2386/leet | /external/合并区间/solution.py | 953 | 3.515625 | 4 | # coding: utf-8
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
if not intervals:
return []
intervals.sort()
ret = [intervals[0]]
for i, j in intervals[1:]:
... |
320c4ae46efb9f9e1fb5079b081bf2719377b7b4 | richmonddecker/drawn-out-repetitives | /kochpinski/kochpinski.pyde | 3,893 | 3.671875 | 4 | def rainbowCircle(radius, outside):
"""Makes a rainbow gradient circle that expands out."""
outside = int(outside % (2 * radius))
strokeWeight(2)
noFill()
colorMode(HSB)
if outside <= radius:
radii = range(1, outside)
else:
radii = range(outside - radius, radius)
for i in... |
78db89dac3daf4718ea110e72dded10806da41e0 | hahnejo/Interview-Questions | /Daily-Coding-Problem/my_02.py | 1,061 | 4 | 4 | # input : [1, 2, 3, 4, 5]
# output : [
# (2 * 3 * 4 * 5),
# (1 * 3 * 4 * 5),
# (1 * 2 * 4 * 5),
# (1 * 2 * 3 * 5),
# (1 * 2 * 3 * 4)
# ]
def mul_no_index(list):
before = []
after = []
print ("my list", list)
for item in list:
if (be... |
edf71478df24ed8e8450dfb911169c2ca6858bee | hahnejo/Interview-Questions | /Hackerrank/hourglassSum.py | 611 | 3.734375 | 4 | def hourglassSum(arr):
collection = []
for i in range(len(arr) - 2):
for j in range(len(arr) - 2):
collection.append(arr[i][j]+arr[i][j+1]+arr[i][j+2]+
arr[i+1][j+1]+
arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2])
big = collection[0]
... |
78e32d8627f699d17fe4332007ec0ff7852fa7bd | csjoey/Dungeon_game_client | /engine/classPlayerData.py | 1,737 | 3.609375 | 4 | import json
class PlayerData:
"""
Class for the storage and retrieval of player saves
"""
def __init__(self):
self.seed = None
self.max_health_upgrades = None
self.max_speed_upgrades = None
self.coins = None
self.score = None
self.playtime = Non... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.