blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
44408436b8299a52ca3c8849b70e6b81fca2b066 | woongsup123/jigsaw-solver | /node.py | 1,799 | 3.65625 | 4 | class Node:
def __init__(self, node_number):
self.rotate_sum = 0
self.directions = [-1, -1, -1, -1]
self.location = [False, False, False, False] # NE, SE, SW, NW
self.node_number = node_number
def print_node(self):
print(self.directions)
print(self.rotate_sum)
... |
7635fb1160dd0e034e84c1f6610b496705f90ede | chenyang929/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python-Notes | /04 递归/to_str.py | 264 | 3.578125 | 4 | # to_str.py
def to_str(n, base):
cover_str = '0123456789ABCDEF'
if n < base:
return cover_str[n]
else:
return to_str(n//base, base) + cover_str[n%base]
if __name__ == '__main__':
print(to_str(20, 8))
print(to_str(10 ,2))
|
0404323c3a9a60789a53571afc4750d3ad6d93c7 | kailunfan/lcode | /107.二叉树的层次遍历-ii.py | 1,424 | 3.921875 | 4 | #
# @lc app=leetcode.cn id=107 lang=python
#
# [107] 二叉树的层次遍历 II
#
# https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/description/
#
# algorithms
# Easy (64.90%)
# Likes: 235
# Dislikes: 0
# Total Accepted: 58.7K
# Total Submissions: 89.6K
# Testcase Example: '[3,9,20,null,null,15,7]'
#
# 给定... |
a2f855aa29da3b4b8e4a36b44e714f3924b66eab | droconnel22/QuestionSet_Python | /leet_code/hash_maps/anagram.py | 2,044 | 4.3125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
"""
Two words are anagram of one another if their letters can be
re-arranged to form the other word.
In this challenge you will be given a string.
YOu must split it into two contigous substrings, then
determine the minimum number of characters ... |
ddae4cf870ada38f5688099a4d2cabd4921fe8cf | xent3/Python | /Ödev1/Ödev_8.py | 635 | 4.21875 | 4 | """
Kullanıcıdan aldığınız bir sayının "Armstrong" sayısı olup olmadığını bulmaya çalışın.
Örnek olarak, Bir sayı eğer 4 basamaklı ise ve oluşturan rakamlardan herbirinin 4. kuvvetinin toplamı( 3 basamaklı sayılar için 3.kuvveti ) o sayıya eşitse bu sayıya "Armstrong" sayısı denir.
Örnek olarak : 1634 = 1^4 + 6^4 + ... |
d6b9df9369de4bdfa9159e410451e614b48a23c8 | Beomsudev/Git | /DAY10/P1/02_arrayDimShape.py | 846 | 3.71875 | 4 | # 02_arrayDimShape.py
# 배열의 크기(dimension)와 형상(shape)
import numpy as np
# ndarray : n(정수) d(차원) array(행렬/배열)
data = np.array([[1,2,3], [4,5,6]])
data2 = np.array([[1,2,3], [4,5,6], [7,8,9]])
print(type(data))
print('rank(차원) : ', data.ndim) # ndim 속성 이라고함
print('형상 : ', data.shape) # shape 속성
print('몇... |
1112a4063c80da87ac644f33943ae62177281c04 | projeto-de-algoritmos/PD_01Knapsack | /knapsack.py | 874 | 3.65625 | 4 | # -*- coding: utf-8 -*-
def knapSack(W, wt, val, n):
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
for i in range(n + 1):
for w in range(W + 1):
if i == 0 or w == 0:
K[i][w] = 0
elif wt[i-1] <= w:
K[i][w] = max(val[i-1] + K[i-1][w... |
80577190a80a442882851864dd12fde02219bb10 | TEAMLAB-Lecture/basic-math-ebbunnim | /basic_math.py | 440 | 3.625 | 4 | def get_greatest(number_list):
return max(number_list)
def get_smallest(number_list):
return min(number_list)
def get_mean(number_list):
return sum(number_list)/len(number_list)
def get_median(number_list):
number_list.sort()
l=len(number_list)
if l%2:
return number_list[l//2]
... |
479fcc95db51207baff93d75463111bdb204866e | gcolson11/Capstone_Books | /collaborative_filtering.py | 14,063 | 3.6875 | 4 | # Code for building the book recommendation system and Web App
import pandas as pd
import numpy as np
from math import sqrt
from statistics import pstdev
import random
import streamlit as st
ratings_file = 'Data/ratings_cleaned.csv'
books_file = 'Data/books_cleaned.csv'
#ratings_file = '/Users/gregoryolson/Documents/... |
26614f5cbe266818c5f34b536b9f921c922a18d2 | WSMathias/crypto-cli-trader | /innum.py | 2,012 | 4.5625 | 5 | """
This file contains functions to process user input.
"""
# return integer user input
class Input:
"""
This class provides methods to process user input
"""
def get_int(self, message='Enter your number: ', default=0, warning=''):
"""
Accepts only integers
"""
hasInputN... |
d9501dc4070b15277b7742828329f656887c9199 | IBordfeld/ToDoList | /ToDoList.py | 2,228 | 4 | 4 | # Isaac Bordfeld and Karley Conroy
# ToDoList
class ToDoList:
def __init__(self):
self.ToDo = {}
self.OpenList()
# function used to add a new list in the program
def addParentList(self, ListName):
self.ToDo[ListName] = list()
# function used to remove a list from a program
... |
b55508a6427a7646b6397e3e9a7e5a4c686658c7 | chandramohank/Logical-Programes | /Python/findthesecondlowest.py | 371 | 3.75 | 4 |
import sys
def findtheSecondLowest(inputarray):
first,second=sys.maxsize ,sys.maxsize
for i in range(0,len(inputarray)):
if inputarray[i] < first:
second=first
first=inputarray[i]
elif inputarray[i]<second and inputarray[i]!=first:
second=inputarray[i]
... |
a738bb798113738fe937e80c71d20eae2ce194fb | cmwright12/QED-promoter_prediction | /Python/Sample_scripts/sample_script.py | 757 | 4.40625 | 4 | # defining variables
#x = 40
#city = "Jackson"
#fruits = ["fruits", 8, "abc", x]
#print(x)
#print(city)
#print(fruits)
# lists versus sets
#mylist = [1, 2, 2, 7, 3, 8, 2, 7]
#print(mylist)
#print(len(mylist))
#print(type(mylist))
#myset = set(mylist)
#print(myset)
#print(len(myset))
#print(type(myset))
# Playing with... |
ef4c4b85636ff0aaeb1475e9b3da912949ad6996 | Vijf/blockathon | /var/PyBlockchain-master/PyBlockchain/baseblock.py | 1,644 | 3.5 | 4 | """Base classes for all objects."""
from hashlib import sha256
class BaseBlock(object):
"""base block"""
@staticmethod
def calculate_hash_block(unverified_block):
"""
a nonce "seals" a block to the blockchain.
parameters
----------
unverified_block : Block object... |
a9aeb4a7acb0524aa03d249d039bfc27e5f658ce | franciscoguemes/python3_examples | /advanced/tkinter/40_place_example.py | 1,657 | 4.34375 | 4 | #!/usr/bin/python3
# The place layout manager places the widgets at the specific position you want.
# Example inspired from: https://www.youtube.com/watch?v=D8-snVfekto&t=1479s
# For an in-detail explanation about place visit: https://effbot.org/tkinterbook/place.htm
import tkinter
HEIGHT = 700
WIDTH = 800
window ... |
ff339003d1f00ab402d33dbbed22ed1d48e7db81 | anobhama/Intern-Pie-Infocomm-Pvt-Lmt | /Array/ArrInMatrix.py | 216 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 10:49:35 2020
@author: Anobhama
"""
#array using matrix function
from numpy import *
arr1=array([[1,2,3,4,9,0],[5,6,7,8,1,2]])
arr2=matrix(arr1)
print("array",arr2)
|
af0f8fbfce6070e42b64c6d24daa67ca4673988f | balamini-dev/exercices_python | /LOTO_Version 1 (sans fonction) - Partie 1 fonctionnel.py | 756 | 3.640625 | 4 | import random
grille_visiteur=[0]*6
for i in range (len(grille_visiteur)):
numero_visiteur = int(input("veuillez entrer 1 numéro compris entre 1 et 49 : "))
grille_visiteur[i]= numero_visiteur
print("Votre grille est : ")
print(grille_visiteur)
grille_loto=[0]*6
for i in ra... |
5e8e140326002d4ad6d4c999ce947f067a326965 | thanh-falis/Python | /bai__54/Parameter.py | 437 | 3.53125 | 4 | """
- Python hỗ trợ parameter mặc định khi khai báo hàm
- Hàm print() thường dùng cũng có parameter mặc định
"""
def fl(n, m = 0):
s = 0
for i in range(1, n + m, 1):
s += 1
return s
print(fl(5))
print(fl(5, 1))
def fl2(n, m = 1, k = 2):
s = 0
for i in range(1, m+n+k, 1):
s += i
... |
f918c0ff34fde19b1e2de29cec5d62c11ed55de6 | Tejagani/cricket | /tkint5.py | 1,040 | 3.703125 | 4 | import tkinter as tk
root=tk.Tk()
v=tk.IntVar()
def test():
if v.get()==1:
print("python selected")
elif v.get()==2:
print("perl selected")
b1=tk.Button(root,
text="find",
padx=40,
command=test)
l1=tk.Label(root,
... |
498ac593e31603e23b349c16abf26770265d7be5 | Killerpol/PC2 | /p1.py | 288 | 4.0625 | 4 | x = int(input("Ingrese una coordenada x"))
y = int(input("Ingrese una coordenada y"))
##Importamos libreria math para hacer funcionar el math.sqrt que seria raiz cuadrada.
import math
##Posicion cero o origen
x0 = 0
y0 = 0
distancia = math.sqrt( (x-x0)**2 +(y-y0)**2 )
print (distancia) |
5dc7330050df4a4bf23049151d356aee27542480 | hansen487/CS-UY1114 | /Fall 2016/CS-UY 1114/HW/HW3/hc1941_hw3_q2.py | 629 | 3.828125 | 4 | """
Name: Hansen Chen
Section: EXB3
netID: hc1941
Description: Program that computes how much customer pays
"""
item1=int(input("Enter price of first item: "))
item2=int(input("Enter price of second item: "))
clubcard=str(input("Does the customer have a club card? (Y/N): "))
tax=float(input("Enter tax rate, e.g. 5.5 f... |
2daf5d102fc9b1b124d21e3b202d5bce63b9861f | samyunwei/LearnPython | /hotel.py | 777 | 3.59375 | 4 | # -*-coding:utf-8 -*-
# File Name: hotel.py
# Author: Sam
# mail: samyunwei@163.com
#########################################################################
#!/usr/bin/env python
class HotelRoomClac(object):
'Hotel room rate calculator'
def __init__(self,rt,sales=0.085,rm=0.1):
''''HotelRoomClac defaul... |
b72555a9018c0bfa330a193ad5cc3d8d0e0b0c57 | pogross/bitesofpy | /75/cal.py | 549 | 3.921875 | 4 | import re
from typing import Dict
def get_weekdays(calendar_output: str) -> Dict[int, str]:
"""Receives a multiline Unix cal output and returns a mapping (dict) where
keys are int days and values are the 2 letter weekdays (Su Mo Tu ...)"""
weekday_names = calendar_output.splitlines()[1].split()
we... |
52f6d74d26fd0be5e86adc7818557e337898d6ee | Santos1000/Curso-Python | /PYTHON/pythonDesafios/desafio072.py | 587 | 3.9375 | 4 | cont = ('zero' ,'um' ,'dois' ,'tres' ,'quatro' ,'cinco' ,'seis' ,
'sete' ,'oito' ,'nove' ,'dez' ,'onze' ,'doze' ,'treze' ,
'catorze' ,'quinze' ,'desesseis' ,'desessete' ,'desoito','vinte')
resp =' '
while True:
numero = int(input(' Digite um número entre 0 e 20: '))
if 0 <= numero <=20:
br... |
4ca63a7a9aaa432f4dcba077e9af8131c296b3dd | tainenko/Leetcode2019 | /leetcode/editor/en/[2363]Merge Similar Items.py | 2,978 | 3.921875 | 4 | # You are given two 2D integer arrays, items1 and items2, representing two sets
# of items. Each array items has the following properties:
#
#
# items[i] = [valuei, weighti] where valuei represents the value and weighti
# represents the weight of the iᵗʰ item.
# The value of each item in items is unique.
#
... |
51ab2c00fbbbd19c48389687faa44fcef1542fdd | 84danie/CS408PythonDemo | /demo.py | 3,285 | 4.09375 | 4 | # CS 408 - Group Project - Python Demo
# Joshua Camacho and Danielle Holzberger
#
# Root approximation using bisection and Newton's method
# with graphic results
import math
import matplotlib.pyplot as plt
import numpy as np
#Function whose roots are to be calculated
def f1(x):
return 2*math.pow(x,3)-11.7*math.po... |
50dcc02772117019845185ac80796bc1dbb0803e | ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck | /problems/AE88.py | 667 | 3.609375 | 4 | # Numbers In Pi
# O(n³+m)
# n = len(pi) | m = len(numbers)
def numbersInPi(pi, numbers):
numbers = set(numbers)
res = explore(pi, numbers, 0, 0, [None for _ in pi])
return res if res != float('inf') else -1
def explore(pi, numbers, i, spaces, necessarySpacesAfter):
cur = ""
best = float('inf')
for j ... |
cb67d23c791f5c02f2d555b2169cd981020b7c7c | balmydawn/- | /Base/Day05/Exercises/习题3.py | 371 | 3.765625 | 4 | # 编写一段代码,让用户输入两个数字,求两个数之间所有整数的和(不包括两个数),并打印
num1 = int(eval(input('输入第一个数:')))+ 1
num2 = input('输入第二个数:')
if type(eval(num2)) is float:
num2 = int(eval(num2))
else:
num2 = int(num2) - 1
res = 0
while num1 <= num2:
res = res + num1
num1 += 1
print(res)
|
012fa11116891811442027db929a5420442cbe3a | GodsloveIsuor123/holbertonschool-higher_level_programming-3 | /0x0B-python-input_output/4-append_write.py | 264 | 4 | 4 | #!/usr/bin/python3
'''
file: 4-append_write.py
functions:
-> append_write
'''
def append_write(filename="", text=""):
''' appends a string at the end of a text file '''
with open(filename, 'a', encoding="utf-8") as file:
return file.write(text)
|
7b17274aac6c92a871ea055d36c1922566b19615 | samuelbeaubien/FrozenLake_OpenAI | /tests.py | 163 | 3.515625 | 4 | # Test getting inputs from the user
move = input("Enter a move (0, 1, 2, 3): ")
print (type(move))
move_int = int(move, 10)
print (move_int)
print (type(move_int)) |
6ccc7b7e7c143a6a8a101a54f24052e1e906c1e0 | Offliners/Python_Practice | /code/024.py | 189 | 4.3125 | 4 | # using the third parameter
# in a range
str = "abcdefghijklmn"
# print every second character
print(str[::2])
# print every third character
print(str[::3])
# Output:
# acegikm
# adgjm
|
4c0a535de8d60c844497d731f063d6ecdcf76f79 | rhaussmann/data_sci | /ex_pyplot.py | 5,850 | 3.578125 | 4 | # https://matplotlib.org/gallery/index.html#pyplot-examples
from __future__ import division
from matplotlib import colors as mcolors
import matplotlib.pyplot as plt
import numpy as np
def easy_subplots():
x = np.random.randn(50)
# old style
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fi... |
bef6ab5427693cf403f193728060b74296195b1e | Tim-Sotirhos/statistics-exercises | /probability_distributions.py | 6,035 | 4.4375 | 4 | # Probability Distribution
import numpy as np
import math
from scipy import stats
import matplotlib.pyplot as plt
import pandas as pd
# 1.) A bank found that the average number of cars waiting during the noon hour at a drive-up window follows a Poisson distribution with a mean of 2 cars.
# Make a chart of this distri... |
9e645c1c9c934ae57187fb6294a2428b8a955ad5 | claytonjwong/Sandbox-Python | /fizz_buzz.py | 1,132 | 3.9375 | 4 | """
412. Fizz Buzz
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
n = 15,
Return:
[
"1"... |
294820bc4c447ebb3d9a679f04cf4d82b71cb836 | rolfwessels/bar-craft-keg-cleaner | /misc/StartcodePUMPTEST.py | 817 | 3.609375 | 4 |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# init list with pin numbers
pinList = [2, 3, 4, 5, 6, 12, 13, 19]
"""
2-Air
3_DUMP
4-H2O PMP
5 - H"O
6-SANRECIRC
12-SAN
13-
19-H2O RECIRC
"""
# loop through pins and set mode and state to 'low'
for i in pinList:
GPIO.setup(i, GPIO.OUT)
GPIO.out... |
45269148de868a50c87103e809fb27ca3fc8fec2 | allenGKC/Leetcode_Practice | /python_code/Pow(x, n).py | 548 | 3.921875 | 4 | '''
Problem:Pow(x, n)
Implement pow(x, n).
'''
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if not n:
return 1
if n<0:
return 1/self.myPow(x, -n)
if n == 1:
return ... |
3dc03d4c0650b3c762d205f16380af76bdae657b | Sheetal2304/if_else | /Age.py | 329 | 4.03125 | 4 | age=int(input("enter the number"))
if age<5:
print("baccha hai")
elif age>=5 and age <18:
print("school ja skta h")
elif age>=18 and age <21:
print("vote daal skta h")
elif age>=21 and age <24:
print("drive kr skta h")
elif age>=24 and age <25:
print("shaadi kr skta h")
elif age>=25:
print("legally drink kr s... |
c11ca88fceba34ac84fea10277e9d720996012de | Aissen-Li/lintcode | /124.longestConsecutive.py | 1,123 | 3.65625 | 4 | class Solution:
"""
@param num, a list of integer
@return an integer
"""
def longestConsecutive(self, num):
nums = set(num)
res = 0
for currentNum in num:
if currentNum in nums:
tempLen = 0
leftNum = currentNum - 1
... |
389d749c093ebbca3a974601928e6fda5d75f172 | jnixon7007/Functions_Parameters-Global_Variables | /diceRoller.py | 847 | 3.96875 | 4 | #Dice Roll program
#This program rolls a dice and prints out the dices face
import random,time
s1 = "- - - - -\n| |\n| O |\n| |\n- - - - -\n"
s2 = "- - - - -\n| O |\n| |\n| O |\n- - - - -\n"
s3 = "- - - - -\n| O |\n| O |\n| O |\n- - - - -\n"
s4 = "- - - - -\n| O O |\n| ... |
a10c14aecbe96f0f8a0eb7617a7e3e39ed122268 | pattric0222/Python | /week2/test1.py | 249 | 4.0625 | 4 | first = input("Input First Number \n")
second = input("Input Second Number \n")
print("{} = {} : ".format(first,second),first == second)
print("{} > {} : ".format(first,second),first > second)
print("{} < {} : ".format(first,second),first < second)
|
71c513fa365a859abc90c6cd52cbde80090b9ea3 | wenyaowu/leetcode-js | /problems/splitArrayLargestSum.py | 1,380 | 3.921875 | 4 | """
Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.
Note:
If n is the length of array, assume the following constraints are satisfied:
1 ≤ n ≤ 1000
1 ≤ m ≤ mi... |
78638fbb27e51d492866598778007ff9651a1c89 | Brukvo/PyBasics | /lesson06/task02.py | 1,519 | 4.03125 | 4 | """
2. Реализовать класс Road (дорога), в котором определить атрибуты:
length (длина), width (ширина).
Значения данных атрибутов должны передаваться при создании экземпляра класса.
Атрибуты сделать защищенными.
Определить метод расчета массы асфальта, необходимого для покрытия всего
дорожного полотна. Использовать форм... |
87b8dab004797ba1a35dc2e5a9900190436db6ed | cvhs-cs-2017/practice-exam-RushBComrades | /MyFile.py | 289 | 4.34375 | 4 | """Step 3: In MyFile.py, define a function for the turtle program that will draw
a regular polygon with 'n' sides."""
n = int(input())
import turtle
def meme(o):
Vex = turtle.Turtle()
Vex.speed(0)
for x in range (n):
Vex.forward(1)
Vex.right((360/n))
meme(n)
|
c45fd4f5a8e15cd035acf90dac7bafd543d04c90 | Joexder/Python-Curse | /Conditionals.py | 297 | 4 | 4 | x = input("<escribe tu edad: ")
if int(x) > 26:
print("Por mayor")
elif int(x) == 26:
print("En el limite")
else:
print("Por menor")
y = input("Escribe un Color:")
if y == 'red' or y == 'blue' or y == 'yellow':
print("Colores primarios")
else:
print("Colores Secundarios")
|
857d42b5342ee738566323e7c7a13cda4adeefe4 | hoang-ng/LeetCode | /Tree/437.py | 1,315 | 3.5625 | 4 |
# 437. Path Sum III
# You are given a binary tree in which each node contains an integer value.
# Find the number of paths that sum to a given value.
# The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
# The tree has no more than ... |
f0f488f2b2ac4f039ff44e2ddf1b34dbb4898be1 | daadestroyer/20MCAOOPS | /LabComponent/App10_generator.py | 684 | 3.75 | 4 | import time
def timeit(func):
def timed(*args, **kw):
starttime = time.time()
result = func(*args, *kw)
endtime = time.time()
print("time taken", endtime-starttime)
return result
return timed
@timeit
def fib(a=0, b=1):
while True:
yield a
a, b = b... |
2b0bc88b5ad4e7a454728b912dfad2cdd13cdb37 | IhToN/DAW1-PRG | /Ejercicios/PrimTrim/Ejercicio38.py | 516 | 3.578125 | 4 | """
Comprobar las Leyes de Demorgan
a. not (AUB) = not A or not B
b. not(AorB) = not A and not B
La negación de una conjunción es la desconjunción de la negación de los términos.
"""
A, B = {1, 2, 3}, {2, 3, 4}
Universal = {x for x in range(100)}
aleft = Universal - (A | B)
aright = Universal -... |
43303916c52c7b6277582892af4d2b3eef492db3 | jwyx3/practices | /leetcode/binary-search/bs-answer/preimage-size-of-factorial-zeroes-function.py | 1,117 | 3.609375 | 4 | # https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/
# https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/solution/
# Time: O(log5(10*K)*log2(10*K))
# Space: O(1)
class Solution(object):
def preimageSizeFZF(self, K):
"""
:type K: int
:rtype: int
... |
f2ad155fb39c8cbaec3d8cc4b1155c7d3a153976 | guedanie/python-exercises | /warm-up.py | 1,248 | 4.03125 | 4 | # Take the word EASY: Its first three letters — E, A and S — are the fifth, first, and nineteenth letters,
# respectively, in the alphabet. If you add 5, 1, and 19, you get 25, which is the value of the
# alphabetical position of Y, the last letter of EASY.
## Cna you think of a common five-letter word that works in... |
70ec80f7cafbf0c16d17a8e408d1c86101c69abd | addn2x/python3 | /ex08-strings/string03.py | 277 | 3.765625 | 4 | a = 'This is some text'
b = '123456'
print(a.find('is'))
print(a.find('other'))
print(a.isalpha())
print(a.isdigit())
print(b.isalpha())
print(b.isdigit())
print(a.upper())
print(a.lower())
print(a.split())
print(a.join(b))
print(a + b)
print(a.replace('is', 'was')) |
1a833fd1f61e7f9f8a074cb5fac516909bb7445e | webclinic017/best_performance-python | /algorithm/linear/1.py | 232 | 3.5 | 4 | import numpy as np
A = np.array( [ [1,2,4,1], [2,1,3,1], [5,2,1,4] ], dtype=np.float64 )
print(A)
print(A.shape)
# 오류 발생
#A[0,2] = 1+2j
#A[2,1] = 1+2j
# 0으로 바꿔보기
A[0,2] = 0
A[2,1] = 0
print(A) |
4801233fbca798a2439ad0529ea365b904b29269 | smarky7CD/PyNTRU | /PyNTRU/poly.py | 2,286 | 3.59375 | 4 | #!/usr/bin/env python3
from itertools import zip_longest
class Polynomial():
def __init__(self,c, N):
self._coeff = strip(c,0)
self._N = N
def __add__(self, other):
new_coeff = [sum(x) for x in zip_longest(self, other, fillvalue=0)]
return Polynomial(new_coeff, self._... |
1bb1cb878947ed52d427d0f78fba0ca7f1e9b9e4 | eush77/blackbox | /examples/test/factor.py | 519 | 3.765625 | 4 | #!/usr/bin/python3
from math import sqrt, floor
from collections import defaultdict
def factor(n):
for k in range(2, floor(sqrt(n))+1):
if not n%k:
powers = factor(n // k)
powers[k] += 1
return powers
return defaultdict(int, {n: 1})
if __name__ == '__main__':
n ... |
c16f8aa85f81d185151c9db2a88e1daa5774fe48 | bgswaroop/tsai-epai-session15 | /session15.py | 1,890 | 3.6875 | 4 | from collections import namedtuple
from datetime import datetime
from itertools import islice
Ticket = namedtuple('Ticket', 'summons_number, plate_id, registration_state, plate_type, issue_date, violation_code, '
'vehicle_body_type, vehicle_make, violation_description')
date_formatter = l... |
0adc9c83b412d2cfe8ab01095bcd951f0c6a50c9 | FawneLu/leetcode | /264/Solution.py | 475 | 3.625 | 4 | ```python3
import heapq
class Solution:
def nthUglyNumber(self, n: int) -> int:
heap=[1]
count=1
while count<=n:
target=heapq.heappop(heap)
if target*2 not in heap:
heapq.heappush(heap,target*2)
if target*3 not in heap:
heap... |
4d1fc819ef5a7a306b3eaae5d340af3e9fd7cd32 | srividhyaravi/ML_Assignment | /Assignment_MLP/mlp_program.py | 4,158 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# In[2]:
#reading the dataset from csv file
def read_data(file):
data = pd.read_csv(file, header=None , index_col=None)
return data
data = read_data('data.txt')
data... |
9a824124ce6934707dbce9f9f3dcd457e5a4d855 | aayush2906/data_structures-Python | /InsertionSort.py | 382 | 4.125 | 4 |
def InsertionSort(seq):
for sliceEnd in range(len(seq)):
pos=sliceEnd
while pos > 0 and seq[pos] < seq[pos-1]:
(seq[pos],seq[pos-1])=(seq[pos-1],seq[pos])
pos=pos-1
seq=[]
n=int(input("Size of list::"))
for i in range(0,n):
x=int(input("Enter element::"))
seq.insert(... |
5645e7dbda048b8a2d02ea45d28a9a134a80f0f2 | ardhysevenfold/animasi | /fiqoh.py | 1,299 | 3.515625 | 4 | from tkinter import *
import time
lebar = 600
tinggi = 400
tk = Tk()
canvas = Canvas(tk, width=lebar, height=tinggi)
tk.title("Gambar Bola Banyak Bergerak")
canvas.pack()
bola = canvas.create_oval(10, 10, 70, 70, fill="yellow")
bola2 = canvas.create_oval(10, 10, 70, 70, fill="orange")
bola3 = canvas.c... |
8382a5c5de68f1d79e21a0fd99baa388f19c7df7 | prasannakumarj/Learning_Python | /Chapter 02_Object_types/2_Lists/prg5.py | 440 | 4.4375 | 4 | #!/usr/bin/python
#Title: List comprehension "expression"
M=[[1,2,3],
[4,5,6],
[7,8,9]] #matrix in the form of list
print('The matrix is:',M)
col1=[i[0] for i in M]
print('Column 1 elements are:',col1)
col2=[i[1] for i in M]
print('Column 2 elements are:',col2)
col3=[i[2] for i in M]
print('Column 3 elements... |
66f2cfddb4ff48bd193552ce441888dff137087a | ltzone/EE447-Project | /backend/test.py | 431 | 3.609375 | 4 | s = """
for x in range(10):
print(x, end='')
print()
"""
code_exec = compile(s, '<string>', 'exec')
code_eval = compile('10 + 20', '<string>', 'eval')
code_single = compile('name = input("Input Your Name: ")', '<string>', 'single')
a = exec(code_exec)
b = eval(code_eval)
c = exec(code_single)
d = eval(code_singl... |
464000d7c90d89720624b8267e9bf2f4081217c6 | LevenWin/Algorithm | /Python/Code/LinkedList/12-13.py | 2,489 | 3.75 | 4 | # -*- coding: UTF-8 -*-
# 入环点
from linkedlist import LinkedLink
from linkedlist import LinkNode
import math
def circleNode(head):
meetNode = circleMeet(head)
if meetNode == None:
return None
cur = head.next
while cur != None and meetNode != None:
if cur == meetNode:
return ... |
4b6ac9aa0a2c62eeedf8a2df914cc8fa4c0e0e55 | pickerxxr/CLRS-lab-practice | /Advantage_Shuffle.py | 554 | 3.78125 | 4 | # classic greedy
def advantage_shuffle(arr_1, arr_2):
arr_1_ctr = sorted(arr_1)
arr_1_new = []
for i in arr_2:
ctr = 0
for j in arr_1_ctr:
if j > i:
arr_1_new.append(j)
ctr = 1
break
if ctr == 0:
arr_1_new.append... |
59bd6af5bd2c79973183de4e8e7142b74fe1efa9 | ujuc/introcs-py | /introcs/ch1/exp_q/2/1_2_2.py | 253 | 3.546875 | 4 | import math
import sys
from introcs.stdlib import stdio
theta = float(sys.argv[1])
cos = math.cos(theta)
sin = math.sin(theta)
cos_sqrt = cos ** 2
sin_sqrt = sin ** 2
stdio.writeln(f"{cos_sqrt}, {sin_sqrt}")
stdio.writeln(f"{cos_sqrt + sin_sqrt}")
|
aa5aa0ffde657aecf5372241d6d9f6e02dbf4afc | nabilchowdhury/comp551-applied-ml | /Assignment1/Q3.py | 8,436 | 3.625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
'''
3) Real-life dataset
'''
df = pd.read_csv('./Datasets/communities.csv', header=None)
df[0] = 1
df.drop([i for i in range(1, 5)], axis=1, inplace=True) # These columns are not predictive according to the dataset
df.columns = [i for i in range(d... |
0dba48939a7bfa51e829aafb5d4a3ea53cc1bdca | mnihatyavas/Python-uygulamalar | /Brian Heinold (243) ile Python/p10204.py | 153 | 3.71875 | 4 | # coding:iso-8859-9 Trke
for i in range(10): print ('*' * 10)
for i in range(10): print ('*' * (i+1))
for i in range(10): print ('*' * (10-i))
|
08a6bd2a0ae1a0528a7ab26135c2738196dae764 | nghidinh/python-learning | /FundamentalProgramming/lecture8/StudentScoreMaintenance.py | 4,372 | 3.734375 | 4 | # a = [5, 9, 'Three', 2, 'Six']
# print a[3:]
# print a[:4]
# print a[2:5]
# print a[4]
# print a[-1]
#
# score = [65, 78, 90, 85, 50]
# k = int(raw_input('Student number '))
# if k < 150001 or k > 150005:
# print 'No such student number'
# else:
# print 'score = ', score[k - 150001]
#
# score = [-2... |
ba34128d174c722d46b0c6a213a0593d8f4937eb | mmutiso/svpino_challenge | /find_missing_number.py | 1,028 | 3.765625 | 4 | import random
def data_generator():
array = [i for i in range(1,101)]
random_number = random.randint(1,100)
array.remove(random_number)
random.shuffle(array)
return (array, random_number)
def solution(arr):
'''
create a visited array initialized with all False.
The size of the visi... |
235093da6c5dd075d79da9d3007ae69c44f11528 | NicolasBaak/primeros_programas_python | /Funciones/clase.py | 628 | 3.9375 | 4 | #Nos piden diseñar un procedimiento que recibe como datos las dos listas y una cadena con
#el nombre de un estudiante. Si el estudiante pertenece a la clase, el procedimiento imprimirá
#su nombre y nota en pantalla. Si no es un alumno incluido en la lista, se imprimirá un mensaje
#que lo advierta.
def muestra_nota_de_... |
277dcda3a4abcf5244545b7390576e044f9770dc | MihailoJoksimovic/cs6006-implementations | /depth_first.py | 1,582 | 3.859375 | 4 | # Implement depth first graph search. Try implementing edge classification and topological sort as well
# How to represent graphs? 1. Adjacency lists, 2. Objects
graph = {
'a': ['b', 'd'],
'b': ['e'],
'c': ['e', 'f'],
'd': ['b'],
'e': ['d', 'g'],
'f': [],
'g': ['d']
}
visiting_order = []
... |
5d1ae44cfc5234ccbfcfcf12782be925619d646b | r-hague/Python_work | /Loan_time_payment.py | 2,057 | 4.21875 | 4 | import math
myFunc = input("Press 1 to calculate payment amount for a given duration and principal. \n Press 2 to calculate duration for a given payment amount and principal. \n Press 3 to calculate principal for a given duration and payment amount: ")
interestRate = input("Interest rate (%): ")
r = interestRate... |
c59f9438bcff90694fd5938c20285707498adc18 | matyama/zal-tutorials | /tutorial04.py | 2,239 | 4.5 | 4 | #!/usr/bin/env python3
import math
from combinatorics import factorial
def range_sum_loop(a, b):
pass
def range_sum_func(a, b):
pass
def range_sum_expr(a, b):
pass
def euler_naive(num_iters):
pass
def euler(num_iters):
pass
def sqrt(x):
pass
def prime(n):
pass
if __name__ ==... |
ecc5c3563103ce17063704276583c3bd529a4110 | YosraAouini/pandas-numpy | /world_statistics_data.py | 3,085 | 3.96875 | 4 | # world_data.py
#
# A terminal-based application for computing and printing statistics based on given input.
# Detailed specifications are provided via the Assignment 5 git repository.
# You must include the main listed below. You may add your own additional classes, functions, variables, etc.
# You may import an... |
990f06031119e8d514d26f48a1d2896426edb5f7 | 531621028/python | /函数式编程/filter.py | 964 | 3.921875 | 4 | #和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素
def is_odd(x):
return x % 2 == 1
print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9])))
#注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list
def _odd_iter():
n = 1
while True:
n = n + 2
yield... |
9f24f047b3966e31dc38ce21ca8f3a261f692bd1 | Shubham-cod/Data-Reporting | /data_report_server.py | 1,207 | 3.765625 | 4 |
#################################### creating socket TCP server to recieve the data #########################################
import socket
import pickle
HOST = '127.0.0.1' # hostname or IP address
PORT = 65432 # Port to listen
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOS... |
e7f8e237f7c0cc8b3645a4d3efa4dd7d586fabf4 | awesomediff/cs207-FinalProject | /awesomediff/core.py | 12,946 | 4.09375 | 4 | import math
import numpy as np
class variable:
def __init__(self,val,der=1):
"""
Initialize a variable object
with a specified value and derivative.
Expect scalar for val. Expect scalar
or a numpy array for der.
If no derivative is specified,
... |
aaeee0275cbd100624c088e4966234edb4aa4226 | crystal616/8480Group | /code/recom.py | 7,250 | 3.546875 | 4 | '''
recom.py
Author: Ying Cai
Date: 11/10/12
Description:
Compute movie similarity.
Analyze user's watching list, select similar movies and recommend.
Compute the recall and precision of the recommendation list.
'''
import pandas as pd
import numpy as np
import scipy as sp
import math
import json
#cleaned full movie... |
8b6181752ad87fc8c37b98bdb9f3cbbd159746eb | pinkrespect/HappyHappyAlgorithm | /test_score.py | 212 | 3.53125 | 4 | import stdin from sys as read
score = int(read.readline().rstrip())
if score > 89:
print("A")
elif score > 79:
print("B")
elif score > 69:
print("C")
elif score > 59:
print("D")
else: print("F")
|
78f3ae2d87f3a3d494feff8186737798caeb6379 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/1/summing.py | 621 | 3.75 | 4 | def sum_numbers(numbers=None):
total = 0
if numbers == None:
for i in range(1,101):
total = total + i
elif len(numbers) == 0:
total = 0
elif isinstance(numbers, list) or isinstance(numbers, tuple):
for i in numbers:
total = total + i
elif not isinstanc... |
ea1b63f1c1810daff85f30ef678b9ed47eb5a6d8 | KARTHICKMUTHUSAMY/beginer | /detective saikat.py | 168 | 3.765625 | 4 | def stair():
x=0
y=[]
z=int(input())
for i in range(z):
y.append(int(input()))
for i in y:
x+=(z-i)
print(x)
try:
stair()
except:
print('invalid')
p
|
6a681d0495baf3f0ce68b022ebccdbff043341a4 | binarioGH/codewars | /simpletrans.py | 204 | 3.703125 | 4 | #-*-coding: utf-8-*-
def encode(text):
plain_text = ["", ""]
index = 0
for symbol in text:
plain_text[index] += symbol
if index == 0:
index += 1
else:
index -= 1
return "".join(plain_text) |
93fa93c1ab92ebed9582be1a5699b6eb63d8072a | YaroslavGavrilychev/Python_1594 | /HW3.py | 885 | 3.640625 | 4 | name_percent_main_part = 'процент'
while True:
try:
percent_from_input = int(input('Введите пожалуйста число от 1 до 20: '))
except:
print('Пожалуйста введите целое число')
else:
if percent_from_input < 1 or percent_from_input > 20:
print('Ваше число не входит в диапазон... |
37c9a4b0920c424e1c5b4bd34b3b7a9098a9083b | Adam-Of-Earth/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 323 | 3.875 | 4 | #!/usr/bin/python3
"""a class Square
Description of a square class
"""
class Square:
"""square shape
infomation about the square and how to use it
"""
def __init__(self, size):
"""Create a square size large
size(int): how large the size wil be
"""
self.__size = si... |
b6d4d895080d924b49da87976f8e9604a8e80fbf | green-fox-academy/balazsbarni | /week04/day01/09-teachers-and-students.py | 561 | 3.671875 | 4 | #### Teacher Student
#- Create `Student` and `Teacher` classes
#- `Student`
# - learn()
# - question(teacher) -> calls the teachers answer method
#- `Teacher`
# - teach(student) -> calls the students learn method
# - answer()
class Student(object):
def question(self, teacher):
teacher.answer()
... |
b11c5aaca7509dea3a7f0c9ed54defabc3a01811 | twtrubiks/python-notes | /__len__tutorial.py | 710 | 3.734375 | 4 | class Product(object):
def __init__(self):
self.items = [
{
'id': 1,
'value': 10
},
{
'id': 2,
'value': 20
},
{
'id': 3,
'value': 30
},
... |
f70f0c5b5a05003fb026b312a535cdf8fece228c | npankaj365/survivor-bias | /luck.py | 2,344 | 3.546875 | 4 | import random
import colorama
import persons
import argparse
def show_top(persons, number):
count = 0
for person in persons[:number]:
if person.talent_rank < number:
count += 1
print(colorama.Fore.GREEN, end='')
elif person.talent_rank < number * 2:
print(co... |
d3dff9d3eb34385cca871f0fe8f2fb16d747ff98 | kgashok/pygorithm | /pygorithm/sorting/tim_sort.py | 3,625 | 4.5 | 4 | def inplace_insertion_sort(arr, start_ind, end_ind):
"""
Performs an in-place insertion sort over a continuous slice of an
array. A natural way to avoid this would be to use numpy arrays,
where slicing does not copy.
This is in-place and has no result.
:param arr: the array to sort
:param ... |
4cb5626a12a93cd280931061a84fdc6b660e6b73 | EmmanuelJeanBriand/hello-world | /cleancode/calculadora/calculadora.py | 1,982 | 3.96875 | 4 | def ask_option(): return int(input("Seleccione opción"))
def ask_int(s): return int(input(s))
header = r"""********
Calculadora
********"""
menu = r"""Menu
1) Suma
2) Resta
3) Multiplicación
4) División
5) Salir"""
pairs = {1: ('La suma es: {res}', lambda a, b: a + b),
2: ('La resta es:... |
36044d929d19fe21dbad7636b6506a13d09704ef | Eduardo271087/python-udemy-activities | /section-10/inheritance.py | 1,021 | 3.828125 | 4 | class Fabrica:
def __init__(self, marca, nombre, precio, descripcion, ruedas = None, distribuidor = None):
self.marca = marca
self.nombre = nombre
self.precio = precio
self.descripcion = descripcion
self.ruedas = ruedas
self.distribuidor = distribuidor
def __str__(self):
return """\
MAR... |
81a6e59840b3d3656a142c4823f4aa1899a1e133 | lgl90pro/colloquium2 | /56.py | 643 | 3.765625 | 4 | '''56. Якщо в одновимірному масиві є три поспіль однакових елемента, то
змінній r привласнити значення істина.
Виконав: Лещенко В. О.'''
import numpy as np
A = np.random.randint(0, 9, 15)
print(f'Вихідний масив: {A}.\n')
for i in range(len(A) - 2):
if (A[i] == A[i+1] == A[i+2]): # якщо зустрічається 3 ... |
942247a1a2d2f2ff344161521ed462e57403b78b | dothuan96/machine-learning-coursera | /ML Basic - Python/linear reg_one var.py | 1,885 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 2 13:08:14 2020
@author: thuando
"""
"""
Linear regression for 1 variable
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#reading dataset
data = pd.read_csv('ex1data1.txt', header = None)
#read 1st column
X = data.iloc[... |
16d8f90c8b1a78afcb1adfd78d348c690e62174f | nareshkr22/gtu_python | /pract17.py | 178 | 3.765625 | 4 | from module import *
num1 = input("Enter Number 1 : ")
num2 = input("Enter Number 2 : ")
oper = input("Enter the operation : ")
print(perform(int(num1),int(num2),oper)) |
936dc0b530010a91aa1ee114b7ca41ba4dda91cf | felipe-basina/python | /modulos/modulo_leitura_arquivo.py | 939 | 3.828125 | 4 | '''
Script utilizado para leitura de arquivo
from modulo_leitura_arquivo import ler_arquivo
arquivo = 'e:/instalados/python/dev/exercicios/modulos/arquivo_leitura.txt'
ler_arquivo(arquivo)
'''
def ler_arquivo(nome_arquivo):
if not nome_arquivo:
print('Um nome de arquivo deve ser definido!')
else:
... |
d93ea266d20bb08f219c36bf69d8ed1635c335b2 | aswinishiyana/shiyana | /positive.py | 126 | 4.15625 | 4 | num=float(input("Enter a number"))
if num>0
print("positive number")
elif num==0
print("zero")
else:
print("Negative number")
|
3b3b623b172c9b69c1c40b1032b0bb264bde0087 | allatambov/allatambov.github.io | /PyProgPerm/practice/practice01/problem01.py | 563 | 3.703125 | 4 | line = ["Третьяковская", "Марксистская", "Площадь Ильича", "Авиамоторная",
"Шоссе Энтузиастов", "Перово", "Новогиреево", "Новокосино"]
station = input("Enter current station: ")
i = line.index(station)
print("Следующая станция: " + line[i + 1] + ".")
# alternatives (uncomment):
# print(f"Следующая станция: {... |
43d87f386f4145ff5977b12174f04f8db9216be8 | rossmfadams/AlgorithmsP2 | /arrayGenerator.py | 712 | 3.78125 | 4 | # This program returns the N amount of elements in an array
import random
# create four lists of random numbers
def generate_random_list_number(number):
first_list = []
second_list = []
third_list = []
fourth_list = []
for i in range(number):
value = random.randint(0, number)
firs... |
4b0cc072f13613fc04c15b90bd9f769a94cd92ff | ShallowAlex/leetcode-py | /101-200/146.py | 2,036 | 3.515625 | 4 | class Node:
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.pre = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.head = Node()
self.tail = Node()
self.head.... |
a4e46386f722808a8e904e8118d0f266d69cf611 | kylechenoO/812pytest | /pynative/q14.py | 204 | 4.0625 | 4 | #!/opt/anaconda/bin/python
## Question 14: Print downward Half-Pyramid Pattern with Star (asterisk)
def getHalfPyramid(size):
for i in range(size):
print('*' * (size - i))
getHalfPyramid(5)
|
252cfe8cba3c5a85b2def4aeb4ea7aada76247d1 | goalong/lc | /v1/61.rotate-list.133330774.ac.py | 1,225 | 3.703125 | 4 | #
# [61] Rotate List
#
# https://leetcode.com/problems/rotate-list/description/
#
# algorithms
# Medium (24.43%)
# Total Accepted: 131.8K
# Total Submissions: 539.7K
# Testcase Example: '[1,2,3,4,5]\n2'
#
# Given a list, rotate the list to the right by k places, where k is
# non-negative.
#
#
#
# Example:
#
# G... |
f78a688ec2f6a58de128d60278efffc9c4f69754 | wlommusic/machine-learning-repo | /#2 regression/1 linear reg/linear-reg.py | 1,351 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 11:56:19 2021
@author: wlom
"""
#importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#importing the dataset
data = pd.read_csv('Salary_Data.csv')
x= data.iloc[:,:-1].values #rows,col
y= data.iloc[:,-1].values
#splitting t... |
a79955480941c6a3516aaa750fafdc1fe3dc4dbc | satojkovic/algorithms | /problems/bulb_switch.py | 392 | 3.625 | 4 | def bulb_switch(n):
bulbs = [1 for _ in range(n)]
for i in range(1, n + 1):
if i == 1:
continue
elif i == n:
bulbs[-1] = 0 if bulbs[-1] == 1 else 1
else:
for j in range(i - 1, n, i):
bulbs[j] = 0 if bulbs[j] == 1 else 1
return sum(b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.