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 |
|---|---|---|---|---|---|---|
5da1487437a7556fac90072c2d7dddbb01a965a6 | jonovik/cgptoolbox | /cgp/utils/extrema.py | 2,060 | 3.8125 | 4 | """Find local maxima and minima of a 1-d array"""
import numpy as np
from numpy import sign, diff
__all__ = ["extrema"]
# pylint:disable=W0622
def extrema(x, max=True, min=True, withend=True): #@ReservedAssignment
"""
Return indexes, values, and sign of curvature of local extrema of 1-d array.
The ... |
9247bc433012c2af963293105933a1e422af281e | bariskucukerciyes/280201035 | /lab9/harmonic.py | 146 | 3.5 | 4 | def harmonic(x):
h_sum = 0
if x == 1:
return 1
h_sum = (1 / x) + harmonic(x - 1)
return h_sum
print(harmonic(5)) |
f5ad9e7ceadf975f9c3af3917bd4c3557ef39972 | bariskucukerciyes/280201035 | /lab5/evens.py | 169 | 4.03125 | 4 | N = int(input("How many number?"))
evens = 0
for i in range(N):
number = int(input("Enter integer:"))
if number % 2 == 0:
evens += 1
print(evens/N * 100, "%")
|
ba5de5ac9904058a9c7a5d48e881b9bd564b2824 | bariskucukerciyes/280201035 | /lab1/fahrenheit.py | 162 | 4.0625 | 4 | Celcius = int(input("Enter celcius value:"))
Fahrenheit = int(Celcius*1.8 + 32)
print(Celcius, "Celcius degree is equals to", Fahrenheit, "Fahrenheits degree" ) |
6acb845b6105cc4253fbc3421ef3b3354a23be3d | bozkus7/Python_File | /neural.py | 985 | 3.84375 | 4 | import numpy
import matplotlib.pyplot
data_file = open('mnist_train_100.csv.txt', 'r')
data_list = data_file.readlines()
data_file.close()
#The numpy.asfarray() is a numpy function to convert the text strings into real numbers and to create an array of those numbers
all_values = data_list[0].split('... |
38e59e24c8a8d4a11c1bc6d8bb9fe4a9071ef492 | amansharma2910/DataStructuresAlgorithms | /02_PythonAlgorithms/Sorting/singly_linked_list.py | 3,113 | 4.34375 | 4 | class Node:
# Node class constructor
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
# LinkedList constructor
def __init__(self):
self.head = None
def print_list(self):
"""Method to print all the elements in a singly linked list.
... |
df369f3cd5db77a5ed5fa071a3a8badfcf404905 | ea3/Exceptions-Python | /exception.py | 887 | 4.03125 | 4 | def add(a1,a2):
print(a1 + a2)
add(10,20)
number1 = 10
number2 = input("Please provide a number ") # This gives back a string.
print("This will never run because of the type error")
try:
#You you want to attempt to try.
result= 10 + 10
except:
print("It looks like you are not adding correctly")
else:
print(... |
8f76584b2645bb0ef6d525cd456ab11b7b2933c7 | stanton101/Ansible-Training | /core_python_ep6.py | 462 | 3.90625 | 4 | # Tuples
# t = ("Norway", 4.953, 3)
# print(t * 3)
# print(t[0])
# print(t[2])
# print(len(t))
# for item in t:
# print(item)
# t + (338186)
# a = ((220, 284), (1184, 1210), (2620,2924), (5020, 5564), (6232, 6368))
# print(a[2][1])
# def minmax(self):
# return min(self), max(self)
# num = minmax([83, 33, ... |
e613ee5e149ff0ed9af83a11e1571421c9c8551c | charlesrwinston/nlp | /lab0/winston_Lab0.py | 1,326 | 3.5625 | 4 | # Winston_Lab0.py
# Charles Winston
# September 7 2017
from nltk.corpus import gutenberg
def flip2flop():
flip = open("flip.txt", "r")
flop = open("flop.txt", "w")
flip_text = flip.read()
flop.write(reverse_chars(flip_text) + "\n")
flop.write(reverse_words(flip_text) + "\n")
emma = gutenberg... |
4074f1ca36b2ad151d2b918274f661c8e0ae4b80 | htars/leetcode | /algorithms/1_two_sum.py | 733 | 3.546875 | 4 | from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)-1):
n1 = nums[i]
for j in range(i+1, len(nums)):
n2 = nums[j]
if (n1+n2) == target:
return [i, j]
if ... |
742952425469528b62320860c834a73d8f52e444 | americanchauhan/problem-solving | /Find the maximum element and its index in an array/Find the maximum element and its index in an array.py | 428 | 4.0625 | 4 | def FindMax(arr):
#initialze first value as largest
max = arr[0]
for i in range(1, len(arr)):
#if there is any other value greater than max, max is updated to that element
if arr[i] > max:
max = arr[i]
ind = arr.index(max)
#Print the maximum value
print(max)
... |
68e668797ce78e861ba24a295f05a4e7aaf07086 | rupalisinha23/problem-solving | /rotating_series.py | 517 | 3.9375 | 4 | """
given two arrays/lists A and B, return true if A is a rotation of B otherwise return false
"""
def is_rotation(A,B):
if len(A) != len(B): return False
key=A[0]
indexB = -1
for i in range(len(B)):
if B[i] == key:
indexB = i
break
if indexB == -1: return False
... |
3da789960183c8f13bb5b22307c60fe57adf316b | rupalisinha23/problem-solving | /pallindrome_linked_list.py | 493 | 3.734375 | 4 | class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Pallindrome:
def isPallindrome(self, head:ListNode) -> bool:
if not head or not head.next:
return True
stack = []
while head:
stack.append(head.val)
head =... |
75260678d000751037a56f69e517b253e7d82ad9 | aasmith33/GPA-Calculator | /GPAsmith.py | 647 | 4.1875 | 4 | # This program allows a user to input their name, credit hours, and quality points. Then it calculates their GPA and outputs their name and GPA.
import time
name = str(input('What is your name? ')) # asks user for their name
hours = int(input('How many credit hours have you earned? ')) # asks user for credit hours ea... |
89899700c49efdc29c14accb87082a865da2b896 | darpanhub/python1 | /task4.py | 2,041 | 3.984375 | 4 | # Python Program to find the area of triangle
a = 5
b = 6
c = 7
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
# python program finding square root
print('enter your number')
n = int(input())
import math
print(math.sqrt(n))
# Pytho... |
99a99291c1dc2b399b282914db4e5f57da7f46d8 | darpanhub/python1 | /list.py | 1,242 | 3.796875 | 4 | # student_list=[1,45,6,6,7]
# print(student_list)
# print('Welcome User')
# admin_list = ['manish' , 'darpan' , 'sandeep', 'mohammed']
# print('hey user, Please enter your name for verification')
# name = input()
# if name in admin_list:
# print('hey ' + name + ', happy to see you Welcome back')
# e... |
cf43e8c07ad2deeeb928439291b3fd97ddcde57c | ronaldoussoren/pyobjc | /pyobjc-core/Examples/Scripts/subclassing-objective-c.py | 1,656 | 4.09375 | 4 | #!/usr/bin/env python
# This is a doctest
"""
=========================================
Subclassing Objective-C classes in Python
=========================================
It is possible to subclass any existing Objective-C class in python.
We start by importing the interface to the Objective-C runtime, although
you'... |
eaa7fec6da4273925a0cb7b68c910a729bf26f3c | Yaguit/lab-code-simplicity-efficiency | /your-code/challenge-2.py | 822 | 4.15625 | 4 | """
The code below generates a given number of random strings that consists of numbers and
lower case English letters. You can also define the range of the variable lengths of
the strings being generated.
The code is functional but has a lot of room for improvement. Use what you have learned
about simple and efficien... |
3b9eb781f9ae784e62b9e4324f34120772209576 | inniyah/MusicDocs | /HiddenMarkovModel.py | 11,115 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# See: https://github.com/adeveloperdiary/HiddenMarkovModel
# See: http://www.adeveloperdiary.com/data-science/machine-learning/introduction-to-hidden-markov-model/
import numpy as np
# Hidden Markov Model (θ) has with following parameters :
#
# S = Set of M Hidden Sta... |
2e36c061760bd5fc34c226ecbe4b57ef3965c52c | tchen01/tupper | /tupper.py | 368 | 3.515625 | 4 | from PIL import Image
im = Image.open("bd.jpg")
width = im.size[0]
height = im.size[1]
k = ''
def color( c ):
sum = c[0] + c[1] + c[2]
if ( sum < 383 ):
return 1
else:
return 0
for x in range(0, width):
for y in reversed(range(0, height)):
k += str( color( im.getpixel( (x,y) ) ))
k = int(k, base... |
661d4a1116284d03356f5114ff955edac0b00c90 | AlberVini/exp_regulares | /aulas_exemplos/aula06.py | 443 | 3.546875 | 4 | # ^ a expressão deve começar de x maneira
# ^ [^a-z] serve para negar algo em especifico
# $ a expressão deve terminar de x maneira
# os meta caracteres acima servem para a busca exata da expressão passada
import re
cpf = '293.457.246-99'
cpf2 = 'a 293.457.246-99'
print(re.findall(r'^((?:[0-9]{3}\.){2}[0-9]{3}-[0-9... |
d32928cf7ee10d8298ed8eb9272759b53f94b85a | aktilekpython/pyth-on | /new.py | 1,801 | 4.03125 | 4 | #1 задание
# number = int(input("Введите первое число"))
# number2 = int(input("Введите второе число"))
# print(number - number2)
#name =input ("Введите свое имя:")
#print(name* 18
#2 задание
#print(36 % 5)
#3 задание
#a = input ("Введите свое имя:")
#b = (a[::-1])
#if a==b:
#print ("Полиндром")
#else:
#prin... |
c5dd8782dfe182b77f0afbd5bbc9700c3237fcd1 | 100sun/hackerrank | /sherlock-and-the-valid-string.py | 2,283 | 3.71875 | 4 | # https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings&h_r=next-challenge&h_v=zen
from collections import Counter
import time
# Complete the isValid function below.
def isValid_sun_1(s):
freq = Counter(s)... |
695bcb02901af251d4ece24a84976015eb7201d0 | newkstime/PythonLabs | /Lab14/Problem2/electricity_bill.py | 1,113 | 3.8125 | 4 | from Problem2.utility_bill import Utility_bill
class Electricity_bill(Utility_bill):
def __init__(self, customer_name, customer_address):
base = super()
base.__init__(customer_name, customer_address)
self._kwh_used = 0
def calculate_charge(self):
while isinstance(self._kwh_use... |
59a5e4e86c2ccfd9b33ca254a220754fe981ebf7 | newkstime/PythonLabs | /Lab07/Lab07P4.py | 2,277 | 4.1875 | 4 | def main():
numberOfLabs = int(input("How many labs are you entering?"))
while numberOfLabs <= 0:
print("Invalid input")
numberOfLabs = int(input("How many labs are you entering?"))
labScores = []
i = 0
while i < numberOfLabs:
score = float(input("Enter a lab score:"))
... |
842938b66f413e4a260395823d59a0a589bbdecf | newkstime/PythonLabs | /Lab03 - Selection Control Structures/Lab03P2.py | 824 | 4.21875 | 4 | secondsSinceMidnight = int(input("Please enter the number of seconds since midnight:"))
seconds = '{:02}'.format(secondsSinceMidnight % 60)
minutesSinceMidnight = secondsSinceMidnight // 60
minutes = '{:02}'.format(minutesSinceMidnight % 60)
hoursSinceMidnight = minutesSinceMidnight // 60
if hoursSinceMidnight < 24 and... |
f97e5dbe14092f39d82077b6d610022bee8dd921 | newkstime/PythonLabs | /Lab02 - Variables/Problem5.py | 532 | 3.859375 | 4 | jackpot = int(input("Enter in the jackpot amount:"))
jackpot_annual = jackpot / 20
jackpot_annual_taxed = jackpot_annual * .70
jackpot_lump = jackpot * .65
jackpot_lump_taxed = jackpot_lump * .70
print("Your pre tax annual installment amount is: $", format(jackpot_annual, ",.2f"))
print("Your annual installment amount ... |
f02598ce41301d20062740172132e99841afa6f7 | newkstime/PythonLabs | /Lab11/Lab11P01.py | 782 | 3.96875 | 4 | import re
user_input = input("Enter a string:")
user_input = user_input.upper()
user_input = re.sub("[^a-zA-Z]","", user_input)
occurs_dict = {}
for n in user_input:
keys = occurs_dict.keys()
if n in keys:
occurs_dict[n] += 1
else:
occurs_dict[n] = 1
print("Dictionary:", occurs_dict)
find... |
fca87e784502567925ce41bdd5574ba263c30fe0 | newkstime/PythonLabs | /Lab08/Lab08P1.py | 614 | 3.984375 | 4 | def get_kWh_used():
kWh = float(input("Enter the number of kilowatt hours used:"))
while kWh < 0:
print("Invalid input.")
kWh = float(input("Enter the number of kilowatt hours used:"))
return kWh
def bill_calculator(kWhUsed):
lowRate = 0.12
highRate = 0.15
kWhLimit = 500
if ... |
269dde29e6bc2a138c37e57bfcbe02a3e9c31da7 | newkstime/PythonLabs | /Lab13/fly_drone_new/fly_drone_main.py | 531 | 3.640625 | 4 | from drone import Drone
drone1 = Drone()
keep_going = True
while keep_going == True:
user_input = input("Enter 1 for accelerate, 2 for decelerate, 3 for ascend, 4 for desend, 0 to exit:")
if user_input == "1":
drone1.accelerate()
elif user_input == "2":
drone1.decelerate()
elif user_inp... |
5b6c65b831d23d515d1374ff1d16fbf451bd15a9 | newkstime/PythonLabs | /Lab14/Problem1/main.py | 862 | 3.890625 | 4 | from Problem1.dinner_combo import Dinner_combo
from Problem1.deluxe_dinner_combo import Deluxe_dinner_combo
def main():
choose_dinner_type = input("For Dinner Combo, enter [1]. For Deluxe Dinner Combo, enter [2]: ")
while choose_dinner_type != '1' and choose_dinner_type != '2':
print("Invalid selection... |
762f0115352b4b776ece45f8d5998b5ec06cd2ea | M-Karthik7/Numpy | /main.py | 2,932 | 4.125 | 4 | Numpy Notes
Numpy is faster than lists.
computers sees any number in binary fromat
it stores the int in 4 bytes ex : 5--> 00000000 00000000 00000000 00000101 (int32)
list is an built in int type for python it consists of 1) size -- 4 bytes
2) reference count -- 8... |
7aed164cec411ae8a7cc3675a7b7b06512f6c742 | satishkmrsuman/tg | /printboard.py | 843 | 3.9375 | 4 | def create_board(num_place):
if(num_place-1)%3 != 0:
return ""
space_count=num_place*2
brace_space_count=0
hyphen_count=1
brace_string=""
board=" "*space_count+" {}\n"
for i in range(num_place-2):
if hyphen_count%3==0:
brace_string=" "*space_count+"{}"+"-"*(int((b... |
1334de81ce0e73855b4ee93b6ddd6b009271bb43 | Arkelis/adventofcode-2020 | /python/day06.py | 567 | 3.765625 | 4 | def count_yes(possible_answers, group_answers, need_all=False):
if need_all:
group_answers = set.intersection(*map(set, group_answers.split(" ")))
return sum(q in group_answers for q in possible_answers)
if __name__ == "__main__":
with open("inputs/day06.txt", "r") as f:
lines = (f.read() + "\... |
9344dfc77da748a5bcfc5c2eac7a1cd0b0e810f3 | Panda-ing/practice-py | /python_course/pentagram/pentagram_v3.0.py | 573 | 4.25 | 4 | """
作者:xxx
功能:五角星绘制
版本:3.0
日期:17/6/2020
新增功能:加入循环操作绘制不同大小的图形
新增功能:使用迭代绘制不同大小的图形
"""
import turtle
def draw_pentagram(size):
count = 1
while count <= 5:
turtle.forward(size)
turtle.right(144)
count = count + 1
def main():
"""
主函数
"""
size = 50
... |
785112f03098cc2414e8c6ac891305497ad58767 | yujin75/python | /6-6.py | 524 | 3.609375 | 4 | from random import randint
i = 4
#랜덤수 생성
answer = randint(1, 20)
#4번의 기회
while i>0:
guess = int(input("기회가 %d번 남았습니다. 1-20 사이의 숫자를 맞춰보세요: " % i))
if(guess == answer):
print("축하합니다. %d번만에 숫자를 맞추셨습니다." % (4-i+1))
break
elif(guess > answer):
print("Down")
i = i - 1
else:
... |
9ced4b8770aae2448d8e2e248bd5d6a1c654b595 | sverma1012/HackerRank-30-Days-of-Code | /Day 2: Operators.py | 601 | 3.890625 | 4 | # Day 2
# Goal: Operators
import math
import os
import random
import re
import sys
# Complete the solve function below.
def solve(meal_cost, tip_percent, tax_percent):
meal_tip = meal_cost + (meal_cost * (tip_percent / 100)) # The meal cost plus the tip given
meal_tip_tax = meal_tip + (meal_cost * (tax_perc... |
3e250750eca7c8bbb2796ee95d8dd61a2ffe27b1 | GrayThinker/PyAlgorithms | /test/test_sorts.py | 2,761 | 3.953125 | 4 | from src.sort import *
import unittest
"""
TODO:
Even number of elements
odd number of elements
empty list
single elements
only letters
only integers (+ve)
only floats (+ve)
mix of floats and integers (+ve)
mix of floats and letters (+ve)
mix of floats, letters, and integers (+ve)
only integers (+ve)
only floats (+ve)... |
700fb28af3caa49e9b8acc28cc41c7452f945845 | chenchaojie/leetcode350 | /stack/二叉树的前序遍历-144.py | 1,093 | 3.796875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ret = []
def preorder(root):
if not root... |
0f80eb652915be236193605ce1a2a088ed74adc0 | helkey/algorithm | /python/1114_PrintInOrder.py | 1,806 | 3.90625 | 4 | # 1114. Print in Order
TypeError: '_thread.lock' object is not callable
# Python offers mutexes, semaphores, and events for syncronization
import threading
import threading
class Foo:
def __init__(self):
self.lock2nd = threading.Lock()
self.lock3rd = threading.Lock()
self.lock2n... |
949b5ed3ca2e1c8e5b2c35834e8bdb201aec08fd | helkey/algorithm | /python/277FindCelebrity.py | 1,423 | 3.765625 | 4 | """ Find the Celebrity
Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity.
The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them.
https://leetcode.com/problems/find-the-celebrity/
Faster tha... |
9f32a55e154df63cb2abcccebe2204529d452a4d | helkey/algorithm | /python/912_sortarray.py | 1,323 | 3.703125 | 4 | # 912. Sort Array
# Merge Sort: Faster than 33% of Python submissions
# Merge sort has good cache performance and [parallelizes well](https://en.wikipedia.org/wiki/Parallel_algorithm)
# Time complexity O(n log n)
# Space complexity O(n)
# (illustration why not O(n log n): stackoverflow.com/questions/10342890... |
4fbbed2f514176ecc901224d3c1c487ef2389059 | helkey/algorithm | /python/111_Min_Dept_Binary_Tree.py | 592 | 3.671875 | 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 minDepth(self, root: TreeNode) -> int:
if not root: return 0
def mindp(node):
if not node: return 0
... |
1ab4306672ddfc5d4b2f0816942e097b06e1d0ca | helkey/algorithm | /python/110_Balanced_Binary.py | 1,879 | 3.625 | 4 | // 110.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def treeDepth(node: TreeNode) -> int:
if (node == None):
... |
7b827ff1f40b044c83f6aec9c06008840b550404 | hercules261188/python-studies | /Fibonacci/Iterative.py | 178 | 3.5625 | 4 | def fib(n):
if n == 0:
return 0
left = 0
right = 1
for i in range(1, n):
left, right = right, left + right
return right
print(fib(1)) |
dd11f7442672f3c2408d563d7924bd2d2b0d8ad3 | hercules261188/python-studies | /Fibonacci/Recursive.py | 509 | 3.90625 | 4 | # def fib(n):
# if n == 0 or n == 1:
# return n
# return fib(n - 1) + fib(n - 2)
# print(fib(2))
## Kotu cozum. Cunku olusan agacta fib degerleri sol ve sag
## dallanmalarda da hesaplaniyor.
## fib(3) + fib(2) icin => agacta fib(1), fib(2) iki kere hesaplaniyor
################# Daha iyi yol ######... |
9c87465b70bef73db613262b8d219b9cc92817d7 | BipronathSaha99/dailyPractiseCode | /class_4_help.py | 655 | 4.09375 | 4 | # Write a program to determine the smallest number among the four integers.
num_1=int(input('1st number:'))
num_2=int(input('2nd number:'))
num_3=int(input('3rd number:'))
num_4=int(input('4th number:'))
#==================> Condition<======================#
if (num_1<num_2 and num_1<num_3 and num_1<num_4):
... |
c23c54bbb0e2d2d322eabb501e0bf5954e9216d8 | BipronathSaha99/dailyPractiseCode | /pravin.py | 239 | 3.953125 | 4 | a=str(input("Enter numbers:"))
b=list(a) #type caste
print(b,type(b))
d= tuple(a) # type casting
print(d,type(d))
e={'a':2,'b':'d','c':4,'v':'u'}
print(e,type(e))
f=list(e)
print(f,type(f))
g=tuple(e)
print(g,type(g))
|
b9a452d73d50db7f8a601032ad5d7ce121ebfa21 | BipronathSaha99/dailyPractiseCode | /try_2.py | 431 | 4.09375 | 4 | #----------------------------Second list operation----------------------------------#
#--------------------------- Changing a member--------------------------------------#
my_list=["car","chalk","phone","bag"]
#--------------------------Q--------------------------------------#
#----------------------replace "phone"... |
23cbfdbc4c65c7b5c4b3012d6bd2d1938d27e4cb | BipronathSaha99/dailyPractiseCode | /oop_11.py | 4,332 | 4.78125 | 5 | '''Python datetime
In this article, you will learn to manipulate date and time in
Python with the help of examples.
Python has a module named datetime to work with dates and times.
Let's create a few simple programs related to date and time before we dig deeper.'''
# Example 1: Get Current Date and Time
# imp... |
842537dd9dc81702334029a1f9b2e702ae4900e8 | BipronathSaha99/dailyPractiseCode | /operator_presidence.py | 395 | 3.921875 | 4 | # operator presidency
# Precedence of or & and
# meal = "fruit"
# money = 0
# if meal == "fruit" or meal == "sandwich" and money >= 2:
# print("Lunch being delivered")
# else:
# print("Can't deliver lunch")
meal = "fruit"
money = 0
if (meal == "fruit" or meal == "sandwich") and money >= 2:
... |
c3fa208e407461517404f378a50ca85af3802e36 | sasa233/myLeetcode | /median-of-two-orderd-arrays.py | 1,567 | 4.0625 | 4 | '''
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 =... |
cdde76101e71f71436ab7201a9453101b6127bc9 | sasa233/myLeetcode | /search-a-2d-matrix.py | 2,420 | 3.890625 | 4 | '''
Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16... |
21f34d90b397554ace70954070fa42d55e402dfa | Yzoni/leren_2015-2016 | /leren2/schrijven3.py | 3,159 | 3.59375 | 4 | #!/bin/env python3.4
import csv
from enum import Enum
import math
# Enum to identify column index by name
class VarType(Enum):
x1 = 0
x2 = 1
y = 2
# Return the csvfile as a list of lists. A list for every row.
def readFile(csvfilename):
list = []
with open(csvfilename, 'r') as csvfile:
re... |
b332c5e5c54e330ff2b79c644cafab78924f158e | YiwenPang/Python-Code | /测试用解决方案/测试用解决方案/测试用解决方案.py | 1,081 | 3.515625 | 4 | def is_magicsquare(ls):
ls_width=len(ls[0])
s=set()
for i in range(0,ls_width):
for j in range(0,ls_width):
s.add(ls[i][j])
s_width=len(s)
if ls_width**2!=s_width:
return False
else:
answer = set()
for i in range(0,ls_width):
sum=0
... |
596529267281c086f4c763d565158516e423abd9 | ankitcs03/Python | /ind.py | 369 | 3.5 | 4 |
# Define an alphabetic indexing tuple.
ind = tuple('abcdefghijklmnopqrstuvwxyz')
typ = ('DVD_FULL_SCREEN','DVD_WIDE_SCREEN','BLU-RAY')
mat = {}
stmt=""
for j, e in enumerate(typ):
mat[str(ind[j])] = typ[j]
if j == len(typ) - 1:
stmt = stmt + ":" + str(ind[j])
else:
stmt = stmt + ":" + str(ind... |
80c382ad5fcdcb2b4f38760c0b3fb02af3737cf5 | ankitcs03/Python | /class.py | 445 | 3.6875 | 4 |
class Test:
def __init__(self, name=None):
print("Initial method has been called")
self.name = name
def say_hi(self):
if self.name:
print("Hello ! " + self.name + " Good Morning. ")
else:
print("Hello ! there, Good Morning")
def get_name(self):
return self.name
def set_name(self, name):
sel... |
92715a493240b5629dc84ae4c219cbe9b89e287e | ankitcs03/Python | /decorator.py | 286 | 3.578125 | 4 |
def our_decorator(func):
def function_wrapper(x):
print("Before calling the function " + func.__name__)
func(x)
print("After calling the function " + func.__name__)
return function_wrapper
@our_decorator
def foo(x):
print("function is called with string " + str(x))
foo(25)
|
4da010af3dc4c4175ee18da9c57a2e7296b7ec9b | kenilpatel/Analysis-of-search-algorithm | /BST.py | 2,482 | 4 | 4 | class node:
def __init__(self,val):
self.key=val
self.right=None
self.left=None
def data(self):
print(self.key)
def add(root,val):
if(val<root.key):
if(root.left==None):
temp=node(val)
root.left=temp
else:
add(root.left,val)
elif(val>root.key):
if(root.right==None):
temp... |
eecff8d0603298af3c4f90363a039b4437065f75 | NateTheGrate/Fretboard-Memorizer | /src/main.py | 1,119 | 3.546875 | 4 | from note import AltNote, Note
from card import Card
import constants
import util
import random
guitar = util.generateGuitar()
cards = []
for string in guitar:
for note in string:
cards.append(Card(note))
def leveler(card: Card, isRight):
cardLevel = card.getLevel()
if(isRight):
card.s... |
59cd9b98d34273e0b122c715419209a30650260f | fifabell/Algorithm | /real_/test_.py | 106 | 3.609375 | 4 | t = [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
# for k in range(3):
# for i in range(3):
print(t[0]) |
584535e69b9d25a407d577481b2d16fe72715f4e | fifabell/Algorithm | /real_/test08_.py | 1,124 | 3.625 | 4 | T = int(input())
for i in range(T):
deque = input() # R과 D를 저장
ar_size = int(input()) # 배열의 크기를 저장
if deque.count("D") > ar_size: # D의 개수가 ar의 크기보다 많으면 error출력
print("error")
input()
continue
if deque.count("R") % 2 == 0: # R이 짝수이면 최종 값은 reverse를 하지않아도 됨.
final_reverse ... |
1ca0d3089cf33131b408c6f11ff4ec813a02f6f4 | chengyin38/python_fundamentals | /Fizz Buzz Lab.py | 2,092 | 4.53125 | 5 | # Databricks notebook source
# MAGIC %md
# MAGIC # Fizz Buzz Lab
# MAGIC
# MAGIC * Write a function called `fizzBuzz` that takes in a number.
# MAGIC * If the number is divisible by 3 print `Fizz`. If the number is divisible by 5 print `Buzz`. If it is divisible by both 3 and 5 print `FizzBuzz` on one line.
# MAGIC ... |
faa3bd2bb899f33f45daa9ce54a38f75183459db | dennis1219/baekjoon_code | /if/9498.py | 146 | 3.875 | 4 | a = int(input())
if 90<=a<=100:
print("A")
elif 80<=a<=89:
print("B")
elif 70<=a<=79:
print("C")
elif 60<=a<=69:
print("D")
else:
print("F") |
7cea3bb59ffc5beddadd98aef1857a15ad21acd8 | koichi210/Python | /OfficialTutorial/03_1_3_1_list.py | 342 | 3.90625 | 4 | # -*- coding: utf-8 -*-
# リスト型
param = [1, 2, 4, 8, 16]
introduction = 'my name is python'
# すべての値
print(param)
# 先頭の値
print(param[0])
# 最後の値
print(param[-1])
# 指定Index以降の値
print(param[-3:])
# 要素追加
param.append(32)
print(param[:])
# リストの連結
print(param[:] + [64, 128])
|
10279b24d88b34263fa954797876b26ddb3baeb7 | koichi210/Python | /Pytest/main/counter.py | 575 | 3.6875 | 4 | class Counter:
def __init__(self):
print("init")
self.counter = 0
def Increment(self):
print("inc=", self.counter)
self.counter += 1
return self.counter
def Decrement(self):
print("dec=", self.counter)
self.counter -= 1
return self.counter
... |
8a58f4a0d6625b2f191d0fefdc1e45f06edd8ebe | cc200723/My-way-of-learning | /python project/程序员.py | 2,037 | 3.90625 | 4 | from turtle import *
import math
# 设置画布宽高/背景色和设置画笔粗细/速度/颜色
screensize(600, 500, '#99CCFF')
pensize(5),speed(10),color('red')
# 定义椭圆函数: 绘制蜡烛火焰和被圆柱函数调用
def ellipse(x,y,a,b,angle,steps):
penup(),goto(x,y),forward(a),pendown()
theta = 2*math.pi*angle/360/steps
for i in range(steps):
nextpoint ... |
26eaae35a73bf292aa9a4a2b637eb9dca6a9b11d | aseruneko/diceforge-ai | /src/main/resolve.py | 3,433 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
効果解決用のモジュール
"""
"""
- 後で書く
"""
__author__ = "seruneko"
__date__ = "30 May 2020"
from main.Board import Board
from main.Face import Face
"""
[関数]
resolve_effect(player, effect):
何らかのエフェクトを処理するメソッド。
将来的にどこかに切り出したい。
resolve_face(player, face)... |
b81f7ec2dd98736d89a62899636f9f2b1abe7025 | greywolf37/my_playground | /merge.py | 2,385 | 3.984375 | 4 | '''
algorithm
introduce a splitting function
introduce merge function
takes two lists
ind_1 and ind_2 as indexes for the two lists (initial at 0)
while both are smaller tahn length
the smaller one is appended to a new list, and that counter in increases
when on index reaches its lenth -1, app... |
ad50eac801550d2fc0df1580e457b048f06076f7 | angelfaraldo/intro_python_music | /ejercicios/2-02E_text-drum-sequencer.py | 986 | 3.875 | 4 | """
INTRODUCCIÓN A LA PROGRAMACIÓN EN PYTHON A TRAVÉS DE LA MÚSICA
Ángel Faraldo, del 19 al 23 de julio de 2021
Campus Junior, Universitat Pompeu Fabra
EJERCICIO 2 - DÍA 2
======
En este ejercicio te pido que crees un secuenciador de batería
polifónico que convierta secuencias de texto en un patrón de batería.
REGLAS... |
a85d09e57b7a1e7fdaa8055003c922b494b7e437 | angelfaraldo/intro_python_music | /1-01_crear-y-ejecutar-programas.py | 1,424 | 4.46875 | 4 | """
INTRODUCCIÓN A LA PROGRAMACIÓN EN PYTHON A TRAVÉS DE LA MÚSICA
Ángel Faraldo, del 19 al 23 de julio de 2021
Campus Junior, Universitat Pompeu Fabra
"1-01_crear-y-ejecutar-programas"
contenidos: print(), comentarios, input(), variables, string concatenation
"""
# PRINT y CADENAS
print("hola, chicas y chicos!")
pri... |
5cbc0e9ee358b075eca47fe9ee07467bd89bbbc9 | angelfaraldo/intro_python_music | /1-03_timbre.py | 584 | 3.53125 | 4 | """
INTRODUCCIÓN A LA PROGRAMACIÓN EN PYTHON A TRAVÉS DE LA MÚSICA
Ángel Faraldo, del 19 al 23 de julio de 2021
Campus Junior, Universitat Pompeu Fabra
"1-03_aritmetica-y-parametros-del-sonido"
contenidos: intensidad, timbre
"""
from sine_tone import *
# ============================================================
#... |
fa1ae280d38126576183aa11dd92a9bffc54f075 | imjs90/Python_Exercises | /Username_Password.py | 403 | 3.78125 | 4 | #create a username and password system for a Email service
name = ['','']
while name[0] != 'iman' or name[1] != "123":
name[0] = input("enter name:")
name[1] = input("enter pass:")
print('Thank you!')
'''
stars = ''
for i in ('*'):
i = ' ' + i
while stars != '**':
stars += i
print(sta... |
6c5346e39123497c12ed7e01cf956fefb2aa456d | NToepke/glowing-spoon | /Python Intro Projects/Gradebook/gradebook.py | 3,102 | 3.78125 | 4 | # gradebook.py
# Nathan Toepke NST9FK
# Display the average of each student's grade.
# Display tthe average for each assignment.
gradebook = [[61, 74, 69, 62, 72, 66, 73, 65, 60, 63, 69, 63, 62, 61, 64],
[73, 80, 78, 76, 76, 79, 75, 73, 76, 74, 77, 79, 76, 78, 72],
[90, 92, 93, 92, 88, 93, 90... |
d9a10876de3734ff92d0aa77aff01c8fe5f280f8 | maslyankov/python-small-programs | /F87302_L3_T1.py | 550 | 4.28125 | 4 | # Encrypt a string using Cesar's cipher.
import sys
plain = sys.argv[1]
key = int(sys.argv[2])
translated = ''
for i in plain:
if i.isalpha():
num = ord(i)
num += key
if i.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
... |
90ffafae4bd67ca781bb3022287c9cf0adda7e57 | opi-lab/preliminares-pedroelectronico1995 | /ch01-example1.py | 1,784 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 01 21:12:08 2018
@author: PEDRO NEL MENDOZA
"""
# The module Image of PIL is imported:
from PIL import Image
mod_image = Image.open('data/torres_blancas.jpg') # Read an image
mod_image.show() # Show the image
pil_image = Image.... |
cef9193396d0cf4e87b7bd0e595b1168ffd13e17 | claudewill1/CodingDojo | /python/fundamentals/oop/Ninjas_vs_Pirates/classes/ninjas.py | 828 | 3.546875 | 4 | import random
import math
class Ninja:
def __init__(self,name) -> None:
self.name = name
self.strength = 15
self.speed = 5
self.health = 100
def show_stats(self):
print(f"Name: {self.name}\nStrength: {self.strength}\nSpeed: {self.speed}\nHealth: {self.health}")
de... |
c3581471b802aad77a47e9b0bd6ce01b7493d910 | jcwyatt/speedtrap | /speedtrap.py | 1,432 | 4 | 4 | import datetime as dt
#speed trap
def timeValidate(t):
#check the length
if len(t) != 8:
print(t, "invalid length, must be hh:mm:ss")
return False
#check for numbers in the right places
numPosns=(0,1,3,4,6,7)
for i in numPosns:
if not t[i].isnumeric():
print (t,"invalid time format, must be numeric eg... |
42fdc065b4d1a8935e37d3d4abb7a2703916cc77 | suntyneu/test | /test/2个数字比较大小.py | 379 | 3.84375 | 4 | print("请输入2个2位数")
num1 = int(input())
num2 = int(input())
if num1 // 10 > num2 // 10:
print("第一个输入的数字大。")
if num1 // 10 == num2 // 10 and num1 % 10 > num2 % 10:
print("第一个输入的数字大。")
if num1 // 10 == num2 // 10 and num1 % 10 == num2 % 10:
print("两个数字相等。")
else:
print("第二个输入的数字大")
|
78c81da0381174869334638036a3d11d5bb493a0 | suntyneu/test | /test/类Class/6、析构函数.py | 915 | 4.15625 | 4 | """
析构函数:__del__(): 释放对象时候自动调用
"""
class Person(object):
def run(self):
print("run")
def eat(self, food):
print("eat" + food)
def say(self):
print("Hello!my name is %s,I am %d years old" % (self.name, self.age))
def __init__(self, name, age, height, weight): # 可以有其他的参数列表
... |
6755aead3f29751165fd43e89e2cbc338d6be20b | suntyneu/test | /.idea/8、Checkbutton多选框按钮控件.py | 943 | 3.671875 | 4 | import tkinter
# 创建主窗口
win = tkinter.Tk()
# 创建标题
win.title("sunty")
# 设置大小和位置
win.geometry("400x400+200+20")
def update():
message = ""
if hobby1.get() == True:
message += "money\n"
if hobby2.get() == True:
message += "power\n"
if hobby3.get() == True:
message += "girl"
#... |
650d4aef4badd81c9fa5ca857488a3210ec2c735 | suntyneu/test | /test/类Class/对象属性与类属性/3、运算符重载.py | 417 | 3.96875 | 4 | # 不同的类型用加法会有不同的解释
class Person(object):
# name = "运算符重载"
def __init__(self, num1):
self.num1 = num1
def __add__(self, other):
return Person(self.num1 + other.num1)
def __str__(self):
return "num = " + str(self.num1)
per1 = Person(1)
per2 = Person(2)
print(per1 + per2)
# 等同于
... |
516e25c0109b5f341a09918ad53f0cf929399a1c | suntyneu/test | /test/Tkinter/23、相对布局.py | 476 | 3.59375 | 4 | import tkinter
# 创建主窗口
win = tkinter.Tk()
# 创建标题
win.title("sunty")
# 设置大小和位置
win.geometry("600x400+200+20")
label1 = tkinter.Label(win, text="good", bg="red")
label2 = tkinter.Label(win, text="ok", bg="yellow")
label3 = tkinter.Label(win, text="nice", bg="blue")
# 相对布局 窗体改变对控件有影响
label1.pack(fill=tkinter.Y, side=t... |
01fad2b064745800f95aed23c0ecfdd00e339d35 | suntyneu/test | /test/while-else语句.py | 250 | 3.875 | 4 | """
while 表达式:
语句1
else:
语句2
逻辑:在条件语句(表达式)为False时,执行else中的的“语句2”
"""
a = 1
while a <= 3:
print("sunck is a good man!")
a += 1
else:
print("very very good!")
|
065abbd254823c5bd5cfdcc7a14a5b66b36441fa | suntyneu/test | /for语句.py | 733 | 4.1875 | 4 | """
for 语句
格式:
for 变量名 in 集合:
语句
逻辑:按顺序取 "集合" 中的每个元素,赋值给 "变量"
在执行语句。如此循环往复,直到取完“集合”中的元素截止。
range([start,]end[,step]) 函数 列表生成器 start 默认为0 step 步长默认为1
功能:生成数列
for i in [1, 2, 3, 4, 5]:
print(i)
"""
a = range(12)
print(a)
for x in range(12):
print(x)
for y in range(2, 20, 2):
pr... |
634ec7c51e7db7cdc6a46c67478617c4f8d1748c | suntyneu/test | /面向对象/练习.py | 916 | 4.1875 | 4 | """
公路(Road):
属性:公路名称,公路长度
车 (car):
属性:车名,时速
方法:1.求车名在那条公路上以多少时速行驶了都吃,
get_time(self,road)
2.初始化车属性信息__init__方法
3、打印显示车属性信息
"""
class Road(object):
def __init__(self, road_name, road_len):
self.road_name = road_name
self.road_len = road_len
print(self.ro... |
7b29da5b17daf339adaeb121a55e425007daa363 | suntyneu/test | /类Class/对象属性与类属性/2、@property.py | 852 | 3.890625 | 4 | class Person(object):
def __init__(self, age):
# self.age = age
# 限制访问
self.__age = age
# per = Person(18)
# print(per.age)
# 属性直接暴露,不安全,没有数据的过滤
# def get_age(self):
# return self.__age
#
# def set_age(self, age):
# if age < 0:
# ... |
f93465e46e7201df11fcd754cf9bcffeb9fe17f1 | suntyneu/test | /函数/装饰器.py | 2,659 | 4.15625 | 4 | """
装饰器
概念:一个闭包,把一个函数当成参数,返回一个替代版的函数。
本质上就是一个返回函数的函数
"""
def func1():
print("sunck is a good man")
def outer(func):
def inner():
print("*******************")
func()
return inner
# f 是函数func1的加强版本
f = outer(func1)
f()
"""
那么,函数装饰器的工作原理是怎样的呢?假设用 funA() 函数装饰器去装饰 fu... |
d1a5fb15360cd089ab69ac5a15ab6a8f3228e662 | ClementRabec/Project-Euler | /Problem 25/1000-digit_Fibonacci_number.py | 166 | 3.6875 | 4 | Fn1 = 1
Fn2 = 1
length = 0
index = 2
digits = 1000
while length < digits:
Fn = Fn1 +Fn2
Fn2 = Fn1
Fn1 = Fn
length = len(str(Fn))
index += 1
print index
|
96bebcfc1ae29d264dc7607edcc6da21d59830fd | AniketGurav/PyTorch-learning | /MorvanZhou/MorvanZhou_2_NeuralNetwork_2_Classification.py | 2,895 | 3.921875 | 4 | """
Title: 莫烦/ 建造第一个神经网络/ Lesson2-区分类型(分类)
Main Author: Morvan Zhou
Editor: Shengjie Xiu
Time: 2019/3/21
Purpose: PyTorch learning
Environment: python3.5.6 pytorch1.0.1 cuda9.0
"""
# 分类问题:类型0和类型1,分别在(2,2)附近和(-2,2)附近
import torch
import matplotlib.pyplot as plt
# 假数据
n_data = torch.ones(100, 2) # 数据的基本形态
x0 ... |
f72939444cd1d81c5330aa59aceda121e1d85c04 | Gangamagadum98/Python-Programs | /revision/insertionSort.py | 294 | 3.796875 | 4 |
def insertion(num, x, pos):
b = []
if pos <= len(num):
for i in range(0, len(num)):
if i == pos:
num[i] = x
else:
b = num
return b
num = [4, 5,1, 3,8]
x=7
pos=3
res = insertion(num, x, pos)
print(res) |
d0808e2744eb995a353a7dc85c55644ccfa00825 | Gangamagadum98/Python-Programs | /revision/array.py | 781 | 3.5 | 4 | from array import *
vals = array('i',[2,6,4,3])
print(vals.buffer_info())
vals.append(9)
print(vals)
vals.reverse()
print(vals)
for i in range(4):
print(vals[i])
for e in vals:
print(e)
value = array('i',[3,2,1,4,5,6,7])
newarr = array(value.typecode,(a*a for a in value))
print(newarr)
arr = array('i',[])
n =... |
91d973b7cb61b34c9fbc5d2570ca43c0984e6b21 | Gangamagadum98/Python-Programs | /revision/jump.py | 549 | 3.65625 | 4 | import math
def jump(a, num):
n = len(li)
prev = 0
step = math.sqrt(n)
while a[int(min(step, n-1))] < num:
prev = step
step += math.sqrt(n)
if prev >= n:
return -1
while a[int(prev)] < num:
prev += 1
if prev == min(step, n):
return ... |
42213a5ffbb32930905ca90352602b247c5c2b2d | Gangamagadum98/Python-Programs | /prgms/main.py | 464 | 3.59375 | 4 | # import test
# print(__name__)
#If we r executing in the same file than (__name__) vl print as (__main__), but if we r import file from another module
# In that module is(__name__) is present then it vl display the file name not (__main__)
def func():
print("Hello")
print("Hi")
if __name__=="__main__": #... |
d87ea216dac12fd6c38edc1816f8a4b8b75dbba9 | Gangamagadum98/Python-Programs | /prgms/tuple.py | 113 | 3.75 | 4 | t=(1,3,"hi",7.3,"Hello")
print(t[1])
print(t[1:4])
print(t[:3])
print(t*2)
print(t+t)
print(t[0])
print(type(t))
|
82c60df06ae44e6306e3849563c3b195408e7429 | Gangamagadum98/Python-Programs | /prgms/ex.py | 1,009 | 3.734375 | 4 | from array import *
def fact(x):
fact = 1
for i in range(1,x+1):
fact= fact*i
return fact
result = fact(4)
print(result)
def fact(n):
if n == 0:
return 1
return n*fact(n-1)
result1 =fact(4)
print(result1)
def fib(n):
a=0
b=1
if n==1:
... |
d8e7380b90c6b5ce1452fd8b6dcfec04ace3aff6 | Gangamagadum98/Python-Programs | /PythonClass/LearningPython.py | 774 | 3.9375 | 4 | name="Ganga"
#print(name)
def learnPython(x):
# print("We are learning python")
# print(x)
return 12
num=learnPython(10)
#print(num)
def add(a,b):
return a+b
num1 =add(5,1)
#print(num1)
def sub(a,b):m1 =mul(5,4)
#print(num1)
def random(*... |
77091f08b893364629e2d7170dbf1aeffe5fab5a | Gangamagadum98/Python-Programs | /sample/Calculator.py | 451 | 4.15625 | 4 | print("Enter the 1st number")
num1=int(input())
print("Enter the 2nd number")
num2=int(input())
print("Enter the Operation")
operation=input()
if operation=="+":
print("the addition of two numbers is",num1+num2)
elif operation == "-":
print("the addition of two numbers is", num1 - num2)
... |
6a9bbf06a420871ba02156e8b2edd1f74accf35a | Gangamagadum98/Python-Programs | /PythonClass/BubbleSort.py | 409 | 4.09375 | 4 | def bubbleSort(unsorted_list):
for i in range (0, len(unsorted_list)-1):
for j in range (0, len(unsorted_list)-i-1):
if unsorted_list[j] > unsorted_list[j+1]:
temp = unsorted_list[j]
unsorted_list[j] = unsorted_list[j+1]
unsorted_list[j+1] = temp
... |
84f0474f6b6a62bb456200998e037c6efbd9c294 | Gangamagadum98/Python-Programs | /prgms/Decorators.py | 353 | 3.65625 | 4 | # Decorators - Add the extra features to the existing functions'
#suppose code is in another functioon , you dont want to change that function that time use decorators
def div(a,b):
print(a/b)
def smart_div(func):
def inner(a,b):
if a<b:
a,b=b,a
return func(a,b)
return inner
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.