blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
fb689544fb8d2c7267a2eea35063279182cce32f | emanuelrv/avc | /p11.py | 212 | 3.671875 | 4 | numbers = range(1, 21)
print numbers
##test
sum = 0
for counter in numbers:
sum = sum + counter
print "la suma" , sum
my_names = {"Joe", "Bob", "Ned"}
print my_names[0]
print my_names[2]
print my_names[3]
|
51f9c23d2637cf1b8746f45720d73b3fbf543cb3 | disCCoRd1/Machine-Learning---Basis | /statistical_methods_for_machine_learning/code/chapter_12/03_correlation.py | 560 | 3.75 | 4 | # calculate the pearson's correlation between two variables
from numpy.random import randn
from numpy.random import seed
from scipy.stats import pearsonr
# seed random number generator
seed(1)
# prepare data
data1 = 20 * randn(1000) + 100
data2 = data1 + (10 * randn(1000) + 50)
# calculate Pearson's correlation
corr, p... |
484bf5426bc66fac06ed3d08460f9b5fafb5f522 | myfairladywenwen/cs5001 | /hw09/word_ladder_no_extra_solution/word_ladder.py | 1,722 | 3.90625 | 4 | from queue import Queue
from stack import Stack
class WordLadder:
"""A class providing functionality to create word ladders"""
def __init__(self, w1, w2, wordlist):
self.word1 = w1
self.word2 = w2
self.valid_words_set = wordlist
self.myqueue = Queue()
self.mystack = St... |
c2a80c99f8e11e6ec7bb29ad9df2f59dca25df08 | Dipesh13/doc-classification | /extract_text.py | 884 | 3.703125 | 4 | # encoding=utf8
import PyPDF2
import os
# filename = 'Frankenstein.pdf'
def text_ext(filename):
"""
Function to extract text from pdf and save it in txt format
:param filename:
:return:
"""
dump = ''
pdfFileObj = open(filename, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
for ... |
bff1ac93bbda37435a2df3337b4a4b8f794164d3 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/phone-number/c38910c17dc94006afa9ebb06148a586.py | 388 | 3.65625 | 4 | class Phone:
def __init__(self, s):
s = "".join(c for c in s if c.isnumeric())
self.number = (s[-10:] if len(s) == 10 or len(s) == 11 and s[0] == "1"
else "0" * 10)
def area_code(self):
return self.number[:3]
def pretty(self):
return "({}) {}-{}".form... |
fcfa717f0b15f54e166b56c96687dcbe789c1a6e | StianHanssen/RockPaperScissors | /game.py | 2,028 | 3.671875 | 4 | from action import Action
__author__ = 'Stian R. Hanssen'
class SingleGame():
def __init__(self, player1, player2):
self.__player1 = player1
self.__player2 = player2
self.__point1 = 0
self.__point2 = 0
self.__pick1 = None
self.__pick2 = None
def execute_game(s... |
7544cd1bed43dd52fe078359bd35d3be57c83857 | bhawnagurjar27/CodeForces-Problems-Solution | /Word Capitalization/Word Capitalization.py | 350 | 3.75 | 4 | number_of_testcases = 1 #int(input())
for _ in range(number_of_testcases):
given_string = input()
given_string = list(given_string)
if ord(given_string[0]) >= 97:
given_string[0] = chr(ord(given_string[0]) - 32)
answer = ""
for char in given_string:
answer += c... |
ece2405adbebc7b93bf9f7e1be0a0d70610bf22b | pfalcon/pycopy | /tests/basics/subclass_native6.py | 183 | 3.609375 | 4 | # Calling native base class unbound method with subclass instance.
class mylist(list):
pass
l = mylist((1, 2, 3))
assert type(l) is mylist
print(l)
list.append(l, 4)
print(l)
|
5cba7fef05646ffa7a250172dd8cdc8501e56ce5 | python20180319howmework/homework | /caixiya/20180328/3.py | 449 | 3.921875 | 4 | '''
定义一个函数,计算给定的整型数是否为质数
'''
def isprime(num):
if num>=2:
for i in range(2,num//2+1):
if(num%i==0):
return False
else:
return True
else:
#print("{}是质数".format(num))
return True
else:
#print("{}不是质数".format(num))
return False
num=int(input("请输入一个整型数:"))
if isprime(num):
print("{}是质数".forma... |
7768e0c5d9296c50c9655c55ae15156fd582e614 | prabhatpal77/Complete-core-python- | /intplusstring.py | 151 | 3.53125 | 4 | #int+string
x="prabhatpal"
print(x)
y="python"
z="1234"
print(z)
p=1000
print(p)
print(x+y)
print(x+z)
print(x+str(p))
print(int(z)+p)
print(z+str(p))
|
39a96e86355a2a5b8ffdb2f26aed985b537810de | zelzhan/Challenges-and-contests | /Python-Hackerrank/polar-coordinates.py | 578 | 4 | 4 | '''You are given a complex . Your task is to convert it to polar coordinates.'''
import cmath
print(*cmath.polar(complex(input())), sep='\n')
# polar = [c for c in input() if c not in "+j"]
# indexes = [i for i in range(len(polar)) if polar[i] == '-']
# if len(polar) > 2:
# polar = map(int, [c for c in polar if c ... |
0e6fc731688307bd2e3581d8177327379c492f8d | rehman20/python | /python_sandbox_starter/files.py | 454 | 3.84375 | 4 | # Python has functions for creating, reading, updating, and deleting files.
myFile=open('name.txt','w')
print('Name of File: '+myFile.name)
print('Mode of Operation: '+myFile.mode)
myFile.write('My name is Rehman Aziz.\n')
myFile.write('I am 23 years old.')
myFile.close()
myFile=open('name.txt','a')
myFile.write('... |
9285766eedce90df6678f25e1fb766386403ac62 | divad417/sandbox | /kalman/kalman.py | 2,716 | 3.703125 | 4 | #!/usr/local/bin/python3
# Python class to implement a Kalman Filter
import numpy as np
import matplotlib.pyplot as plt
from random import random
from math import *
class kalman():
# Init assuming 2d problem with no control input or process noise
def __init__(self, t0, dx):
self.t = t0
# Me... |
67967e704ce17dad07f28ac5c292a817f57a1b18 | pbcquoc/coding-interview-python | /sort_algorithm/shell_sort.py | 535 | 3.765625 | 4 | def shell_sort(arr):
gap = len(arr)//2
while gap > 0:
i = 0
j = gap
while j < len(arr):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
i += 1
j += 1
print(i, j, gap)
k = i
while ... |
f4ad96f88f426ba8d4bca05205c06ae345c2bb6e | aadithpm/leetcode | /Sprint/SumOfRootToLeafBinaryTreeNumbers.py | 604 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumRootToLeaf(self, root: TreeNode) -> int:
self.bin_sum = 0
def dfs(node, res):
res += str(node... |
18d198e72ed9a132a5a1c428eafbffaa255c5465 | SomethingRandom0768/PythonBeginnerProgramming2021 | /Chapter 6 ( Dictionaries )/Exercises/6-11cities.py | 942 | 4.21875 | 4 | cities = {'Gaborone' : {
'Country' : 'Botswana',
'Population' : "208,411",
'Fact' : "Home to the world's largest concentration of African elephants",
},
'Vilnius' : {
'Country' : 'Lithuani... |
1054f40a28ddc711f1833161a1775be66902f415 | Datamine/Project-Euler | /Problems/006/solution.py | 286 | 3.5625 | 4 | #!/usr/bin/python3
def main():
sum_of_squares_accumulator = 0
for i in range(1,101):
sum_of_squares_accumulator += i**2
square_of_sum = sum(range(1,101)) ** 2
return abs(square_of_sum - sum_of_squares_accumulator)
if __name__=='__main__':
print(main())
|
6c26f91218caf24cef355f23c5cc4e7bbac725b3 | aijunbai/bandit | /python/bandit.py | 1,829 | 3.890625 | 4 | import random
class Arm:
"simulation of bendit's arm"
def __init__(self, average):
self.average = average
def pull(self):
"""returns the result (1/0)"""
if random.random() < self.average :
return 1
else:
return 0
def getAverage(self):
... |
244c83ce42b8870c6a3a9456e99c077057899196 | amete/MyAnalysis | /scripts/python_tools.py | 1,808 | 3.5 | 4 | #1/bin/bash/env python
import os
import glob
import re
def main():
print "Testing Tools"
directory_with_subdir = 'LOCAL_inputs_LFV'
directory_with_files = '/data/uclhc/uci/user/armstro1/SusyNt/analysis_n0232_run/scripts'
list_of_subdirectories = get_list_of_subdirectories(directory_with_subdir)
... |
58deb07656c17374fbe0136a45abd61ec7daa9f3 | CloudLouis/algorithm_python_implementation | /golden_section_search.py | 891 | 3.59375 | 4 | import math
def f_function(x):
res = (4*x*x*x) - (60*x*x) + 25*x - 7
return res
def golden_ratio(xu, xl):
res = ((math.sqrt(5)-1)/2)*(xu-xl)
return res
def golden_section_search(xu, xl):
d = golden_ratio(xu, xl)
print("\niteration ", v + 1)
print("d: ", d)
print("xl: ", xl)
pri... |
778390bb9e7055402c0d55bd63d14c4e2086a827 | soldierloko/Curso-em-Video | /Ex_44.py | 1,267 | 3.765625 | 4 | #Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento:
#A vista Dinheiro ou Cheque: 10% de Desconto
#A vista no cartão: 5% de Desconto
#2x No cartão: preço normal
#3x ou mais no cartão: 20% de juros
vProduto = float(input('Digite o valor do Produto... |
0278554da3e17273fcb004165b562ae18e917175 | huragok/LeetCode-Practce | /11 - Container With Most Water/cwmw.py | 669 | 3.6875 | 4 | #!/usr/bin/env python
class Solution:
# @return an integer
def maxArea(self, height):
n = len(height) # number of lines
l = 0
r = n - 1
v_max = 0
while l < r:
if height[l] > height[r]: # Right wall is the bottle neck, next left wall need not to be checked!
... |
90d0de828d589a37d170011af8e1a7ea07fcb6a3 | codio-content/Python_Maze-Algorithms_conditional_statements | /public/py/py-4.py | 170 | 3.5625 | 4 |
def keyPressedEvent(keyCode):
if keyCode == 'LEFT':
moveLeft()
elif keyCode == 'RIGHT':
moveRight()
else:
showMessage('Left or Right was NOT pressed')
|
1579d662365a8987ead4dbd7ea7d219571a645d2 | Abhishek-IOT/Data_Structures | /DATA_STRUCTURES/Array/SearchinBitonic.py | 1,846 | 4.125 | 4 | """
Search an Element in Bitonic Array.Bitonic Array is first increasing and then decreasing.
So we will find the Peak ELement and then we will divide the array and have binary search for increasing and decreasing array.
"""
def PeakELement(arr):
low=0
high=len(arr)-1
while(low<high):
mid=lo... |
ee58b369b6ae8dfc2781d34856ee3d2cde83c95a | kesch9/Alg_Data_Structur_Python_Homework | /lesson_2/task1.py | 1,626 | 3.609375 | 4 | # Написать программу, которая будет складывать, вычитать, умножать или делить два числа.
# Числа и знак операции вводятся пользователем. После выполнения вычисления программа
# не должна завершаться, а должна запрашивать новые данные для вычислений. Завершение
# программы должно выполняться при вводе символа '0' в каче... |
6d467b9feccb818394169ff03993f8d39140ae39 | NeilWangziyu/Leetcode_py | /asteroidCollision.py | 2,102 | 3.546875 | 4 | class Solution:
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
if not asteroids:
return []
keep = True
while(keep):
keep = False
new_star = []
i = 0
whil... |
2c062c5f5e7347202acfb5b1307ec72f76fd3586 | brandonharris177/Python-Practice | /scratch.py | 4,497 | 3.96875 | 4 | from room1 import Room
from player1 import Player
# Declare all the rooms
room = {
'outside': Room("Outside Cave Entrance",
"North of you, the cave mount beckons."),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""),
'overlook': Room("Gra... |
3c7c3d524b665ddb94be976967dbf98c42f2edae | lmhavrin/python-crash-course | /chapter-ten/f_num_rem.py | 1,027 | 3.890625 | 4 | # Exercise 10-12: Favorite Number Remembered
import json
def favorite_number():
"""Prompts for a users favorite number"""
while True:
f_number = input("What is your favorite number? ")
prompt = print("Enter q to quit.")
if f_number == "q":
break
else:
try... |
d4a4e09d895996a9ac41d84e8189977fc20ce4df | nguyenbienthuy/nguyenbienthuy.github.io | /mymodule/fun_assistant.py | 360 | 3.6875 | 4 | import datetime
def last_of_date(str_date):
yy = int(str_date[0:4])
mm = int(str_date[5:7])
dd = int(str_date[8:10])
day_str = datetime.date(yy, mm, dd) - datetime.timedelta(1)
last_day = day_str.strftime('%Y-%m-%d')
return last_day
def datetime_to_string(d):
if isinstance(d, datetim... |
5d201b1d2f594931d70420a6c8c3e881c3c32563 | democraciaconcodigos/election-2013 | /scripts/geocode.py | 2,213 | 3.65625 | 4 | #!/usr/bin/python
import csv
import json
import urllib2
"""
Convert CSV file with format:
"id","mesa_hasta","codigo_distrito","mesa_desde","codigo_postal","cant_mesas","direccion","seccion","circuito","localidad","distrito","establecimiento","dne_distrito_id","dne_seccion_id"
To output CSV file:
"Id","Lat","Lng"
... |
330c622e6fa9587bcdf1a5afb3465c836548f63d | avastjohn/Exercise01 | /numberguessing.py | 750 | 3.953125 | 4 | # greet player
# get player name
# choose random number between 1 and 100
# while True:
# get guess
# if guess is incorrect:
# give hint
# else:
# congratulate player
from random import randint
print "Greetings earthling! What's your name?"
name = raw_in... |
0ead23fbb45cdc7098a3be65b2b37ed1b6923b6e | alvina2912/CodePython | /datetime/datetimetest.py | 161 | 3.515625 | 4 | import datetime
import time
today = datetime.date.today()
print 'Today :', today
tomorrow= today+ datetime.timedelta(days=1)
print "Tomorrow :", tomorrow
|
97a176970992e0a13afe55b9c8d031bea0300962 | Marcus893/algos-collection | /array/EquiLeader.py | 1,633 | 3.84375 | 4 | A non-empty array A consisting of N integers is given.
The leader of this array is the value that occurs in more than half of the elements of A.
An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences A[0], A[1], ..., A[S]
and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value.
For exam... |
9a63bc8e6109ae259b9a785537efe235b581ddda | redteamcaliber/csaw_ctf_2014 | /code/crypto200-stage2.py | 1,225 | 3.5 | 4 | #!/usr/bin/env python
from math import floor
from sys import argv, exit
def decode(myStr):
strLen = len(myStr)
max = strLen / 2
if max < 3:
max = 30
for key in range(2,max):
rows = list()
counter = 0
i = 0
last = 0
leftover = strLen % key #num of rows with one extra character
minNum = int(floor(floa... |
6d059568493bb2fd3f59df930e2aafc78956d6a9 | amandaserex/dimensionality_reduction | /main | 2,765 | 3.546875 | 4 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
#import scipy
def read_data(path):
"""
Read the input file and store it in data_set.
DO NOT CHANGE SIGNATURE OF THIS FUNCTION
Args:
path: path to the dataset
Returns:
data_set: n_samples x n_features
... |
f4a1015421794cf5dee9a9ad0243bdb4b74486f9 | white3/Python-Exercise-Code | /test22.py | 2,909 | 3.984375 | 4 | # coding=utf-8
# 字符串组合问题
# 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符
# 例如:
# 打印排列 permutation 情况: "abc" "acb" "bac" "bca" "cab" "cba"
# 23.字符串全排列问题
def swap(arr, i, j): arr[i],arr[j]=arr[j],arr[i]
def permutationStr(str):
result = []
def permutationDao(chars, begin):
if begin==len(chars):result.append(''.join(char... |
08f236bec5014f763c6b58d039a42921e054b27f | vicch/leetcode | /0100-0199/0128-longest-consecutive-sequence/0128-longest-consecutive-sequence-2.py | 939 | 3.96875 | 4 | """
The key is a performant way to check for a certain number's existence in the list, which can be achieved with hash map.
By knowing if a number exists, we can try to extend the incrementing sequence from each number in the list:
- If x exists, check if x + 1 exists.
- Stop when the next value doesn't exist, then the... |
083fe636adece4b26e72fc92d2d831a0522d388b | vavronet/python-for-beginners | /functions/examples/example_3.py | 110 | 3.5 | 4 | def volume_of_square_prism(s, h):
volume = (s * s * h) / 3
print(volume)
volume_of_square_prism(6, 3) |
f1189b1234b1520aa7fa3f89e9b7575cd604c2c0 | ohsean93/algo | /08월/08_30/4579.py | 465 | 3.578125 | 4 | import sys
sys.stdin = open("input.txt", "r")
T = int(input())
for test_case in range(T):
str_origin = input()
ans = 'Exist'
if '*' in str_origin:
str_list = str_origin.split('*')
a, b = str_list[0], str_list[-1]
n = min(len(a), len(b))
if a[:n] != b[::-1][:n]:
... |
f4aea76e38c99e8e647d01c893bbb566170ad32c | dwardu89/learning-python-programming | /Sorting/Sorter.py | 1,244 | 4.34375 | 4 | __author__ = 'edwardvella'
def bubble_sort(arr):
"""
Performs a bubble sort algorithm.
:param arr: an unsorted array
:return: a sorted array
"""
arr_len = len(arr)
swaps = True
while swaps:
swaps = False
for i in range(0, arr_len - 1):
if arr[i] > arr[i + 1]... |
bbf253b5e70d1fd850be0a81871c96464d229d0c | jay3393/ShopAlert | /display.py | 650 | 3.546875 | 4 | '''
Module to display information on console
'''
class Display:
def __init__(self):
self.console_log = ""
def generate_console_log(self, name, price, url, store):
self.console_log += "==================================================\n"
self.console_log += (f'Product >> {name}\n')
... |
4444f1a7d70a239aac7794c8bf26e547262d40c5 | Jimmycheong/Simple-Calculator | /Backup/backup1.py | 8,209 | 3.53125 | 4 | from tkinter import *
from tkinter import ttk
class MyCalculator:
def __init__(self, master):
master.title("Jimmy's calculator")
master.geometry('240x305+200+50')
master.resizable(False, False)
#WIDGET CREATION
self.entry = Entry(master, width = 15, font = ('Arial', 24), justify = RIGHT)
sel... |
7e12512fc0bd2d604c10bef61f67e6042b1ed405 | guzelsafiullina/final | /angle.py | 1,172 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
class angle:
def __init__(self, degrees = 0, minutes = 0, direction = 'W'):
self.degrees = degrees
self.minutes = minutes
self.direction = direction
def __str__(self):
return str(self.degrees) + u'\N{DEGREE SIGN}' + str(s... |
fc880227af27e3bc85318559ddbd2cc7deaf13e4 | fujunguo/learning_python | /The_last_week_in_Dec_2017/func_partial.py | 555 | 3.953125 | 4 | # 1.对数字字符串进行进制转换
import functools
int2 = functools.partial(int, base=2)
print(int2("1000000"))
print(int2("1000000", base=10))
print(int2("1010101"))
# 创建偏函数时,实际上可以接收函数对象、*args和**kw这3个参数,当传入:
# int2 = functools.partial(int, base=2)
# 实际上固定了int()函数的关键字参数base,也就是:
# int2('10010')
# 相当于:
# kw = { 'base': 2 }
# int('1001... |
54bf2f7b240e5f0d1bc5910bf2c8658913bb9d18 | Moziofmoon/algorithm-python | /Week_07/208-tire-tree.py | 1,190 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/6/1 9:54
# @Author : edgar
# @FileName: 208-tire-tree.py
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.dic = {}
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
... |
31065a668e97d8d0dae7fe68d27bffbc7559814c | DanieleMagalhaes/Exercicios-Python | /Mundo3/Listas/listaComposta_Peso.py | 950 | 3.515625 | 4 | cadastro = []
dado = []
maior = menor = 0
print('='*60)
while True:
dado.append(str(input('Nome: ')))
dado.append(int(input('Peso: ')))
if len(cadastro) == 0:
maior = menor = dado[1]
else:
if dado[1] > maior:
maior = dado[1]
if dado[1] < menor:
menor = dad... |
ca02c7fd9e2bce5f22a9088b892ae2543f1ba999 | LittleMinWu/MLprojects | /week4/funcfile.py | 974 | 3.78125 | 4 | import matplotlib.pyplot as plt
import sympy as sp
#plot the data
from matplotlib.ticker import MultipleLocator
"""when y’s value equals 1 color is “red” ,else “green”, and set the x axis as ‘x_1’ ,
set the y axis as ‘x_2’ , because on the plot the x-axis is the value of parameter ‘x1 ’,
the y-axis is the value of th... |
aa8801a0f2c6b87b406fb4420feca4497a5717ae | svanan77/udacity-ud120-machine-learning | /ud120-projects/datasets_questions/explore_enron_data.py | 2,434 | 3.578125 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
3d8ac32b9c17cb98ae409adc8bb706357897ad83 | AndrewDPena/Monopoly | /Deck.py | 1,752 | 3.765625 | 4 | import random
import unittest
class Deck(object):
class Card(object):
def __init__(self, name, value, effect):
self.name = name
self.value = value
self.effect = effect
def __str__(self):
return str(self.name)
def __init__(self, file=None):
... |
9f333128debc4cc7d52f17e9fb30946fdfa277be | waleOkare/PythonGames | /PY GAME - TICTAETOE.py | 4,304 | 3.796875 | 4 |
from IPython.display import clear_output
def display_board(board):
clear_output()
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
p... |
b951115b13d536bda7871244df0ae79c07846cfc | Abdur15/100-Days-of-Code | /Day_003/Challenge 9 - BMI _2.0.py | 1,432 | 4.8125 | 5 | ## BMI Calculator 2.0
# Instructions
# Write a program that interprets the Body Mass Index (BMI) based on a user's weight and height.
# It should tell them the interpretation of their BMI based on the BMI value.
# - Under 18.5 they are underweight
#- Over 18.5 but below 25 they have a normal weight
# - Over 25 but ... |
0a823e363af62a6a44546cae00915645a7d1a9a8 | vosergey/python3_btree_traversal | /LevelorderTraversal.py | 1,028 | 3.828125 | 4 | import collections
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def iterativelyLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
queue = ... |
b33abc5f4ebc1fd874f624343beeb28b5e1fb3d4 | leeo1116/PyCharm | /Algorithms/leetcode/051_N_queens.py | 684 | 3.6875 | 4 | __author__ = 'Liang Li'
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
queen_stack, solution = [[(0, i) for i in range(n)]], []
while queen_stack:
board = queen_stack.pop()
row = len(board)
... |
a416f19e358afa1633dc643a2b4bacf27cb38fb7 | jtlai0921/MP31909_Example | /MP31909_Example/範例/RPi/EX2_8.py | 974 | 3.71875 | 4 | # Homework 2-8
class property():
def __init__(self, name, value):
self.__name = name
self.__value = value
def getName(self):
return self.__name
def getValue(self):
return self.__value
class house(property):
def __init__(self, name, value, ownerName, address):
supe... |
afe37cabf0d7d0de27d5fb12d106e32caa4d64e0 | zanuarts/100DaysCodeChallenge | /Day003/Day003.py | 178 | 3.78125 | 4 | # We need a function that can transform a number into a string.
# What ways of achieving this do you know?
def number_to_string(num):
return str(num)
number_to_string(67)
|
81b6f7178074965575e96d8c9c0fe8469c21f8aa | eovallea3786/While | /menor_elemento.py | 383 | 3.71875 | 4 | def menor_elemento(vector):
'''
Funcion que define cual es el mayor elemento del vector
list of num -> num
>>> menor_elemento([1,2,3])
1
>>> menor_elemento([4,5,6])
4
:param vector: Vector a calcular el mayor elemento
:return: El elemento mayor del vector
'''
menor = min(... |
58be6f12fa5d8b522649b3b703455f356601b895 | MJ-K-18/Python | /python 2일차 실습 답/training2_2.py | 877 | 3.84375 | 4 | '''
training2_2.py
Python 2일차 실습 #2
2. 10개의 정수를 입력받아 양수 개수, 음수 개수, 양수일 때 짝수 개수, 홀수 개수
출력 되는 프로그램
'''
positive = 0
negative = 0
even = 0
odd = 0
error = 0
for i in range( 1, 11, 1 ):
number = int( input( '{0:3} 번째 정수 입력 : '.format( i ) ) )
if number != 0:
if number > 0:
... |
c97327498686b4fc8025c73d5542e3ad8ae5ccb5 | filipo18/-uwcisak-filip-unit3 | /Inventoryproject/userpractise.py | 587 | 3.71875 | 4 | # Create bank info
customer1 = {'FirstName': 'Filip', 'LastName': 'Keitaro', 'AccNumber': '00001', 'PinNumber': '1119', 'Balance': 5, 'Age': 18, 'Contact': 'filip@keitaro.jp'}
def depoist(customerdict, amount):
# This function deposits amount in the customer dict
customerdict['Balance'] += amount
... |
b038d4390e7a90f23680ca6af745f7bd74dcd310 | georgeteo/Coding_Interview_Practice | /chapter_4/4.4.py | 1,178 | 4.1875 | 4 | '''
CCC 4.4: Design an algorithm that turns a binary tree into a linked list by level
'''
from binary_tree import binary_tree
def make_linked_list(bt):
'''
BFS:
Time Complexity: O(V + E)
Space Complexity: O(V)
traversal_queue is a queue represented by a list
linked_lists is a list of linked li... |
a9db289ca835732ebb735d15d2371a87009e948f | sansbacon/pangadfs | /pangadfs/misc.py | 2,817 | 3.828125 | 4 | # pangadfs/pangadfs/misc.py
# -*- coding: utf-8 -*-
# Copyright (C) 2020 Eric Truett
# Licensed under the MIT License
from typing import Dict, Iterable, Tuple
import numpy as np
def diversity(population: np.ndarray) -> np.ndarray:
"""Calculates diversity of lineups
Args:
population (np.ndarray):... |
a52eb026b29d7e42d99d3303c65253230938eecd | ZhongruiNing/ProjectEuler | /Code of ProjectEuler/problem25.py | 420 | 4.0625 | 4 | def Fibonacci(num):
if num == 1 or num == 2:
return 1
else:
Fibo.append(Fibo[-1] + Fibo[-2])
return Fibo[-1]
def length(num):
return len(str(num))
Fibo = [1, 1]
i = 1
threshold = 1000
while True:
if length(Fibonacci(i)) >= threshold:
print(str(i) + " is... |
5093793c8b9b00b9aa73e2cf1857f3dd064d1c04 | hanfang302/py- | /python基础/复习.py/列表乘方.py | 185 | 4 | 4 | #number = []
#for value in range(1,11):
#num = value**2
#number.append(num)
#print(number)
number = []
for value in range(1,11):
number.append(value**2)
print(number)
|
f3592702be4876e54dc1604914ece01d38ac3854 | easternpillar/AlgorithmTraining | /SW Expert Academy/D3/보충학습과 평균.py | 402 | 3.828125 | 4 | # Problem:
# When you convert a score less than 40 to 40, print the average score.
# My Solution:
answer = []
for i in range(int(input())):
score = list(map(int, input().split()))
cnt = 0
for j in range(len(score)):
if score[j] < 40:
score[j] = 40
answer.append(sum(score) // len(s... |
4ecb65bfbce961768be17c44e73859d3329e4e4e | k-schmidt/Project_Euler | /Python/P016.py | 345 | 3.921875 | 4 | def compute_exponent_base_two(exp):
return 2 ** exp
def int_to_string(integer):
return str(integer)
def main(exp):
exponent = compute_exponent_base_two(exp)
string_int = int_to_string(exponent)
result = 0
for i in string_int:
result += int(i)
return result
if __name__ == "__main__... |
a1734b0cc09efac3275c594b3a04af1e4bd76619 | micriver/leetcode-solutions | /1480-RunningSum.py | 1,444 | 4.25 | 4 | """
Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
at first index, add the lone index, at second index,... |
ac50a7d9324ae10a1294e21492687f3e63493569 | hhllbao93/Interactive-program-in-pyhon | /Guess the number.py | 1,965 | 4.125 | 4 | # input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
import math
num_range = 100
n = 7
# helper function to start and restart the game
def new_game():
global num_range, n, secret_number
if num_range == 100:
n = 7
... |
c20acc9dafa582630a32127a373af08a383a4512 | CAgAG/Arithmetic_PY | /基本数学运算/实现异或.py | 362 | 3.796875 | 4 | def XOR(x, y):
res = 0
i = 32 - 1
while i >= 0:
# 获取当前bit值
b1 = (x & (1 << i)) > 0
b2 = (y & (1 << i)) > 0
if b1 == b2:
xoredBit = 0
else:
xoredBit = 1
res <<= 1
res |= xoredBit
i -= 1
return res
if __name__ == '... |
a2b318691ae6db644a4f36fcc3e6652fe1734027 | sankeerth/Practice | /leet_code/is_symmetric.py | 2,322 | 3.671875 | 4 | class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return 'TreeNode({})'.format(self.val)
def deserialize(string):
if string == '{}':
return None
nodes = [None if val == 'null' ... |
4bdb02fa6d55d67938158812efee89fa7c24c875 | SeiteAlexMH/pyhton-stuff | /randomtree.py | 823 | 4.1875 | 4 | #randomtree.py
#Alexandre Seite
import turtle as t
import random
def drawTree(levels, len, angle,shrink):
# draw the tree starting basic value then randomizes from them
if levels > 0:
if levels<=3:
t.color(0,1,0)
else:
t.color("brown")
... |
1db036fc5e416362efcbb9214d3a443540330bd4 | CJRicciardi/cs-module-project-hash-tables | /applications/histo/trial.py | 135 | 3.515625 | 4 | # words = ['fuck', 'this', 'couch']
# for i in range(len(words)):
# print(f"{words[i]:{10}}: #####")
x = '#'
y = '##'
print(x+y) |
da99769c39db7af9d98e5aa9368979c62373c45f | j-hmd/daily-python | /Object-Oriented-Python/magic_call.py | 632 | 3.953125 | 4 | # Calling an object as if it were a funciton
class Book:
def __init__(self, title, author, price):
super().__init__()
self.title = title
self.author = author
self.price = price
def __str__(self):
return f"{self.title} by {self.author}, costs {self.price}"
def __cal... |
346d119edb229681dd900bd8005df913ac4327ff | andprogrammer/crackingTheCodingInterview | /python/chapter3/4/solution.py | 799 | 4.0625 | 4 | class MyQueue(object):
def __init__(self):
self.stack = []
def push(self, elem):
self.stack.append(elem)
def pop(self):
if self.is_empty():
raise Exception('Queue is empty')
del self.stack[-1]
def top(self):
if self.is_empty():
raise Exc... |
f0b07dfa02cfd9b71bf3539dc89ea179bc559474 | decimozack/coding_practices | /leetcode/python/regular_expression_match_recursion.py | 1,171 | 4.09375 | 4 | # https://leetcode.com/problems/regular-expression-matching/
class Solution:
def isMatch(self, s: str, p: str) -> bool:
# if pattern is empty but str is not, the str does not match the pattern
if not p:
return not s
# first we check if str is empty. if it is em... |
779d7c501cb77ec677544e80cc5fb376313f6838 | ThenuVijay/workout1-python | /neon.py | 244 | 4 | 4 | # neon number---->9^2=81-->8+1=9
num=int(input("Enter num: "))
sqr=num**2
total=0
#print(sqr)
while sqr>0:
total=total+sqr%10
sqr=sqr//10
#print(total)
if num==total:
print("Neon number")
else:
print("Non Neon Number")
|
185b57b73ef074c85d6bc1e51c3d56d9da50a17b | Srikumar-R/Sri | /55pl.py | 84 | 3.703125 | 4 | a,b=input().split()
if a.lower()==b.lower():
print("yes")
else:
print("no")
|
6eb79b031b500f4f8b4e377b9df3448f400b91a9 | romanpitak-classroom/all-possible-products-of-a-list-of-primes-lucyb1 | /hw_1.py | 684 | 3.984375 | 4 |
# 1st try: cycle inside a cycle ... inside definition of course
my_input_numbers_1 = [2, 3, 5, 11]
print my_input_numbers_1
def products(primes):
my_output_1 = []
for i in range(len(primes)):
x = primes[i]
if x not in my_output_1:
my_output_1.append(x)
self_const = 1
... |
f634c644bedbe5d356fc3a23ed3a37ad05b5915e | maheshde791/python_samples | /pythonsamples/thread1.py | 375 | 3.96875 | 4 | #! usr/bin/python
import time
from threading import Thread
def printer():
for num in range(3):
print("hello",num)
time.sleep(1)
thread1 = Thread(target=printer)
thread1.start()
thread2 = Thread(target=printer)
thread2.start()
threads = []
threads.append(thread1)
threads.append(thread2)
for t in ... |
513a493ed2bc3aacc39ee9065835c9b6a3aa83f2 | yangjinke1118/createmath | /maths.py | 5,362 | 3.578125 | 4 | """
本模块实现各种数学算术题型
1、竖式100以内加减法,进位、借位;逆向思维
2、横式100以内加减法,进位、借位,逆向思维
3、个位乘法,十位数除法。
"""
from random import randint
def get_ab_cd(ab_max, cd_max):
ab = 0
cd = 0
# 获取符合要求的ab数值
if ab_max > 9 and ab_max <= 99: # 当ab最大值大于9
ab = randint(0, ab_max)
while ab <= 9:
ab = randint(0, ab_ma... |
037fefbffd79817866209230c72ac28080e63724 | Thibautguerin/EpitechMaths | /202unsold_2018/202unsold | 4,004 | 3.609375 | 4 | #!/usr/bin/python3
from __future__ import print_function
from math import *
import re
import sys
def marginal():
a = int(sys.argv[1])
b = int(sys.argv[2])
x = 10
y = 10
calcul = float(0)
total = 0
tab = []
i = int(0)
divisor = (5 * a - 150) * (5 * b - 150)
x_total = []
print("-----------------------------... |
ff4d54cfd96fbcf0ab01cd7bd7d7961f3beec7cb | SozinM/PTests | /test_dict.py | 862 | 3.734375 | 4 |
class FormattedDict(dict):
def __str__(self):
print self.items()
string = ''
for key, value in self.items():
tmpstr = ''
if isinstance(value,dict):
string += '%s:\n' % (tmpstr + key)
while(isinstance(value,dict)):#thing to b... |
1231b4dd5be7294016746cff95eaa9c1ed1d60e4 | zainllw0w/skillbox | /lessons 20/HomeWork/task9.py | 1,734 | 3.78125 | 4 | def sort(data, time):
tt = False
ft = True
st = False
is_find = True
winers_name = set()
index = 0
while is_find:
index += 1
for key, values in data.items():
if time[0 - index] == int(values[1]) and ft and values[0] not in winers_name:
first_id = k... |
92effa71c7d4c5c8b9c8ab392cbaa838780d1567 | hamzaharoon1314/Python-Basics-Beginner | /Class #2/basics.py | 280 | 3.625 | 4 | # indentation
if True:
print 'hello'
print 'HaMza'
# commenting
# single-line comment
"""
line 1
line 2
line 3
"""
# variables
name = 'engineer man'
# multi-line
num1 = 5; num2 = 8
# continuance
long_name = \
"something" + \
"something else"
# printing
print 'hello world',
|
bc84b117291f514b88bd69bd7c83fe09bea4cf81 | maurusian/sudoku | /draw.py | 5,585 | 3.6875 | 4 | import turtle
import os
from datetime import datetime
#size of the square side
SQUARE_SIDE = 75
DEF_WINDOW_SIZE_X = 1000
DEF_WINDOW_SIZE_Y = 800
#display coordinate corrections for numbers
#these were obtained by trial and error on
#multiple board sizes
CORRX = 25
CORRY = 60
class Drawing():
"""
Class that ... |
2a726249bfa813c7f984cb9002e79b19eba0e272 | nikola825/pp1_projekat | /block_ciphers/algorithms/aes256.py | 581 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 13 20:29:47 2016
@author: bulse_eye
"""
import aes128
BLOCK_SIZE = 16
def generate_key(key):
valid_key = ''
for i in range(8):
if len(key) < 4:
key = key + ' ' * (4 - len(key))
valid_key += key[:4]
key = key[4:]
return va... |
26ed90b458ae9633c430eba0ccc09fcb8a3be511 | vedant1551/111_VedantRajyaguru | /index.py | 986 | 3.71875 | 4 | import nltk # Python library for NLP
from nltk.corpus import twitter_samples # sample Twitter dataset from NLTK
import matplotlib.pyplot as plt # library for visualization
import random # pseudo-random number generator
#downloads sample twitter dataset.
nltk.download('twitter_samples')
# select the set of positive and... |
8b666724caa105b60f8e04a621a49f6269f94873 | OmarCamaHuara/RecodePro2020 | /Aulas/7_PYTHON/tuplas.py | 406 | 3.71875 | 4 | # Formato de declaracao de uma Tupla
carros = ("KA", "HB20", "Kwid", "Onix", "UP", "Mobi")
# EStrutura de tratamento de execao
# (se o que esta dentro de Try trouxe algum erro e retornado o Exception)
try:
carros[0] = "Fiesta"
except:
print("Nao e possivel efectuar alteracoes em tuplas")
# Imressao de Tuplas... |
268f348a920fa28b23b4e996ba5376c4d656e0da | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_200/5371.py | 564 | 3.828125 | 4 |
def is_tidy(number):
number = list(str(number))
for i in range(0, len(number)-1):
if number[i] > number[i+1]:
return False
return True
def solve(lnumber):
temp_tidy = lnumber
for number in range(1,lnumber+1):
if is_tidy(number):
temp_tidy = number
return temp_tidy
if __name__ == "__main__":
t =... |
82d3e8b10d0dd2f32a003f16631e06960002f0eb | rgbbatista/python-iniciante-udemy | /python avançado função enumerate.py | 401 | 4.21875 | 4 | #Função enumerate
'''navegar por uma lista e obter ao mesmo tempo que
imprime nomes queira imprimir o índice de cada
elementos normalmente usando a função renge e len '''
lista = ['abacate', 'bola', 'cachorro']
for i in range(len(lista)):
print(i,lista[1])
print()
'''Usando a função Enumerate'''
print('Usando a... |
3457127afa1105c0ac0450730974d1732d0d04d7 | JanNoszczyk/CountMeUp | /count_me_up.py | 1,818 | 4.28125 | 4 | import queue
class CountMeUp:
"""
CountMeUp creates a FIFO queue to store all the votes. It also has methods to add new votes to the queue and to
display the current vote statistics.
CountMeUp will also track the total number of votes per candidate and the number of votes done per each user using
hashmaps s... |
7b9e9ec8833d472e27407026003fc2323471dbbc | alcebytes/Phyton-Estudo | /04_estruturas_de_repeticao/01_laco_while.py | 422 | 3.96875 | 4 | senha = "54321"
leitura = " "
while (leitura != senha):
leitura = input("Digite a senha: ")
if leitura == senha:
print('Acesso liberado')
else:
print('Senha incorreta. Tente novamente')
contador = 0
somador = 0
while contador < 5:
contador = contador + 1
valor = float(input('Digi... |
b007eb134646483b0f18951ac8391fc6f2e01104 | Jaires/advent | /day10.py | 4,599 | 3.5625 | 4 | #!/usr/bin/python
# coding=utf8
from adventOfCode import AdventWithFile
import re
from abc import ABCMeta, abstractmethod
class Robot:
def __init__(self, microchip, botNumber):
if not isinstance(microchip, list):
microchip = [microchip]
self.microchip = microchip or []
self.botNumber = botNumb... |
d3a445f556bf826cd7f5f28691d8695be58d11c3 | Bubliks/bmstu_Python | /sem_1/RK_3 - Matrix/First.py | 1,515 | 3.6875 | 4 | from math import *
from random import *
M = int(input("Длина Строки: "))
N = int(input("Длина Столбца: "))
X =[]
B=[]
G=[]
mas=[]
h=0;h1=N-1
for i in range(N):
X.append([])
for j in range(M):
X[i].append(float(input()))
print("Исходная Матрица")
for i in range(N):
for j in range(M):
print(... |
17a626eccc9b85bd0c4b816b5501b286edc9569b | MilaShar/String-Operations | /UEFA Euro 1988 Final part 02.py | 663 | 3.8125 | 4 | #assignment 1
player = "Frank Rijkaard"
#assignmnet 2
first_name = player[:5]
print (first_name)
#assignment 3
last_name = player [5:]
#print (last_name)
print (len(last_name))
#assignment 4
name_short = (first_name[0] + "." + "" + last_name)
print (name_short)
#assignment 5
chant = "Rijkaard!"
le... |
685ed3e39f353be9b9d72d37a11187c8802e2dba | ltltlt/algorithms | /algorithms/eight-queen/iter.py | 726 | 3.734375 | 4 | '''
> File Name: iter.py
> Author: ty-l
> Mail: liuty196888@gmail.com
'''
import itertools
NUM = 8
num = 0
not_print = True
def print_board(arglist):
global num
num += 1
if not_print:
return
for pos in arglist:
print('_ ' * pos + '@ ' + (NUM - pos -1) * '_ ')
print()
def chec... |
914ac4741f44c2715dc12ccc354bf18a9a3a869a | MailsonFelipe/Brincando_Com_Python | /Quest08.py | 328 | 4.03125 | 4 | # Autor: Mailson Felipe
# Data: 26/03/2021
def quantosNumeros(digito):
qtd = 0
valor = 1
while valor <= digito:
valor *= 10
qtd += 1
print("Quantidade de digitos: "+str(qtd))
def main():
digito = int(input("Digite um numero: "))
quantosNumeros(digito)
if __name__ == "__ma... |
a797f07c59e3e72c2c922e4da6679a9f461c94a4 | Ismile-Hossain/Python_Codes | /27_Exercise01.py | 688 | 4.25 | 4 | """
Write a program with an infinite loop and a list of numbers.
Each time through the loop the program should ask the user
to guess a number (or type q to quit).If they type q,
the program should end. Otherwise,it should tell them
whether or not they successfully guessed a number in the list or not.
"""
numbers... |
3ad0a6b1d17649a37d8b309ae3ff6484787bef9e | estakaad/goodreads-stats | /stats.py | 5,431 | 4 | 4 | from datetime import datetime
import sys
import calendar
# Returns the book that took the longest to read in the given year. It doesn't
# necessarily mean that the user started reading the book the same year it
# was finished. If the date of starting a book or finishing it unknown,
# the book is skipped.
def book_rea... |
8d28557fa8a5d40ea28d4c9b985db6723d0d9504 | zhch-sun/leetcode_szc | /94.binary-tree-inorder-traversal.py | 3,041 | 3.703125 | 4 | #
# @lc app=leetcode id=94 lang=python
#
# [94] Binary Tree Inorder Traversal
#
def listToTree(input):
if not input:
return None
root = TreeNode(int(input[0]))
nodeQueue = [root] # 最后这个包含所有node
front = 0 # to index queue
index = 1 # to index list
while index < len(input):
nod... |
e14a5adb055e33d7a0f0b131fe3897d200c2a489 | ganhan999/ForLeetcode | /504、七进制数.py | 435 | 3.65625 | 4 | """
给定一个整数,将其转化为7进制,并以字符串形式输出。
示例 1:
输入: 100
输出: "202"
示例 2:
输入: -7
输出: "-10"
"""
"""
递归
"""
#大神做法1
class Solution:
def convertToBase7(self, num: int) -> str:
if num < 0:
return "-" + self.convertToBase7(-num)
if num < 7:
return str(num)
return self.convertToBase... |
acfbf58bdae6ebf704861b94d485a502c1d0e94a | SercanSB/PYCHARM | /Listeye Eleman Ekleme Çıkarma Silme vs.py | 300 | 3.671875 | 4 | sesliHarfler=["a","e","ı","i"]
print(sesliHarfler)
sesliHarfler += ["ö","o"]
print(sesliHarfler)
sesliHarfler.append("U")
print(sesliHarfler)
sesliHarfler[1:3]=("Ü")
print(sesliHarfler)
sesliHarfler[:1]=("")
print(sesliHarfler)
sesliHarfler.clear()
print(sesliHarfler)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.