blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
87bae709c255462ab50550134d9e5a1cfbd403d3 | tkonopka/phenoscoring | /tools/timing.py | 711 | 3.75 | 4 | """
Helper functions for timing performance
"""
from timeit import default_timer as timer
def time_function_2(a, b, fun, replicate=5000):
"""assess running time for fun(a, b)"""
start = timer()
for i in range(replicate):
fun(a, b)
end = timer()
return end-start
def time_fu... |
7ede0f3575b66c272333a551759186138902bf66 | Big-Pony/daily | /力扣/练习/面试题01.07.py | 627 | 3.875 | 4 | class Solution:
def rotate(self, matrix):
import math
"""
Do not return anything, modify matrix in-place instead.
"""
n=len(matrix)
half=math.ceil(n/2)
print(n,half)
for i in range(n):
for j in range(i,n):
matrix[i][j],matr... |
eab6badae1944e4241bdf9cf2596db0e1f58bb4e | unites/code_library | /python/variables.py | 326 | 3.828125 | 4 |
# Strings and other static Vars
a_string = ""
# Lists
a_list = []
# Dictionaries
a_dictionary = {"plane": "p40", "country": "US", "type": "fighter"}
## Store value
key_value = a_dictionary["plane"]
## Change values
a_dictionary["plane"] = "p38"
## Number of values in dictionary
print(len(a_dictionary))... |
37dfadf1a146dcc832f5f531710189c6f95024b2 | gitcommer/Python | /python-notes.py | 38,336 | 3.9375 | 4 | """
error - mo matter and spacing in python code
note: - everything in python is an object or function
- there are two types of number in python integers and float
- python start always in 0
- inig human nimo og input adto mag start sa top ang pag read sa code
- ang p... |
3571e74cb926624097c5d2c24bca4cbe372c7de6 | MMesbahU/FamiLinx_PY | /V0.1/pythonUI/libs/Kinship/CAsearch.py | 5,646 | 3.71875 | 4 | """
this is a general module for conducting searches in pedigrees
it requires an implementation of an interface class that walks the pedigree by retrieving children or parents for each entry (ID)
the interface class is defined in pedInterface.py
"""
from numpy import *
DEBUG=False
DEBUG1=False
# helpers
class Ances... |
a4b8d994f7a4fbc14732d43a7ac12db94383e839 | mpsb/practice | /codewars/python/cw-remove-the-minimum.py | 1,253 | 4.25 | 4 | '''
The museum of incredible dull things wants to get rid of some exhibitions. Miriam, the interior architect, comes up with a plan to remove the most boring exhibitions. She gives them a rating, and then removes the one with the lowest rating.
However, just as she finished rating all exhibitions, she's off to an impo... |
c372e0e79d7b386e36aabb76158701f29e7c5108 | Kelpsykongroo/kelpsykongroo.github.io | /parte 2/contaSegundos.py | 278 | 3.859375 | 4 | segundos = float(input("Por favor, entre com o número de segundos que deseja converter:"))
d=int(segundos//86400)
h=int((segundos%86400)//3600)
m=int(((segundos%86400)%3600)//60)
s=int(((segundos%86400)%3600)%60)
print(d,"dias,",h,"horas,",m,"minutos e",s,"segundos.")
|
76210e093d925d9cce30b4951d605fa46d2744a1 | ictlyh/PythonExamples | /exam3.py | 487 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@desc: 一个整数,它加上100和加上268后都是一个完全平方数,请问该数是多少?
@author: Yuanhao Luo
@contact: luoyuanhao@software.ict.ac.cn
@file: exam3.py
@time: 2016/12/18 20:44
"""
import math
def func():
for i in range(1, 10000):
x = int(math.sqrt(i + 100))
y = int(math.sqrt(i... |
75d9dee6c59edcda54671929d469dac1ab5300c0 | afcarl/CS450 | /week01/hardcodedClassifier.py | 2,889 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 17 21:24:15 2016
@author: nick
"""
import sys
import random
import collections
from sklearn import datasets
# 5. Create a class for a "HardCoded" classifier
class HardCoded():
guess = "something"
def train(self, dataset):
for item in dataset:
... |
0a97c14f4036ddb1681646c65240220bb5b31cf7 | shashi29/hangman- | /task_2.py | 3,198 | 3.578125 | 4 | import pandas as pd
import time
def predict(data , word):
word = word
data = data.copy()
word = word.lower()
Flag = 0
input_word_length = len(word)
print("Lenght of input character",input_word_length)
#Filter out the word from data which has length = input_word_length
specific_... |
f4d5844322da659e36d46b2dc66fb61bc1636423 | DimpleOrg/PythonRepository | /Python Crash Course/vAnil/Chapter-10/10-10.py | 726 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 21:34:59 2021
@author: ANIL
"""
def findWord(file_name, word):
with open(file_name) as f:
contents = f.read()
return contents.lower().count(word)
print(findWord('hints_for_lovers.txt', 'the'))
print(findWord('little_masterpieces_of_sc... |
6acbf1c52b8491953831af22613c0b027e6e553e | LanaTch/Algorithms | /Lesson3/Lesson3_t9_hw.py | 787 | 4.1875 | 4 | # 9. Найти максимальный элемент среди минимальных элементов столбцов матрицы.
import random
SIZE_COL = 4
SIZE_ROW = 5
MIN_ITEM = -10
MAX_ITEM = 20
matrix = [[random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE_COL)] for _ in range(SIZE_ROW)]
for i in range(SIZE_ROW):
for j in range(SIZE_COL):
print(mat... |
85d1bace6aa438bf850a7385b7cf9b04e8b5f7f3 | thvithran/Python-Projects- | /Basic Encryption.py | 728 | 4.5 | 4 | def encryption(string,step):
output = ""
for char in string:
# Every character has a numeric value, this is how the computer can understand it
output += chr(ord(char) - step)
# We simply change the numeric value of the character, which results in another character
return output
def ... |
f174a95854eeae48be21b43266c5db198853a40e | Tiffanylqc/SAT-Solver | /WALK_SAT.py | 6,946 | 3.6875 | 4 | import random
import time
import copy
# A clause consists of a set of symbols, each of which is negated
# or not. A clause where
# clause.symbols = {"a": 1, "b": -1, "c": 1}
# corresponds to the statement: a OR (NOT b) OR c .
class Clause:
def __init__(self):
pass
def from_str(self, s):
s = s.... |
8cab27df80b952500ecab186ebc099dca671bf60 | MayankVachher/scrabby-MacApps | /buildFiles/trie.py | 1,134 | 4 | 4 | #Trie implementation using child pointers in hash table (dictionary)
class TrieNode(object):
def __init__(self, char):
self.char = char
self.children = {}
def setChild(self, node):
self.children[node.char] = node
def getChild(self, character):
return self.children.get(character)
class Trie(object):
def... |
85ffa36cd7bf337de0a436b702d869f0da9f77fb | nrprice/5-3-1-Planner | /five_three_one_planner.py | 7,514 | 3.953125 | 4 | import pandas as pd
from pandas import ExcelWriter
import math
5/3/1 is a workout program where your loads are based on a percentage of your one rep max for four exercises: the squat, deadlift, bench press and overhead press.
This program will ask a user for their best rep max, be it one rep or more, and will calculat... |
de8565f90a5b1160a386a1bf1030010f1e547261 | NixonZ/PythonZ | /Practice_ques/List Comprehensions.py | 285 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 4 22:42:43 2018
@author: Nalin Shani
"""
A=[]
x=''
while 1:
temp=input("Enter a number to add to the array(type 'exit'to quit)\n")
if temp=='exit':
break
A.append(int(temp))
B=[temp for temp in A if not(temp%2)]
print(B) |
4744052a94f420973356a7d6bf97f9bfc6a56f85 | chihkaiyu/sorting | /insertion/main.py | 583 | 4.125 | 4 | def insertion_sort(nums):
for i in range(1, len(nums)):
for j in range(i, 0, -1):
if nums[j] < nums[j-1]:
nums[j], nums[j-1] = nums[j-1], nums[j]
return nums
def main():
test = [
[1, 2, 3, 4, 5],
[5, 4, 3, 2, 1],
[2, 4, 1, 3, 5],
]
expec... |
81a0618fa9a868af920db70cc9bbd2248e516bed | gowthamnvg/gowtham | /bin.py | 99 | 3.75 | 4 | inp1=input()
S=set(inp1)
L={'0','1'}
if S==L or S=='0' or L=='1':
print("yes")
else:
print("no")
|
4aca055394ae17a9a7d9ca09e2ca813bf5af35a9 | DKNY1201/programming-python | /Tree/ConstructBinarySearchTreeFromPreorderTraversal.py | 740 | 3.625 | 4 | class Solution:
def bstFromPreorder(self, preorder):
if not preorder:
return None
root = TreeNode(preorder[0])
for i in range(1, len(preorder)):
self.helper(root, preorder[i])
return root
def helper(self, root, n):
# print(root and root.val)
... |
2aa68a7dff1abb9dc256fcb989484abf68a744e7 | remixknighx/quantitative | /exercise/leetcode/toeplitz_matrix.py | 821 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
766. Toeplitz Matrix
@link https://leetcode.com/problems/toeplitz-matrix/
"""
from typing import List
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
width = matrix[0].__len__()
height = matrix.__len__()
for x in range(height):
... |
3e5d6863354ea3852d2c8bbd79ac1cc91ebb9a49 | algorithm005-class01/algorithm005-class01 | /Week_02/G20190343020352/LeetCode_49_0352.py | 384 | 3.578125 | 4 | import collections
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
hashMap = collections.defaultdict(list)
for str in strs:
count = [0] * 26
for char in str:
count[ord(char) - ord('a')] += 1
h... |
97757997335b5822026b13c3c09f9a6948b140e5 | Chidi-nwachukwu/python-exercise2 | /python_frestyling/home_work.py | 787 | 4.375 | 4 | # let's collect an unknown number of student grades and find the average of the grades
# Algorithm
# step 1
# collect first student grade
# step 2
# initialize counter to zero
# step 3
# check if student grade is not a negative 1
# step 4
# keep collecting student grade... |
3fc4c707c3ff4a428f003d304306fff9c726224d | shumingpeh/kaggle-ncaa-madness-men | /Logistics_Regression_Model.py | 2,536 | 3.546875 | 4 |
# coding: utf-8
# ___
# This notebook tries to do a simple prediction of which team will win in a random match based on seeding
# In[51]:
import pandas as pd
import numpy as np
import scipy
from sklearn import *
# ## Read data
# In[36]:
raw_data = pd.read_csv("input/tour-results-seed.csv")
# ## Data Transfo... |
7247941436363e6c080a68e930653b3b9981d133 | KamilPrzybysz/python | /18.03.18/zad14/zad14.py | 549 | 3.5625 | 4 | s1='abC'
s2='123'
s3='pies i kot'
s4=''
print('a)'+str(s1.isalnum())+str(s2.isalnum())+str(s3.isalnum())+str(s4.isalnum()))
print('b)'+str(s1.isalpha())+str(s2.isalpha())+str(s3.isalpha())+str(s4.isalpha()))
print('c)'+str(s1.isdigit())+str(s2.isdigit())+str(s3.isdigit())+str(s4.isdigit()))
print('d)'+str(s1.islower()... |
cd7d980a2aab220bb972cff966a178272ba1d538 | mouyleng2508/PycharmProjects | /week03:ex/42_dec_to_oct.py | 390 | 3.859375 | 4 | # First:
# def dec_to_oct(decimal):
# return oct(decimal)[2:]
#
# print(dec_to_oct(98))
# Second:
# def dec_to_oct(decimal):
# octal = [0] *100
# x = 0
# while decimal != 0:
# octal[x] = decimal % 8
# decimal = int(decimal/8)
# x += 1
#
# for y in range(x-1, -1, -1):
# ... |
ebfc72bf50954a3d2728d49a0d0912502e003a9b | ASravanthi1/python1 | /amstrong.py | 136 | 3.765625 | 4 | a=int(input(""))
temp=a
sum=0
while(a>0):
b=a%10
sum=b**3+sum
a=a//10
if(temp==sum):
print("yes")
else:
print("no")
|
770d187a19fcec1deb0b8d964060edcfa5f9198f | gratisninja/advent-of-code | /2016/8/main.py | 1,315 | 3.5625 | 4 | import os
def printscreen(screen):
os.system('cls')
for a in screen:
for b in a:
print("_" if b == False else "#", end = "")
print()
def row_rotate(screen, row, step):
screen[row] = screen[row][-step:] + screen[row][:-step]
def column_rotate(screen, col, step):
column = [s... |
9faa0a0924aebf888f0007645d9f34c29a439695 | RichardcLee/Py_Notes | /High Performance/Multiprocess/1.py | 1,089 | 3.515625 | 4 | from multiprocessing import Process
import os
import time
# 子进程要执行的代码
def run_proc(name):
time.sleep(1)
print('Run child process %s (%s)...' % (name, os.getpid()))
if __name__ == '__main__':
# 例1
print('---------------------------------')
print('Parent process %s.' % os.getpid())
p = Process... |
09b375f73000da5727113ba6750fc144f3d2add8 | 1oser5/LeetCode | /算法/leastInterval.py | 1,068 | 3.5 | 4 | #!/usr/bin/env python3.7
# -*- encoding: utf-8 -*-
'''
@File : leastInterval.py
@Time : 2019/12/30 16:04:16
@Author : Xia
@Version : 1.0
@Contact : snoopy98@163.com
@License : (C)Copyright 2019-2020, HB.Company
@Desc : None
'''
# here put the import lib
from typing import List
class Solution:
... |
a2afd44e19e05f90d5ede775e1ea2a53f74a81db | getWatermelon/JetBrains-Academy-Zookeper | /Problems/Find even/main.py | 102 | 4.0625 | 4 | num = int(input())
even_num = 0
num -= 2
while even_num < num:
even_num += 2
print(even_num)
|
721614750aa36c1eb624a9660b901fcd68dd45a5 | singhr2/Python101 | /basics/BasicOSandFiles.py | 639 | 4.03125 | 4 | '''
This files demos basic functions related to OS and Files
'''
import os
print('Current Directory :', os.getcwd())
import sys
# Is it python version ?
print('sys.version :', sys.version) # 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)]
print('OS :', sys.getwindowsversion()) #sys.getwin... |
85839535527b0c9f8670f9b0ee079b7947effa74 | jabhij/UTAx-CSE1309x-PYTHON | /ASSIGNMENT-2/Part2.py | 1,861 | 4.1875 | 4 | """
(30 points possible)
Write a function named single_insert_or_delete that accepts two strings as input arguments and returns:
0 if the two strings match exactly.
1 if the first string can become the same as the second string by inserting or deleting a single character. Notice that inserting and
deleting a characte... |
db4936597e0fd5db37fc3a2e481bbc9fc6010708 | wko1375/Data-Structures | /Homework 3/wk700_hw3_q3.py | 650 | 3.765625 | 4 | #question 3a
def print_triangle(n):
if n == 1:
print("*" * n)
if n <= 0:
print()
else:
print_triangle(n-1)
print("*" * n)
def print_triangle_right(n):
if n == 1:
print("*")
if n <= 0:
print()
else:
print("*" * n)
p... |
b1037bc6f0be6c4ea1bf5ae76a81ad1bd37b96a3 | jknguyen621/jknguyen621_Dev_Notes | /Python/MyYieldGeneratorLambdaMap.py | 1,464 | 4.21875 | 4 | """
@Author: I didnt write this, dont remembered where i got it from, years ago from internet, i think.
MyYieldGeneratorLambdaMap.py
This program demonstrate Lambda function, Yield-generator vs. List, and Map for iterable.
"""
#Routine to search for a keyword in a file and yield return full line where keyboard was ... |
2b8f8c94b660ce240936e2a14a42481afa731bd0 | quocthai200x/NguyenXuanQuocThai-Fundamentals-C4E27 | /session 5/HW_5/sum_of_numbers.py | 140 | 3.625 | 4 | def sum_(a,b):
print('tông 2 số a và b là :',(a+b))
a = int(input('nhập số a : '))
b = int(input('nhập số b : '))
sum_(a,b) |
18ae843ca44240c89d70dc55969ed932e9b8013c | Victorli888/Python-Tutorial-Workbook | /InterviewCake/IC_Reverse_Words.py | 1,102 | 4.5 | 4 | """You're working on a secret team solving coded transmissions.
Your team is scrambling to decipher a recent message, worried it's a plot to break into a major
European National Cake Vault. The message has been mostly deciphered, but all the words are backward!
Your colleagues have handed off the last step to you.
Wr... |
c7cbe9c5fdb0c37844d00ce044970152172c2301 | dhanashree0107/training_assignment | /7th_june/book_management_map2.py | 1,996 | 4.46875 | 4 | #Book Management System to store book records like ID, Book name, Author name, Cost using map
# Operations performed on record:
# insert record
# search record
# delete record
# display records
#Date: 07/06/2021
bookDict = {}
def insertBook(key1, bookName, authorName, cost):
bookDict[key1] = [bookNam... |
f817aa23ca1148beb72730858a12403aac42ac78 | Bit4z/python | /python/tuple2.py | 538 | 4.40625 | 4 | tup1=(1,2,3,4,5)
tup2=(6,7,8,9)
print("after adding two tuples")
print(tup1+tup2)
print("delete first tuple")
del tup1
#print(tup1*2)
print("slicing of tuples")
print(tup1[:3])
print(tup1[1:-3])
print(tup1[-3:])
print(tup1[1:4])
tup3=tup1
print(tup3)
#tup1[2]=9
#prin(tup1)
print("traverse tuple throug... |
9c1d1dfd498fb498aaf427b4d61c7acb5fbcbafd | mrchocoborider/py4e | /socket1.py | 1,319 | 3.515625 | 4 | import socket
#C12 Exercise 1
url = input('Enter url - ')
#C12 Exercise 5, only show data after the headers and a new line have been received
try:
prts = url.split('/')
hst = prts[2]
print(hst)
print(url)
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((hst, 80))
... |
6dd23b9cdcec2b65e14d97c45ed8c4f682ea8982 | yiicao/final_project | /week 2/hw1_yiicao.py | 6,812 | 4.40625 | 4 | """
############################## Homework #1 ##############################
% Student Name: Yi Cao
% Student Unique Name: yiicao
% Lab Section 00X: 006
% I worked with the following classmates: Nobody else
%%% Please fill in the first 4 lines of this file with the appropriate information before submitting on Can... |
6e9dfeee33a1d47bb564ed9cd27fcbbf61062f81 | RishabhRyber/git-it | /interface.py | 362 | 3.640625 | 4 | import sys
import main
if len(sys.argv) < 3:
print("Invalid number of arguments passed:")
quit()
type = sys.argv[1]
if type=="-u" or type =="-U":
if sys.argv[2] == "-r" or sys.argv[2] == "-r":
main.user_info(sys.argv[3],True)
else:
main.user_info(sys.argv[2],False)
if type=="e" or ty... |
edd58aaf5d294dd351dce018b209a698d114c1d7 | Aaron2018/functions-of-string | /myUpper.py | 143 | 3.703125 | 4 | s=input("please input a string: ")
aA=ord('a')-ord('A')
for ord in range(ord('a'),ord('z')+1):
s=s.replace(chr(ord),chr(ord-aA))
print(s) |
cd1956bbb17fbac2f2e593647aec5d46f9a086ef | manish59/Practice_Problems | /circular_linked_list.py | 1,088 | 4 | 4 | class Head:
def __int__(self,next=None,prev=None):
self.next=None
self.prev=None
class Node:
def __init__(self,data):
self.next=None
self.prev=None
self.data=data
class Double_Linked_List:
def __init__(self,data):
self.root=Head()
self.root.prev=None
... |
3ea2fa7e65fbee8cf7d6c639219d6ffa42f9b65f | BingxianChen/Algorithm | /src/Algorithm/chapter2_Link/1_PrintCommonPart.py | 679 | 3.890625 | 4 | # coding: utf8
# 打印两个有序链表的公共部分
class Node(object):
def __init__(self,data,next=None):
self.data = data
self._next = next
def printCommonPart(head1,head2):
print "Common Part:"
while head1._next is not None and head2._next is not None:
if head1.data < head2.data:
head1 =... |
0ae29764338b5c69c2091e594cca31e07dc819f8 | lambdagirl/leetcode-practice | /inflight-entertainment.py | 934 | 3.796875 | 4 | '''
input: flight_length(in minutes) int, movie_lengths(in minutes)list[int]
output: Boollen (movie1 +movie2 == flight_length)
1.movie1 != movie2
2.runtime complicity
### example
input: 300 , [100,110,190,200,230]
output: True 300 = 100 + 200
input: 300, [100,110,130,220,230]
output: False
input: 90, [100,110,1... |
2a6a4eeae714f76a9f4cddf31bd5e6168db9f4e6 | DavLivesey/algoritms_02 | /Neighbors.py | 944 | 3.84375 | 4 | '''
Дана матрица.
Нужно написать функцию, которая для элемента возвращает всех его соседей.
Соседним считается элемент, находящийся от текущего на одну ячейку влево,
вправо, вверх или вниз. Диагональные элементы соседними не считаются.
'''
count_strings = int(input())
count_columns = int(input())
matrix = []
for i in ... |
20222a883962b8f705015a5b8d4aec84be7fcdd1 | yzl232/code_training | /mianJing111111/new_leetcode_new/Swap Kth node from beginning with Kth node from end in a Linked List.py | 1,829 | 3.78125 | 4 | # encoding=utf-8
'''
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..et... |
60aacd062e330257e638005e0338a3422c64f4ec | konstantinats/ergasies-python | /ergasia python 1.py | 460 | 3.703125 | 4 | def sumIntervals(lista):
sum = 0
lista.sort()
x = len(lista) - 1
print(lista)
for i in range(0, x):
if (lista[i][1] > lista[i + 1][0]):
if (lista[i][1] < lista[i + 1][1]):
lista[i + 1][0] = lista[i][1]
else:
lista[i + 1][0] = 0
lista[i + 1][1] = 0
for i in range(0, len(lista)):
... |
b17ad69d9d22e63bd6b92140fe14d27f8e5a8258 | Nagendracse1/Competitive-Programming | /450/Ratndeep/Binary Tree/mirrortree.py | 231 | 3.671875 | 4 | #Given a Binary Tree, convert it into its mirror.
def mirror(root):
# Code here
if root==None:
return
mirror(root.left)
mirror(root.right)
temp=root.left
root.left=root.right
root.right=temp |
20ee6f0a61902dcb52d36132f264e70be0f9dfb9 | mhlemonh/leet-code-python | /130.surrounded_region.py | 2,068 | 3.5 | 4 | class leet130solver(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if len(board) != 0:
tmp_board = [[c for c in r] for r in board]
search_queue = []
... |
1ad1685d4cb8cff4eae645649a19e4644aa6eae9 | gautam4941/Python_Basics_Code | /IfElse/Prog4.py | 1,333 | 4.15625 | 4 | #Calculate the attendance of a student by taking input of class_held and class_attended.
#attendance = (class_attended/class_held) * 100. If attendace is less than 75 then, ask student for any
#medical certifiate. If medicate certificate is there. Print Student can sit in exam. If attendace is less
#than 75 and stu... |
e04ffaeab2ada4fb69d447f226a96208db2765b5 | sandip308/python-program-for-beginners | /N natural no reverse in recursion.py | 185 | 4.0625 | 4 | def reverse(n):
if n==0:
return
else:
print(n)
return (reverse(n-1))
if __name__ == '__main__':
x=int(input("Enter a range "))
reverse(x) |
278bedc0e201179dc514c637ac46c911e5693e91 | JianFengY/leetcode-python | /codes/plus_one.py | 737 | 3.78125 | 4 | class Solution:
"""
https://leetcode-cn.com/explore/learn/card/array-and-string/198/introduction-to-array/772/
给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
"""
def plus_one(self, digits):
"""
:type digits: List[int]
:rty... |
0eeded1fc5d0fee9233e33deb0d389eeb4d9d73e | yzxchn/nn_backpropagation | /nn_comps/functions.py | 738 | 3.671875 | 4 | import numpy as np
def identity(x):
"""
An identity function.
x: a numpy array
returns the same array
"""
return x
def sigmoid(x):
return 1.0/(1 + np.exp(-x))
sigmoid_vectorized = np.vectorize(sigmoid)
def sigmoid_derv(x):
return sigmoid(x)*(1-sigmoid(x))
sigmoid_derv_vectoriz... |
a2d9a52cefce3a583a81b6ba085725bfaa58fef5 | hzhhzh456/daima | /第51题.py | 148 | 3.75 | 4 | a=int(input("请输入一个数"))
b=int(input("请输入另一个数"))
if(a>b):
print("%d大于%d"%(a,b))
else:
print("%d大于%d"%(b,a))
|
d6d213cb0199b24afeb33bc94738acda2e52ed12 | kogansheina/euler | /p1_30/p14.py | 794 | 4.125 | 4 | #!/usr/bin/env python
import os
import sys
"""
Longest Collatz sequence
"""
if __name__ == '__main__':
from sys import argv
number = 13
if len(argv) > 1:
number = int(argv[1])
if number > 1000000:
print "Number too big"
sys.exit()
#final = []
longest = 0... |
f2d6c400ff3157dca0079c902aac8487bf54227f | predmsystem/projeto_python | /EXE025.py | 163 | 4 | 4 | """Crie um programa que leia o nome de uma pessoa e diga se ela tem SILVA no nome"""
nome = str(input('Digite seu Nome: ')).strip()
print('SILVA' in nome.upper())
|
f55daa45eba576f444b282d59a7fd861327a21b7 | ryu-jihye/Digital-ConvergenceProgram2 | /starcraft_project.py | 4,801 | 3.65625 | 4 | #일반 유닛
class Unit: #지상 유닛에 speed 추가
def __init__(self, name, hp, speed): #스피드 추가
self.name = name
self.hp = hp
self.speed = speed
print("{0} 유닛이 생성되었습니다.".format(name)) #self.name도 가능
def move(self, location):
print("[지상 유닛 이동]")
print("{0} : {1} 방... |
df12df108bac0847c161986741437b3776a4476d | ni-da/iap_1819 | /Les7_Recursion/reverse_a_list.py | 511 | 3.546875 | 4 | a = ['a', 'b', 'c', 'd', 'e']
# def reverse_list(old_ls, new_ls=[]):
# if 0 == len(old_ls):
# return
# else:
# new_ls.append(old_ls.pop(len(old_ls) - 1))
# reverse_list(old_ls, new_ls)
# return new_ls
def reverse_list(l):
if len(l) == 0:
return []
else:
re... |
f2e616b3eb26cb190912e9d2a3c4980c478ce584 | elu3/Python | /zagadka4cichonia2.py | 4,123 | 3.515625 | 4 | from math import *
from string import *
def wstaw(tekst, nowe, pozycja):
return tekst[:pozycja] + nowe + tekst[pozycja:]
def zamien_jeden_znak(text,indeks_znaku, znak):
nowy = text[:indeks_znaku] + znak + text[(indeks_znaku+1):]
return nowy
def znajdz_indeks_nastepnego_miejsca_do_wstawienia_nawiasu_w_dol(wyra... |
32e255b58414a934688bc4e5f55edf2578d6ae56 | alicefrancener/code-problems | /uri/data-structures-and-libraries/1340.py | 1,463 | 3.75 | 4 | while True:
try:
pilha, fila, fila_p, contagem = [], [], [], [0, 0, 0]
desconhecido = False
for n in range(int(input())):
comando = list(map(int, input().split()))
if comando[0] == 1: # inserir elemento
pilha.append(comando[1])
fila.ap... |
d22f56e7d6ca757865652eaa08ff02ed20356a82 | poojakhatri/JetBrainsAcademy-Projects | /Coffee Machine/Coffee Machine/task/machine/coffee_machine.py | 3,957 | 4.28125 | 4 |
# print("how many ml of water the coffee machine has:")
water_cap = 400
# print("how many ml of milk the coffee machine has:")
milk_cap = 540
# print("how many grams of water the coffee machine has:")
coffee_cap = 120
disposable_cups = 9
money_have = 550
# p = water_cap // 200
# q = milk_cap // 50
# r = coffee_ca... |
e17b67b76234f383dd60361f4d06c450e2f86c6b | fijila/PythonExperiments | /pkg/wordfrequency.py | 134 | 3.78125 | 4 | frequent_words={"one":5,"two":10,"three":15}
frequent_words = {k:v for (k,v) in frequent_words.items() if v>5}
print (frequent_words)
|
e479566a72323d7cb785a64708334de4cd60f0e1 | rachelyeshurun/magic-of-dynamic-programming | /notebooks/solutions/00/sum_n_numbers.py | 122 | 3.59375 | 4 | def sum(numbers):
n = len(numbers)
if n <= 0:
return 0
return sum(numbers[0: n - 1]) + numbers[n - 1] |
d29b55f7f90f3bc4257dafd2370f541c4c066318 | psolikov/MathStat | /hw3/hw3.py | 873 | 3.578125 | 4 | import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.stats import moment
def nmoment(x, i, n):
return np.sum(x**i) / n
print('Write a range: ')
r = float(input())
print('Write number of Xs: ')
n = int(input())
k = range(1, 100)
u = [np.mean([pow(r - pow(nmoment(np.random.uniform(0, r, n), i... |
c22c6783a2c8fb0006a0a3e1258d985cfb6d76ed | manches300/LearnPythonTheHardWayExcercises | /hardwayEx21.py | 649 | 4 | 4 | def add(a,b):
print "Adding %d and %d" % (a,b)
return a+b
def sub(a,b):
print "Subtracting %d and %d" % (a,b)
return a-b
def mul(a,b):
print "Multiplying %d and %d" % (a,b)
return a*b
def div(a,b):
print "dividing %d and %d" % (a,b)
return a/b
print "Let's do math with functi... |
3fa46141d73d5863397530095c2a4519017a1257 | SmalRat/target_game | /target_game.py | 3,319 | 3.890625 | 4 | """
Module of game about making words
"""
from typing import List
import random
def generate_grid() -> List[List[str]]:
"""
Generates list of lists of letters - i.e. grid for the game.
e.g. [['I', 'G', 'E'], ['P', 'I', 'S'], ['W', 'M', 'G']]
>>> random.seed(2190)
>>> generate_grid()
[['S', 'L'... |
9a39dff557c84fc0c37061340e31011b3c88689b | soulorman/Python | /practice/practice_4/classde3.py | 446 | 3.640625 | 4 | class Singleton(object):
__instance = None
def __init__(self):
if not Singleton.__instance:
print('调用__init__, 实例未创建')
else:
print('调用__init__,实例已经创建过了')
@classmethod
def get_instance(cls):
if not cls.__instance:
cls.__instance = Singleton()
... |
84cffbe3a8315ea1c4aa408d2b9b8bf5eb5c76eb | malaggang2/project_euler | /problem_41~80/problem_75.py | 1,459 | 3.8125 | 4 | # Problem_75
# Singular integer right triangles
# It turns out that 12 cm is the smallest length of wire that can be bent
# to form an integer sided right angle triangle in exactly one way,
# but there are many more examples.
#
# 12 cm: (3,4,5)
# 24 cm: (6,8,10)
# 30 cm: (5,12,13)
# 36 cm: (9,12,15)
# 40 cm: (8,15,17)
... |
9a41d83d43e58b3cf50e9f3f2d102131cd2ad8a3 | xren/algorithms | /4-6.py | 875 | 3.953125 | 4 | # write a function to find the next node of a given node in BST
def getNext(root):
if root == root.parent.left:
if not root.right:
return root.parent
else:
return getLeftMost(root.right)
elif root == root.parent.right:
if not root.right:
parent = roo... |
8d6c9947fcf38f9be256fc06a1524caff3a8cc86 | kdung109/OpenSource_Class | /예제.py | 345 | 3.9375 | 4 | def findMax(a,b,c):
if a>b:
biggest=a
else:
biggest=b
if c>biggest:
biggest=c
return biggest
a=int(input("첫번째 숫자 입력:"))
b=int(input("두번째 숫자 입력:"))
c=int(input("세번째 숫자 입력:"))
biggest = findMax(a,b,c)
print(a,b,c,"중 가장 큰 수는" ,biggest,"입니다.")
|
bbb350a4f76f9e10a4d520cbf89be54f17495c81 | benaan123/spaceindavers | /spaceinvaders.py | 3,670 | 3.921875 | 4 | # Space invaders
# Set up the screen
import turtle
import os
import math
import random
# hey
# Set up screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Space Invaders")
wn.screensize(800, 600)
# Draw border
border_pen = turtle.Turtle()
# speed = 0 is instant
border_pen.speed(0)
border_pen.color("white")
bord... |
7d4e9fd7969d2765ec92fe8b1e8d2c231eaa0e26 | silky/moxie | /moxie/facts.py | 10,433 | 3.859375 | 4 | import random
def get_fact():
return random.choice(FACTS)
def printable_fact(x):
if len(x) > 80:
return "{}\r\n{}".format(x[:80], printable_fact(x[80:]))
return x
def get_printable_fact():
return printable_fact(get_fact())
FACTS = [
"The billionth digit of Pi is 9.",
"Humans can ... |
647f647ac12c197e006c9d5e10e8d45433363883 | piffs1/Python | /AnyPython/taskListToStr.py | 219 | 3.703125 | 4 | def lstToStr(a_list):
result = ""
for i in range(len(a_list)-1):
result += a_list[i] +", "
result += "and " + a_list[len(a_list)-1]
return result
spam = ["apples", "bananas", "tofu", "cats"]
print(lstToStr(spam)) |
65fe4f6734a813882756e1aa1b485c549b58ff0c | pathbox/python-example | /algorithms/sort/merge_sort.py | 859 | 3.96875 | 4 | import math
def mergeSort(arr):
if (len(arr) < 2):
return arr
middle = math.floor(len(arr)/2) # 取中间为分区点
left, right = arr[0:middle], arr[middle:] # 得到左右两个数组
return merge(mergeSort(left), mergeSort(right))
def merge(left, right):
result = []
while left and right: # 不断的遍历 left right... |
bfbc7172e519d943196585d43a6ce3ddf39d6f58 | bmihovski/PythonFundamentials | /folder_size.py | 540 | 3.703125 | 4 | from os import stat, walk
"""
You are given a folder named "TestFolder". Get the size of all files in the folder, which are NOT directories.
The result should be written to another text file in Megabytes.
Examples
Output.txt
5.161738395690918
"""
FILES_PATH = "./Resources/07. Folder Size/TestFolder/"
for root, dirs... |
0346875d9d3633de7aeef17d7e0206df8514bc1c | handsome-fish/tips-python | /execute_time.py | 408 | 3.640625 | 4 | # 代码执行消耗时间
# 利用time()函数,在核心程序开始前记住当前时间点
# 然后在程序结束后计算当前时间点和核心程序开始前的时间差
# 可以帮助我们计算程序执行所消耗的时间
import time
start = time.time()
# 代码块
num = 0
for i in range(1000000):
num = i
# 打印消耗时间
print("共消耗时间: " + str(time.time()-start), "s")
|
9cc9baf7cd35cfa22525a3ccead661a0c20c37ee | ystop/algorithms | /sword/不用加减乘除做加法.py | 456 | 3.9375 | 4 | # -*- coding:utf-8 -*-
# 写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
class Solution:
def Add(self, num1, num2):
# write code here
while num2:
sum = num1 ^ num2
carry = 0xFFFFFFFF&(num1 & num2)<<1
carry = -(~(carry - 1) & 0xFFFFFFFF) if carry > 0x7FFFFFFF else carry
... |
54eb8bb054e6185cae10244f8b3a61ed48b4fbad | kasm2015/PythonExamples | /Operations/assignment_operators.py | 568 | 4.21875 | 4 | #ASSIGNMENT OPERATIONS
a = 18
b =20
a = a+b
print("\nAssignment of two variables to one variable ",a)
a+=b
print("Shorthand Expresion for addition of two variables --> ",a)
a = a-b
print("Subtraction of two numbers --> ",a)
a-=b
print("Shorthand Expresion for substraction of two variables --> ",a)
a = a*b
print("M... |
b2446a7d08e5af2db9080c9b1e7b58069b4dedc6 | babiswas/Python-Design-Patterns | /Abstract_factory.py | 1,165 | 4.1875 | 4 | from abc import ABC,abstractmethod
class Pet:
@abstractmethod
def speak(self):
pass
@abstractmethod
def have_food(self):
pass
class Cat(Pet):
def __init__(self,name):
self.name=name
def speak(self):
return f"{self.name} Mew"
def have_food(self):
retur... |
6be4a72c38caa8442195c305041d2ddf3b89bf2d | devAmoghS/Python-Interview-Problems-for-Practice | /find_products_pair_k.py | 293 | 3.5 | 4 | def product_pair(arr, x):
arr_sorted = sorted(arr)
for i in range(0, len(arr_sorted)):
sub_array = arr_sorted[i + 1 :]
if x // arr_sorted[i] in sub_array:
return True
return False
arr = [10, 20, 9, 40]
x = 400
res = product_pair(arr, x)
print(res)
|
d06bbfc1e0bc4fd0fa26b89fcc190b585d2049f3 | JasonYichongXing/Data-Structure | /Linkedlist.py | 2,700 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 19 13:27:24 2018
@author: xingyichong
"""
# linked list
class node:
def __init__(self, data):
self.data = data
self.next = None
class linkedlist:
def __init__(self, Iter=None):
self.head = None
if Iter: ... |
b6b2e175b0fea9bb56751c11418f90d678a71811 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/tmldan001/question2.py | 670 | 3.90625 | 4 | '''program to reformat a text file so that all lines are at most a given length. Do not break up words.
Daniel M.Tamale
TMLDAN001
2014-05-16'''
file_input = input("Enter the input filename:\n")
f = open (file_input, "r")
l = f.read()
f.close ()
file_output = input("Enter the output filename:\n")
width = eval(input("... |
5db81f7146cf2a8c393df22478de636ad0b5a405 | TedCha/open-kattis-problems | /python/reveresed_binary_searching_1.5.py | 849 | 4.03125 | 4 | #https://open.kattis.com/problems/reversebinary
#create empty list to store binary number
binaryL = []
#create recursive function to turn decimal into function
def toBinary(num):
#if num
if num == 1:
binaryL.append(1)
return 1
#if number != 1, call the function again to reduce num value
else:
... |
18ae7593a2862e1c14847bf069ea4d5fc3b5ff43 | nicolleromero/dicts-word-count | /wordcount.py | 2,283 | 4.28125 | 4 | import re
import sys
from collections import Counter
def count_words():
"""Count how many times each space-separated word occurs in that file"""
file = open(str(sys.argv[1]))
word_count = {}
for line in file:
words = line.split(" ")
for word in words:
word = word.lower... |
cb8a809982fb0f3ff129098cbe3ffb836129456d | RodrigoCh99/basic-challenges-in-python-language | /desafio71.py | 993 | 4.09375 | 4 | """
Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao
usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas
cédulas de cada valor serão entregues.
OBS:
Considere que o caixa possui cédulas de R$ 50, R$ 20, R$ 10 e... |
64d6766b2f22ca8a3ff966d7ff43ac3425fcba5e | erinkelsey/rabbitmq-python-pika | /fanout_exchange/fanout_exchange_publisher.py | 4,042 | 3.734375 | 4 | import pika, time
from random import randint
class publish_engine:
"""
Class to publish messages to RabbitMQ server using pika.
Messages are published to a Fanout Exchange, so that they are
received by all consumers subscribed to that exchange. Queues are
automatically created when a consumer conn... |
7b71c6b4ee64ce7aa7146af6367890949ca5f9a8 | moyales/Python-Crash-Course | /8_functions/demo_code_8/city_country.py | 150 | 3.59375 | 4 | def city_country(city, country):
"""Takes the name of a city, and the country its in"""
c_country = city + ", " + country
return c_country.title()
|
af478321e2f7a58b2e9ea74487ba2072de6b6747 | ankit1997/CC_project | /tester/14103005_1.py | 720 | 3.78125 | 4 | import math
primes = []
def prime_(x):
if x==2:
return 1
if x%2==0 or x<=1:
return 0
p=3
while p<=(int)(math.sqrt(x)):
if x%p==0:
return 0
p+=2
return 1
def const_primes(n):
global primes
if len(primes)==0:
primes += [2]
... |
7c12c4378b3cae511c2e07a762f607d25baa8ff7 | akimi-yano/algorithm-practice | /lc/review_82.RemoveDuplicatesFromSortedList.py | 1,423 | 3.8125 | 4 | # 82. Remove Duplicates from Sorted List II
# Medium
# 4910
# 152
# Add to List
# Share
# Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
# Example 1:
# Input: head = [1,2,3,3,4,4... |
ef8a287b9d875f6ad6228990f796f516a0cafc27 | Easyvipin/PYTHON-FOR-WEB-DEV | /Basic/var and condition.py | 127 | 3.859375 | 4 | a=9
b=10
if a >b :
print("a is bigger")
elif a == b :
print("equal value")
else:
print("b is bigger")
|
d65f52794f2ed28e58a4e1b3a789c4e7c2ada6d8 | ryan-berkowitz/python | /Python Exercises Folder/Python Variables/Assign Multiple Values.py | 301 | 4.125 | 4 | #Assign multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
#Assign multile variables to one value
a = b = c = "Blueberry"
print(a)
print(b)
print(c)
#Unpack a collection
fruits = ["apple", "banana", "cherry"]
d, e, f = fruits
print(d)
print(e)
print(f) |
64c0f26a42f3afb67238bb8686e20f707939bc3f | westgate458/LeetCode | /P0268.py | 768 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 20:34:48 2019
@author: Tianqi Guo
"""
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# Solution 1 beats 98.03%: length and sum
# length of the number list... |
4daa1f5de7d1f4f63b30d0bb149b029c5355f15f | LeonardoEichs/Gomoku-Brute-AI | /Board.py | 6,391 | 3.578125 | 4 | WIN = 'w'
DRAW = 'd'
CONTINUE = 'c'
class Board():
BoardWidth = 15
BoardHeight = 15
def __init__(self):
self.board = [[0 for i in range(self.BoardWidth)] for ii in range(self.BoardHeight)]
self.pieces = 0
def __repr__(self):
board = ''
for i in range(self.BoardHeight):... |
e259c5b82cdb6b5f778f78fdcb4918315d330bd2 | seun-beta/OOP | /fish.py | 806 | 3.859375 | 4 | class Fish:
def __init__(self, first_name, last_name='Fish', skeleton='bone', eyelids=False):
print("The object has been instantiated")
self.first_name = first_name
self.last_name = last_name
self.skeleton = skeleton
self.eyelids = eyelids
def swim(self):
pri... |
a976092c5c070113a49fa466847769a2679e36c4 | htmlfarmer/valua | /file.py | 734 | 3.765625 | 4 | import os.path
# READ(filename, directory)
def READ(filename, *argv):
directory = argv
if directory is None or directory is ():
directory = "./"
else:
directory = directory[0]
file_path = os.path.join(directory, filename)
text = None
if os.path.exists(file_path): # read the ol... |
33919a767f44e5ac54cacad6c07642b0fd97e0bd | zaoyuaner/Learning-materials | /python1812/python_1/12_面向对象/代码/singletonDemo01.py | 553 | 3.765625 | 4 | class Singleton(object):
#类属性
instance = None
#类方法
@classmethod
def __new__(cls, *args, **kwargs):
#如果instance的值不为None,说明已经被实例化了,则直接返回;如果为NOne,则需要被实例化
if not cls.instance:
cls.instance = super(Singleton,cls).__new__(*args, **kwargs)
return cls.instance
class My... |
732a9400149b8054c3f29d6a8cd1300eb2cdcf33 | Michellecp/Python | /python_teste/desafio034.py | 331 | 3.65625 | 4 | sal=float(input('Qual o salario do funcionario? R$'))
if sal <= 1250 :
sal_novo = (sal/100*15)+sal
print('Você recebeu 15% de aumento e seu salario novo será: {:.2f}'.format(sal_novo))
else:
sal_novo = (sal / 100 * 10) + sal
print('Você recebeu 10% de aumento e seu salario novo será: {:.2f}'.format(sal_... |
c25a332bdfb2d242cdfd1ace1f483de8d5205a8f | Sersh4745/python_learn | /Diachenko.hw7/lucky_ticket.py | 892 | 3.96875 | 4 | """
Написать функцию, которая будет проверять счастливый билетик или нет.
Билет счастливый, если сумма одной половины цифр равняется сумме второй.
"""
def is_lucky(lucky):
lucky = str(lucky)
length = (len(lucky) + 1)//2
part_1 = lucky[0:length]
part_2 = lucky[length:]
part_11 = []
par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.